text stringlengths 7 3.69M |
|---|
import React from "react";
import { Link } from "react-router-dom";
import "./Footer.css";
function Footer() {
return (
<div className="footer">
<div className="footer__icons">
<a
href="https://www.twitter.com/"
target="_blank"
rel="noopener noreferrer"
>
<i className="fab fa-twitter" />
</a>
<a
href="https://www.facebook.com/"
target="_blank"
rel="noopener noreferrer"
>
<i className="fab fa-facebook-f" />
</a>
<a
href="https://www.instagram.com/"
target="_blank"
rel="noopener noreferrer"
>
<i className="fab fa-instagram" />
</a>
<a
href="https://www.pinterest.com/"
target="_blank"
rel="noopener noreferrer"
>
<i className="fab fa-pinterest-p" />
</a>
</div>
<div className="footer__address">
<span>Smooth GmbH</span>
<span>Wesendorfer Str. 8</span>
<span>13439 Berlin</span>
</div>
<div className="footer__others">
<Link to="terms-and-conditions">Terms and Conditions</Link>
<Link to="privacy-policy">Privacy Policy</Link>
</div>
</div>
);
}
export default Footer;
|
import React from 'react';
import { BrowserRouter as Router, Link, Route, Redirect } from 'react-router-dom'
import withFirebaseAuth from 'react-with-firebase-auth'
import * as firebase from 'firebase/app';
import 'firebase/auth';
import firebaseApp from './firebase';
import Navbar from 'react-bootstrap/Navbar';
import Nav from 'react-bootstrap/Nav';
import FilledButton from './components/atoms/buttons/Filled';
import styles from './App.module.scss';
import Home from './components/pages/Home';
import GraphsPageLoader from './components/pages/GraphsPageLoader';
import ScoresPage from './components/pages/ScoresPage';
function App({user, signOut, signInWithGoogle}) {
return (
<Router>
<div className={ styles.App }>
<Navbar bg="none" expand="lg" variant="dark">
<Link to={'/'} className="navbar-brand">Wine on the Rocks</Link>
<Navbar.Toggle aria-controls="responsive-navbar-nav" />
<Navbar.Collapse id="responsive-navbar-nav">
<Nav className="mr-auto">
<Link to={'/'} className="nav-link">Home</Link>
<Link to={'/graphs'} className="nav-link">View Graphs</Link>
{ user ? <Link to={'/scores'} className="nav-link">Submit Scores</Link> : '' }
</Nav>
<Nav>
{
user ? <FilledButton variant='primary' onClick={signOut}>Sign Out</FilledButton> : <FilledButton variant='primary' onClick={signInWithGoogle}>Sign In</FilledButton>
}
</Nav>
</Navbar.Collapse>
</Navbar>
<div className="container">
<Route exact={true} path="/" component={Home} user={user}/>
<Route path="/graphs" component={GraphsPageLoader} user={user}/>
<PrivateRoute path="/scores" component={ScoresPage} user={user}/>
</div>
</div>
</Router>
);
function PrivateRoute({ component: Component, ...rest }) {
return (
<Route
{...rest}
render={props =>
user ? (
<Component {...props} />
) : (
<Redirect
to={{
pathname: "/",
state: { from: props.location }
}}
/>
)
}
/>
);
}
}
const firebaseAppAuth = firebaseApp.auth();
const providers = {
googleProvider: new firebase.auth.GoogleAuthProvider(),
};
export default withFirebaseAuth({
providers,
firebaseAppAuth,
})(App);
|
var searchData=
[
['setexam',['setExam',['../class_student.html#ae4dfc9ea1f586f44d4f748f667db9ac3',1,'Student']]],
['sethomework',['setHomework',['../class_student.html#a9f667f98c5b87ad21643090de3d69508',1,'Student']]],
['setmed',['setMed',['../class_student.html#a129afdaabbf26f19413101595a8428b2',1,'Student']]],
['setname',['setName',['../class_student.html#a489c963162c2b5798154a3217815cfc8',1,'Student']]],
['setsurname',['setSurname',['../class_student.html#a60c08d94f09c69cec567ed399dbafde1',1,'Student']]],
['setvid',['setVid',['../class_student.html#a4834bbde9c9dffa6f5db82f1f65367fe',1,'Student']]],
['student',['Student',['../class_student.html#af9168cedbfa5565cf0b20c1a9d3f5c9d',1,'Student::Student()'],['../class_student.html#aa8659e569d5a87efe8553b439142ad4d',1,'Student::Student(string name)'],['../class_student.html#ab2d9c6e05ea5a505708a3d82ece8a5ae',1,'Student::Student(std::string name, std::string surname)']]],
['surname',['surname',['../class_student.html#addd918dab403a4181f4761b53148855f',1,'Student']]]
];
|
function addDots(string, number) {
var stringLength = string.length;
if (stringLength > number) {
var newString = string.substr(0,number-3);
} return newString + "...";
} |
import React, { useState } from "react";
import Form from "react-bootstrap/Form";
import { CardElement, injectStripe } from "react-stripe-elements";
import LoaderButton from "./LoaderButton";
import { useFormFields } from "../libs/hooksLib";
function BillingForm({ isLoading, onSubmit, ...props }) {
const [fields, handleFieldChange] = useFormFields({
name: "",
});
const [isProcessing, setIsProcessing] = useState(false);
const [isCardComplete, setIsCardComplete] = useState(false);
isLoading = isProcessing || isLoading;
function validateForm() {
return fields.name !== "" && isCardComplete;
}
async function handleSubmitClick(event) {
event.preventDefault();
setIsProcessing(true);
const { token, error } = await props.stripe.createToken({
name: fields.name,
});
setIsProcessing(false);
onSubmit({ token, error });
}
return (
<div className="col-6 payment">
<Form className="BillingForm p-5" onSubmit={handleSubmitClick}>
<h4 className="billingheader">Donate a dollar to help with hosting</h4>
<hr />
<Form.Group size="lg" controlId="name">
<Form.Label className="whitetext">Name on Card</Form.Label>
<Form.Control
type="text"
value={fields.name}
onChange={handleFieldChange}
/>
</Form.Group>
<Form.Label className="whitetext">Credit Card Info</Form.Label>
<CardElement
className="card-field"
onChange={(e) => setIsCardComplete(e.complete)}
style={{
base: {
color: "#303238",
backgroundColor: "#FFFFFF",
fontSize: "28px",
fontFamily: '"Open Sans", sans-serif',
fontSmoothing: "antialiased",
"::placeholder": {
color: "#CFD7DF",
},
},
invalid: {
color: "#e5424d",
":focus": {
color: "#303238",
},
},
}}
></CardElement>
<br></br>
<LoaderButton
block
size="lg"
type="submit"
isLoading={isLoading}
disabled={!validateForm()}
>
Donate
</LoaderButton>
</Form>
</div>
);
}
export default injectStripe(BillingForm);
|
import React, {Component} from 'react';
import {Icon, message, Input} from 'antd';
import {getBase64} from '../utils';
export default class UpdateBtn extends Component{
static defaultProps = {
onChange: () => {},
maxSize: null // ๅไฝ kb
}
constructor(props) {
super(props);
this.state = {
img: null
}
}
onChange = e => {
const file = e.target.files[0];
const {maxSize} = this.props;
if(maxSize && file.size > maxSize * 1024){
message.error('ๆไปถ่ฟๅคง๏ผ่ฏท้ๆฐไธไผ ');
return false;
}
getBase64(file, res => {
this.setState({
img: res
})
this.props.onChange(file)
})
}
render(){
const {img} = this.state;
return(
<div style={styles.btnWrap}>
{
img ? (
<img style={styles.img} src={img} alt="picture" />
) : (
<Icon type='plus' />
)
}
<Input style={styles.input} onChange={this.onChange} type="file" encType="multipart/form-data"/>
</div>
)
}
}
const styles = {
btnWrap: {
width: '102px',
lineHeight: '102px',
textAlign: 'center',
position: 'relative',
border: '1px dotted red',
borderRadius: '4px',
backgroundColor: '#f9f9f9'
},
input: {
opacity:0,
width:'100%',
height:'100%',
position:'absolute',
top:0,
left:0,
cursor: 'pointer'
},
img: {
width: '86px',
height: '86px'
}
} |
import React, { Component } from 'react';
import { Container, Divider, Header } from 'semantic-ui-react';
const ContentComponent = () => {
return (
<Container textAlign='justified'>
<Header as="h2">Big Data๋ ๋ฌด์์ธ๊ฐ?</Header>
<Divider />
<p>
๋์งํธ ๊ฒฝ์ ์ ํ์ฐ์ผ๋ก ์ฐ๋ฆฌ ์ฃผ๋ณ์๋ ๊ท๋ชจ๋ฅผ ๊ฐ๋ ํ ์ ์์ ์ ๋๋ก ๋ง์ ์ ๋ณด์ ๋ฐ์ดํฐ๊ฐ ์์ฐ๋๋ '๋น
๋ฐ์ดํฐ(Big Data)' ํ๊ฒฝ์ด ๋๋ํ๊ณ ์๋ค.
๋น
๋ฐ์ดํฐ๋ ๊ณผ๊ฑฐ ์๋ ๋ก๊ทธ ํ๊ฒฝ์์ ์์ฑ๋๋ ๋ฐ์ดํฐ์ ๋นํ๋ฉด ๊ทธ ๊ท๋ชจ๊ฐ ๋ฐฉ๋ํ๊ณ , ์์ฑ ์ฃผ๊ธฐ๋ ์งง๊ณ , ํํ๋ ์์น ๋ฐ์ดํฐ๋ฟ ์๋๋ผ ๋ฌธ์์ ์์ ๋ฐ์ดํฐ๋ฅผ ํฌํจํ๋ ๋๊ท๋ชจ ๋ฐ์ดํฐ๋ฅผ ๋งํ๋ค.
</p>
<p>
PC์ ์ธํฐ๋ท, ๋ชจ๋ฐ์ผ ๊ธฐ๊ธฐ ์ด์ฉ์ด ์ํํ๋๋ฉด์ ์ฌ๋๋ค์ด ๋์ฒ์ ๋จ๊ธด ๋ฐ์๊ตญ(๋ฐ์ดํฐ)์ ๊ธฐํ๊ธ์์ ์ผ๋ก ์ฆ๊ฐํ๊ณ ์๋ค(์ ์ฉ์ฐฌ, 2012a).
์ผํ์ ์๋ฅผ ๋ค์ด ๋ณด์. ๋ฐ์ดํฐ์ ๊ด์ ์์ ๋ณด๋ฉด ๊ณผ๊ฑฐ์๋ ์์ ์์ ๋ฌผ๊ฑด์ ์ด ๋๋ง ๋ฐ์ดํฐ๊ฐ ๊ธฐ๋ก๋์๋ค. ๋ฐ๋ฉด ์ธํฐ๋ท์ผํ๋ชฐ์ ๊ฒฝ์ฐ์๋
๊ตฌ๋งค๋ฅผ ํ์ง ์๋๋ผ๋ ๋ฐฉ๋ฌธ์๊ฐ ๋์๋ค๋ ๊ธฐ๋ก์ด ์๋์ ์ผ๋ก ๋ฐ์ดํฐ๋ก ์ ์ฅ๋๋ค. ์ด๋ค ์ํ์ ๊ด์ฌ์ด ์๋์ง, ์ผ๋ง ๋์ ์ผํ๋ชฐ์ ๋จธ๋ฌผ๋ ๋์ง๋ฅผ ์ ์ ์๋ค.
์ผํ๋ฟ ์๋๋ผ ์ํ, ์ฆ๊ถ๊ณผ ๊ฐ์ ๊ธ์ต๊ฑฐ๋, ๊ต์ก๊ณผ ํ์ต, ์ฌ๊ฐํ๋, ์๋ฃ๊ฒ์๊ณผ ์ด๋ฉ์ผ ๋ฑ ํ๋ฃจ ๋๋ถ๋ถ์ ์๊ฐ์ PC์ ์ธํฐ๋ท์ ํ ์ ํ๋ค.
์ฌ๋๊ณผ ๊ธฐ๊ณ, ๊ธฐ๊ณ์ ๊ธฐ๊ณ๊ฐ ์๋ก ์ ๋ณด๋ฅผ ์ฃผ๊ณ ๋ฐ๋ ์ฌ๋ฌผ์ง๋ฅํต์ (M2M, Machine to Machine)์ ํ์ฐ๋ ๋์งํธ ์ ๋ณด๊ฐ ํญ๋ฐ์ ์ผ๋ก ์ฆ๊ฐํ๊ฒ ๋๋ ์ด์ ๋ค.
</p>
<p>
์ฌ์ฉ์๊ฐ ์ง์ ์ ์ํ๋ UCC๋ฅผ ๋น๋กฏํ ๋์์ ์ฝํ
์ธ , ํด๋์ ํ์ SNS(Social Network Service)์์ ์์ฑ๋๋ ๋ฌธ์ ๋ฑ์ ๋ฐ์ดํฐ์ ์ฆ๊ฐ ์๋๋ฟ ์๋๋ผ,
ํํ์ ์ง์์๋ ๊ธฐ์กด๊ณผ ๋ค๋ฅธ ์์์ ๋ณด์ด๊ณ ์๋ค. ํนํ ๋ธ๋ก๊ทธ๋ SNS์์ ์ ํต๋๋ ํ
์คํธ ์ ๋ณด๋ ๋ด์ฉ์ ํตํด ๊ธ์ ์ด ์ฌ๋์ ์ฑํฅ๋ฟ ์๋๋ผ, ์ํตํ๋
์๋๋ฐฉ์ ์ฐ๊ฒฐ ๊ด๊ณ๊น์ง๋ ๋ถ์์ด ๊ฐ๋ฅํ๋ค. ๊ฒ๋ค๊ฐ ์ฌ์ง์ด๋ ๋์์ ์ฝํ
์ธ ๋ฅผ PC๋ฅผ ํตํด ์ด์ฉํ๋ ๊ฒ์ ์ด๋ฏธ ์ผ๋ฐํ๋์๊ณ ๋ฐฉ์ก ํ๋ก๊ทธ๋จ๋ TV์์๊ธฐ๋ฅผ ํตํ์ง ์๊ณ PC๋ ์ค๋งํธํฐ์ผ๋ก ๋ณด๋ ์ธ์์ด๋ค.
</p>
</Container>
)
}
export default ContentComponent; |
import _ from 'underscore';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import {
checkScoreForUpdate,
updateVisibleItems,
} from 'robScoreCleanup/actions/Items';
import DisplayComponent from 'robScoreCleanup/components/ScoreList';
export class ScoreList extends Component {
constructor(props) {
super(props);
this.handleCheck = this.handleCheck.bind(this);
}
componentWillReceiveProps(nextProps){
if (nextProps.selectedScores != this.props.selectedScores ||
nextProps.items != this.props.items ||
nextProps.selectedStudies != this.props.selectedStudies){
this.props.dispatch(updateVisibleItems(nextProps.selectedScores, nextProps.selectedStudies));
}
}
handleCheck({target}) {
this.props.dispatch(checkScoreForUpdate(target.id));
}
renderEmptyScoreList(){
return <p className='lead'>No items meet your criteria.</p>;
}
render() {
if (!this.props.isLoaded) return null;
let { items, visibleItemIds, idList, config } = this.props,
filteredItems = items.filter((d)=>_.contains(visibleItemIds, d.id));
if (filteredItems.length === 0){
return this.renderEmptyScoreList();
}
return (
<DisplayComponent
idList={idList}
items={filteredItems}
config={config}
handleCheck={this.handleCheck} />
);
}
}
function mapStateToProps(state) {
const { items, visibleItemIds, updateIds, isLoaded } = state.items;
return {
selectedScores: state.scores.selected,
selectedStudies: state.studyTypes.selected,
items,
visibleItemIds,
idList: updateIds,
isLoaded,
};
}
export default connect(mapStateToProps)(ScoreList);
|
/**
* External dependencies
*/
import classnames from 'classnames';
import { ChromePicker } from 'react-color';
import { map } from 'lodash';
/**
* WordPress dependencies
*/
const { __, sprintf } = wp.i18n;
const {
Button,
Dropdown,
Tooltip,
} = wp.components;
/**
* Copy of gutenberg 3.9.0 /packages/components/src/color-palette
* enabled alpha ChromePicker
*/
export default function ColorPaletteAlpha( { colors, disableCustomColors = false, value, onChange, className } ) {
function applyOrUnset( color ) {
return () => onChange( value === color ? undefined : color );
}
const customColorPickerLabel = __( 'Custom color picker' );
const classes = classnames( 'components-color-palette', className );
return (
<div className={ classes }>
{ map( colors, ( { color, name } ) => {
const style = { color: color };
const itemClasses = classnames( 'components-color-palette__item', { 'is-active': value === color } );
return (
<div key={ color } className="components-color-palette__item-wrapper">
<Tooltip
text={ name ||
// translators: %s: color hex code e.g: "#f00".
sprintf( __( 'Color code: %s' ), color )
}>
<button
type="button"
className={ itemClasses }
style={ style }
onClick={ applyOrUnset( color ) }
aria-label={ name ?
// translators: %s: The name of the color e.g: "vivid red".
sprintf( __( 'Color: %s' ), name ) :
// translators: %s: color hex code e.g: "#f00".
sprintf( __( 'Color code: %s' ), color ) }
aria-pressed={ value === color }
/>
</Tooltip>
</div>
);
} ) }
{ ! disableCustomColors &&
<Dropdown
className="components-color-palette__item-wrapper components-color-palette__custom-color"
contentClassName="components-color-palette__picker"
renderToggle={ ( { isOpen, onToggle } ) => (
<Tooltip text={ customColorPickerLabel }>
<button
type="button"
aria-expanded={ isOpen }
className="components-color-palette__item"
onClick={ onToggle }
aria-label={ customColorPickerLabel }
>
<span className="components-color-palette__custom-color-gradient" />
</button>
</Tooltip>
) }
renderContent={ () => (
<ChromePicker
color={ value }
onChangeComplete={ ( color ) => onChange( color ) }
/>
) }
/>
}
<Button
className="components-color-palette__clear"
type="button"
onClick={ () => onChange( undefined ) }
isSmall
isDefault
>
{ __( 'Clear' ) }
</Button>
</div>
);
}
|
import Vue from 'vue'
import VueRouter from 'vue-router'
import Add from './add'
import List from './list'
import $ from 'jquery'
window.$ = $
// require('../../assets/sass/app.sass')
// import weui from '/static/lib/weui'
// import { loading } from 'weui.js'
import weui from 'weui.js'
window.weui = weui
import fetch from '../../utils/fetch'
console.log(fetch)
window.fetchs = fetch
import posts from '../../api/posts'
posts.getArticle().then(res => {
console.log(res)
})
posts.getPosts({data: {a: 'aaa'}}).then(res => {
console.log(res)
})
// console.log(weui)
// weui.alert('test')
Vue.use(VueRouter)
// ๅๅปบไธไธช่ทฏ็ฑๅจๅฎไพ
// ๅนถไธ้
็ฝฎ่ทฏ็ฑ่งๅ
const router = new VueRouter({
mode: 'history',
// base: baseUrl,
routes: [
{
path: '/adddd',
component: Add
},
{
path: '/list',
component: List
}
]
})
// ็ฐๅจๆไปฌๅฏไปฅๅฏๅจๅบ็จไบ๏ผ
// ่ทฏ็ฑๅจไผๅๅปบไธไธช App ๅฎไพ๏ผๅนถไธๆ่ฝฝๅฐ้ๆฉ็ฌฆ #index ๅน้
็ๅ
็ด ไธใ
/* eslint-disable no-new */
new Vue({
router: router
}).$mount('#index')
|
import Vue from 'vue';
import App from './App.vue';
import router from './router';
import store from './store';
import 'normalize.css';
import '@/assets/styles/main.scss';
import TheHeader from './components/TheHeader.vue';
Vue.component('TheHeader', TheHeader);
import AppShip from './components/AppGameboard/AppShip.vue';
Vue.component('AppShip', AppShip);
Vue.config.productionTip = false;
new Vue({
router,
store,
render: (h) => h(App),
}).$mount('#app');
|
import React from 'react';
import PropTypes from 'prop-types';
import Button from 'material-ui/Button';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
const galleryStyles = {
display: 'flex',
justifyContent: 'space-around'
}
function Gallery(props) {
const { classes, images, galleryIndex, openGallery } = props;
console.log('images', images)
const renderGallery = images.map((image, imageIndex) =>
<div className="gallery" key={imageIndex}>
<Button onClick={(e) => openGallery(galleryIndex, imageIndex)}>
<img src={image.thumbnail} className="gallery-thumbnail" alt="" />
</Button>
</div>
);
return (
<MuiThemeProvider>
<div style={galleryStyles}>{renderGallery}</div>
</MuiThemeProvider>
)
}
Gallery.propTypes = {
classes: PropTypes.object.isRequired,
images: PropTypes.array,
openGallery: PropTypes.func,
closeGallery: PropTypes.func,
nextImage: PropTypes.func,
previousImage: PropTypes.func,
};
export default Gallery;
|
function HanoiGraphics(hObj) {
var currentMove = 0;
function relocate(from, to, item) {
var fromTower = document.getElementById("tower-" + from);
var toTower = document.getElementById("tower-" + to);
var itemToMove = document.getElementById("disc-" + item);
toTower.insertBefore(itemToMove, toTower.firstChild);
}
function initiateMove() {
if (currentMove < hObj.towerStates.length) {
var from = hObj.towerStates[currentMove].from;
var to = hObj.towerStates[currentMove].to;
var item = hObj.towerStates[currentMove].item;
relocate(from, to, item);
console.log(hObj.towerStates[currentMove++]);
} else {
console.log("We are done, actually.");
}
}
function loadTower() {
var discs = hObj.getStackHeight();
currentMove = 0;
var startingTower = document.getElementById("tower-0");
for (let i = discs - 1; i >= 0; i--) {
var discElContainer = document.createElement("div");
var discEl = document.createElement("div");
discElContainer.className = "disc";
discElContainer.id = "disc-" + i;
discElContainer.appendChild(discEl);
startingTower.insertBefore(discElContainer, startingTower.firstChild);
}
document.getElementById("move").addEventListener("click", initiateMove);
document.getElementById("reset").addEventListener("click", resetHanoi);
}
window.addEventListener("load", loadTower);
}
|
(function (projectName, angular) {
'use strict';
angular
.module('app.components.welcome')
.controller('WelcomeController', WelcomeController);
WelcomeController.$inject = ['$interval', 'logger'];
function WelcomeController($interval, logger) {
var vm = this;
var angularSuperlatives;
logger.info('Loading controller:', vm);
angularSuperlatives = ['rocks', 'is easy to use', 'has a steep learning curve'];
vm.nextItem = 0;
vm.superlative = angularSuperlatives[vm.nextItem];
$interval(loadNext, 1500);
function loadNext() {
vm.nextItem = (vm.nextItem >= angularSuperlatives.length - 1) ? 0 : vm.nextItem + 1;
vm.superlative = angularSuperlatives[vm.nextItem];
}
}
})(window.projectName = window.projectName || {}, angular);
|
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Card from '@material-ui/core/Card';
import CardActionArea from '@material-ui/core/CardActionArea';
import CardActions from '@material-ui/core/CardActions';
import CardContent from '@material-ui/core/CardContent';
import CardMedia from '@material-ui/core/CardMedia';
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';
const useStyles = makeStyles({
card: {
maxWidth: 345,
width: '100%'
},
media: {
height: 140,
},
span: {
color: '#3f51b5',
marginLeft: 4
},
});
export default function InventoryCard({
firstName,
lastName,
streetAddress,
city,
id,
selectInventory
}) {
const classes = useStyles();
console.log()
return (
<Card className={classes.card} onClick={() => selectInventory(id)}>
<CardActionArea>
<CardContent>
<Typography gutterBottom variant="h5" component="h2">
{firstName} {lastName}
</Typography>
<Typography variant="body2" color="textSecondary" component="p">
{streetAddress} -
<span className={classes.span}>{city}</span>
</Typography>
</CardContent>
</CardActionArea>
<CardActions>
<Button size="medium" color="primary" onClick={() => selectInventory(id)}>
Show Details
</Button>
</CardActions>
</Card>
);
} |
import styled from 'styled-components';
export const LayoutContainerStyles = styled.section`
display: flex;
flex-direction: column;
align-items: center;
height: ${(props) => props.inLandingPage && '0vh'};
min-height: ${(props) => !props.inLandingPage && '100vh'};
padding-top: ${(props) => (props.inLandingPage ? '0px' : '75px')};
padding-bottom: ${(props) => (props.inLandingPage ? '0px' : '60px')};
box-sizing: box-sizing;
`;
|
import Power from '../src/common/operator/Power';
import tape from 'tape';
tape('Power', t => {
const power = new Power({
exponent: 2,
});
power.processStreamParams({ frameSize: 4 });
const a = power.inputVector([-1, 0, 1, 2]);
t.looseEqual([1, 0, 1, 4], a, 'should rise vector at given exponent power');
const b = power.inputSignal([-1, 0, 1, 2]);
t.looseEqual([1, 0, 1, 4], b, 'should rise signal at given exponent power');
power.params.set('exponent', 0.5);
const c = power.inputVector([9, 0, 1, 4]);
t.looseEqual([3, 0, 1, 2], c, 'should rise vector at given exponent power');
const d = power.inputSignal([9, 0, 1, 4]);
t.looseEqual([3, 0, 1, 2], d, 'should rise signal at given exponent power');
t.end();
});
|
import React from 'react'
import {compose, onlyUpdateForKeys, withPropsOnChange} from 'recompose'
import {withStyles} from '@material-ui/core/styles'
import ArrowRight from '@material-ui/icons/ChevronRight'
import ListSubheader from '@material-ui/core/ListSubheader'
import ListComponent from '@material-ui/core/List'
import ListItem from '@material-ui/core/ListItem'
import ListItemIcon from '@material-ui/core/ListItemIcon'
import ListItemText from '@material-ui/core/ListItemText'
// local libs
import {
PropTypes,
ImmutablePropTypes,
setPropTypes,
breakpoints,
breakpointSM as sm,
plainProvedGet as g,
compareCurrentBreakpoint as ccb,
} from 'src/App/helpers'
import {
immutableNichesListModel,
immutableTagArchiveListModel,
immutablePornstarsListWithLetterModel
} from 'src/App/models'
import {ListsInner, StyledLink, Section, SectionInner} from 'src/generic/Lists/assets'
import {muiStyles} from 'src/generic/Lists/assets/muiStyles'
const
// Generic list item component generator
renderItem = (isSponsor, idKey, titleKey, countKey, subPage, year, month) =>
(x, classedBounds, linkBuilder) => <StyledLink
to={
isSponsor
? linkBuilder(x.toLowerCase())
: year && month
? linkBuilder(x.get(year), x.get(month)) // archive links
: linkBuilder(x.get(subPage)) // niche link
}
key={isSponsor ? x : x.get(idKey)}
>
<ListItem button classes={g(classedBounds, 'item')}>
<ListItemIcon classes={g(classedBounds, 'icon')}>
<ArrowRight/>
</ListItemIcon>
<ListItemText
inset
primary={isSponsor ? x : x.get(titleKey)}
secondary={isSponsor ? null : x.get(countKey)}
classes={g(classedBounds, 'listItemText')}
/>
</ListItem>
</StyledLink>,
SponsorsListItem = renderItem(true),
NichesListItem = renderItem(false, 'id', 'name', 'itemsCount', 'subPage'),
ArchiveYearListItem =
renderItem(false, 'archiveDate', 'month', 'itemsCount', 'subPage', 'year', 'monthNumber'),
ModelsLetterListItem = renderItem(false, 'id', 'name', 'itemsCount', 'subPage', 'letter'),
ArchiveList = ({classedBounds, tagArchiveList, linkBuilder, i18nListArchiveHeader}) => {
const
years = tagArchiveList
.groupBy(x => x.get('year'))
.sortBy((v, year) => year, (a, b) => a < b ? 1 : -1)
.map(x => x.sortBy(y => y.get('archiveDate')))
return <ListComponent component="nav" subheader={<li/>}>
{years.map((listByYear, year) =>
<Section key={`section-${year}`}>
<SectionInner>
<ListSubheader classes={g(classedBounds, 'listSubheader')}>
{`${i18nListArchiveHeader} ${year}`}
</ListSubheader>
{listByYear.map(x => ArchiveYearListItem(x, classedBounds, linkBuilder))}
</SectionInner>
</Section>
).toList()}
</ListComponent>
},
ModelsList = ({classedBounds, modelsList, linkBuilder}) => {
const
letters = modelsList
.groupBy(x => x.get('letter'))
.sortBy((v, year) => year, (a, b) => a < b ? 1 : -1)
.reverse()
.map(x => x.sortBy(y => y.get('name')))
return <ListComponent component="nav" subheader={<li/>}>
{letters.map((listByYear, letter) =>
<Section key={`section-${letter}`}>
<SectionInner>
<ListSubheader classes={g(classedBounds, 'listSubheader')}>
{`${letter}`}
</ListSubheader>
{listByYear.map(x => ModelsLetterListItem(x, classedBounds, linkBuilder))}
</SectionInner>
</Section>
).toList()}
</ListComponent>
},
Lists = ({
classedBounds,
cb,
maxHeight,
sponsorsList,
sponsorLinkBuilder,
tagList,
tagLinkBuilder,
tagArchiveList,
archiveLinkBuilder,
modelsList,
modelLinkBuilder,
i18nListNichesHeader,
i18nListArchiveHeader,
}) =>
ccb(cb, sm) === 1
? <ListsInner maxHeight={maxHeight}>
{ sponsorsList ? <ListComponent
component="nav"
subheader={
<ListSubheader classes={g(classedBounds, 'listSubheader')}>
{i18nListArchiveHeader}
</ListSubheader>
}
>
{sponsorsList.map(x => SponsorsListItem(x, classedBounds, sponsorLinkBuilder))}
</ListComponent> : null }
{ tagList ? <ListComponent
component="nav"
subheader={
<ListSubheader classes={g(classedBounds, 'listSubheader')}>
{i18nListNichesHeader}
</ListSubheader>
}
>
{tagList.map(x => NichesListItem(x, classedBounds, tagLinkBuilder))}
</ListComponent> : null }
{ tagArchiveList ? <ArchiveList
classedBounds={classedBounds}
tagArchiveList={tagArchiveList}
linkBuilder={archiveLinkBuilder}
i18nListArchiveHeader={i18nListArchiveHeader}
/> : null }
{ modelsList ? <ModelsList
classedBounds={classedBounds}
modelsList={modelsList}
linkBuilder={modelLinkBuilder}
/> : null }
</ListsInner> : null
export default compose(
onlyUpdateForKeys(['cb', 'maxHeight']),
withStyles(muiStyles),
withPropsOnChange([], props => ({
classedBounds: Object.freeze({
listSubheader: Object.freeze({root: g(props, 'classes', 'listSubheader')}),
item: Object.freeze({root: g(props, 'classes', 'itemRoot')}),
icon: Object.freeze({root: g(props, 'classes', 'iconRoot')}),
listItemText: Object.freeze({
root: g(props, 'classes', 'itemTextRoot'),
primary: g(props, 'classes', 'primaryTypography'),
})
}),
})),
setPropTypes(process.env.NODE_ENV === 'production' ? null : {
classes: PropTypes.exact({
listSubheader: PropTypes.string,
itemRoot:PropTypes.string,
iconRoot: PropTypes.string,
itemTextRoot: PropTypes.string,
primaryTypography: PropTypes.string,
}),
classedBounds: PropTypes.exact({
listSubheader: PropTypes.object,
item: PropTypes.object,
icon: PropTypes.object,
listItemText: PropTypes.object,
}),
cb: PropTypes.oneOf(breakpoints),
maxHeight: PropTypes.nullable(PropTypes.number),
sponsorsList: ImmutablePropTypes.listOf(PropTypes.string).isOptional,
sponsorLinkBuilder: PropTypes.func.isOptional,
tagList: immutableNichesListModel.isOptional,
tagLinkBuilder: PropTypes.func.isOptional,
tagArchiveList: immutableTagArchiveListModel.isOptional,
archiveLinkBuilder: PropTypes.func.isOptional,
modelsList: immutablePornstarsListWithLetterModel.isOptional,
modelLinkBuilder: PropTypes.func.isOptional,
i18nListNichesHeader: PropTypes.string.isOptional,
i18nListArchiveHeader: PropTypes.string.isOptional,
})
)(Lists)
|
const modelPage = require('../models/page.js');
function renderQueue(request, response) {
modelPage.getRequestsAndServing(function (error, results) {
if (error)
return response.status(error.code).json(error); //change this to render and error page
response.render("pages/queue", {
serving: results.serving,
requests: results.requests,
class_names: results.class_names,
location_names: results.location_names,
helper: request.session.helper || false,
student: request.session.student || false
});
});
}
module.exports = {
renderQueue: renderQueue
};
|
var Stage = {
media: null,
mediaTimer: null,
bubbles:[],
parameters: {MIN_DURATION : 15, MAX_DURATION : 45, MIN_DELAY : 5, MAX_DELAY : 50, MAX_BUBBLES : 10,
DEVICE_WIDTH : 300, DEVICE_HEIGHT : 500, TWEET_DUR_TIME : 2000, THEME : "zen",RANDOM_TYPE:"random",
NUMBER_OF_FRAMES : 4, SHOW_WELCOME : 1,B_TEXT_SIZE:0,suggestions:true},
init: function(path) {
// set user settings
var storedParameters = 'undefined';
try {storedParameters = JSON.parse(localStorage.getItem('parameters')) || 'undefined'; }catch(e){} ;
if (storedParameters != 'undefined') {
Stage.parameters = storedParameters;
}
/* ---- done with parameters ------*/
Stage.setDeviceDimensions();
if (this.parameters.THEME != "default") {
Stage.setTheme(null,Stage.parameters.THEME)
};
$('#startBtn').on('click', function(event) {event.preventDefault(); Stage.startRandomness(Stage.parameters.RANDOM_TYPE);});
$('#startA').on('click', function(event) {event.preventDefault(); Stage.startRandomness(Stage.parameters.RANDOM_TYPE);});
$("#loadLocalBtn").on('click', function(event) { event.preventDefault(); loadLocal();});
$('.cloudPosibility').on("click", NC.login);
//$('#gdrive').on("click", loadCloud);
//$('#onedrive').on("click", loadCloud);
//play / pause / fwd buttons
$('#play').css('display','block');
$('#pause').css('display','none');
$('#play').on('click', function(event) {
event.preventDefault(); $(event.target).css('display','none');
$('#pause').css('display','block'); $('audio#mejs:first')[0].play();
});
$('#pause').on('click', function(event) {event.preventDefault(); $(event.target).css('display','none');
$('#play').css('display','block'); $('audio#mejs:first')[0].pause();
});
$('#fwd').on('click', function(event) {event.preventDefault(); $('#pause').click(); MC.playRandomSong(event.target);});
if ( Stage.parameters.SHOW_WELCOME) { $('#guideBtn').click();
Stage.parameters.SHOW_WELCOME = 0; };
//this.startRandomness(this.parameters.RANDOM_TYPE);
$('#searchInput').on('keyup', function(){
//event.preventDefault();
var searchStr = $('#searchInput').val().toLowerCase();
if (searchStr.length > 3) {
Stage.search(searchStr)};
//$('#searchInput').val('')
});
$('#clearSearch').on('click', function(event) {
event.preventDefault(); $('#searchInput').val(''); Stage.parameters.RANDOM_TYPE = 'random';});
Stage.adjustFontSize(Stage.parameters.B_TEXT_SIZE);
Stage.saveParameters();
},
refresh : function() {
Stage.setDeviceDimensions();
Stage.startRandomness(this.parameters.RANDOM_TYPE);
},
setDeviceDimensions: function() {
Stage.parameters.DEVICE_WIDTH = document.documentElement.clientWidth;
Stage.parameters.DEVICE_HEIGHT = document.documentElement.clientHeight;
},
startRandomness: function(type) {
type = Stage.parameters.RANDOM_TYPE;
// stop previous bubbles
var bubbles = Stage.bubbles;
$(bubbles).velocity("stop");
bubbles.forEach(function(bubble) {$(bubble).remove(); });
Stage.bubbles = bubbles = [];
Stage.generateKeyframes(type,bubbles,'#stage');
},
generateKeyframes: function(type,elements,container) {
var i, j, time = 0, color = Utilities.getColor(Stage.parameters.BUBBLE_COLOR);
for (i = 0; i < Stage.parameters.MAX_BUBBLES; i++) {
time = Stage.parameters.TWEET_DUR_TIME;
elements[i] = Stage.makeBubble(type,color,container);
// initial frame - send the bubble to the bottom of the screen
$(elements[i]).velocity({
translateX : Stage.parameters.DEVICE_WIDTH / 2 + 'px',
translateY : Stage.parameters.DEVICE_HEIGHT + 5 + 'px',
opacity : 1, translateZ : 0}, {duration : 10,delay : 0,loop : false});
// random frames
for (j = 0; j < Stage.parameters.NUMBER_OF_FRAMES; j++) {
time = Stage.generateRandomFrame(elements[i], time);
};
//final frame - make the bubbl explode
$(elements[i]).velocity({opacity : 0,translateZ : 0,scale : 4},
{duration : 200,loop : false,complete : Stage.startRandomness});
//bind to click events
//$(".bubble").one("click", MC.playSelectedSong);
};
},
makeBubble: function(type,color,container) {
var newMediaInfo = document.createElement('div');
newMediaInfo.style.color = color;
$(newMediaInfo).addClass("bubble");
var newMediaInfoText = document.createElement('span');
if (type === "search") {$(newMediaInfoText).text(Utilities.getRandomSongKeySearch())}
else {$(newMediaInfoText).text(Utilities.getRandomSongKey())};
$(newMediaInfo).append(newMediaInfoText);
$(newMediaInfo).textfill({minFontPixels : 0,maxFontPixels : 0});
$(container).append(newMediaInfo);
if (Stage.parameters.B_TEXT_SIZE > 0) {
$(newMediaInfo).css('font-size',Stage.parameters.B_TEXT_SIZE);
};
$(newMediaInfo).one("click", MC.playSelectedSong);
return newMediaInfo;
},
generateRandomFrame : function(element,time) {
$(element).velocity({
translateX : Utilities.getBubbleX(this.parameters.DEVICE_WIDTH) + 'px',
translateY : Utilities.getBubbleY(this.parameters.DEVICE_HEIGHT) + 'px',
translateZ : 0
}, { duration : time, delay : 2500, easing : Utilities.getRandomEasing(),loop : false });
return time += Stage.parameters.TWEET_DUR_TIME;
},
setTheme : function (event, theme) {
var themeId = "", cssId="", fullPath="";
if (event != null) {
event.preventDefault(); themeId = theme = event.target.id;
} else { themeId = theme };
if ( (themeId.indexOf("http://") >= 0 || themeId.indexOf("file:///") >= 0) && themeId.indexOf(".css") >= 0 ) {
cssId = "externalThemeCss"; fullPath = theme;}
else {
//cssId = theme + "ThemeCss"; fullPath = "./styles/"+themeId+"_theme.css";};
cssId = themeId;};
$('html').removeClass('zen waterfall');
console.log('Please wait, loading theme...');
if (cssId === "externalThemeCss") { //load external file
$('head').append('<link href="'+ fullPath+'" rel="stylesheet" id="' +cssId +'" />');
} else { $('html').addClass(cssId);};
console.log('Theme loaded !');
if (Stage.parameters.THEME !== theme) {
Stage.parameters.THEME = themeId;Stage.saveParameters();};
return;
},
saveParameters : function () {
localStorage.setItem('parameters', JSON.stringify(Stage.parameters));
return;
},
applyColor : function(color) {
if (color === 'default') {
delete Stage.parameters.BUBBLE_COLOR;
} else {
Stage.parameters.BUBBLE_COLOR = color;
};
Stage.saveParameters();
return;
},
adjustFontSize : function(newSize) {
if (newSize > 0) {
$('.bubble').css('font-size', newSize);
Stage.parameters.B_TEXT_SIZE = newSize;
} else {
$('.bubble').css('font-size', '');
Stage.parameters.B_TEXT_SIZE =0;
};
Stage.saveParameters();
},
initSettingsModal : function() {
$('.settings').on("click",Stage.setTheme);
// Settings modal - number of bubbles //
$('#nmbrBbls').text(Stage.parameters.MAX_BUBBLES);
$('#plusBblsBtn').on('click', function(event) { event.preventDefault();
if (Stage.parameters.MAX_BUBBLES < 30) {
Stage.parameters.MAX_BUBBLES++; Stage.saveParameters();};
$('#nmbrBbls').text(Stage.parameters.MAX_BUBBLES); });
$('#minusBblsBtn').on('click', function(event) { event.preventDefault();
if (Stage.parameters.MAX_BUBBLES > 0) {
Stage.parameters.MAX_BUBBLES--; Stage.saveParameters();};
$('#nmbrBbls').text(Stage.parameters.MAX_BUBBLES); });
// ------------------------------------//
//Settings modal - adjust font size
$('#fntBbls').text(Stage.parameters.B_TEXT_SIZE);
$('#plusFntBtn').on('click', function(event) { event.preventDefault();
Stage.adjustFontSize(++Stage.parameters.B_TEXT_SIZE)
$('#fntBbls').text(Stage.parameters.B_TEXT_SIZE); });
$('#minusFntBtn').on('click', function(event) { event.preventDefault();
Stage.adjustFontSize(--Stage.parameters.B_TEXT_SIZE)
$('#fntBbls').text(Stage.parameters.B_TEXT_SIZE); });
$('#loadThemeBtn').on('click',function(event) { event.preventDefault();
var themeAddr = $('#loadThemeAddr').text() || '';
if (themeAddr != '') {
Stage.setTheme(null,themeAddr);
};
});
// ------------------------------------//
//color buttons
$('#dfltClrBtn').on('click', function(event) {event.preventDefault(); Stage.applyColor('default');});
$('#crntClrBtn').on('click', function(event) {event.preventDefault();
var crnt = $('.bubble:first').css('color') || "";
if (crnt !== "") {Stage.applyColor(crnt);} });
// ------------------------------------//
},
search : function(q) {
if (q === "") {Stage.startRandomness(Stage.parameters.RANDOM_TYPE = 'random'); return;};
Stage.parameters.searchResult = new Array();
for (i in localStorage) {if (i !== "hello" && i !== "parameters" && i.toLowerCase().indexOf(q) >=0) {
var strSong = localStorage.key(i).toString();
var element = '{ "' + i + '" : ' + localStorage[i] + ',"name":' +i+' }' ;
Stage.parameters.searchResult.push(element );
}
};
//NC.searchSuggestions(q);
if (Stage.parameters.searchResult.length == 0) {return;}
//Stage.parameters.searchResult = searchResult;
Stage.parameters.RANDOM_TYPE = 'search';
Stage.startRandomness('search');
return;
}
};
/* utility methods */
var Utilities = {
getColor: function (color) {
if (color == undefined) { return Utilities.getRandomColor();}
return color;
},
getRandomColor: function () {
return 'rgb(' + parseInt(Math.random() * 255, 10) + ','
+ parseInt(Math.random() * 255, 10) + ','
+ parseInt(Math.random() * 255, 10) + ')'
},
getRandomEasing :function () {
var keys = [ 'bouncePast', 'easeInOutBack', 'swingFromTo' ]
return keys[parseInt(Math.random() * keys.length, 10)];
},
getBubbleX :function (device_width) {
return Math.floor(Math.random() * device_width - 30 );
// return Math.floor(Math.random() * (DEVICE_WIDTH - 100 + 1)) + 100;
},
getBubbleY : function (device_height) {
//return Math.random() * DEVICE_HEIGHT-150;
return Math.floor(Math.random() * (device_height - 60) ) - 120;
},
getRandomSongKey : function() {
var max = localStorage.length;
if (max <= 2) {return 'there are no songs';}
var i = Math.floor(Math.random() * max);
var songKey = localStorage.key(i);
if (songKey === 'hello' || songKey === 'parameters') {
return Utilities.getRandomSongKey();
} else {return songKey};
},
getRandomSongKeySearch : function() {
var searchResult = Stage.parameters.searchResult;
var max = searchResult.length;
var i = Math.floor(Math.random() * max);
//return searchResult[i];
var songKey = JSON.parse( searchResult[i] );
return songKey.name;
if (songKey === 'hello' || songKey === 'parameters') {
return Utilities.getRandomSongKey();
} else {return songKey};
}
};
/* Media Controller */
var MC = {
keyActions : [],
iPadUseNativeControls: true,
iPhoneUseNativeControls: true,
AndroidUseNativeControls: true,
enableAutosize: false,
features: ['playpause','tracks'],
init :function () {
/*$('video,audio').mediaelementplayer({
success : function(mediaElement, domObject) {
mediaElement.addEventListener('ended', function(e) {
MC.playRandomSong(e.target);
}, false);
},
keyActions : MC.keyActions,
iPadUseNativeControls: MC.iPadUseNativeControls,
iPhoneUseNativeControls: MC.iPhoneUseNativeControls,
AndroidUseNativeControls: MC.AndroidUseNativeControls,
enableAutosize: MC.enableAutosize,
features: MC.features
});*/
new MediaElement('mejs', {
success: function (mediaElement, domObject) {
// add event listener
mediaElement.addEventListener('ended', function(e) {
MC.playRandomSong(e.target);
}, false);
//mediaElement.play();
},
// fires when a problem is detected
error: function () {
},
keyActions : MC.keyActions,
iPadUseNativeControls: MC.iPadUseNativeControls,
iPhoneUseNativeControls: MC.iPhoneUseNativeControls,
AndroidUseNativeControls: MC.AndroidUseNativeControls,
enableAutosize: MC.enableAutosize,
features: MC.features
});
},
playSelectedSong : function (event) {
var key = $(this).text();
var audio_src = localStorage[key];
MC.retrievePathAndPlay(key,audio_src);
//playSong('undefined',audio_src);
//playSongNative(audio_src);
/* only for installed apps
Player.stop();
$('#media-name').text(key);
$('#media-path').text(audio_src);
$('#player-play').click(function() {
Player.playPause(audio_src);
});
$('#player-stop').click(Player.stop);
$('#time-slider').on('slidestop', function(event) {
Player.seekPosition(event.target.value);
});
//Player.initMedia(audio_src);
Player.playPause(audio_src);
*/
if (event) { event.preventDefault();};
return;
},
playSong : function (currentPlayer, source) {
if (currentPlayer === 'undefined') {
currentPlayer = $('audio#mejs:first')[0];
};
currentPlayer.pause(); $('#pause').click();
currentPlayer.setSrc(source);
currentPlayer.play(); $('#play').click();
},
playRandomSong : function (currentPlayer) {
var key = '';
if (Stage.parameters.RANDOM_TYPE == 'search') {key = Utilities.getRandomSongKeySearch();}
else {key = Utilities.getRandomSongKey();};
//var key = Utilities.getRandomSongKey();
var audio_src = localStorage[key];
MC.retrievePathAndPlay(key,audio_src);
//playSong(currentPlayer,audio_src);
/*$('#songTitle').text(key);*/
},
retrievePathAndPlay : function (key,infoStr) {
$('#songTitle').text(key);
var info = $.parseJSON(infoStr);
var provider = info.provider, fileId = info.id;
if (provider === 'local') {
MC.playSong('undefined',fileId);
} else {NC.getNetworkLink(provider,fileId);}
return;
}
};
/* Network Controller */
var NC = {
init : function() {
// Initate the library
hello.init({
google : '550306267493-5jcdcdg55ffe9hlkt5gruk8mv5mb8ppd.apps.googleusercontent.com',
windows : '0000000040136FF4', dropbox : 'fdov2qv0majt9nk', soundcloud : '46d8abdf4419023d86776f6c735f02b4',
'4shared' : '8e319df9f196364b706e34fe10620354',spotify : '6ff834e4665f4703ba88f0b0ce12ec65'
}, { redirect_uri : '../redirect.html'});
/*hello.init({
dropbox : 'fdov2qv0majt9nk'
}, { redirect_uri : 'https://www.dropbox.com/1/oauth2/redirect_receiver'});*/
//NC.autoLogin('google');
},
login : function(provider) {
var provider = this.id;
switch (provider) {
case 'dropbox': hello('dropbox').login( NC.retrieveList); return;
case 'gdrive': hello('google').login( NC.retrieveList); return;
case 'onedrive': hello('windows').login( NC.retrieveList); return;
case 'soundcloud': hello('soundcloud').login( NC.retrieveList);return;
case '4shared': hello('4shared').login( NC.retrieveList); return;
default:return;
}
},
autoLogin : function(provider) {
hello(provider).login({force:false}).then(NC.retrieveList);
},
retrieveList : function(r) {
var callback;
switch (r.network) {
case 'dropbox': hello(r.network).api('audio').on('complete', NC.listItemsDropbox); return;
case 'google': hello(r.network).api('audio').on('complete', NC.listItemsGdrive); return;
case 'windows': hello(r.network).api('audio').on('complete', NC.listItemsOnedrive); return;
case 'soundcloud': hello(r.network).api('audio').on('complete', NC.listItemsSoundcloud); return;
case '4shared': hello(r.network).api('audio').on('complete', NC.listItems4shared); return;
default: return;
}
},
listItemsDropbox : function (files) {
if (files.error) {return; };
for ( var i in files) {
if (files[i].is_dir === true) {
hello('dropbox').api('metadata/dropbox/' + files[i].path).on('complete', NC.listItemsDropbox);
} else {
if ( files[i].mime_type.indexOf('audio')!= -1 && files[i].size.indexOf('MB') != -1) {
var name = files[i].path.split("/").pop().replace(/\_/g,' ');
var src = '{"provider":"dropbox", "id":"' + files[i].path +'"}';
localStorage.setItem(name, src);
}
}
};
},
listItemsGdrive : function (items) {
for ( var i in items.items) {
var src = '{"provider":"google", "id":"' + items.items[i].id +'"}';
localStorage.setItem(items.items[i].title.replace(/\_/g,' '), src);
};
},
listItemsOnedrive :function (response) {
for (item = 0; item < response.data.length; item++) {
if (response.data[item].type === 'folder') {
hello('windows').api(response.data[item].id + "/files?filter=audio,folders").on('complete', NC.listItemsOnedrive);
} else {
var src = '{"provider":"windows", "id":"' + response.data[item].id +'"}';
localStorage.setItem(response.data[item].name.replace(/\_/g,' '),src /*response.data[item].source*/);
}
};
},
listItemsSoundcloud :function (response) {
for (item = 0; item < response.data.length; item++) {
var tracks = response.data[item].tracks;
for(track =0; track < tracks.length; track++) {
var src = '{"provider":"soundcloud", "id":"' + tracks[track].id +'"}';
localStorage.setItem(tracks[track].title.replace(/\_/g,' '),src );
}
};
},
listItems4shared :function (response) {
for (item = 0; item < response.files.length; item++) {
var src = '{"provider":"4shared", "id":"' + response.files[item].id +'"}';
localStorage.setItem(response.files[item].name.replace(/\_/g,' '),src );
};
},
getNetworkLink : function(provider, fileId) {
var session = hello.utils.store(provider) || {};
var at = session.access_token || 'undefined';
switch (provider) {
case 'dropbox':
hello('dropbox').login({force:false,display:'none'}).
then(function() {
hello('dropbox').api('media/dropbox'+fileId).
then( function(data) {
MC.playSong('undefined',data.url + "?access_token=" + at); })
}); break;
case 'google':
hello('google').login({force:false,display:'none'}).
then(function() {
hello('google').api('drive/v2/files/'+ fileId + '?fields=downloadUrl').
then( function(data) {
MC.playSong('undefined',data.downloadUrl + "&access_token=" + at); })
}); break;
case 'windows':
hello('windows').login({force:false,display:'none'}).
then(function() {
hello('windows').api(fileId + '/content?download=true&suppress_redirects=true').
then( function(data) {
MC.playSong('undefined',data.location + "&access_token=" + at); })
}); break;
case 'soundcloud':
hello('soundcloud').login({force:false}).
then(function() {
MC.playSong('undefined','https://api.soundcloud.com/tracks/' + fileId + '/stream?oauth_token=' + at);}
); break;
case '4shared':
hello('4shared').login({force:false,display:'none'}).
then(function() {
hello('4shared').api('files/' + fileId + '.jsonp').
then( function(data) {
MC.playSong('undefined',data.downloadUrl ); })
}); break;
default:return;
};
},
searchSuggestions : function(searchStr) {
if (searchStr === "") {return;};
//if (!Stage.parameters.suggestions) {return;};
var session = hello.utils.store('soundcloud') || {};
var at = session.access_token || 'undefined';
hello('soundcloud').login({force:false}).
then(function() {
hello('soundcloud').api('tracks/?q=' + searchStr + '&sharing=public&limit=2&oauth_token=' + at).
then (function(response) {
for (item = 0; item < response.data.length; item++) {
//var tracks = response.data[item].tracks;
//for(track =0; track < tracks.length; track++) {
var src = '{"provider":"soundcloud", "id":"' + response.data[item].id +'"}';
Stage.parameters.searchResult.push(response.data[item].title.replace(/\_/g,' '),src );
//}
};
})
});
}
}
/* runtime init */
$(document).ready(function() {
Stage.init();
MC.init();
NC.init();
});
window.onresize = function(event) {
Stage.refresh();
};
|
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var jwt = require('jsonwebtoken');
var morgan = require('morgan');
var crypto = require('crypto');
var validators = require('mongoose-validators');
var connectDB = require('../config/config.js');
// app.set('Secret', 'amit');
userInfoSchema = mongoose.Schema({
fname: {
type: String,
minlength: 4,
maxlength: 128,
required: true,
},
lname: {
type: String,
minlength: 4,
maxlength: 128,
required: true,
},
mobile: {
type: Number,
minlength: 10,
maxlength: 10,
// unique: true,
required: true,
},
email: {
type: String,
minlength: 4,
maxlength: 30,
required: true,
unique: true,
validate: validators.isEmail()
},
password: {
type: String,
minlength: 8,
maxlength: 100,
required: true
}
});
userInfoSchema.statics.encrypt = function(text) {
var cipher = crypto.createCipher(connectDB.algorithm, connectDB.password)
var crypted = cipher.update(text, 'utf8', 'hex')
crypted += cipher.final('hex');
return crypted;
}
userInfoSchema.statics.decrypt = function(text) {
var decipher = crypto.createDecipher(connectDB.algorithm, connectDB.password)
var dec = decipher.update(text, 'hex', 'utf8')
dec += decipher.final('utf8');
return dec;
}
userInfoSchema.statics.saveUser = function(data, cb) {
// console.log("saveUserdata"+data.email);
var ref = this;
this.findOne({
email: data.email
}, function(error, user) {
if (user) {
console.log("user"+user);
cb(null,false);
} else {
console.log("data"+ data);
var userObj = new ref(data);
console.log("userObj"+ userObj);
userObj.save(cb);
}
});
}
userInfoSchema.statics.ValidateUser = function(data, cb) {
var token;
userInfo.findOne({ email: data.email },cb);
};
userInfoSchema.statics.getRegisterUserProfile = function(userid, cb) {
this.findById(userid,cb);
};
var userInfo = mongoose.model('userInfo', userInfoSchema);
module.exports = userInfo;
|
"use strict";
// https://stackoverflow.com/questions/3492322/javascript-createelementns-and-svg
export class Clockface {
elemClockface;
get time() {
return {
clocks: Number(this.elemClockface.getAttribute("clocks")),
minutes: Number(this.elemClockface.getAttribute("minutes")),
};
}
/**
* @param {{ clocks: number; minutes: number; }} time
*/
set time(time) {
const elemLineArray = this.elemClockface.getElementsByTagName("line");
{
const elemClockArrow = elemLineArray["clock"];
const angle = (30 * time.clocks + 0.5 * time.minutes) * (Math.PI / 180);
const clockArrowLengthPercent = 25;
elemClockArrow.setAttributeNS(
null,
"x2",
50 + clockArrowLengthPercent * Math.sin(angle) + "%"
);
elemClockArrow.setAttributeNS(
null,
"y2",
50 - clockArrowLengthPercent * Math.cos(angle) + "%"
);
}
{
const elemMinuteArrow = elemLineArray["minute"];
const angle = 6 * time.minutes * (Math.PI / 180);
const minuteArrowLengthPercent = 35;
elemMinuteArrow.setAttributeNS(
null,
"x2",
50 + minuteArrowLengthPercent * Math.sin(angle) + "%"
);
elemMinuteArrow.setAttributeNS(
null,
"y2",
50 - minuteArrowLengthPercent * Math.cos(angle) + "%"
);
}
this.elemClockface.setAttribute("clocks", time.clocks);
this.elemClockface.setAttribute("minutes", time.minutes);
}
constructor(params) {
if (params instanceof SVGElement) {
this.elemClockface = params;
return;
}
const radiusPercent = 45;
const clockMarkerWidtPercent = 8;
var xmlns = "http://www.w3.org/2000/svg";
var boxWidth = "5em";
var boxHeight = "5em";
var svgElem = document.createElementNS(xmlns, "svg");
svgElem.setAttributeNS(null, "width", boxWidth);
svgElem.setAttributeNS(null, "height", boxHeight);
svgElem.style.display = "block";
const svgBorder = document.createElementNS(xmlns, "circle");
svgBorder.setAttributeNS(null, "cx", "50%");
svgBorder.setAttributeNS(null, "cy", "50%");
svgBorder.setAttributeNS(null, "r", radiusPercent + "%");
//svgBorder.setAttributeNS(null, "stroke", params.color);
svgBorder.setAttributeNS(null, "fill", "transparent");
svgBorder.setAttributeNS(null, "stroke-width", "2");
svgElem.appendChild(svgBorder);
const svgCenter = document.createElementNS(xmlns, "circle");
svgCenter.setAttributeNS(null, "cx", "50%");
svgCenter.setAttributeNS(null, "cy", "50%");
svgCenter.setAttributeNS(null, "r", "5%");
//svgCenter.setAttributeNS(null, "fill", params.color);
svgElem.appendChild(svgCenter);
for (let i = 0; i < 12; i++) {
const angle = 30 * i * (Math.PI / 180);
const svgLine = document.createElementNS(xmlns, "line");
svgLine.setAttributeNS(
null,
"x1",
50 + (radiusPercent - clockMarkerWidtPercent) * Math.sin(angle) + "%"
);
svgLine.setAttributeNS(
null,
"y1",
50 -
(radiusPercent - clockMarkerWidtPercent) +
(radiusPercent - clockMarkerWidtPercent) * (1 - Math.cos(angle)) +
"%"
);
svgLine.setAttributeNS(
null,
"x2",
50 + radiusPercent * Math.sin(angle) + "%"
);
svgLine.setAttributeNS(
null,
"y2",
50 - radiusPercent + radiusPercent * (1 - Math.cos(angle)) + "%"
);
//svgLine.setAttributeNS(null, "stroke", params.color);
svgLine.setAttributeNS(null, "fill", "transparent");
svgLine.setAttributeNS(null, "stroke-width", "2");
svgElem.appendChild(svgLine);
}
// Beg Clock Arrow
if (null != params.clocks) {
//const angle = 30 * params.clocks * (Math.PI / 180);
const angle =
(30 * params.clocks + 0.5 * params.minutes) * (Math.PI / 180);
const clockArrowLengthPercent = 25;
const svgLine = document.createElementNS(xmlns, "line");
svgLine.setAttributeNS(null, "x1", "50%");
svgLine.setAttributeNS(null, "y1", "50%");
/*svgLine.setAttributeNS(
null,
"x2",
50 + clockArrowLengthPercent * Math.sin(angle) + "%"
);
svgLine.setAttributeNS(
null,
"y2",
50 - clockArrowLengthPercent * Math.cos(angle) + "%"
);*/
//svgLine.setAttributeNS(null, "stroke", params.color);
svgLine.setAttributeNS(null, "fill", "transparent");
svgLine.setAttributeNS(null, "stroke-width", "4");
svgLine.setAttributeNS(null, "stroke-linecap", "round");
svgLine.setAttributeNS(null, "id", "clock");
svgElem.setAttributeNS(null, "clocks", params.clocks);
svgElem.appendChild(svgLine);
}
// End Clock Arrow
// Beg Minute Arrow
if (null != params.minutes) {
const angle = 6 * params.minutes * (Math.PI / 180);
const minuteArrowLengthPercent = 35;
const svgLine = document.createElementNS(xmlns, "line");
//svgLine.id = "minuteArrow";
svgLine.setAttributeNS(null, "x1", "50%");
svgLine.setAttributeNS(null, "y1", "50%");
/*svgLine.setAttributeNS(
null,
"x2",
50 + minuteArrowLengthPercent * Math.sin(angle) + "%"
);
svgLine.setAttributeNS(
null,
"y2",
50 - minuteArrowLengthPercent * Math.cos(angle) + "%"
);*/
//svgLine.setAttributeNS(null, "stroke", params.color);
svgLine.setAttributeNS(null, "fill", "transparent");
svgLine.setAttributeNS(null, "stroke-width", "2");
svgLine.setAttributeNS(null, "stroke-linecap", "round");
svgLine.setAttributeNS(null, "id", "minute");
svgElem.setAttributeNS(null, "minutes", params.minutes);
svgElem.appendChild(svgLine);
}
// End Minute Arrow
this.elemClockface = svgElem.cloneNode(true);
this.time = params;
}
}
|
import React, {Component} from 'react';
import {
View,
Text,
Image,
StyleSheet,
} from 'react-native';
import {
Colors,
} from 'react-native/Libraries/NewAppScreen';
class Icone extends Component{
constructor(props){
super(props);
}
render(){
//this.props.escolha
//this.props.jogador
if(this.props.escolha == "pedra"){
return(
<View style={styles.palco}>
<Text>{this.props.jogador}</Text>
<Image source={ require('../../imgs/pedra.png')}></Image>
</View>
);
}else if(this.props.escolha == "papel"){
return(
<View style={styles.palco}>
<Text>{this.props.jogador}</Text>
<Image source={ require('../../imgs/papel.png')}></Image>
</View>
);
}else if(this.props.escolha == "tesoura"){
return(
<View style={styles.palco}>
<Text>{this.props.jogador}</Text>
<Image source={ require('../../imgs/tesoura.png')}></Image>
</View>
);
}else{
return false;
}
}
}
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',
},
btnEscolha: {
width:90,
},
painelAcoes: {
flexDirection: 'row',
justifyContent: 'space-between',
marginTop: 10,
},
palco:{
alignItems: 'center',
marginTop: 10,
},
txtResultado:{
fontSize: 25,
fontWeight: 'bold',
color: 'red',
height:60,
},
txtJogador:{
textAlign:"center",
fontSize:35,
color: "green"
},
});
export default Icone; |
$(function(){
a = getCookie('tixian');
value = JSON.parse(a);
var tixian=parseFloat(value.money).toFixed(2);
$(".card1 p").html("ๆฏๅฆ็ณ่ฏทๆ็ฐ"+tixian+"ๅ
?");
$(".card1 .yes").click(function(){
a = getCookie('tixian');
value = JSON.parse(a);
$.ajax({
url: "../vip/customer/withdraw/apply",
type: 'GET',
dataType: 'json',
data: {user_id:value.user_id,money:value.money,bank_card:value.bank_card},
success:function(result) {
webToast(result.message, "middle", 1000);
},
error:function(){
webToast("ๆจ็็ฝ็ปไธๅคช้็
ๅฆ~");
}
});
$(".card1").css("display","none");
$(".card2").css("display","block");
})
$(".card1 .no,.card2 .yes").click(function(){
window.location.href='money.html';
})
})
function getCookie(name)
{
var arr=document.cookie.split('; ');
var i=0;
for(i=0;i<arr.length;i++)
{
//arr2->['username', 'abc']
var arr2=arr[i].split('=');
if(arr2[0]==name)
{
var getC = decodeURIComponent(arr2[1]);
return getC;
}
}
return '';
} |
const ThresholdProfile = require('../models/ThresholdProfile')
module.exports.getAll = () => {
return new Promise((resolve, reject) => {
ThresholdProfile.find({}, (err, thresholdProfiles) => {
if (err) {
reject(err)
} else {
resolve(thresholdProfiles)
}
})
})
} |
const db = require("../db");
const QueryBuilder = require("../querybuilder");
class Product {
create(product) {
return new Promise(async (resolve, reject) => {
try {
let query = "INSERT INTO product(name,description,price,discounted_price,"
+ "display) "
+ "VALUES(" + db.escape(product.name) + ","
+ db.escape(product.description) + ","
+ db.escape(product.price) + ","
+ db.escape(product.discounted_price) + ","
+ db.escape(product.display) + ")";
let insertResult = await db.query(query);
let newProduct = await db.query("SELECT * "
+ "FROM product "
+ "WHERE product_id=" + db.escape(insertResult.insertId));
resolve(newProduct[0]);
} catch (e) {
e.status = 500;
e.errCode = "PRD_01";
reject(e);
}
});
}
update(product) {
return new Promise(async (resolve, reject) => {
try {
let getOneResult = await db.query("SELECT * "
+ "FROM product "
+ "WHERE product_id=" + db.escape(product.product_id));
if (getOneResult.length === 0) {
let notFoundErr = new Error("Product Not Found");
notFoundErr.status = 404;
notFoundErr.errCode = "PRD_02";
reject(notFoundErr);
return;
}
let query = "UPDATE product SET "
+ "name=" + db.escape(product.name) + ","
+ "description=" + db.escape(product.description) + ","
+ "price=" + db.escape(product.price) + ","
+ "discounted_price=" + db.escape(product.discounted_price) + ","
+ "display=" + db.escape(product.display)
+ " WHERE product_id=" + db.escape(product.product_id)
;
let updateResult = await db.query(query);
let newProduct = await db.query("SELECT * "
+ "FROM product "
+ "WHERE product_id=" + db.escape(product.product_id));
resolve(newProduct[0]);
} catch (e) {
e.status = 500;
e.errCode = "PRD_03";
reject(e);
}
});
}
list(fields) {
return new Promise(async (resolve, reject) => {
try {
let queryBuilder = new QueryBuilder();
queryBuilder.select("p.*,IF(LENGTH(p.description) <= "
+ fields.description_length + ","
+ "p.description,"
+ "CONCAT(LEFT(p.description, " + fields.description_length + "),"
+ "'...')) AS description")
.from("product p")
;
if (fields.category_id || fields.department_id) {
queryBuilder.leftJoin("product_category pc using(product_id)");
if (fields.category_id) {
queryBuilder.where("category_id=" + db.escape(fields.category_id));
}
if (fields.department_id) {
queryBuilder.leftJoin("category c using(category_id)")
.where("c.department_id=" + db.escape(fields.department_id));
;
}
}
if (fields.start && fields.limit) {
queryBuilder.limit(fields.start + "," + fields.limit);
} else if (fields.limit) {
queryBuilder.limit(fields.limit);
}
if (fields.query_string && fields.all_words === "on") {
queryBuilder.where("MATCH(p.name,p.description) AGAINST ("
+ db.escape(fields.query_string) + " IN BOOLEAN MODE)");
queryBuilder.order("MATCH(p.name,p.description) AGAINST ("
+ db.escape(fields.query_string) + " IN BOOLEAN MODE) DESC");
} else if (fields.query_string) {
queryBuilder.where("MATCH(p.name,p.description) AGAINST ("
+ db.escape(fields.query_string) + ")");
queryBuilder.order("MATCH(p.name,p.description) AGAINST ("
+ db.escape(fields.query_string) + ") DESC");
}
let results = await db.query(queryBuilder.toString());
queryBuilder.columns = [];
queryBuilder.select("count(*) as countAll");
let countResults = await db.query(queryBuilder.toString());
resolve({
count: countResults[0].countAll,
rows: results
});
} catch (e) {
e.status = 500;
e.errCode = "PRD_04";
reject(e);
}
});
}
delete(product_id) {
return new Promise(async (resolve, reject) => {
try {
let getOneResult = await db.query("SELECT * "
+ "FROM product "
+ "WHERE product_id=" + db.escape(product_id));
if (getOneResult.length === 0) {
let notFoundErr = new Error("Product Not Found");
notFoundErr.status = 404;
notFoundErr.errCode = "PRD_05";
reject(notFoundErr);
return;
}
await db.query("call catalog_delete_product(" + db.escape(product_id) + ")");
resolve(getOneResult[0]);
} catch (e) {
e.status = 500;
e.errCode = "PRD_06";
reject(e);
}
});
}
uploadImage(product_id, image) {
return new Promise(async (resolve, reject) => {
try {
await db.query("UPDATE product SET "
+ "image=" + db.escape(image)
+ "WHERE product_id=" + db.escape(product_id));
let getOne = await db.query("SELECT * "
+ "FROM product "
+ "WHERE product_id=" + db.escape(product_id));
resolve(getOne);
} catch (e) {
e.status = 500;
e.errCode = "PRD_07";
reject(e);
}
});
}
uploadImage2(product_id, image2) {
return new Promise(async (resolve, reject) => {
try {
await db.query("UPDATE product SET "
+ "image_2=" + db.escape(image2)
+ "WHERE product_id=" + db.escape(product_id));
let getOne = await db.query("SELECT * "
+ "FROM product "
+ "WHERE product_id=" + db.escape(product_id));
resolve(getOne);
} catch (e) {
e.status = 500;
e.errCode = "PRD_08";
reject(e);
}
});
}
uploadThumbnail(product_id, thumbnail, handler) {
return new Promise(async (resolve, reject) => {
try {
await db.query("UPDATE product SET "
+ "thumbnail=" + db.escape(thumbnail)
+ "WHERE product_id=" + db.escape(product_id));
let getOne = await db.query("SELECT * "
+ "FROM product "
+ "WHERE product_id=" + db.escape(product_id));
resolve(getOne);
} catch (e) {
e.status = 500;
e.errCode = "PRD_09";
reject(e);
}
});
}
getOne(product_id) {
return new Promise(async (resolve, reject) => {
try {
let results = await db.query("SELECT * "
+ "FROM product "
+ "WHERE product_id=" + db.escape(product_id));
if (results.length === 0) {
let notFoundErr = new Error("Product Not Found");
notFoundErr.status = 404;
notFoundErr.errCode = "PRD_10";
reject(notFoundErr);
return;
}
let result = results[0];
result.categories = await db.query("SELECT c.* "
+ "FROM product_category pc "
+ "INNER JOIN category c using(category_id) "
+ "WHERE pc.product_id=" + db.escape(product_id));
result.attributes = await db.query("SELECT pa.*,a.name,"
+ "av.value "
+ "FROM product_attribute pa "
+ "INNER JOIN attribute_value av USING(attribute_value_id) "
+ "INNER JOIN attribute a USING(attribute_id) "
+ "WHERE pa.product_id=" + db.escape(product_id));
resolve(result);
} catch (e) {
e.status = 500;
e.errCode = "PRD_11";
reject(e);
}
});
}
locations(product_id) {
return new Promise(async (resolve, reject) => {
try {
let getOne = await db.query("SELECT * "
+ "FROM product "
+ "WHERE product_id=" + db.escape(product_id));
if (getOne.length === 0) {
let notFoundErr = new Error("Product Not Found");
notFoundErr.status = 404;
notFoundErr.errCode = "PRD_12";
reject(notFoundErr);
return;
}
let locations = await db.query("SELECT c.category_id, "
+ "c.name AS category_name, c.department_id,"
+ "(SELECT name "
+ "FROM department "
+ "WHERE department_id = c.department_id) AS department_name "
+ "FROM category c "
+ "WHERE c.category_id IN "
+ "(SELECT category_id "
+ "FROM product_category "
+ "WHERE product_id = " + db.escape(product_id) + ")");
resolve(locations);
} catch (e) {
e.status = 500;
e.errCode = "PRD_13";
}
});
}
reviews(product_id) {
return new Promise(async (resolve, reject) => {
try {
let getOne = await db.query("SELECT * "
+ "FROM product "
+ "WHERE product_id=" + db.escape(product_id));
if (getOne.length === 0) {
let notFoundErr = new Error("Product Not Found");
notFoundErr.status = 404;
notFoundErr.errCode = "PRD_14";
reject(notFoundErr);
return;
}
let reviews = db.query("SELECT c.name, r.review, r.rating, r.created_on "
+ "FROM review r "
+ "INNER JOIN customer c "
+ "ON c.customer_id = r.customer_id "
+ "WHERE r.product_id = " + db.escape(product_id)
+ "ORDER BY r.created_on DESC");
resolve(reviews);
} catch (e) {
e.status = 500;
e.errCode = "PRD_15";
reject(e);
}
});
}
saveReview(review) {
return new Promise(async (resolve, reject) => {
try {
let getOne = await db.query("SELECT * "
+ "FROM product "
+ "WHERE product_id=" + db.escape(review.product_id));
if (getOne.length === 0) {
let notFoundErr = new Error("Product Not Found");
notFoundErr.status = 404;
notFoundErr.errCode = "PRD_16";
reject(notFoundErr);
return;
}
let reviewId = 0;
let existingReview = await db.query("SELECT * "
+ "FROM review "
+ "WHERE customer_id=" + db.escape(review.customer_id)
+ " AND product_id=" + db.escape(review.product_id));
if (existingReview.length === 0) {
let insertQuery = "INSERT INTO review(review,rating,customer_id,product_id,created_on) "
+ "VALUES(" + db.escape(review.review) + ","
+ db.escape(review.rating) + "," + db.escape(review.customer_id) + ","
+ db.escape(review.product_id) + ",now())"
;
let insertResult = await db.query(insertQuery);
reviewId = insertResult.insertId;
} else {
reviewId = existingReview[0].review_id;
await db.query("UPDATE review "
+ "SET review=" + db.escape(review.review) + ","
+ "rating=" + db.escape(review.rating)
+ " WHERE review_id=" + db.escape(reviewId));
}
let newReview = await db.query("SELECT * "
+ "FROM review "
+ "WHERE review_id=" + db.escape(reviewId));
resolve(newReview);
} catch (e) {
e.status = 500;
e.errCode = "PRD_17";
reject(e);
}
});
}
}
module.exports = Product; |
var searchYouTube = (options, callback) => {
// console.log('in the function');
$.ajax({
url: 'https://www.googleapis.com/youtube/v3/search',
type: 'GET',
contentType: 'json',
data: {
part: 'id,snippet',
q: options.q,
maxResults: options.max,
key: options.key,
type: 'video',
videoEmbeddable: 'true'
},
success: function(data) {
if(data) {
callback(data.items);
}
},
error: function(err) {
console.log("You got the " + JSON.stringify(err) + " error. Oh no.");
}
});
};
var getVideoDetails = (options, callback) => {
console.log(options.id);
$.ajax({
url: 'https://www.googleapis.com/youtube/v3/videos',
type: 'GET',
contentType: 'json',
data: {
part: 'snippet, statistics',
key: options.key,
id: options.id
},
success: (data) => {
if (data) {
callback(data.items);
}
},
error: (err) => {
console.log("You got the " + JSON.stringify(err) + " error. Oh no.");
}
});
}
window.searchYouTube = searchYouTube;
window.getVideoDetails = getVideoDetails;
|
import Ball from '../js/ball.js';
import Game from './game.js';
let canvas = document.getElementById("mainscreen")
let ctx = canvas.getContext("2d")
const GAME_WIDTH = 800;
const GAME_HEIGHT = 800;
let game = new Game(GAME_WIDTH, GAME_HEIGHT, 10)
game.start();
let lastTime = 0;
function gameLoop(currentTime){
if(!game.over){
let dt = currentTime - lastTime;
ctx.clearRect(0, 0, GAME_WIDTH, GAME_HEIGHT)
game.update(dt);
game.draw(ctx);
document.getElementById("numberOfBalls").oninput = function(){
ctx.clearRect(0, 0, GAME_WIDTH, GAME_HEIGHT)
game.over = true;
game = new Game(GAME_WIDTH, GAME_HEIGHT, this.value)
game.start();
game.over = false;
gameLoop();
document.getElementById("ballcount").innerText = this.value
console.log(game.balls[0].speed)
}
requestAnimationFrame(gameLoop)
}
}
gameLoop();
|
var crypto = require('crypto');
module.exports = function(db) {
var User = function() {};
//
// Locate a user by a user name
//
User.findByUser = function(userName, callback) {
db.collection('users').findOne({userName: userName}, callback);
};
//
// Locate a user by user name and password
//
User.findByUserAndPassword = function(userName, password, callback) {
// Hash password
var sha1 = crypto.createHash('sha1');
sha1.update(password);
// Get digest
var hashedPassword = sha1.digest('hex');
// Locate user
db.collection('users').findOne({userName: userName, password: hashedPassword}, callback);
};
//
// Create a new user with full name and password
//
User.createUser = function(fullName, userName, password, callback) {
// Hash password
var sha1 = crypto.createHash('sha1');
sha1.update(password);
// Get digest
var hashedPassword = sha1.digest('hex');
// Insert user
db.collection('users').insert({fullName: fullName, userName: userName, password: hashedPassword}, callback);
};
return User;
}; |
import React from 'react'
import { createTodo } from '../todoApi'
class AddTodo extends React.Component {
constructor (props) {
super(props)
this.state = {
todoText: ''
}
this.textChange = this.handleChange.bind(this)
this.addTodo = this.createTodo.bind(this)
}
createTodo (event) {
let { todoText } = this.state
if (todoText.length === 0) return
createTodo(todoText)
this.setState({ todoText: '' })
event.preventDefault()
return false
}
handleChange (event) {
this.setState({ todoText: event.target.value })
}
render () {
let { todo } = this.props
return (
<div>
<form onSubmit={this.addTodo}>
<input value={this.state.todoText} onChange={this.textChange} />
<button onClick={this.addTodo}>Add</button>
</form>
<br />
<br />
</div>
)
}
}
export default AddTodo
|
import { connect } from 'react-redux'
import CreateMeshPointForm from 'components/CreateMeshPointForm'
import { createMeshPoint } from 'store/ethereum/meshPoint'
const mapStateToProps = (state, ownProps) => {
return {
meshPoint: state.meshPoint
}
}
const mapDispatchToProps = (dispatch) => {
return {
onCreateFaucetSubmit: (data) => {
event.preventDefault()
dispatch(createMeshPoint(data.name, data.fromAddress))
}
}
}
const CreateMeshPointContainer = connect(
mapStateToProps,
mapDispatchToProps
)(CreateMeshPointForm)
export default CreateMeshPointContainer
|
import React, { useState, useEffect } from 'react';
// import { connect } from 'dva';
import { Upload, Icon, Modal, message } from 'antd';
const PicturesWall = props => {
const { uploadImg, viewModal, showUploadList, listType, form, fieldName, single, onChange, callBack, defaultImg } = props
const [fileList, setFileList] = useState([])
const [previewVisible, setPreviewVisible] = useState(false)
const [previewImage, setPreviewImage] = useState('')
const [imageUrl, setImageUrl] = useState('')
const [uploading, setUploading] = useState(false)
// ่ฎพ็ฝฎ้ป่ฎคๅพๅ
useEffect(() => {
if (defaultImg) {
addPicture()
}
}, [defaultImg])
// ๆทปๅ ๅพ็
function addPicture(data) {
const uid = Math.random() * 10000
const fieldValue = {}
if (single) {
setImageUrl(data ? data.url : defaultImg)
setUploading(false)
if (form && fieldName) fieldValue[fieldName] = data ? data.url : defaultImg
} else {
if (data) {
fileList.push({
uid,
name: data.name,
status: 'done',
url: data.url,
})
} else {
defaultImg.split().forEach(c => {
fileList.push({
uid,
name: c,
status: 'done',
url: c,
})
})
}
setFileList([...fileList])
if (form && fieldName) fieldValue[fieldName] = fileList.map(c => c.url).join()
}
if (form && fieldName) form.setFieldsValue(fieldValue)
}
// ่ชๅฎไนไธไผ ๅพ็ๅฐ OSS
async function handleUpload({ file }) {
if (single) setUploading(true)
try {
const imgData = await uploadImg()
addPicture(imgData)
if (callBack) callBack(single ? imgData.data.url : fileList)
} catch (err) {
setUploading(false)
}
// await dispatch({
// type: 'upload/uploadImg',
// file,
// success(data) {
// addPicture(data)
// if (callBack) callBack(single ? data.url : fileList)
// },
// fail(msg) {
// message.error(msg);
// setUploading(false)
// },
// });
if (!single) setFileList([...fileList])
}
// ๅพ็้ข่ง
function handleImgPreview(file) {
if (!file.url) return
setPreviewVisible(true)
setPreviewImage(file.url)
}
// ๅพ็ไธไผ ้ๅถ
function beforeUpload(file) {
const isJpgOrPngOrGif = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif';
if (!isJpgOrPngOrGif) {
message.error('ๅชๅฏไปฅไธไผ jpgใgifใpng ๆ ผๅผ');
}
const isLt5M = file.size / 1024 / 1024 < 5;
if (!isLt5M) {
message.error('ๅพ็ๅคงๅฐไธๅพ่ถ
่ฟ2MB!');
}
return isJpgOrPngOrGif && isLt5M;
}
function handleChange(e) {
if (onChange) onChange(e)
}
function onRemove(e) {
const removedFileList = fileList.filter(c => c.name !== e.name)
if (form && fieldName && !single) {
const fieldValue = {}
fieldValue[fieldName] = removedFileList.map(c => c.url).join()
form.setFieldsValue(fieldValue)
if (callBack) callBack(removedFileList)
setFileList(removedFileList)
}
}
return (
<div>
<Upload
listType={listType || 'picture-card'}
fileList={fileList}
customRequest={handleUpload}
onPreview={file => handleImgPreview(file)}
beforeUpload={beforeUpload}
showUploadList={showUploadList || true}
onChange={e => handleChange(e)}
onRemove={onRemove}
>
{!single &&
<div>
<Icon type="plus" />
<div className="ant-upload-text">ไธไผ ๅพ็</div>
</div>}
{single &&
(imageUrl !== '' ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : (
<div>
<Icon type={uploading ? 'loading' : 'plus'} />
<div className="ant-upload-text">ไธไผ ๅพ็</div>
</div>
))}
</Upload>
{viewModal &&
<Modal visible={previewVisible}
footer={null}
onCancel={() => setPreviewVisible(false)}>
<img alt="example" style={{ width: '100%' }} src={previewImage} />
</Modal>
}
</div>
)
}
// export default connect()(PicturesWall);
export default PicturesWall;
|
var json =
{
"moto":
[
{"marca":"Zanella",
"modelo":
[
{"nombre":"ZB110"},
{"nombre":"RX150"}
]
},
{"marca":"Honda",
"modelo":
[
{"nombre":"Wava 110 S"},
{"nombre":"CG150 Titan"}
]
},
{"marca":"Motomel",
"modelo":
[
{"nombre":"B110"},
{"nombre":"CX150"}
]
}
]
};
var d = '<tr>'+
'<th>Marca</th>'+
'<th>Modelos</th>'+
'</tr>';
$(function () {
for (var i = 0; i < json.moto.length; i++) {
d+= '<tr>'+ '<td>'+ json.moto[i].marca+'</td>';
d+= '<td>';
for (var j =0; j< json.moto[i].modelo.length;j++)
{
d+= '<p>'+ json.moto[i].modelo[j].nombre+'</p>';
}
d+= '</td>';
d+= '</tr>';
}
$("#tabla").append(d);
}); |
define([
'jquery',
'backbone'
],
function(
$,
Backbone
){
var FlavorModel = Backbone.Model.extend({
defaults: {
kosher: true
},
initialize: function(attributes, options) {
//console.log('flavor', this);
var type = '-' + this.get('type');
var imageId = this.get('id').split(type).join('');
if(!this.get('hasNameplate')) imageId = 'no-nameplate';
var image = 'images/nameplates/' + imageId + '.jpg';
this.set({ image: image });
}
});
return FlavorModel;
});
|
import React, { useState } from "react";
import { useSelector, useDispatch } from "react-redux";
import { fetchCountry } from "./countrySlice";
export default function CountryDisplay() {
const country = useSelector((state) => state.country);
const dispatch = useDispatch();
const [userCountry, setUserCountry] = useState();
return (
<section style={{ margin: "0 auto", width: "40%" }}>
{country.findCountry ? (
<div>
<p>Name: {country.countries[0].name}</p>
<p>Capital: {country.countries[0].capital}</p>
<p>Flag:</p>{" "}
<img style={{ height: "100px" }} src={country.countries[0].flag} />
<p>Region: {country.countries[0].region}</p>
</div>
) : (
<div style={{ height: "200px" }}>Country does not exist.</div>
)}
<form
onSubmit={(e) => {
e.preventDefault();
dispatch(fetchCountry(userCountry));
}}
>
<input onChange={(e) => setUserCountry(e.target.value)} />
<button>Search Country and Save Payload to Store</button>
</form>
</section>
);
}
|
//ๅ
จๅฑๅ้
//็ๅฐๅ
ๆต
var comHttp = "://192.168.1.201:";
var http = "http"+comHttp+"8001";//ๅๅฐ
var httpBefore = "http"+comHttp+"8002";//ๅ็ซฏ
var ws = "ws"+comHttp+"8001";
//ๅค็ฝ
// var comHttp = "://121.12.148.53:";
// var http = "http"+comHttp+"8001";//ๅๅฐ
// var httpBefore = "http"+comHttp+"8002";//ๅ็ซฏ
// var ws = "ws"+comHttp+"8001";
//ๅ
็ฝ
// var comHttp = "://172.50.70.163";
// var http = "http"+comHttp+":7001";//ๅๅฐ
// var httpBefore = "http"+comHttp;//ๅ็ซฏ
// var ws = "ws"+comHttp+":7001";
//ๆญฆ้ขๆผ็คบ
//var comHttp = "//wugang.nat123.net:";
//var http = "http"+comHttp+"50077";//ๅๅฐ
//var httpBefore = "http"+comHttp+"50088";//ๅ็ซฏ
//var ws = "ws"+comHttp+"50077";
var idStr = localStorage.getItem("idStr");
|
// PALINDROME EST UN MOT QUI LORSQUE L'ON INVERSE CHAQUE LETTRE RESTE LE MEME MOT
// EXEMPLE : aba, kayak
function isPalindrome(word) {
if(word.split('').reverse().join('') == word){
return true +' '+ word + ' est un palindrome';
} else
return false +' '+ word + ' n\est pas un palindrome';
}
// split permet de dรฉcomposer le chaine de caractรจre sout forme s'un tableau
// reverse inverse toute les donnรฉes du tableau
// join modifie la sรฉparation des valeurs du tableau
const dataTest = ['aba', 'aka', 'refjlsfk', 'kayak', 'Kayak', 'fooaoaoaf']
const test = (testVal, testFn) => {
console.log(testFn(testVal))
};
dataTest.map(testVal => test(testVal, isPalindrome)) |
import React from 'react';
import {Scene, Router} from 'react-native-router-flux';
import Albums from './components/Albums';
import Album from './components/Album';
import AlbumDetails from "./components/AlbumDetails";
const RouterComponent = () => {
return (
<Router sceneStyle={{paddingTop: 1}}>
<Scene key="MyAlbum" initial>
<Scene key="Albums" component={Albums} title="My Albums"/>
<Scene key="Album" component={Album} title="Album"/>
<Scene key="AlbumDetails" component={AlbumDetails} title="Album"/>
</Scene>
</Router>
);
};
export default RouterComponent;
|
const _BOARD = [
['.', '9', '.', '.', '4', '2', '1', '3', '6'],
['.', '.', '.', '9', '6', '.', '4', '8', '5'],
['.', '.', '.', '5', '8', '1', '.', '.', '.'],
['.', '.', '4', '.', '.', '.', '.', '.', '.'],
['5', '1', '7', '2', '.', '.', '9', '.', '.'],
['6', '.', '2', '.', '.', '.', '3', '7', '.'],
['1', '.', '.', '8', '.', '4', '.', '2', '.'],
['7', '.', '6', '.', '.', '.', '8', '1', '.'],
['3', '.', '.', '.', '9', '.', '.', '.', '.'],
]
const _QUADS = [
[1,1,1, 2,2,2, 3,3,3],
[1,1,1, 2,2,2, 3,3,3],
[1,1,1, 2,2,2, 3,3,3],
[4,4,4, 5,5,5, 6,6,6],
[4,4,4, 5,5,5, 6,6,6],
[4,4,4, 5,5,5, 6,6,6],
[7,7,7, 8,8,8, 9,9,9],
[7,7,7, 8,8,8, 9,9,9],
[7,7,7, 8,8,8, 9,9,9],
]
function getRow(board, row) {
//return an array with all the elements from the row
return board[row]
}
function getCol(board, col) {
//returns an array with all of the arrays element from the column
let inCol = [];
for(row in board){
inCol.push(board[row][col])
}
return inCol
}
function getQuad(board, quadNum) {
//Creates an array of all the elemants in the same quad
let inQuad = [];
for(row in board){
for(col in board[row]){
if(_QUADS[row][col] == quadNum){
inQuad.push(board[row][col])
}
}
}
return inQuad
}
function getPossiable(board, row, col) {
//Any [row][col] on the board you will return the arrays of all possiable numbers
let inRow = getRow(board, row);
let inCol = getCol(board, col);
let inQuad = getQuad(board, _QUADS[row][col]);
let possiable = [];
let used = [];
//Every row elements that isn't possiable
//and remove any that have already been added
for(r in inRow){
let included = false;
for(u in used){
if(inRow[r] == used[u]){
included = true;
break;
}
}
if(!included){
used.push(inRow[r]);
}
}
for(c in inCol){
let included = false;
for(u in used){
if(inCol[c] == used[u]){
included = true;
break;
}
}
if(!included){
used.push(inCol[c]);
}
}
for(q in inQuad){
let included = false;
for(u in used){
if(inQuad[q] == used[u]){
included = true;
break;
}
}
if(!included){
used.push(inQuad[q]);
}
}
for(u in used){
if(used[u] == '.'){
used.splice(u, 1);
}
}
for(let num = 1; num < 10; num++){
if(! used.includes(num+"")){
possiable.push(num+"")
}
}
return possiable
}
let updated = true;
function fillInCell(board, row, col){
if(board[row][col] == '.'){
let possiable = getPossiable(board, row, col);
if(possiable.length == 1){
board[row][col] = possiable[0]
updated = true;
}
}
}
//Your Way
while(updated) {
updated = false;
for(row2 in _BOARD){
for(col in _BOARD[row2]){
fillInCell(_BOARD,[row2],[col]);
}
}
}
//My way of doing it //Run it 9 times
for(num in _BOARD){
if(_BOARD != '.'){
for(row2 in _BOARD){
for(col in _BOARD[row2]){
fillInCell(_BOARD,[row2],[col]);
}
}
}
}
console.table(_BOARD) |
/**
* Sample React Native App
* https://github.com/facebook/react-native
*
* @format
* @flow
*/
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View} from 'react-native';
import Login from './Component/Login/Login'
import Contacts from './Component/Contacts/Contacts'
import Detail from './Component/Contacts/Detail/Detail'
import Keyboard from './Component/Keyboard/Keyboard'
import { Router, Scene } from 'react-native-router-flux';
export default class App extends React.Component {
render() {
return (
<Router>
<Scene key="root">
<Scene key="Login"
component={Login}
title="Login"
hideNavBar={true}
initial
/>
<Scene
key="contact"
component={Contacts}
hideNavBar={true}
title="Contacts"
/>
<Scene
key="detail"
component={Detail}
hideNavBar={true}
title="Detail"
/>
<Scene
key="Keyboard"
component={Keyboard}
hideNavBar={true}
title="Keyboard"
/>
</Scene>
</Router>
);
}
}
|
/* navbar*/
const faq = document.querySelector(".faq");
const ans = document.querySelector(".ans");
faq.addEventListener("click", function (){
if (ans.classList.contains("active")){
ans.classList.remove("active");
}
else {
ans.classList.add("active");
}1
})
// const faqs = document.querySelector(".faq");
// faqs.foreach((faq) => {
// faq.addEventListener("click", () => {
// faq.classList.toggle("active");
// });
// }); |
import { Fab, Icon } from 'native-base';
import React from 'react';
import { NavigationActions } from "react-navigation";
import { FlatList, StyleSheet, Text, View } from 'react-native';
import { connect } from "react-redux";
import EstilosComuns, { FUNDO_CINZA_CLARO, VERDE } from '../../assets/estilos/estilos';
import { BotaoLoading, BotaoOpacity } from '../../components/botao/Botao';
import { InputTexto } from '../../components/input/InputTexto';
import { MensagemConfirmacao, MensagemInformativa } from "../../components/mensagens/Mensagens";
import { TELA_ADD_CLINICA, TELA_BUSCA_CLINICA, TELA_LISTA_CLINICAS, TELA_ADD_MEDICOS, TELA_HOME } from '../../constants/AppScreenData';
import { onChangeFieldBusca, buscarClinica, vincularClinica} from "../../actions/clinicas/CadastroClinicasAction";
class ProcuraClinica extends React.Component {
static navigationOptions = ({navigation}) => ({
title: TELA_BUSCA_CLINICA.title
});
constructor(props){
super(props);
// const backAction = NavigationActions.back({
// key: TELA_HOME.name,
// params: {atualizaLista: true}
// });
// this.props.navigation.dispatch(backAction);
}
buscarClinicas(){
if (this.props.nomeClinica.trim() == ''){
MensagemInformativa('Informe o nome da clรญnica para filtrar');
return false;
}
this.props.buscarClinica(this.props.nomeClinica, this.medico.idMedico);
}
confirmarVinculo(clinica){
if (! this.medico){
MensagemInformativa('O mรฉdico deve ser selecionado!');
return false;
}
let botaoConfirma= {
text: 'SIM',
onPress: () => {
this.props.vincularClinica(clinica, this.medico.idMedico);
},
style: 'destructive'
};
let botaoDescarta= {
text: 'NรO',
style: 'cancel'
};
MensagemConfirmacao(`Vocรช realmente deseja vincular esta clinica ao Dr(a) ${this.medico.nomeMedico}? `,
[botaoConfirma, botaoDescarta]
);
}
componentDidMount(){
const {params} = this.props.navigation.state;
this.medico = params && params.medico ? params.medico : null;
}
componentDidUpdate(prevProps){
console.log('encaminha para a tela de mรฉdicos', this.props.bolVinculoClinica);
if (this.props.bolVinculoClinica){
this.props.navigation.navigate(TELA_LISTA_CLINICAS.name, {atualizaLista: true});
}
}
onChangeField(field,value){
this.props.onChangeFieldBusca(field, value);
}
editarClinica(clinica){
this.props.navigation.navigate(TELA_ADD_CLINICA.name, {clinica, medico: this.medico});
}
render() {
return (
<View style={EstilosComuns.container}>
<Text style={EstilosComuns.tituloJanelas}>Vincular clรญnica ร mรฉdico</Text>
{/* <Text style={[styles.nota, EstilosComuns.italico]}>Antes de incluir, verifique se a clรญnica jรก existe no aplicativo efetuando a busca pelos dados abaixo</Text> */}
<View style={EstilosComuns.bodyMain}>
<View style={styles.containerBusca}>
<InputTexto placeholder="Nome da clรญnica" maxLength={50}
autoCapitalize="characters"
value={this.props.nomeClinica}
keyboardType={InputTexto.KEYBOARD_DEFAULT}
onChangeInput={value => this.onChangeField('nomeClinica', value)}
/>
<BotaoLoading carregaLoading={this.props.loading} tituloBotao="Consultar" onClick={() => this.buscarClinicas()}/>
</View>
<View style={[styles.containerResultado]}>
<FlatList
data= {this.props.listaClinicas}
keyExtractor={clinica => new String(clinica.idClinica)}
ListEmptyComponent= {
<Text style={[EstilosComuns.textoCentralizado, EstilosComuns.corVerde, styles.emptyResult]} >Nenhum resultado encontrado, informe os filtros para consultar!</Text>
}
renderItem = {clinica => {
return (
<BotaoOpacity onClick={()=> this.editarClinica(clinica.item)}>
<View style={styles.containerMedico}>
<View style={{flex: 9, flexDirection: 'column'}}>
<Text style={EstilosComuns.negrito}>{clinica.item.nomeClinica}</Text>
<Text style={EstilosComuns.italico}>{clinica.item.numTelefone}</Text>
<Text style={EstilosComuns.italico}>{clinica.item.nomeCidade != null ? clinica.item.nomeCidade : ''}</Text>
</View>
<View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
<Icon name="link" style={{color: 'blue'}} onPress={() => this.confirmarVinculo(clinica.item)} />
</View>
</View>
</BotaoOpacity>
)
}}
/>
</View>
<Fab
style={{ backgroundColor: VERDE }}
position="bottomRight"
onPress={() => this.props.navigation.navigate(TELA_ADD_CLINICA.name)}>
<Icon name="add" />
</Fab>
</View>
</View>
)
};
}
const mapStateToProps = state => ({
nomeClinica: state.procuraClinicaReducer.nomeClinica,
loading: state.procuraClinicaReducer.loading,
buscaSucesso: state.procuraClinicaReducer.buscaSucesso,
bolVinculado: state.procuraClinicaReducer.bolVinculado,
mensagemFalha: state.procuraClinicaReducer.mensagemFalha,
listaClinicas: state.procuraClinicaReducer.listaClinicas,
bolVinculoClinica: state.cadastroMedicosReducer.bolVinculoClinica
})
const styles= StyleSheet.create({
containerBusca: {
flex: 2,
flexDirection: 'column',
padding: 3
},
containerResultado: {
flex: 5,
},
containerMedico: {
flex: 1,
flexDirection: 'row',
justifyContent: 'space-between',
padding: 6,
borderBottomWidth: 1,
borderBottomColor: FUNDO_CINZA_CLARO
},
tituloResultado: {
borderBottomColor: FUNDO_CINZA_CLARO,
borderBottomWidth: 1
},
nota: {
fontSize: 15,
textAlign: 'center'
},
emptyResult: {
padding: 20,
}
})
export default connect( mapStateToProps,
{onChangeFieldBusca, buscarClinica,vincularClinica}
)
(ProcuraClinica); |
var gulp = require('gulp');
var sass = require("gulp-ruby-sass");
var cleanCSS = require('gulp-clean-css');
var autoprefixer = require('gulp-autoprefixer');
var browser = require('browser-sync');
var browserSync = browser.create();
var reload = browser.reload;
var server = require('gulp-express');
var sourcemaps = require('gulp-sourcemaps');
gulp.task('serve',['minify-css'],function(){
server.run(['app.js']);
browser({
proxy: "localhost:7000"
});
gulp.watch("./src/scss/**/*.scss", ['minify-css']);
gulp.watch("./*.html").on('change', reload);
gulp.watch("./dist/js/*.js").on('change',reload);
});
gulp.task('sass',function(){
return sass('./src/scss/pages/*.scss', {sourcemap: true})
.on('error', function (err) {
console.error('Error!', err.message);
})
.pipe(sourcemaps.write('./', {
includeContent: false,
sourceRoot: '../../src/scss/pages/'
}))
.pipe(gulp.dest('./src/css/'));
});
gulp.task('autoprefixer',['sass'],function(){
return gulp.src('./src/css/*.css')
.pipe(sourcemaps.init())
.pipe(autoprefixer())
.pipe(sourcemaps.write())
.pipe(gulp.dest('./src/css/'));
});
gulp.task('minify-css',['autoprefixer'], function(){
return gulp.src('./src/css/*.css')
.pipe(cleanCSS())
.pipe(gulp.dest('./dist/css/'))
.pipe(browserSync.stream());
});
gulp.task('default', ['serve']); |
const BetterDB = require("better-sqlite3");
/**
* Get a list of Envelope ID, whose Mz value is between min and max. Async mode.
* @param {string} dir - Project directory
* @param {number} min - Minimum envelope m/z value
* @param {number} max - Maximum envelope m/z value
* @param {number} scan - Scan number
* @return {array} EnvelopeIDList
* @async
*/
function getEnvIDListByMZRange(dir, min, max, scan) {
let dbDir = dir.substr(0, dir.lastIndexOf(".")) + ".db";
let resultDB = new BetterDB(dbDir);
let stmt = resultDB.prepare('SELECT DISTINCT envelope.envelope_id ' +
'FROM env_peak INNER JOIN envelope ON env_peak.envelope_id = envelope.envelope_id ' +
'INNER JOIN SPECTRA ON envelope.scan_id = SPECTRA.ID ' +
'WHERE SPECTRA.SCAN = ? AND env_peak.mz >= ? AND env_peak.mz <= ?;');
let envIDList = stmt.all(scan, min, max);
resultDB.close();
return envIDList;
}
module.exports = getEnvIDListByMZRange; |
//Problem 2. Correct brackets
//Write a JavaScript function to check
// if in a given expression the brackets
//are put correctly.
//Example of correct expression:
//((a+b)/5-d). Example of incorrect expression:
//(a+b)).
var str1,
len, i,
count, flag;
str1 = ' ((((a+b)/5-d)';
len = str1.length;
count = 0;
flag = 0;
function checkBrackets(str){
for (var i = 0; i < len; i++) {
if(str[i] === '('){
count++;
} else if (str[i] === ')') {
flag++;
}
}
if (count === flag) {
console.log('correct brackets');
} else {
console.log('incorrect backets');
}
}
checkBrackets(str1);
|
const logger = require('./logger');
const utils = require('./utils');
const config = require('./config');
const flow = require('./flow');
const { deepAssign, absolutePath } = utils;
const {
getDocInstance, getMDNodeTree, renderCover,
renderMDNodeTree, renderPagination, finishRender,
} = flow;
exports.run = async (cfg) => {
deepAssign(config, cfg);
logger.info('Init config', config);
const { sourceDir, targetFile } = config;
logger.info(`Collect files`);
const mdNodeTree = await getMDNodeTree(sourceDir);
if (mdNodeTree.length === 0) {
logger.info(`No files found`);
return;
}
logger.info(`Init instance`);
const docInstance = await getDocInstance(targetFile);
logger.info(`Render cover`);
await renderCover(docInstance);
logger.info(`Render files`);
await renderMDNodeTree(docInstance, mdNodeTree);
logger.info(`Render pagination`);
await renderPagination(docInstance);
logger.info(`Persistent render`);
await finishRender(docInstance);
logger.info(`Finished`);
};
|
import React, { PropTypes, Component } from 'react';
const UserProfile = ({user, currentUser}) => {
({HeadTags, UserActivity} = Telescope.components);
return (
<div className="row page user-profile">
<HeadTags url={Users.getProfileUrl(user, true)} title={Users.getDisplayName(user)} description={user.telescope.bio} />
<div className="col l12 m12 s12">
<header className="user-profile-header">
<div className="user-image">
<UserAvatar size="large" user={user} link={false} />
</div>
<div className="user-content">
<h2 className="user-content-title">{Users.getDisplayName(user)}</h2>
<p className="user-content-bio">{user.telescope.bio}</p>
</div>
<div className="user-stat">
</div>
</header>
</div>
<div className="col l12 m12 s12">
<UserActivity currentUser={user} />
</div>
<ul>
{user.telescope.twitterUsername ? <li><a href={"http://twitter.com/" + user.telescope.twitterUsername}>@{user.telescope.twitterUsername}</a></li> : null }
{user.telescope.website ? <li><a href={user.telescope.website}>{user.telescope.website}</a></li> : null }
</ul>
</div>
)
}
UserProfile.propTypes = {
user: React.PropTypes.object.isRequired,
currentUser: React.PropTypes.object
}
module.exports = UserProfile; |
const crypto = require('crypto')
module.exports = function(username) {
return `'${crypto.randomBytes(32).toString('hex')}': ${username}`
}
|
import { useState } from 'react';
import classes from './product.module.css';
import Image from 'next/image';
import Button from '../../../components/UI/Button/Button';
import { useAuth } from '../../../context/authContext';
import { useDispatchCart } from '../../../context/cartContext';
import * as actionTypes from '../../../context/actionTypes';
const product = ({ product }) => {
const [productQuantity, setProductQuantity] = useState(1);
const authState = useAuth();
const dispatchCart = useDispatchCart();
const productStars = Math.round(product.starrating);
const changeQuantityHandler = (event) => {
setProductQuantity(event.target.value);
}
const incrementQuantity = () => {
setProductQuantity(parseInt(productQuantity) + 1);
}
const decrementQuantity = () => {
if(productQuantity > 1) {
setProductQuantity(parseInt(productQuantity) - 1);
}
}
const addToCart = async () => {
console.log('Adding to cart');
const productToAdd = {
productId: product._id,
productName: product.name,
price: product.price,
img: product.img,
quantity: productQuantity,
colors: product.colors
}
console.log(product.colors);
if(authState.token) {
try {
const res = await fetch('https://nodejs-estore.herokuapp.com/api/cart', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'auth-token': authState.token
},
body: JSON.stringify(productToAdd),
})
const data = await res.json();
console.log(data);
} catch(err) {
console.log(err);
}
}
dispatchCart({
type: actionTypes.ADD_TO_CART,
payload: {
product: productToAdd,
auth: authState.token ? true : false
},
});
}
return (
<div className={classes.product}>
<div className={classes.productImage}>
<Image src={product.img} alt="product" width={300} height={300} />
</div>
<div className={classes.productDetails}>
<h2 className={classes.name}>{product.name}</h2>
<h3 className={classes.price}>{`$${product.price}`}</h3>
<div className={classes.rating}>
{
Array(productStars).fill('star').map((_, index) => (
<Image key={index} src="/star.svg" alt="star" width={20} height={20} />
))
}
{
Array(5 - productStars).fill('star').map((_, index) => (
<Image key={index} src="/star-black.svg" alt="star" width={20} height={20} />
))
}
</div>
<p>{product.description}</p>
<br />
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Rerum iusto placeat consequatur voluptas sit mollitia ratione autem, atque sequi odio laborum, recusandae quia distinctio voluptatibus sint, quae aliquid possimus exercitationem.</p>
<div className={classes.quantity}>
<button onClick={decrementQuantity}>-</button>
<input
type="number"
name="quantity"
value={productQuantity}
onChange={changeQuantityHandler}
className={classes.inputQuantity}
/>
<button onClick={incrementQuantity}>+</button>
</div>
<p>Available in: {product.colors.map((color, index) => {
if(index + 1 < product.colors.length) return (<span key={color}>{color}, </span>);
return (<span key={color}>{color}</span>);
})}
</p>
<Button btnClassName={classes.addBtn} click={addToCart} disabled={productQuantity < 1 ? true : false}>Add to cart</Button>
</div>
</div>
)
}
export const getStaticPaths = async () => {
const res = await fetch(`https://nodejs-estore.herokuapp.com/api/products`);
const products = await res.json();
const paths = products.map(p => `/shop/product/${p._id}`);
return {
paths,
fallback: false
}
}
export const getStaticProps = async ({ params }) => {
const res = await fetch(`https://nodejs-estore.herokuapp.com/api/products/${params.id}`);
const product = await res.json();
return {
props: {
product
}
}
}
export default product; |
// (The Tab onFocus)
var curtab;
var newtime; // ็พๅจๆ้
var port;
chrome.tabs.getSelected(null, function(tab) {
curtab=tab;
});
// =======================
// for long-lived connections |
// =======================
document.addEventListener('DOMContentLoaded', function () {
// set the channel on Background.js (uport.postMessage(ret))
//
port = chrome.runtime.connect({name: "unionchannel"});
port.onMessage.addListener(function(ret) { //conncet port & show new score infomation
console.log(ret); //ๆฏ็ญ่ณๆ
if ($("#_"+ret.loc).length==0) {
$("#_oppanel").append("<div style='color:white; background:#03161C;'><span> </span><span style='font-size:15px;' id=_"+ret.loc+"lotto"+">GameName</span></div>");
$("#_oppanel").append("<div style='background:#DADADA' id=_"+ret.loc+"></div>");
$("#_oppanel").append("<div style='background:#FFFFFF'> </div>");
}
$("#_cq2lotto").html("้ๆ
ถๆๆๅฝฉ");
$("#_bjcar3lotto").html("ๅไบฌ่ณฝ่ปPK");
$("#_bjkl8lotto").html("ๅไบฌๅฟซๆจๅ
ซ");
$("#_xynclotto").html("ๅนธ้่พฒๅ ด");
$("#_jsk3lotto").html("ๆฑ่ๅฟซไธ");
$("#_gd10lotto").html("ๅปฃๆฑๅฟซๆจๅๅ");
$("#_tj10lotto").html("ๅคฉๆดฅๅฟซๆจๅๅ");
$("#_cqlotto").html("้ๆ
ถๆๆๅฝฉcq");
// *score ้็*
for (var issue in ret.data){
if (ret.data[issue]=="" || ret.data[issue].Number=="" ) {
var html="<table><tr><td> </td><td width='72' style='font-family:arial;color:blue;font-size:14px;'>"+issue+"</td><td> </td><td style='font-family:arial;color:red;font-size:18px;'>"+"้็ไธญ.."+"</td></tr></table>";
$("#_"+ret.loc).html(html);
}else {
var html="<table><tr><td> </td><td width='72' style='font-family:arial;color:blue;font-size:14px;'>"+issue+"</td><td> </td><td style='font-family:arial;color:red;font-size:18px;'>"+ret.data[issue].Number+"</td></tr></table>";
$("#_"+ret.loc).html(html);
}
}
});
});
window.addEventListener("unload",function() {
port.postMessage({error:"",event:"oplogout"});
});
|
$(function () {
console.log("Connection...");
setTimeout(function () {
window.open("about:blank","_self").close();
}, 600000);
var $btn = $(".btn");
var $menu = $(".menu");
var $area = $menu.find(".area");
var $menu_cancel = $area.find(".cancel");
// ๋ฉ๋ด ํธ๋ฆฌ๊ฑฐ
$btn.on("click", function () {
$btn.addClass("on").hide();
$menu.addClass("on").fadeIn(500);
});
$menu_cancel.on("click", function () {
$menu.removeClass("on").hide();
$btn.removeClass("on").show();
});
var li_index = $(".menu .container ul li");
li_index.on("click", function () {
$menu.removeClass("on").hide();
$btn.removeClass("on");
}); // ๋ฉ๋ด ํธ๋ฆฌ๊ฑฐ
// work ์ฌ๋ผ์ด๋ ์ด๋ฒคํธ
$(".work .container").slick({
dots: false,
infinite: true,
speed: 500,
slidesToShow: 1,
slidesToScroll: 1,
arrows: false,
autoplay: true,
autoplaySpeed: 3000,
swipeToSlide: true
});
// ์ฌ๋ผ์ด๋ ์ด๋ฏธ์ง ํธ๋ฒ
var $work_content = $(".work .container .card .imgbox .content");
$work_content.hide();
$(".work .imgbox").on("mouseenter", function () {
$(this).find(".content").show();
$(this).find(".content").stop().animate({
"bottom": "0px"
});
// $(this).stop().animate({
// 'bottom': 0
// }, 1000);
}).on("mouseleave", function () {
$(this).find(".content").slideDown();
$(this).find(".content").stop().animate({
"bottom": "-250px"
});
});
}); |
function calcularSalario() {
var horas=parseInt(document.getElementById("horas").value);
var precio=parseFloat(document.getElementById("precio").value);
var salario;
if(horas <= 38){
salario=horas*precio;
}
else if(horas >38){
var horas_=horas-38;
salario=(38*precio)+(horas_*1.5*precio);
console.log(salario);
}
if (salario > 50000){
salario-=salario*(0.1);
}
console.log(salario);
if( horas<0 || precio <0 ){
$('.toast').toast('show',5000);
}
document.getElementById("result").innerHTML=`El salario es ${salario} `;
} |
myModule.controller('DummyController', ["$scope",'clientName',
function($scope,clientName){
console.log('Dummy controller created');
//$scope.clientName = "dummy";
$scope.getClientName = function(){
$scope.clientName = clientName;
};
}]); |
const animals = ['lion', 'tiger', 'bears']
for (let i = 0; i <animals.length; i++){
console.log(i,animals[i]);
}
const examScores = [98,77,84,91,57,66]
for ( i = 0; i < examScores.length; i++){
console.log(i,examScores[i]);
}
const reverseExamScores = [98,77,84,91,57,66]
for (let i = reverseExamScores.length -1; i >=0; i--){console.log(i, reverseExamScores[i]);
}
let total = 0
const totalExamScores = [98,77,84,91,57,66]
for ( let i = 0; i < totalExamScores.length; i++) {
total += totalExamScores[i];
}
console.log(total);
let total1 = 0
const averageScore = [98,77,84,91,57,66]
for ( let i = 0; i < averageScore.length; i ++){
total + averageScore[i]
}
console.log(total / averageScore.length);
const students = [
{
firstname: 'Zeus',
grade: 86
},
{
firstname: 'Artemis',
grade: 97
},
{
firstname: 'Hera',
grade: 73
},
{
firstname: 'Apollo',
grade: 90
},
]
for ( let i = 0; i < students.length; i++){
let student = students[i]
console.log(`${student.firstname} scored ${student.grade}`);
}
const word = 'Javascript'
let reverseWord = ''
for ( let i = word.length -1; i >= 0; i-- ){
reverseWord += word[i]
}
console.log(reverseWord);
// Nested loops
for (let i = 0; i <= 5; i ++){
console.log("Outer Loop:", i);
for ( let j = 5; j >=0; j -- ){
console.log(" Inner Loop:", j);
}
}
const gameBoard = [
[4,32,8,4],
[64,8,32,2],
[8,32,16,4],
[2,8,4,2],
]
let totalScore = 0
for (let i = 0; i < gameBoard.length; i ++) {
let row = gameBoard[i]
for ( let j = 0; j < row.length; j ++)
totalScore += row[j]
console.log(totalScore);
}
// While loop
let j = 0
while(j <=5){
console.log(j);
j++
}
const target = Math.floor(Math.random() * 10)
let guess = Math.floor(Math.random() * 10)
while (guess !== target) {
console.log(`Target: ${target} Guess:${guess}`);
guess = Math.floor(Math.random() * 10)
}
console.log(`Target: ${target} Guess:${guess}`);
console.log("Congrats, you win!");
// Of loop
let subreddits = ["soccer", "popheads", "cringe", "books"]
for ( let sub of subreddits){
console.log(sub);
}
for ( let char of "javascript"){
console.log(char.toUpperCase());
}
// ######################################################
const magicSquare = [[2,7,6], [9,5,1], [4,3,8]]
for ( let i = 0; i < magicSquare.length; i ++){
let row = magicSquare[i]
let sum = 0
for (let j = 0; j < row.length; j ++){
sum += row[j]
}
console.log(`${row} summed to ${sum}`);
}
// for of
for (let row of magicSquare){
let sum = 0
for (let num of row) {
sum += num
}
console.log(`${row} summed to ${sum}`);
}
// ######################################################
const words1 = ['mail','milk','bath','black']
const words2 = ['box', 'shake', 'tub', 'berry']
for (let i = 0; i < words1.length; i ++) {
console.log(`${words1[i]}${words2[i]}`);
}
const movieReviews = {
Arrivals : 9.5 ,
Alien : 9 ,
Amelie : 8 ,
'In Bruge' : 9 ,
Amadeus : 10 ,
'Kill Bill' : 8 ,
'Little Miss Sunshine' : 8.5 ,
Caroline : 7.7
}
for (let movie of Object.keys(movieReviews)){
console.log(movie, movieReviews[movie]);
}
const ratings = Object.values(movieReviews)
let total3 = 0
for (r of ratings){
total3 += r
}
let avg = total3 / ratings.length
console.log(avg);
// for in
// For in will iterate over the keys, the properties in an object
const jeopardyWinnings = {
regularPlay : 2522700,
watsonChallenge : 30000,
tournamount : 500000,
battleOfDecades : 100000
}
for ( let prop in jeopardyWinnings) {
console.log(prop, jeopardyWinnings[prop]);
}
let total4 = 0
for (let prop in jeopardyWinnings){
total4 += jeopardyWinnings[prop]
}
console.log(`Ken Jennings total ernings: ${total4}`);
|
// hacking gulp-build
// https://github.com/tjeastmond/gulp-build/blob/master/index.js
var through2 = require('through2');
var hbs = require('handlebars');
var path = require('path');
module.exports = function( data, options ) {
data = data || {};
hbs.registerHelper( options.helpers );
hbs.registerPartial( options.partials );
return through2.obj( function build( file, encoding, callback ) {
var fileContents = file.contents.toString();
var template;
if ( typeof options.layout == 'string' ) {
hbs.registerPartial( 'body', fileContents );
template = hbs.compile( options.layout );
} else {
template = hbs.compile( fileContents );
}
// add file data, front matter data to data obj
data.page = file.frontMatter;
data.file_path = path.relative( file.cwd, file.path );
data.basename = path.basename( file.path, path.extname( file.path ) );
file.contents = new Buffer( template( data ) );
return callback( null, file );
});
};
|
const hljs = require("highlight.js");
module.exports = ({ node }) => {
const level = node.getLevel() + 2;
const title = node.getTitle();
const style = node.getStyle();
const content = node.getSource();
let titleEl = "";
if (title) {
titleEl = `<h${level}>${title}</h${level}>`;
}
if (style === "source") {
const lang = node.getAttribute("language");
let highlightedContent = content.trim();
if (lang && lang !== "text") {
try {
highlightedContent = hljs.highlight(content.trim(), {
language: lang,
}).value;
} catch (e) {
if (e.toString().indexOf("Unknown language") === -1) {
console.log(e);
} else {
console.log(`'${lang}' is not a language supported by highlight.js`);
}
}
}
return `${titleEl}
<pre class="language-${lang} hljs"><code class="language-${lang} hljs">${highlightedContent}</code></pre> `;
}
return `${titleEl}
<pre>${content}</pre>`;
};
|
/*
Copyright (c) 2007 - 2008 Arthur C. Ralfs
All rights reserved.
Copyright (c) 2007 - 2008 Alfredo Portes
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
- The name of Arthur C. Ralfs may not be used to endorse or promote
products derived from this software without specific prior written
permission.
- The name of Alfredo Portes may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/* We need to process commands
* that start with ")".
*/
function checkCommand(command) {
/*if (/\)show/.test(command)) {
command = 'showcall='+command;
}
else if (/\)help/.test(command)) {
command = 'interpcall='+command
}
else {*/
command = 'command='+command;
//}
return command;
}
/********************************
* Some functions are not currently
* allowed to be ran in this interface.
********************************/
function invalidCommands(command) {
if (/\)draw/.test(command)) {
return true;
}
return true;
}
/********************************
* The format of passing arguments
* is 'argument,value'. We use
* ',' instead of the standard '='
* so it is not confused by the
* server at the time of processing
* the commands sent to it.
* ******************************/
function redirectToBrowse(value) {
document.location = 'browse.xhtml?' + value + "," + document.getElementById('searchbox').value;
}
/*
*
*/
function asq(domain, key) {
document.location = 'browse.xhtml?' + "asqxml=" + domain + "," + key;
}
/*
*
*/
function remove_extra(targ) {
targ.value = targ.value.replace('/\n+$/g',"");
}
/* ***************************
* Every time a key is pressed
* we check to see if the user
* has requested for a cell to
* be evaluate it.
* **************************/
function keyPressed(e) {
var keynum, keychar, shift;
// var command = document.getElementById ('commreq').value
// this works in Firefox, do we need something else in IE?
if (e.target)
{
targ = e.target;
command = targ.value;
}
if(window.event) // IE
{
keynum = e.keyCode
}
else if(e.which) // Netscape/Firefox/Opera
{
keynum = e.which
}
shift = e.shiftKey;
if(shift && keynum == 13 && command != "") {
//alert(targ.id);
makeRequest(targ);
}
}
/**
*/
function linkEvaluate(stepNum) {
makeRequest(document.getElementById(stepNum));
}
// I think the only place this is used is in making the initial
// top level compCell so maybe this code should be put into
// makeCompCell
function putFocus() {
command = document.getElementById('comm');
command.focus();
}
/*
*
*/
function activeCell(targ) {
document.getElementById(targ.id).style.border="solid 1px #0000FF";
}
/*
*
*/
function passiveCell(targ) {
document.getElementById(targ.id).style.border="solid 1px #CCCCCC";
}
/*
*
*/
function onBlur(e) {
var targ = e.target;
targ.parentNode.lastChild.style.display="none";
passiveCell(targ);
}
/*
*
*/
function onFocus(e) {
var targ = e.target;
var children = document.getElementsByTagName("*");
for (var i = 0; i < children.length; i++) {
if (children[i].className == "evaluate")
children[i].style.display="none";
if (children[i].className == "cell_input")
children[i].style.border="solid 1px #CCCCCC";
}
targ.parentNode.lastChild.style.display="inline";
document.getElementById(targ.id).style.border="solid 1px #0000FF";
//activeCell(targ);
//var root = ctgCompCell(targ);
//document.getElementById(root.lastChild.id).style.display="inline";
}
/*
*
*/
function changeFocus(e) {
if (e.target)
{
targ = e.target;
targ.focus();
e.stopPropagation();
}
}
/* This function is used to resize
* the textareas */
function resize_textarea(t) {
a = t.value.split('\n');
t.rows = a.length;
}
/* This is a dummy writeToFile function.
* Need to be re-written. */
function writeToFile(path,content) {
//content = content.replace('/\n+$/g',"");
makeRequestServer('command','ifile:TextFile := open("'+path+'","output");'
+ 'content:String:="'+content+'";'
+ 'writeLine!(ifile,content);'
+ 'close!ifile;');
}
/*
*
*/
function readFromEditor() {
// getCode is magic from Codepress.
// One gives the id of the textarea
// and getCode gets the content of it.
//writeToFile('casn.input',area.getCode());
makeRequestServer('command',area.getCode());
}
/*
*
*/
function compileFromEditor() {
writeToFile('casn.input',area.getCode());
makeRequestServer('interpcall',')compile casn.input');
}
// check at some point whether I can have targ as an argument
function makeRequest(targ) {
// Other methods for creating the XMLHttpRequest object
// in browsers different from Firefox and IE need to
// to be placed here.
// First test for IE XMLHttp objects.
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
http_request = false;
}
}
// If the previous failed then try for Firefox xmlhttp object.
if (!http_request && typeof XMLHttpRequest != 'undefined') {
try {
http_request = new XMLHttpRequest();
}
catch (e) {
http_request = false;
}
}
if (!http_request && window.createRequest) {
try {
http_request = window.createRequest();
}
catch (e) {
http_request = false;
}
}
var command = targ.value;
http_request.open('POST', '127.0.0.1:8085', true);
http_request.onreadystatechange = addCompCell;
http_request.setRequestHeader('Content-Type', 'text/plain');
//http_request.send(checkCommand(removeOutput(command)));
http_request.send(checkCommand(command));
}
/*
*
*/
function removeOutput(command) {
var ncommand = command.replace(/^\n+|\n+$/g,"");
ncommand = ncommand.replace(/^\s+|\s+$/g,"");
ncommand = ncommand.replace(/\n+/g,";");
return ncommand;
}
/* this function sends compCell as serialized string */
function sendCompCell(compCellString) {
var http_request = HTTP.newRequest();
http_request.open('POST', '127.0.0.1:8085', true);
http_request.onreadystatechange = function() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
var answer = http_request.responseText;
alert(answer);
}
}
}
http_request.setRequestHeader('Content-Type', 'text/plain');
http_request.send("compCellString="+compCellString);
}
/* Here's the structure:
<div class="compCell">
<div class="result">
<!-- div.result contains the results from fricas command
returned via XMLHttpRequest.responseText -->
<div class="stepnum">
<!-- this contains fricas's step number -->
</div>
<div class="command">
<form>
<span>(stepnum)-></span>
<input class="inComm"
type="text"
size="80"
value="command"
alt="command"/><!-- this contains the command sent to fricas -->
</form>
</div>
<div class="algebra">
<!-- this contains the contents of the algebraOutputStream
generated in response to the command -->
</div>
<div class="mathml">
<!-- this contains the mathml generated in response to the command -->
</div>
<div class="type">
Type: <!-- this contains fricas's type of the result -->
</div>
</div>
<!-- may contain any number of child compCells, however when
compCell is initially created it won't contain any child
compCells -->
</div>
makeCompCell should take mathString=XMLHttpRequest.responseText and
the element of which it will be added to as a child. It's position
as a child will depend on whether the prospective parent is "the"
rootCompCell or an ordinary compCell.
*/
function makeCompCell(mathString,parent) {
var compCell = document.createElementNS('http://www.w3.org/1999/xhtml','div');
compCell.setAttribute('class','compCell');
var resultBox = document.createElementNS('http://www.w3.org/1999/xhtml','div');
resultBox.setAttribute('class','result');
var mathRange = document.createRange();
mathRange.selectNodeContents(resultBox);
var mathFragment = mathRange.createContextualFragment(mathString);
resultBox.appendChild(mathFragment);
compCell.appendChild(resultBox);
// command and type come bare and need to be decorated, i.e.
// the command has to have the form and input boxes constructed and
// the type needs just the text "Type: " added.
// alert('makeCompCell1');
var stepNum = getStepBox(resultBox).firstChild.data;
// alert('makeCompCell2');
var typeBox = getTypeBox(resultBox);
var commandBox = getCommandBox(resultBox);
var command = commandBox.firstChild.data;
// This is probably not needed anymore
// Convert the ; into breaklines
//command = command.replace(/;+/g,"\n");
// Count the number of lines so we
// can adjust the inputBox attribute
// (textarea) to have this number of rows.
var nrows = command.split('\n').length;
compCell.setAttribute('id', 'step'+stepNum);
//formBox = document.createElementNS('http://www.w3.org/1999/xhtml','form');
spanBox = document.createElement('span');
spanBox.appendChild(document.createTextNode('('+stepNum+') -> '));
//formBox.appendChild(spanBox);
inputBox = document.createElementNS('http://www.w3.org/1999/xhtml','textarea');
// alert('keyPressedReval(event,' + "'step" + stepNum + "'" + ')');
//inputBox.setAttribute('onkeypress','keyPressedReval(event,' + "'step" + stepNum + "'" + ')');
inputBox.setAttribute('onkeypress','keyPressed(event)');
inputBox.setAttribute('onclick','changeFocus(event)');
inputBox.setAttribute('onkeyup','resize_textarea(event.target)');
inputBox.setAttribute('onkeydown','remove_extra(event.target)');
inputBox.setAttribute('onfocus','onFocus(event)');
//inputBox.setAttribute('onblur','onBlur(event)');
inputBox.setAttribute('class','cell_input');
//inputBox.setAttribute('type','text');
inputBox.setAttribute('rows',nrows);
inputBox.setAttribute('cols','80');
inputBox.setAttribute('value',command);
inputBox.setAttribute('alt',command);
inputBox.setAttribute('id', stepNum);
inputBox.appendChild(document.createTextNode(command));
//inputBox.appendChild(spanBox);
//formBox.appendChild(inputBox);
// Type: Only display the type of the result
// if it something to show (error messages
// do not have types :) )
if (typeBox.firstChild != null)
typeBox.insertBefore(document.createTextNode('Type: '),typeBox.firstChild);
commandBox.removeChild(commandBox.firstChild);
//commandBox.appendChild(formBox);
commandBox.appendChild(inputBox);
// Evaluate Link
var evaluate = document.createElementNS('http://www.w3.org/1999/xhtml','a');
evaluate.setAttribute('class','evaluate');
evaluate.setAttribute('href','javascript:void%200');
evaluate.setAttribute('onclick','javascript:linkEvaluate('+stepNum+')');
evaluate.appendChild(document.createTextNode('evaluate'));
commandBox.appendChild(evaluate);
if (parent.className == "compCell") {
//insert before parents resultBox
updateResultBox(compCell, parent);
//parent.insertBefore(compCell,getResultBox(parent));
inputBox.focus();
}
else {//parent.className = "rootCompCell"
//Make sure to restart the numbers of rows to 1
//in the rootCompCell textarea.
parent.firstChild.firstChild.setAttribute('rows','1');
//insert at top of stack, childNodes[0] is the command box
parent.insertBefore(compCell,getFirstCompCell(parent));
//parent.appendChild(compCell);
}
// do I need 'onclick','javascript:showContext(event)'?
}
/* Each compCell has a unique resultBox determined by its className
*/
function getResultBox(compCell) {
var children = compCell.childNodes;
for (var i = 0; i < children.length; i++) {
if (CSSClass.is(children[i], 'result')) return children[i];
}
}
/* Takes a parent node and replaces its contenst
* with the ones from compCell. This is used when
* the user updates/changes the command in one
* of the cells.
*/
function updateResultBox(compCell, parent) {
var children = parent.childNodes;
for (var i = 0; i < children.length; i++)
parent.removeChild(children[i]);
children = compCell.childNodes;
for (var i = 0; i < children.length; i++)
parent.appendChild(children[i]);
}
/* I don't want to rely on the specific structure of the resultBox to access
* it's children. Rather I want to think of it as a bag containing, at present,
* boxes for stepnum, command, algebra, mathml, and type which could be in any
* order. Also I may want to add something new, for instance a TeX box. So I
* define functions to retrieve these nodes for a given resultBox node.
*/
function getStepBox(resultBox) {
// make sure argument is of right class
if (!CSSClass.is(resultBox,'result')) {
alert('getStepBox: argument not resultBox');
return;
}
var children = resultBox.childNodes;
for (var i = 0; i < children.length; i++) {
if (CSSClass.is(children[i],'stepnum')) return children[i]
}
}
// this function should get the stepnum of the lowest level compCell
// containing the present element 'g'. If g is a compCell then that's
// the stepnum of itself. If g is not a compCell then it is the stepnum
// of the containing compCell
function getStepNum(g) {
return getStepBox(getResultBox(g)).firstChild.data;
}
/*
*
*/
function getCommandBox(resultBox) {
// make sure argument is of right class
if (!CSSClass.is(resultBox,'result')) {
alert('getStepBox: argument not resultBox');
return;
}
var children = resultBox.childNodes;
for (var i = 0; i < children.length; i++) {
if (CSSClass.is(children[i],'command')) return children[i]
}
}
/*
*
*/
function getAlgebraBox(resultBox) {
// make sure argument is of right class
if (!CSSClass.is(resultBox,'result')) {
alert('getStepBox: argument not resultBox');
return;
}
var children = resultBox.childNodes;
for (var i = 0; i < children.length; i++) {
if (CSSClass.is(children[i],'algebra')) return children[i]
}
}
/*
*
*/
function getMathmlBox(resultBox) {
// make sure argument is of right class
if (!CSSClass.is(resultBox,'result')) {
alert('getStepBox: argument not resultBox');
return;
}
var children = resultBox.childNodes;
for (var i = 0; i < children.length; i++) {
if (CSSClass.is(children[i],'mathml')) return children[i]
}
}
/*
*
*/
function getTypeBox(resultBox) {
// make sure argument is of right class
if (!CSSClass.is(resultBox,'result')) {
alert('getStepBox: argument not resultBox');
return;
}
var children = resultBox.childNodes;
for (var i = 0; i < children.length; i++) {
if (CSSClass.is(children[i],'type')) return children[i]
}
}
/* I want a function that will return the first child compCell of a given
* compCell or rootCompCell.
*/
function getFirstCompCell(compCell) {
var children = compCell.childNodes;
for (var i = 0; i < children.length; i++) {
if (CSSClass.is(children[i],'compCell')) return children[i];
}
return null;
}
/*
*
*/
function getSibCompCells(compCell) {
// alert('getSibCompCells 1');
var parent = ctgCompCell(compCell);
var children = parent.childNodes;
var sibs = [];
for (var i = 0; i < children.length; i++) {
if (CSSClass.is(children[i],'compCell')) sibs.push(children[i])
}
return sibs;
}
/* addCompCell is the 'onreadystatechange' function in the
XMLHttpRequest object.
Here's the structure of a compCell produced by makeCompCell
when a successful command has been returned, in this example
the command was 'x'
<div id="step6" class="compCell" style="display: block">
<div class="stepnum">6</div>
<div class="command">
<form>
<span>(6)-></span>
<input type="text" class="inComm" onkeypress="keyPressed(event)" onclick="changeFocus(event)" size="80" value="x" alt="x">x</input>
</form>
</div>
<div class="algebra"></div>
<div class="mathml">
<math xmlns="http://www.w3.org/1998/Math/MathML mathsize="big" display="block">
... result returned from FriCAS
</math>
</div>
<div class="type">Type: ... type returned from FriCAS</div>
</div>
*/
/*
The structure returned from FriCAS now is
<div class="stepnum"></div>
<div class="command"></div>
<div class="algebra"></div>
<div class="mathml"></div>
<div class="type"></div>
*/
function addCompCell() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
// need parent compCell and mathString to pass to makeCompCell
var parent = ctgCompCell(targ);
// var parent = targ.parentNode.parentNode.parentNode;
// restore the original command that was in the input box
targ.value = targ.getAttribute("alt");
var mathString = http_request.responseText;
//alert(mathString);
makeCompCell(mathString,parent);
}
else {
alert('There was a problem with the request.'+ http_request.statusText);
}
}
}
/*
*
*/
function ctgCompCell(targ) {
// given any node this should return the containing compCell
if (targ.parentNode.className == 'compCell' || targ.parentNode.className == 'rootCompCell') {
return targ.parentNode;
}
else {
return ctgCompCell(targ.parentNode);
}
}
/*
*
*/
function showContext(e) {
var x = e.clientX;
var y = e.clientY;
x = x + window.pageXOffset;
y = y + window.pageYOffset;
// set the containing compCell and make sure event doesn't arise
// from a command box
var f = e.target;
while ( !f.className ) {
f = f.parentNode;
}
if ( !(CSSClass.is(f,'mathml') || CSSClass.is(f,'algebra') || CSSClass.is(f,'type') || CSSClass.is(f,'compCell') || CSSClass.is(f,'rootCompCell'))) return;
// if ( CSSClass.is(f,'command') || CSSClass.is(f,'inComm') ) return;
if (f.className == 'compCell') var g = f;
else var g = ctgCompCell(f);
// use an anonymous function to hold everything else
(function() {
var contents = document.getElementById('contents');
// create box to hold the menu
var menuBox = document.createElementNS('http://www.w3.org/1999/xhtml','div');
// create a drag bar at the top
var dragBar = document.createElementNS('http://www.w3.org/1999/xhtml','div');
menuBox.appendChild(dragBar);
dragBar.setAttribute('style','background-color: gray; height: 10px;');
dragBar.setAttribute('onmousedown','drag(this.parentNode,event)');
/*
* next item specifies the compCell Id and allows navigating
* up and down the compCell tree
*/
function makeIdBox() {
var compIdBox = document.createElementNS('http://www.w3.org/1999/xhtml','div');
var idTable = document.createElementNS('http://www.w3.org/1999/xhtml','table');
idTable.className = 'idTable';
var row1 = document.createElementNS('http://www.w3.org/1999/xhtml','tr');
var row1td1 = document.createElementNS('http://www.w3.org/1999/xhtml','td');
var row1td2 = document.createElementNS('http://www.w3.org/1999/xhtml','td');
var row1td3 = document.createElementNS('http://www.w3.org/1999/xhtml','td');
row1.appendChild(row1td1);
row1.appendChild(row1td2);
row1.appendChild(row1td3);
idTable.appendChild(row1);
row1td1.appendChild(document.createTextNode('Comp Cell '));
//
var sibs = getSibCompCells(g);
for ( var i = 0; i < sibs.length; i++) {
var div = document.createElementNS('http://www.w3.org/1999/xhtml','div');
row1td2.appendChild(div);
div.appendChild(document.createTextNode(getStepNum(sibs[i])));
div.setAttribute('style','cursor: pointer;');
if ( sibs[i] == g ) CSSClass.add(div,'active');
div.onclick = function() {
var divs = row1td2.childNodes;
for ( var i = 0; i < divs.length; i++) {
CSSClass.remove(divs[i],'active');
}
CSSClass.add(this,'active');
id = this.firstChild.data;
var sibs = getSibCompCells(g);
for (var i = 0; i < sibs.length; i++) {
if (getStepNum(sibs[i]) == id) {
g = sibs[i];
g.scrollIntoView();
// need to move context menu into view after scrolling
// x = g.offsetLeft;
y = g.offsetTop;
menuBox.setAttribute('style','position: absolute; left: ' + x + 'px; top: ' + y + 'px;');
menuBox.scrollIntoView();
}
}
}
}
//
var idNum = getStepNum(g);
if (CSSClass.is(ctgCompCell(g),'compCell')) {
var div = document.createElementNS('http://www.w3.org/1999/xhtml','div');
div.appendChild(document.createTextNode('\u25b2'));
row1td3.appendChild(div);
div.onclick = function() {
g = ctgCompCell(g);
menuBox.replaceChild(makeIdBox(),compIdBox);
};
div.setAttribute('style', 'cursor: pointer;');
}
if (getFirstCompCell(g)) {
var div = document.createElementNS('http://www.w3.org/1999/xhtml','div');
div.appendChild(document.createTextNode('\u25bc'));
row1td3.appendChild(div);
div.onclick = function() {
g = getFirstCompCell(g);
menuBox.replaceChild(makeIdBox(),compIdBox);
}
div.setAttribute('style', 'cursor: pointer;');
}
compIdBox.appendChild(idTable);
return compIdBox;
}//end makeIdBox
var compIdBox = makeIdBox();
/*
* next item is clickable and sets display: none; for this compCell.
* if display is already none then it should do the reverse.
*/
var cellBox = document.createElementNS('http://www.w3.org/1999/xhtml','div');
var cellText = document.createTextNode('show/hide cell');
cellBox.appendChild(cellText);
cellBox.className = "context-item";
// cellBox.setAttribute('onclick','showCell(\'' + g.id + '\')');
cellBox.onclick = function() {
var children = g.childNodes;
for ( var i = 0; i < children.length; i++) {
if ( !CSSClass.is(children[i],'compCell') ) {
if (CSSClass.is(children[i],'hide')) {
CSSClass.remove(children[i],'hide');
} else {
CSSClass.add(children[i],'hide');
}
}
}
}
/*
* next item sets whole branch to display: none; or the reverse
*/
var branchBox = document.createElementNS('http://www.w3.org/1999/xhtml','div');
var branchText = document.createTextNode('show/hide branch');
branchBox.appendChild(branchText);
branchBox.className = "context-item";
branchBox.onclick = function() {
showBranch(g);
}
/*
* next item hides whole branch from present compCell to
* the end except head
*/
var headBox = document.createElementNS('http://www.w3.org/1999/xhtml','div');
var headText = document.createTextNode('hide except head');
headBox.appendChild(headText);
headBox.className = "context-item";
headBox.setAttribute('onclick','showHead(\'' + g.id + '\')');
headBox.onclick = function() {
showHead(g);
}
/*
* next item is rotate this compCell to top of its containing compCell. If it's
* already at the top then it rotates it to the top of its containing
* branch, and so on
*/
var rotateBox = document.createElementNS('http://www.w3.org/1999/xhtml','div');
rotateBox.appendChild(document.createTextNode('rotate to top'));
rotateBox.className = "context-item";
rotateBox.onclick = function() {
rotateHead(g);
menuBox.replaceChild(makeIdBox(),compIdBox);
};
/*
* next item is for inserting a text box
*/
var textOpt = document.createElementNS('http://www.w3.org/1999/xhtml','div');
var textMenu = null;
textOpt.appendChild(document.createTextNode('insert text'));
textOpt.className = "context-item";
textOpt.onclick = function() {
if (!textMenu) {
textMenu = document.createElementNS('http://www.w3.org/1999/xhtml','div');
textOpt.appendChild(textMenu);
textMenu.setAttribute('style','margin-left: 10px;');
var startResult = document.createElementNS('http://www.w3.org/1999/xhtml','div');
startResult.appendChild(document.createTextNode('start result'));
textMenu.appendChild(startResult);
startResult.onclick = function() {
var textBox = makeTextBox();
getResultBox(g).insertBefore(textBox,getResultBox(g).firstChild);
}
var endResult = document.createElementNS('http://www.w3.org/1999/xhtml','div');
endResult.appendChild(document.createTextNode('end result'));
textMenu.appendChild(endResult);
endResult.onclick = function() {
var textBox = makeTextBox();
getResultBox(g).appendChild(textBox);
}
var beforeResult = document.createElementNS('http://www.w3.org/1999/xhtml','div');
beforeResult.appendChild(document.createTextNode('before result'));
textMenu.appendChild(beforeResult);
beforeResult.onclick = function() {
var textBox = makeTextBox();
g.insertBefore(textBox,getResultBox(g));
}
var afterResult = document.createElementNS('http://www.w3.org/1999/xhtml','div');
afterResult.appendChild(document.createTextNode('after result'));
textMenu.appendChild(afterResult);
afterResult.onclick = function() {
var textBox = makeTextBox();
if (getResultBox(g).nextSibling) g.insertBefore(textBox,getResultBox(g).nextSibling);
else g.appendChild(textBox);
}
var beforeCell = document.createElementNS('http://www.w3.org/1999/xhtml','div');
beforeCell.appendChild(document.createTextNode('before cell'));
textMenu.appendChild(beforeCell);
beforeCell.onclick = function() {
var textBox = makeTextBox();
g.parentNode.insertBefore(textBox,g);
}
var afterCell = document.createElementNS('http://www.w3.org/1999/xhtml','div');
afterCell.appendChild(document.createTextNode('after cell'));
textMenu.appendChild(afterCell);
afterCell.onclick = function() {
var textBox = makeTextBox();
if (g.nextSibling) g.parentNode.insertBefore(textBox,g.nextSibling);
else g.parentNode.appendChild(textBox);
}
}
else {
textOpt.removeChild(textMenu);
textMenu = null;
}
}
/*
* next item is to serialize a compCell
*/
var serialBox = document.createElementNS('http://www.w3.org/1999/xhtml','div');
serialBox.appendChild(document.createTextNode('serialize'));
serialBox.className = "context-item";
serialBox.onclick = function() {
var compCellString = (new XMLSerializer()).serializeToString(g);
// alert(compCellString);
sendCompCell(compCellString);
var downBox = document.createElementNS('http://www.w3.org/1999/xhtml','div');
downBox.appendChild(document.createTextNode('download'));
downBox.setAttribute('style','cursor: pointer; margin-left: 10px; border: outset 2px silver; width: 80px; text-align: center;');
serialBox.appendChild(downBox);
downBox.onclick = function(event) {
window.open('127.0.0.1:8085?compCellString=yes');
event.stopPropagation();
serialBox.removeChild(downBox);
}
}
/*
* next item is to insert a saved compCell
*/
var insertFile = document.createElementNS('http://www.w3.org/1999/xhtml','div');
insertFile.appendChild(document.createTextNode('insert file'));
insertFile.className = "context-item";
insertFile.onclick = function(event) {
if (event.target != insertFile) return;
event.stopPropagation();
var filePick = document.createElementNS('http://www.w3.org/1999/xhtml','input');
filePick.setAttribute('type','file');
filePick.setAttribute('name','filePick');
var fileForm = document.createElementNS('http://www.w3.org/1999/xhtml','form');
fileForm.setAttribute('action','127.0.0.1:8085');
fileForm.setAttribute('method','post');
fileForm.setAttribute('enctype','multipart/form-data');
fileForm.appendChild(filePick);
var submitButt = document.createElementNS('http://www.w3.org/1999/xhtml','input');
submitButt.setAttribute('type','submit');
submitButt.value = 'select';
submitButt.onclick = function() {
var insertButt = document.createElementNS('http://www.w3.org/1999/xhtml','input');
insertButt.setAttribute('type','button');
insertButt.value = 'insert';
insertButt.onclick = function() {
var http_request = HTTP.newRequest();
http_request.open('POST', '127.0.0.1:8085', true);
http_request.onreadystatechange = function() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
var compCellString = http_request.responseText;
//alert(compCellString);
var compCellRange = document.createRange();
compCellRange.selectNodeContents(g);
var compCellFragment = compCellRange.createContextualFragment(compCellString);
g.appendChild(handleCompCellFrag(compCellFragment));
fileForm.removeChild(filePick);
fileForm.removeChild(submitButt);
fileForm.removeChild(insertButt);
}
}
}
http_request.setRequestHeader('Content-Type', 'text/plain');
http_request.send("fileInsert=yes");
}
fileForm.appendChild(insertButt);
}
fileForm.appendChild(submitButt);
insertFile.appendChild(fileForm);
}
/*
* last item in menu is for closing the menu without taking any action
*/
var closeBox = document.createElementNS('http://www.w3.org/1999/xhtml','div');
closeBox.setAttribute('onclick','closeContext(event)');
closeBox.className = "context-item";
var closeText = document.createTextNode('close');
closeBox.appendChild(closeText);
/*
* append above menu items to ctgBox
*/
// create the div to hold the items
menuBox.appendChild(compIdBox);
menuBox.appendChild(cellBox);
menuBox.appendChild(branchBox);
menuBox.appendChild(headBox);
menuBox.appendChild(rotateBox);
menuBox.appendChild(textOpt);
menuBox.appendChild(serialBox);
menuBox.appendChild(insertFile);
menuBox.appendChild(closeBox);
/*
* set the class on the menuBox so it can be styled in mainstyle.css
* and position it
*/
menuBox.setAttribute('class','context-menu');
menuBox.setAttribute('style','position: absolute; left: ' + x + 'px; top: ' + y + 'px;');
/*
* attach everything to document
*/
document.getElementById('contents').appendChild(menuBox);
})()
}
/*
* handleFileInsert gets the saved compCell from the server
* and cleans it up, in particular removing step numbers, so
* I remove number from the ( )-> before the command input
* box however I leave the step num in the the <div class="stepnum">
* box because the order of the old inserted commands might be
* useful.
*/
var uniqueInsId = (function() {
var num = 1;
return function() { return num++; }
})()
function handleCompCellFrag(compCellFrag) {
// this depends on the fact that there is only one child node
// because the serialization option works on a compCell so tmp
// is the top level compCell
var tmpComp = compCellFrag.childNodes[0];
var insNum = uniqueInsId();
(function(tmpComp) {
var tmpResult = getResultBox(tmpComp);
var tmpNum = getStepNum(tmpComp);
var tmpStep = getStepBox(tmpResult);
for (var j = 0; j < tmpStep.childNodes.length; j++) {
tmpStep.removeChild(tmpStep.childNodes[j]);
}
tmpStep.appendChild(document.createTextNode(insNum+'.'+tmpNum));
tmpComp.id = 'ins'+insNum+'.'+tmpNum;
var tmpSpan = getCommandBox(tmpResult).getElementsByTagName('span')[0];
for (var j = 0; j < tmpSpan.childNodes.length; j++) {
tmpSpan.removeChild(tmpSpan.childNodes[j]);
}
tmpSpan.appendChild(document.createTextNode('(ins'+insNum+'.'+tmpNum+')->')); var tmpChildComps = getChildCompCells(tmpComp);
for (j = 0; j < tmpChildComps.length; j++) {
arguments.callee(tmpChildComps[j]);
}
})(tmpComp);
return compCellFrag;
}
/*
* showCell both shows and hides a compCell
*/
function showCell(compId) {
var compCell = document.getElementById(compId);
var children = compCell.childNodes;
for ( var i = 0; i < children.length; i++) {
if ( !CSSClass.is(children[i],'compCell') ) {
if (CSSClass.is(children[i],'hide')) {
CSSClass.remove(children[i],'hide');
} else {
CSSClass.add(children[i],'hide');
}
}
}
}
/*
*
*/
function closeContext(e) {
var tempBox = e.target.parentNode;
tempBox.parentNode.removeChild(tempBox);
}
/*
*
*/
function getX(e) {
var x = 0;
while(e) {
x += e.offsetLeft;
e = e.offsetParent;
}
return x;
}
/*
*
*/
function getY(e) {
var y = 0;
while(e) {
y += e.offsetTop;
e = e.offsetParent;
}
return y;
}
/*
* I only want to set the children elements of the compCell
* to hidden that represent the results of that particular cell
* but leave the children that are compCells visible.
* So this will recursively switch the hidden class for
* all children.
*/
function showBranch(compCell) {
var children = compCell.childNodes;
for ( var i = 0; i < children.length; i++) {
if ( children[i].className != 'compCell' ) {
if (CSSClass.is(children[i],'hide')) {
CSSClass.remove(children[i],'hide');
} else {
CSSClass.add(children[i],'hide');
}
}
}
for ( i = 0; i < children.length; i++) {
if (CSSClass.is(children[i],'compCell')) {
showBranch(children[i]);
}
}
}
/*
* I want to test to see if the present compCell has any children
* and, if not, then I'm at the head of the branch and I do nothing,
* but if it does then apply showHead recursively and hide the present
* cell. First thing is I need a list of the compCell children.
*/
function showHead(compCell) {
var compCells = new Array();
var children = compCell.childNodes;
for ( var i = 0; i < children.length; i++) {
if ( CSSClass.is(children[i],'compCell') ) {
compCells.push(children[i]);
}
}
if ( compCells.length > 0 ) { //if there are children compCells then hide contents
for ( i = 0; i < children.length; i++) {
if ( !CSSClass.is(children[i],'compCell') ) {
if (CSSClass.is(children[i],'hide')) {
CSSClass.remove(children[i],'hide');
} else {
CSSClass.add(children[i],'hide');
}
}
}
// apply showHead recursively to child compCells
for ( i = 0; i < compCells.length; i++) {
showHead(compCells[i]);
}
}
}
/* Get list of sibling compCells, if more than one
* then cyclically rotate the present one to first
*/
function rotateHead(compCell) {
var parent = compCell.parentNode;
var sibCompCells = getSibCompCells(compCell);
var j;
if ( sibCompCells.length > 1 ) { //do the rotation
// find index of compCell among siblings
for ( i = 0; i < sibCompCells.length; i++) {
if ( sibCompCells[i] == compCell ) j = i;
}
// j is index of compCell, if j != 0 rotate to 0
var swap;
for ( i = 0; i < j; i++) {
parent.appendChild(parent.removeChild(sibCompCells[i]));
}
}
}
/*
*
*/
function makeTextBox() {
// edit box
var hidden = false;
var editBox = document.createElementNS('http://www.w3.org/1999/xhtml','div');
editBox.className = 'editBox';
var formBox = document.createElementNS('http://www.w3.org/1999/xhtml','form');
var textareaBox = document.createElementNS('http://www.w3.org/1999/xhtml','textarea');
textareaBox.setAttribute('style','width: 90%; height: 200px;');
textareaBox.setAttribute('onclick','changeFocus(event)');
editBox.appendChild(formBox);
formBox.appendChild(textareaBox);
// update button
var updateButt = document.createElementNS('http://www.w3.org/1999/xhtml','span');
updateButt.appendChild(document.createTextNode('update display'));
updateButt.setAttribute('style','cursor: pointer; border: outset 2px silver; padding: 0px 5px;');
updateButt.onclick = function() {
var textString = textareaBox.value;
// apply tex2mml on tex (inline) elements here
var startTex;
var endTex;
while ( (startTex = textString.search('<tex>')) != -1 ) {
var endTex = textString.search('</tex>');
var texString = textString.slice(startTex+5,endTex);
var mmlString = tex2mml(texString,'inline');
textString = textString.slice(0,startTex) + mmlString + textString.slice(endTex+6);
}
// apply tex2mml on Tex (block) elements here
while ( (startTex = textString.search('<Tex>')) != -1 ) {
var endTex = textString.search('</Tex>');
var texString = textString.slice(startTex+5,endTex);
var mmlString = tex2mml(texString,'display');
textString = textString.slice(0,startTex) + mmlString + textString.slice(endTex+6);
}
textRange = document.createRange();
textRange.selectNodeContents(displayBox);
var textFragment = textRange.createContextualFragment(textString);
var oneBox = document.createElementNS('http://www.w3.org/1999/xhtml','div');
oneBox.appendChild(textFragment);
if (displayBox.firstChild) displayBox.removeChild(displayBox.firstChild);
displayBox.appendChild(oneBox);
}
// display
var displayBox = document.createElementNS('http://www.w3.org/1999/xhtml','div');
displayBox.className = 'displayBox';
displayBox.onclick = function(e) {
var x = e.clientX;
var y = e.clientY;
x = x + window.pageXOffset;
y = y + window.pageYOffset;
var menuBox = document.createElementNS('http://www.w3.org/1999/xhtml','div');
/*
* create switch to toggle visibility of edit box and update button
*/
var toggleBox = document.createElementNS('http://www.w3.org/1999/xhtml','div');
toggleBox.setAttribute('style','cursor: pointer;');
toggleBox.appendChild(document.createTextNode('show/hide edit box'));
toggleBox.onclick = function() {
if (hidden == false) {
CSSClass.add(editBox,'hide');
CSSClass.add(updateButt,'hide');
hidden = true;
menuBox.parentNode.removeChild(menuBox);
}
else {
CSSClass.remove(editBox,'hide');
CSSClass.remove(updateButt,'hide');
hidden = false;
menuBox.parentNode.removeChild(menuBox);
}
}
/*
* set the class on the menuBox, so it can be styled in mainstyle.css,
* and position it
*/
menuBox.setAttribute('class','context-menu');
menuBox.setAttribute('style','position: absolute; left: ' + x + 'px; top: ' + y + 'px;');
/*
* attach everything to document
*/
menuBox.appendChild(toggleBox);
document.getElementById('contents').appendChild(menuBox);
}
// textBox to hold everything
var textBox = document.createElementNS('http://www.w3.org/1999/xhtml','div');
textBox.appendChild(editBox);
textBox.appendChild(updateButt);
textBox.appendChild(displayBox);
return textBox;
}
/*
* module for manipulating CSS classes. Thanks to David Flanagan, 'Javascript The
* Definitive Guide' O'Reilly for these functions
*/
var CSSClass = {};
// Return true if element e is a member of the class c; false otherwise
CSSClass.is = function(e,c) {
if (typeof e == "string") e = document.getElementById(e);
//optimize common cases
var classes = e.className;
if (!classes) return false; // Not a member of any classes
if (classes == c) return true; // Member of just this one class
return e.className.search("\\b" + c + "\\b") != -1;
}
// Add class c to the className of element e if it is not already there.
CSSClass.add = function(e,c) {
if (typeof e == "string") e = document.getElementById(e);
if (CSSClass.is(e,c)) return; // If already a member do nothing
if (e.className) c = " " + c; // Whitespace separator if needed
e.className += c; // Append the new class to the end
}
// Remove all occurrences of class c from the className of element e
CSSClass.remove = function(e,c) {
if (typeof e == "string") e = document.getElementById(e);
e.className = e.className.replace(new RegExp("\\b" + c + "\\b\\s*","g"), "");
}
/* Module to drag an element
*
* Arguments:
*
* elementToDrag: the element that received the mousedown event or
* some containing element. It must be absolutely positioned. Its
* style.left and style.top values will be changed based on the user's
* drag.
*
* event: the Event object for the mousedown event.
*
*/
function drag(elementToDrag, event){
// The mouse position, in window coordinates, at which the
// drag event begins.
var startX = event.clientX, startY = event.clientY;
// The original position, in document coordinates, of the element
// that is going to be dragged. Since elementToDrag is absolutely positioned
// we assume that its offsetParent is the document body.
var origX = elementToDrag.offsetLeft, origY = elementToDrag.offsetTop;
// Even though the coordinates are computed in different coordinate systems
// we can still compute the difference between them and use it in the
// moveHandler() function. This works because the scrollbar position never
// changes during the drag.
var deltaX = startX - origX, deltaY = startY - origY;
// Register the event handlers that will respond to the mousemove events
// and the mouseup event that follow this mousedown event.
document.addEventListener("mousemove",moveHandler,true);
document.addEventListener("mouseup",upHandler,true);
// We've handled this event. Don't let anybody else see it.
event.preventDefault();
/*
* This is the handler that captures mousemove events when an element is
* being dragged. It is responsible for moving the element.
*/
function moveHandler(e) {
// Move the element to the current mouse position adusted as necessary by
// the offset of the initial mouse click.
elementToDrag.style.left = (e.clientX - deltaX) + "px";
elementToDrag.style.top = (e.clientY - deltaY) + "px";
// Don't let anyone else see this event.
e.stopPropagation();
}
/*
* This is the handler that captures the final mouseup event that occurs at
* the end of a drag.
*/
function upHandler(e) {
// Unregister the capturing event handlers.
document.removeEventListener("mouseup",upHandler,true);
document.removeEventListener("mousemove",moveHandler,true);
// Don't let the event propagate any further.
e.stopPropagation();
}
}
/**************************
* Pages Content Section
**************************/
var appname = "JyperDoc";
/*
*
*/
function init() {
displayTitle("<img src='../images/notebook.gif'/>" + appname);
menu();
}
/*
*
*/
function displayTitle(title) {
var banner = document.getElementById("banner");
banner.innerHTML = title;
}
/*
*
*/
function menu() {
var menu = document.getElementById("menu");
var links = document.createElementNS('http://www.w3.org/1999/xhtml', 'div');
links.setAttribute('id','links');
links.setAttribute('class','links');
/* var interp = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
interp.setAttribute('id','interpreter');
//interp.setAttribute('class','nouse');
//interp.setAttribute('href','jyperdoc.xhtml');
interp.appendChild(document.createTextNode('Use '));
*/
var editor = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
editor.setAttribute('id','editor');
editor.setAttribute('href','javascript:void%200');
editor.setAttribute('onclick',"window.open('editor.xhtml')");
editor.appendChild(document.createTextNode('Editor '));
var browser = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
browser.setAttribute('id','browser');
browser.setAttribute('onclick',"window.open('man0page.xhtml')");
browser.appendChild(document.createTextNode('Browse'));
var abook = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
abook.setAttribute('id','axbook');
abook.setAttribute('onclick',"window.open('../axbook/book-contents.xhtml')");
abook.appendChild(document.createTextNode('Axiom Book'));
//links.appendChild(interp);
//links.appendChild(editor);
//links.appendChild(browser);
links.appendChild(abook);
menu.appendChild(links);
}
/*
*
*/
function markInUse(e) {
var targ = e.target;
document.getElementById(targ.id).setAttribute('class','inuse');
//link.style.background-color="#1e90ff";
}
/*
*
*/
function interpreter() {
var contents = document.getElementById("contents");
var rootcompcell = document.createElementNS('http://www.w3.org/1999/xhtml', 'div');
rootcompcell.setAttribute('class','rootCompCell');
rootcompcell.setAttribute('onclick','javascript:showContext(event);');
rootcompcell.setAttribute('onkeyup','javascript:resize_textarea(event.target);');
var command = document.createElementNS('http://www.w3.org/1999/xhtml','div');
command.setAttribute('class','command');
var comm = document.createElementNS('http://www.w3.org/1999/xhtml','textarea');
comm.setAttribute('id','comm');
comm.setAttribute('class','cell_input');
comm.setAttribute('name','command');
comm.setAttribute('rows','1');
comm.setAttribute('cols','80');
comm.setAttribute('onkeypress','keyPressed(event);');
comm.setAttribute('onfocus','onFocus(event);');
command.appendChild(comm);
rootcompcell.appendChild(command);
contents.appendChild(rootcompcell);
}
/*
*
*/
function editor() {
var contents = document.getElementById("contents");
contents.innerHTML = "<div id='buttons'><button id='compile'>)compile</button>" +
"<button id='read'>)read</button>" +
"<button id='open'>open</button>" +
"<button id='save'>save</button>" +
"</div>" +
"<div class='editor'>" +
"<textarea id='myCpWindow' " +
"rows='30' " +
"cols='80' " +
"class='codepress javascript linenumbers'" +
">--This is a test.</textarea></div>";
var selecttags = document.getElementsByTagName("select");
for (var i = 0; i < selecttags.length; i++)
selecttags[i].style.display="none";
}
/*************************
* Database Browse Section
************************/
function getValues() {
var query = window.location.search;
// Skip the leading ?, which should always be there,
// but be careful anyway
if (query.substring(0, 1) == '?') {
query = query.substring(1);
}
var data = query.split(',');
for (i = 0; (i < data.length); i++) {
data[i] = unescape(data[i]);
}
if (data[0] == 'getconstructorhtml')
makeRequestServer(data[0],data[1]);
}
/*
*
*/
function makeRequestServer(command, value) {
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
http_request = false;
}
}
if (!http_request && typeof XMLHttpRequest != 'undefined') {
try {
http_request = new XMLHttpRequest();
}
catch (e) {
http_request = false;
}
}
if (!http_request && window.createRequest) {
try {
http_request = window.createRequest();
}
catch (e) {
http_request = false;
}
}
http_request.open('POST', '127.0.0.1:8085', true);
http_request.onreadystatechange = handleResponse;
http_request.setRequestHeader('Content-Type', 'text/plain');
http_request.send(command+"="+value);
}
/*
*
*/
function handleResponse() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
document.getElementById("contents-browse").innerHTML = http_request.responseText;
}
else {
alert('There was a problem with the request.'+ http_request.statusText);
}
}
}
/* HTTP.newRequest() utility from David Flanagan */
// list of XMLHttpRequest creation factories to try
var HTTP = {};
HTTP._factories = [
function() { return new XMLHttpRequest(); },
function() { return new ActiveXObject("Msxml2.XMLHTTP"); },
function() { return new ActieXObject("Microsoft.XMLHTTP"); }
];
HTTP._factory = null;
HTTP.newRequest = function() {
if (HTTP._factory != null) return HTTP._factory();
for (var i = 0; i < HTTP._factories.length; i++) {
try {
var factory = HTTP._factories[i];
var request = factory();
if (request != null) {
HTTP._factory = factory;
return request;
}
}
catch(e) {
continue;
}
}
// If we get here we failed
HTTP._factory = function() {
throw new Error("XMLHttpRequest not supported");
}
HTTP._factory();
}
|
const express = require('express');
const { MongoClient } = require('mongodb');
const cors = require('cors')
const app = express();
app.use(cors());
app.use(express.json());
const uri = "mongodb+srv://mymongodb1:xfewhmeeRskRn1dO@cluster0.jodbj.mongodb.net/myFirstDatabase?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
client.connect(err => {
async function run() {
try {
await client.connect();
const database = client.db("master");
const usersCollection = database.collection("users");
// get api
app.get('/users', async (req, res) => {
const cursor = usersCollection.find({});
const users = await cursor.toArray();
res.send(users);
})
// post api
app.post('/users', async (req, res) => {
const newUser = req.body;
const result = await usersCollection.insertOne(newUser);
console.log('got new user', req.body);
console.log('added user', result);
res.json(result);
})
}
finally {
// await client.close();
}
}
run().catch(console.dir);
});
// if hitted undefined
const port = process.env.PORT || 5000;
app.get('/', (req, res) => {
res.send('nodemon is awesome');
});
app.listen(port, () => {
console.log('listening to port', port);
});
// user : mymongodb1
// pass : xfewhmeeRskRn1dO
// const users =[
// {id: 0, name: 'Asha', email: 'asha123@gmail.com', phone : '01873626488'},
// {id: 1, name: 'jisnu', email: 'jisnu@gmail.com', phone : '01873626488'},
// {id: 2, name: 'popy', email: 'popy@gmail.com', phone : '01873626488'},
// {id: 3, name: 'tanu', email: 'tanu@gmail.com', phone : '01873626488'},
// {id: 4, name: 'manu', email: 'manu@gmail.com', phone : '01873626488'},
// {id: 5, name: 'mitu', email: 'mitu@gmail.com', phone : '01873626488'},
// {id: 6, name: 'titu', email: 'titu@gmail.com', phone : '01873626488'}
// ]
// app.get('/users', (req, res) => {
// const search = req.query.search;
// if(search) {
// const searchResult = users.filter(user => user.name.toLocaleLowerCase().includes(search));
// res.send(searchResult);
// }
// else{
// res.send(users)
// }
// });
// // app.METHOD
// app.post('/users', (req, res) => {
// const newUser = req.body;
// newUser.id = users.length;
// users.push(newUser);
// console.log('hitting the post', req.body)
// // res.send('inside post')
// res.json(newUser)
// })
// app.get('/fruits', (req, res) => {
// res.send(['aam', 'kola', 'apple'])
// });
// app.get('/fruits/kola/kashmiri', (req, res) => {
// res.send('get kashmiri kola')
// });
// app.get('/users/:id', (req, res) => {
// const id = req.params.id;
// const user = users[id];
// res.send(user);
// }); |
module.exports = {
static: require('./staticController'),
auth: require('./authController')
}; |
import React from 'react';
import ReactDOM from 'react-dom';
import { combineReducers, applyMiddleware, createStore } from 'redux';
import { Provider } from 'react-redux';
import thunk from 'redux-thunk'
import { ConnectedRouter, routerReducer, routerMiddleware, push } from 'react-router-redux'
import createHistory from 'history/createBrowserHistory'
import getBuyList from './reducers/buyReducer';
import login from './reducers/loginReducer';
import getInventory from './reducers/sellReducer';
import getQuestsList from './reducers/questsReducer';
import user from './reducers/userReducer';
import getMySellItems from './reducers/mySellingReducer'
import MainPage from './components/MainPage'
import 'bootstrap/dist/css/bootstrap.css';
import '../resources/static/styles/main.css';
import './images/Logo.png';
import 'material-design-icons/iconfont/material-icons.css';
import './libs/jquery-cookie/jquery.cookie.js'
import SockJS from "sockjs-client"
let Stomp = require("stompjs/lib/stomp.js").Stomp;
const history = createHistory();
const middleware = routerMiddleware(history);
const reducer = combineReducers({getBuyList, getMySellItems, login, getInventory, getQuestsList, user, routing: routerReducer});
const store = createStore(reducer, applyMiddleware(thunk, middleware));
class MainPageWithRouter extends React.Component{
render(){return(
<ConnectedRouter history={history}>
<MainPage />
</ConnectedRouter>
)}
}
export var stompClient = null;
let socket = new SockJS('/updateItems');
stompClient = Stomp.over(socket);
ReactDOM.render(
<Provider store={store}>
<MainPageWithRouter/>
</Provider>, document.getElementById('root')
); |
/// <reference types="Cypress" />
describe('user tests', () =>{
it('get users', () => {
cy.get_usuarios().then((response) => {
expect(response.status).to.eq(200)
})
})
}) |
import mongoose from 'mongoose';
let CandidateSchema = new mongoose.Schema({
name: {type: String, require: true},
lastname: {type: String, require: true},
document: {type: String, require: true},
birthdate: {type: String, require: true},
votes: {type: Number, require: true, default: 0},
img_main: {type: String, require: true, default: "candidate.jpg"}
});
export default mongoose.model('Candidate', CandidateSchema) |
require('styles/Apply.scss');
require('styles/App.scss');
import React from 'react';
import {browserHistory } from 'react-router'
import Modal from 'react-modal'
let redBg = require('../images/red_bg.jpg');
const customStyles = {
content : {
top : '50%',
left : '50%',
right : 'auto',
bottom : 'auto',
marginRight : '-50%',
transform : 'translate(-50%, -50%)',
width : '50%'
}
};
class ApplyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
area: [{value: 'chaozhou', label: 'ๆฝฎๅท่ตๅบ'}, {value: 'shantou', label: 'ๆฑๅคด่ตๅบ'}],
selectArea: '',
num: 0,
isResultPage: false,
modalIsOpen: false,
modalText: ''
}
document.body.style.backgroundImage = 'url(' + redBg + ')';
this.doApply = this.doApply.bind(this);
this.openModal = this.openModal.bind(this);
this.closeModal = this.closeModal.bind(this);
}
componentWillUnmount() {
document.body.style.backgroundImage = '';
}
doApply() {
//console.log("saiqu = ", this.refs.areaSelect.value);
if(this.refs.name.value.length == 0) {
this.setState({
modalText: '่ฏท่พๅ
ฅๅงๅ!'
});
this.openModal();
} else if(this.refs.phone.value.length == 0 || this.refs.phone.value.length != 11) {
this.setState({
modalText: '่ฏท่พๅ
ฅๅ็กฎ็ๆๆบๅท็ !'
});
this.openModal();
} else if(this.refs.idCard.value.length == 0 || this.refs.idCard.value.length != 18) {
this.setState({
modalText: '่ฏท่พๅ
ฅๅ็กฎ็่บซไปฝ่ฏๅท็ !'
});
this.openModal();
} else {
this.setState({
selectArea: this.refs.areaSelect.value,
isResultPage: true,
num: 101
});
}
}
openModal() {
//this.setState({modalIsOpen: true});
confirm('123');
}
closeModal() {
this.setState({modalIsOpen: false});
}
onChange1(value, selectedOptions) {
console.log(value, selectedOptions);
}
render() {
let infoClass;
let nameClass;
let disabled;
let btnText;
if(this.state.isResultPage) {
infoClass = 'input result';
nameClass = 'info-line';
disabled = 'disabled';
btnText = 'ๆฅๅๆๅ';
} else {
infoClass = 'input';
nameClass = 'info-line top-text-margin';
disabled = '';
btnText = '็นๅปๆฅๅ';
}
return (
<div className="apply-component crossCenterH">
<div className="title">็ฌฌไบๅญฃ ไธญๅฝๆฐๆญๅฃฐ</div>
<div className="title">ๅ
จๅฝๅ
จๅฝๅ
จๅฝๅ
จๅฝๅ
จๅฝ</div>
{ this.state.isResultPage ?
<div className="info-line top-text-margin">
<div className="text centerV">NO:</div>
<input ref="num" value={this.state.num} className={infoClass} type="text" disabled={disabled}/>
</div>
: null
}
<div className={nameClass}>
<div className="text centerV">ๅงๅ:</div>
<input ref="name" className={infoClass} type="text" disabled={disabled}/>
</div>
<div className="info-line">
<div className="text centerV">ๆๆบๅท็ :</div>
<input ref="phone" className={infoClass} type="text" disabled={disabled}/>
</div>
<div className="info-line">
<div className="text centerV">่ตๅบ:</div>
{ this.state.isResultPage ?
<input ref="areaInput" value={this.state.selectArea} className={infoClass} type="text" disabled={disabled}/>
: <select ref="areaSelect">
{this.state.area.map((it, index) => {
return (<option key={index} value={it.value}>{it.label}</option>);
})}
</select>
}
</div>
<div className="info-line">
<div className="text centerV">่บซไปฝ่ฏๅท็ :</div>
<input ref="idCard" className={infoClass} type="text" disabled={disabled}/>
</div>
<div className="button center" onClick={
() => {
if(this.state.isResultPage) {
browserHistory.push('/');
} else {
this.doApply();
}
}
}>{btnText}</div>
<Modal isOpen={this.state.modalIsOpen} style={customStyles} contentLabel="Modal">
<div className="crossCenterH">
<div className="modal-content">{this.state.modalText}</div>
<button className="modal-button" onClick={this.closeModal}>ๅฅฝ็</button>
</div>
</Modal>
</div>
);
}
}
ApplyComponent.defaultProps = {
};
export default ApplyComponent;
|
//THIS LOGIC WILL EVENTUALLY GETS MOVED TO SERVER SI
/*All the general form items register here*/
var formData = [userInterface.titleData,userInterface.subtitleData,userInterface.legendDatageneral,userInterface.legendDataitem,userInterface.
legendDataMarker,userInterface.plotareaData,userInterface.plotGeneralData,userInterface.plotAnimationData,userInterface.
plotHoverState,userInterface.hoverMarker,userInterface.plotMarkerData,userInterface.tooltip,userInterface.
valueBox,userInterface.scaleData,userInterface.scaleRData,userInterface.previewData];
/*All series items register here*/
var seriesData = [userInterface.seriesGeneralData,userInterface.seriesAnimationData,userInterface.seriesHoverState,userInterface.
serieshoverMarker,userInterface.seriesMarkerData,userInterface.seriestooltip,userInterface.seriesvalueBox];
/*All scale items register here*/
var scaleData = [userInterface.scaleX,userInterface.scaleXGuid,userInterface.scaleXLabel,userInterface.scaleXmarkers,userInterface.
scaleXrefLine,userInterface.scaleXTick,userInterface.scaleXItem,userInterface.scaleY,userInterface.scaleYGuid,userInterface.scaleYLabel,userInterface.scaleYmarkers,userInterface.
scaleYrefLine,userInterface.scaleYTick,userInterface.scaleYItem ];
window.onload =function load_inputs() {
//If our textarea is not empty it means that we are eddititng so we can draw the chart based on that:
if (document.getElementById("zingcharts-javaScript").value.trim() != "") {
chartData = JSON.parse(document.getElementById('zingcharts-javaScript').value);
document.getElementById('whichChart').value = chartData['graphset'][0]["type"] ;
drawChart();
};
/* All Scale data goes here */
var seriesElement = document.getElementsByClassName("scl-el");
var linebreak = "";
for (var i = 0; i < seriesElement.length; i++) {
for (var m=0; m <scaleData.length;m++) {
if (seriesElement[i].getAttribute('data-category') == scaleData[m]["category"] && seriesElement[i].getAttribute('data-sub-category') == scaleData[m]["subcategory"]) {
for (j=0; j<scaleData[m].inputs.length; j++) {
linebreak = scaleData[m].inputs[j].divider ? "<hr>" :" ";
switch(scaleData[m].inputs[j].type){
case('checkbox') :
seriesElement[i].innerHTML += linebreak
+"<label>"+ scaleData[m].inputs[j].label+": </label>"
+"<input type='checkbox' id='"+scaleData[m].inputs[j].id+"' data-category='"
+scaleData[m]["category"]+"' data-key='"+scaleData[m].inputs[j].key+"' dat-subcat='"+
scaleData[m].subcategory
+"' onchange='modify_chart_scale(this)'><br>";
break;
case("color") :
var defaultVal= '';
if (typeof scaleData[m].inputs[j].defValue != 'undefined' && scaleData[m].inputs[j].defValue != '') {
defaultVal = scaleData[m].inputs[j].defValue;
} else {
defaultVal = "#000000";
}
seriesElement[i].innerHTML += linebreak
+"<label>"+ scaleData[m].inputs[j].label+": </label>"
+"<input type='color' id='"+scaleData[m].inputs[j].id+"' data-category='"
+scaleData[m]["category"]+"' data-key='"+scaleData[m].inputs[j].key+"' dat-subcat='"+
scaleData[m].subcategory +"' onchange='modify_chart_scale(this)' value='"+defaultVal+"'><br>";
break;
case("text") :
var defaultVal= '';
if (typeof scaleData[m].inputs[j].defValue != 'undefined' ) {
defaultVal = scaleData[m].inputs[j].defValue;
};
seriesElement[i].innerHTML += linebreak
+"<label>"+ scaleData[m].inputs[j].label+": </label>"
+"<input type='text' id='"+scaleData[m].inputs[j].id+"' data-category='"
+scaleData[m]["category"]+"' data-key='"+scaleData[m].inputs[j].key+"' dat-subcat='"+
scaleData[m].subcategory +"' onKeyUp='modify_chart_scale(this)' value='"+defaultVal+"'><br>";
break;
case ('select'):
var options = ''
var optionLable = '';
for (var k=0; k<scaleData[m].inputs[j].values.length;k++) {
if (scaleData[m].inputs[j].labels) {
optionLable = scaleData[m].inputs[j].labels[k];
} else {
optionLable = scaleData[m].inputs[j].values[k];
}
options += "<option value='"+scaleData[m].inputs[j].values[k]+"'>"+optionLable +"</option>"
};
seriesElement[i].innerHTML += linebreak
+"<label>"+ scaleData[m].inputs[j].label+": </label>"
+"<select id='"+scaleData[m].inputs[j].id+"' data-category='"+scaleData[m]["category"]
+"' data-key='"+scaleData[m].inputs[j].key+"' dat-subcat='"+
scaleData[m].subcategory
+"'onchange='modify_chart_scale(this)'><option></option> "+options+"</select><br>";
break;
case ("range") :
//oninput is for IE compatibility.
seriesElement[i].innerHTML += linebreak
+"<label>"+ scaleData[m].inputs[j].label+": </label>"
+"<input type='range' id='"+scaleData[m].inputs[j].id+"' data-category='"
+scaleData[m]["category"]+"' data-key='"+scaleData[m].inputs[j].key+"' dat-subcat='"+
scaleData[m].subcategory
+"' min='"+scaleData[m].inputs[j].min+"' max='"+scaleData[m].inputs[j].max+"' step='"+scaleData[m].inputs[j].step
+"' onchange='modify_chart_scale(this)'"
+" oninput='modify_chart_scale(this)'><br>";
break;
case ("bgcolor") :
seriesElement[i].innerHTML += linebreak +"<label> Background:</label>";//ID here represents category
seriesElement[i].innerHTML += "<select id='backgroundType"+scaleData[m].inputs[j].id+"' data-category ='"+scaleData[m]["category"]+"' dat-subcat='"+
scaleData[m]["subcategory"]+"' data-count='"+seriesConfigId
+"'onchange='set_bg_type_series(this,this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"),this.getAttribute(\"data-count\"))'>"
+"<option value='solid'>Solid</option><option value='gradiant'>Gradiant</option></select><br>"
+"<label> Background color 1 : </label> <input type='color' id='backgroundColor1"+scaleData[m].inputs[j].id+"' data-category ='"+scaleData[m]["category"]
+"' dat-subcat='"+scaleData[m]["subcategory"]
+"' onchange='set_bg_color_series(this,this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"))'><br>"
+"<label> Background color 2 : </label> <input type='color' id='backgroundColor2"+scaleData[m].inputs[j].id+"' data-category ='"+scaleData[m]["category"]
+"' dat-subcat='"+scaleData[m]["subcategory"]
+"' onchange='set_bg_color_series(this.previousElementSibling.previousElementSibling.previousElementSibling,this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"))' style='visibility :hidden'><br>";
break;
case ("border") :
seriesElement[i].innerHTML += linebreak +"<label> Border :</label>";//ID here represents category
seriesElement[i].innerHTML += "<input type='checkbox' data-category ='"+scaleData[m]["category"]+"' dat-subcat='"+scaleData[m]["subcategory"]+"' id='border"+scaleData[m].inputs[j].id
+"' onchange='set_border_series(this.nextElementSibling.nextElementSibling.nextElementSibling,this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"))'><br>";
seriesElement[i].innerHTML += "<label> Border width :</label><input type='text' id='borderWidth"+scaleData[m].inputs[j].id+"' data-category ='"+scaleData[m]["category"]+"' dat-subcat='"
+scaleData[m]["subcategory"]+"' onKeyUp='set_border_series(this,this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"))' value='1px'><br>";
seriesElement[i].innerHTML += " <label> Border color:</label><input type='color' id='borderColor"+scaleData[m].inputs[j].id+"' data-category ='"+scaleData[m]["category"]+"' dat-subcat='"
+scaleData[m]["subcategory"]+"'onchange='set_border_series(this.previousElementSibling.previousElementSibling.previousElementSibling,this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"))'><br>";
break;
case ("line") :
seriesElement[i].innerHTML += linebreak + "<label>Line color :</lable>";
seriesElement[i].innerHTML += "<input type='color' id='lineColor"+scaleData[m].inputs[j].id+"' data-category ='"+scaleData[m]["category"]+"' dat-subcat='"+scaleData[m]["subcategory"]
+"' onchange='set_line_series(this.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling,this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"))' value='#000000'><br>";
seriesElement[i].innerHTML += "<label>Line width :</label> <input type='text' id='lineWidth"+scaleData[m].inputs[j].id+"' data-category ='"+scaleData[m]["category"]+"' dat-subcat='"+scaleData[m]["subcategory"]
+"' onKeyUp='set_line_series(this.nextElementSibling.nextElementSibling.nextElementSibling,this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"))' value='2px'><br>";
seriesElement[i].innerHTML += "<label> Line style :</label>"
+"<select id='lineStyle"+scaleData[m].inputs[j].id+"' data-category ='"+scaleData[m]["category"]+"' dat-subcat='"+scaleData[m]["subcategory"]+"' onchange='set_line_series(this,this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"))'>"
+"<option></option>"
+"<option value='solid'> Solid</option>"
+"<option value='dotted'> Dotted</option>"
+"<option value='dashed'> Dashed</option>"
+"</select><br>";
seriesElement[i].innerHTML +="<label>Line gap size :</label> <input type='text' id='lineGapSize"+scaleData[m].inputs[j].id+"' data-category ='"+scaleData[m]["category"]+"' dat-subcat='"+scaleData[m]["subcategory"]
+"' onKeyUp='set_line_series(this.previousElementSibling.previousElementSibling.previousElementSibling,this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"))' value='2px' ><br>";
seriesElement[i].innerHTML +="<label>Line segment size :</label> <input type='text' id='lineSegmentSize"+scaleData[m].inputs[j].id+"' data-category ='"+scaleData[m]["category"]+"' dat-subcat='"+scaleData[m]["subcategory"]
+"' onKeyUp='set_line_series(this.previousElementSibling.previousElementSibling.previousElementSibling.previousElementSibling.previousElementSibling.previousElementSibling,this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"))' value='2px' ><br>";
break;
};
};
};
};
};
/* ALL the series types will go here */
var seriesElement = document.getElementsByClassName("series-el");
var linebreak = "";
for (var i = 0; i < seriesElement.length; i++) {
for (var m=0; m <seriesData.length;m++) {
if (seriesElement[i].getAttribute('data-category') == seriesData[m]["category"] && seriesElement[i].getAttribute('data-sub-category') == seriesData[m]["subcategory"]) {
for (j=0; j<seriesData[m].inputs.length; j++) {
linebreak = seriesData[m].inputs[j].divider ? "<hr>" :" ";
switch(seriesData[m].inputs[j].type){
case('checkbox') :
seriesElement[i].innerHTML += linebreak
+"<label>"+ seriesData[m].inputs[j].label+": </label>"
+"<input type='checkbox' id='"+seriesData[m].inputs[j].id+"' data-category='"
+seriesData[m]["category"]+"' data-key='"+seriesData[m].inputs[j].key+"' data-subcat='"+
seriesData[m].subcategory
+"' onchange='modify_chart_series(this, this.type,this.getAttribute(\"data-key\"),this.getAttribute(\"data-category\"),this.getAttribute(\"data-subcat\"))'><br>";
break;
case("text") :
var defaultVal= '';
if (typeof seriesData[m].inputs[j].defValue != 'undefined' ) {
defaultVal = seriesData[m].inputs[j].defValue;
};
seriesElement[i].innerHTML += linebreak
+"<label>"+ seriesData[m].inputs[j].label+": </label>"
+"<input type='text' id='"+seriesData[m].inputs[j].id+"' data-category='"
+seriesData[m]["category"]+"' data-key='"+seriesData[m].inputs[j].key+"' dat-subcat='"+
seriesData[m].subcategory +"' onKeyUp='modify_chart_series(this,this.type,this.getAttribute(\"data-key\"),this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"))' value='"+defaultVal+"'><br>";
break;
case ('select'):
var options = ''
var optionLable = '';
for (var k=0; k<seriesData[m].inputs[j].values.length;k++) {
if (seriesData[m].inputs[j].labels) {
optionLable = seriesData[m].inputs[j].labels[k];
} else {
optionLable = seriesData[m].inputs[j].values[k];
}
options += "<option value='"+seriesData[m].inputs[j].values[k]+"'>"+optionLable +"</option>"
};
seriesElement[i].innerHTML += linebreak
+"<label>"+ seriesData[m].inputs[j].label+": </label>"
+"<select id='"+seriesData[m].inputs[j].id+"' data-category='"+seriesData[m]["category"]
+"' data-key='"+seriesData[m].inputs[j].key+"' dat-subcat='"+
seriesData[m].subcategory
+"'onchange='modify_chart_series(this,this.type,this.getAttribute(\"data-key\"),this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"))'><option></option> "+options+"</select><br>";
break;
case ("range") :
//oninput is for IE compatibility.
seriesElement[i].innerHTML += linebreak
+"<label>"+ seriesData[m].inputs[j].label+": </label>"
+"<input type='range' id='"+seriesData[m].inputs[j].id+"' data-category='"
+seriesData[m]["category"]+"' data-key='"+seriesData[m].inputs[j].key+"' dat-subcat='"+
seriesData[m].subcategory
+"' min='"+seriesData[m].inputs[j].min+"' max='"+seriesData[m].inputs[j].max+"' step='"+seriesData[m].inputs[j].step
+"' onchange='modify_chart_series(this.id,this.type,this.getAttribute(\"data-key\"),this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"))'"
+" oninput='modify_chart_series(this,this.type,this.getAttribute(\"data-key\"),this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"))'><br>";
break;
case ("bgcolor") :
seriesElement[i].innerHTML += linebreak +"<label> Background:</label>";//ID here represents category
seriesElement[i].innerHTML += "<select id='backgroundType"+seriesData[m].inputs[j].id+"' data-category ='"+seriesData[m]["category"]+"' dat-subcat='"+
seriesData[m]["subcategory"]+"' data-count='"+seriesConfigId
+"'onchange='set_bg_type_series(this,this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"),this.getAttribute(\"data-count\"))'>"
+"<option value='solid'>Solid</option><option value='gradiant'>Gradiant</option></select><br>"
+"<label> Background color 1 : </label> <input type='color' id='backgroundColor1"+seriesData[m].inputs[j].id+"' data-category ='"+seriesData[m]["category"]
+"' dat-subcat='"+seriesData[m]["subcategory"]
+"' data-bgtype='solid' onchange='set_bg_color_series(this,this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"))'><br>"
+"<label> Background color 2 : </label> <input type='color' id='backgroundColor2"+seriesData[m].inputs[j].id+"' data-category ='"+seriesData[m]["category"]
+"' dat-subcat='"+seriesData[m]["subcategory"]
+"' onchange='set_bg_color_series(this.previousElementSibling.previousElementSibling.previousElementSibling,this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"))' style='visibility :hidden'><br>";
break;
case ("border") :
seriesElement[i].innerHTML += linebreak +"<label> Border :</label>";//ID here represents category
seriesElement[i].innerHTML += "<input type='checkbox' data-category ='"+seriesData[m]["category"]+"' dat-subcat='"+seriesData[m]["subcategory"]+"' id='border"+seriesData[m].inputs[j].id
+"' onchange='set_border_series(this.nextElementSibling.nextElementSibling.nextElementSibling,this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"))'><br>";
seriesElement[i].innerHTML += "<label> Border width :</label><input type='text' id='borderWidth"+seriesData[m].inputs[j].id+"' data-category ='"+seriesData[m]["category"]+"' dat-subcat='"
+seriesData[m]["subcategory"]+"' onKeyUp='set_border_series(this,this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"))' value='1px'><br>";
seriesElement[i].innerHTML += " <label> Border color:</label><input type='color' id='borderColor"+seriesData[m].inputs[j].id+"' data-category ='"+seriesData[m]["category"]+"' dat-subcat='"
+seriesData[m]["subcategory"]+"'onchange='set_border_series(this.previousElementSibling.previousElementSibling.previousElementSibling,this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"))'><br>";
break;
case ("line") :
seriesElement[i].innerHTML += linebreak + "<label>Line color :</lable>";
seriesElement[i].innerHTML += "<input type='color' id='lineColor"+seriesData[m].inputs[j].id+"' data-category ='"+seriesData[m]["category"]+"' dat-subcat='"+seriesData[m]["subcategory"]
+"' onchange='set_line_series(this.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling,this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"))' value='#000000'><br>";
seriesElement[i].innerHTML += "<label>Line width :</label> <input type='text' id='lineWidth"+seriesData[m].inputs[j].id+"' data-category ='"+seriesData[m]["category"]+"' dat-subcat='"+seriesData[m]["subcategory"]
+"' onKeyUp='set_line_series(this.nextElementSibling.nextElementSibling.nextElementSibling,this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"))' value='2px'><br>";
seriesElement[i].innerHTML += "<label> Line style :</label>"
+"<select id='lineStyle"+seriesData[m].inputs[j].id+"' data-category ='"+seriesData[m]["category"]+"' dat-subcat='"+seriesData[m]["subcategory"]+"' onchange='set_line_series(this,this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"))'>"
+"<option></option>"
+"<option value='solid'> Solid</option>"
+"<option value='dotted'> Dotted</option>"
+"<option value='dashed'> Dashed</option>"
+"</select><br>";
seriesElement[i].innerHTML +="<label>Line gap size :</label> <input type='text' id='lineGapSize"+seriesData[m].inputs[j].id+"' data-category ='"+seriesData[m]["category"]+"' dat-subcat='"+seriesData[m]["subcategory"]
+"' onKeyUp='set_line_series(this.previousElementSibling.previousElementSibling.previousElementSibling,this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"))' value='2px' ><br>";
seriesElement[i].innerHTML +="<label>Line segment size :</label> <input type='text' id='lineSegmentSize"+seriesData[m].inputs[j].id+"' data-category ='"+seriesData[m]["category"]+"' dat-subcat='"+seriesData[m]["subcategory"]
+"' onKeyUp='set_line_series(this.previousElementSibling.previousElementSibling.previousElementSibling.previousElementSibling.previousElementSibling.previousElementSibling,this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"))' value='2px' ><br>";
break;
};
};
};
};
};
/* Lables will go here */
var lblArrayElemnt = document.getElementsByClassName("lbl-el");
for (var i= 0 ; i< lblArrayElemnt.length;i++) { // This should be only one
for (var j = 0; j<userInterface.labelData.inputs.length; j++ ) {
var linebreak = (userInterface.labelData.inputs[j].divider) ? "<hr>" : "";
switch(userInterface.labelData.inputs[j].type){
case('checkbox') :
lblArrayElemnt[i].innerHTML += linebreak
+"<label>"+ userInterface.labelData.inputs[j].label+": </label>"
+"<input type='checkbox' id='"+userInterface.labelData.inputs[j].id+"' data-category='"
+userInterface.labelData["category"]+"' data-key='"+userInterface.labelData.inputs[j].key+"' dat-subcat='"+
userInterface.labelData.subcategory+"' data-count='"+labelConfigId
+"'onchange='ZCWP.label.modify_chart_label(this.id, this.type,this.getAttribute(\"data-key\"),this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"),this.getAttribute(\"data-count\"))'><br>";
break;
case("text") :
var defaultVal= '';
if (typeof userInterface.labelData.inputs[j].defValue != 'undefined' ) {
defaultVal = userInterface.labelData.inputs[j].defValue;
};
lblArrayElemnt[i].innerHTML += linebreak
+"<label>"+ userInterface.labelData.inputs[j].label+": </label>"
+"<input type='text' id='"+userInterface.labelData.inputs[j].id+"' data-category='"
+userInterface.labelData["category"]+"' data-key='"+userInterface.labelData.inputs[j].key+"' dat-subcat='"+
userInterface.labelData.subcategory+"' data-count='"+labelConfigId
+"' onchange='ZCWP.label.modify_chart_label(this.id,this.type,this.getAttribute(\"data-key\"),this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"),this.getAttribute(\"data-count\"))' value='"+defaultVal+"'><br>";
break;
case("color") :
var defaultVal= '';
if (typeof userInterface.labelData.inputs[j].defValue != 'undefined' && userInterface.labelData.inputs[j].defValue !='') {
defaultVal = userInterface.labelData.inputs[j].defValue;
} else {
defaultVal = "#000000";
}
lblArrayElemnt[i].innerHTML += linebreak
+"<label>"+ userInterface.labelData.inputs[j].label+": </label>"
+"<input type='color' id='"+userInterface.labelData.inputs[j].id+"' data-category='"
+userInterface.labelData["category"]+"' data-key='"+userInterface.labelData.inputs[j].key+"' dat-subcat='"+
userInterface.labelData.subcategory+"' data-count='"+labelConfigId
+"' onchange='ZCWP.label.modify_chart_label(this.id,this.type,this.getAttribute(\"data-key\"),this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"),this.getAttribute(\"data-count\"))' value='"+defaultVal+"'><br>";
break;
case ('select'):
var options = ''
var optionLable = '';
for (var k=0; k<userInterface.labelData.inputs[j].values.length;k++) {
if (userInterface.labelData.inputs[j].labels) {
optionLable = userInterface.labelData.inputs[j].labels[k];
} else {
optionLable = userInterface.labelData.inputs[j].values[k];
}
options += "<option value='"+userInterface.labelData.inputs[j].values[k]+"'>"+optionLable +"</option>"
};
lblArrayElemnt[i].innerHTML += linebreak
+"<label>"+ userInterface.labelData.inputs[j].label+": </label>"
+"<select id='"+userInterface.labelData.inputs[j].id+"' data-category='"+userInterface.labelData["category"]
+"' data-key='"+userInterface.labelData.inputs[j].key+"' dat-subcat='"+userInterface.labelData.subcategory+"' data-count='"+labelConfigId
+"'onchange='ZCWP.label.modify_chart_label(this.id,this.type,this.getAttribute(\"data-key\"),this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"),this.getAttribute(\"data-count\"))'><option></option> "+options+"</select><br>";
break;
case ("range") :
//oninput is for IE compatibility.
lblArrayElemnt[i].innerHTML += linebreak
+"<label>"+ userInterface.labelData.inputs[j].label+": </label>"
+"<input type='range' id='"+userInterface.labelData.inputs[j].id+"' data-category='"
+userInterface.labelData["category"]+"' data-key='"+userInterface.labelData.inputs[j].key+"' dat-subcat='"+
userInterface.labelData.subcategory+"' min='"+userInterface.labelData.inputs[j].min+"' max='"+userInterface.labelData.inputs[j].max+"' step='"+userInterface.labelData.inputs[j].step+"' data-count='"+labelConfigId
+"'onchange='ZCWP.label.modify_chart_label(this.id,this.type,this.getAttribute(\"data-key\"),this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"),this.getAttribute(\"data-count\"))'"
+" oninput='ZCWP.label.modify_chart_label(this.id,this.type,this.getAttribute(\"data-key\"),this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"),this.getAttribute(\"data-count\"))'><br>";
break;
case ("bgcolor") :
lblArrayElemnt[i].innerHTML += linebreak +"<label> Background:</label>";
lblArrayElemnt[i].innerHTML += "<select id='backgroundType"+userInterface.labelData.inputs[j].id+"' data-category ='"+userInterface.labelData["category"]+"' data-count='"+labelConfigId
+"'dat-subcat='"+ userInterface.labelData["subcategory"]+"'onchange='ZCWP.label.set_bg_type_label(this.id,this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"),this.getAttribute(\"data-count\"))'>"
+"<option value='solid'>Solid</option><option value='gradiant'>Gradiant</option></select><br>"
+"<label> Background color 1 : </label> <input type='color' id='backgroundColor1"+userInterface.labelData.inputs[j].id+"' data-category ='"+userInterface.labelData["category"]
+"' dat-subcat='"+userInterface.labelData["subcategory"]+"' data-count='"+labelConfigId
+"' data-bgtype='solid' onchange='ZCWP.label.set_bg_color_label(this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"),this.getAttribute(\"data-count\"))'><br>"
+"<label> Background color 2 : </label> <input type='color' id='backgroundColor2"+userInterface.labelData.inputs[j].id+"' data-count='"+labelConfigId
+"'data-category ='"+userInterface.labelData["category"]+"' dat-subcat='"+userInterface.labelData["subcategory"]
+"' onchange='ZCWP.label.set_bg_color_label(this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"),this.getAttribute(\"data-count\"))' style='visibility :hidden'><br>";
break;
case ("border") :
lblArrayElemnt[i].innerHTML += linebreak +"<label> Border :</lable>";
lblArrayElemnt[i].innerHTML += "<input type='checkbox' data-category ='"+userInterface.labelData["category"]+"' dat-subcat='"+userInterface.labelData["subcategory"]+"' id='border"+userInterface.labelData.inputs[j].id
+"' data-count='"+labelConfigId
+"'onchange='set_border_label(this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"),this.getAttribute(\"data-count\"))'><br>";
lblArrayElemnt[i].innerHTML += "<label> Border width :</label><input type='text' id='borderWidth"+userInterface.labelData.inputs[j].id+"' data-category ='"+userInterface.labelData["category"]+"' dat-subcat='"
+userInterface.labelData["subcategory"]+"' data-count='"+labelConfigId
+"' oninput='set_border_label(this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"),this.getAttribute(\"data-count\"))' value='1px'><br>";
lblArrayElemnt[i].innerHTML += " <label> Border color:</label><input type='color' id='borderColor"+userInterface.labelData.inputs[j].id+"' data-category ='"+userInterface.labelData["category"]+"' dat-subcat='"
+userInterface.labelData["subcategory"]+"' data-count='"+labelConfigId
+"'onchange='set_border_label(this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"),this.getAttribute(\"data-count\"))'><br>";
break;
case ("line") :
lblArrayElemnt[i].innerHTML += linebreak + "<label>Line color :</lable>";
lblArrayElemnt[i].innerHTML += "<input type='color' id='lineColor"+userInterface.labelData.inputs[j].id+"' data-category ='"+userInterface.labelData["category"]+"' dat-subcat='"+userInterface.labelData["subcategory"]+"' onchange='set_line(this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"))' value='#000000'><br>";
lblArrayElemnt[i].innerHTML += "<label>Line width :</lable> <input type='text' id='lineWidth"+userInterface.labelData.inputs[j].id+"' data-category ='"+userInterface.labelData["category"]+"' dat-subcat='"+userInterface.labelData["subcategory"]+"' onKeyUp='set_line(this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"))' value='2px'><br>";
lblArrayElemnt[i].innerHTML += "<lable> Line style :</lable>"
+"<select id='lineStyle"+userInterface.labelData.inputs[j].id+"' data-category ='"+userInterface.labelData["category"]+"' dat-subcat='"+userInterface.labelData["subcategory"]+"' onchange='set_line(this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"))'>"
+"<option></option>"
+"<option value='solid'> Solid</option>"
+"<option value='dotted'> Dotted</option>"
+"<option value='dashed'> Dashed</option>"
+"</select><br>";
lblArrayElemnt[i].innerHTML +="<label>Line gap size :</lable> <input type='text' id='lineGapSize"+userInterface.labelData.inputs[j].id+"' data-category ='"+userInterface.labelData["category"]+"' dat-subcat='"+userInterface.labelData["subcategory"]+"' onKeyUp='set_line(this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"))' value='2px' ><br>";
lblArrayElemnt[i].innerHTML +="<label>Line segment size :</lable> <input type='text' id='lineSegmentSize"+userInterface.labelData.inputs[j].id+"' data-category ='"+userInterface.labelData["category"]+"' dat-subcat='"+userInterface.labelData["subcategory"]+"' onKeyUp='set_line(this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"))' value='2px' ><br>";
break;
};
};
}
/* ALL the generic types will go here */
var element = document.getElementsByClassName("frm-el");
var linebreak = "";
for (var i = 0; i < element.length; i++) {
for (var m=0; m <formData.length;m++) {
if (element[i].getAttribute('data-category') == formData[m]["category"]
&& element[i].getAttribute('data-sub-category')
== formData[m]["subcategory"]) {
for (j=0; j<formData[m].inputs.length; j++) {
linebreak = formData[m].inputs[j].divider ? "<hr>" :" ";
switch(formData[m].inputs[j].type){
case("color") :
var defaultVal= '';
if (typeof userInterface.labelData.inputs[j].defValue != 'undefined' && userInterface.labelData.inputs[j].defValue !='') {
defaultVal = userInterface.labelData.inputs[j].defValue;
} else {
defaultVal = "#000000";
}
element[i].innerHTML += linebreak
+"<label>"+ formData[m].inputs[j].label+": </label>"
+"<input type='color' id='"+formData[m].inputs[j].id+"' data-category='"
+formData[m]["category"]+"' data-key='"+formData[m].inputs[j].key+"' dat-subcat='"+
formData[m].subcategory +"' onchange='ZCWP.general.modify_chart(this,this.getAttribute(\"data-key\"),this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"))' value='"+defaultVal+"'><br>";
break;
case('checkbox') :
element[i].innerHTML += linebreak
+"<label>"+ formData[m].inputs[j].label+": </label>"
+"<input type='checkbox' id='"+formData[m].inputs[j].id+"' data-category='"
+formData[m]["category"]+"' data-key='"+formData[m].inputs[j].key+"' dat-subcat='"+
formData[m].subcategory
+"' onchange='ZCWP.general.modify_chart(this,this.getAttribute(\"data-key\"),this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"))'><br>";
break;
case("text") :
var defaultVal= '';
if (typeof formData[m].inputs[j].defValue != 'undefined' ) {
defaultVal = formData[m].inputs[j].defValue;
};
element[i].innerHTML += linebreak
+"<label>"+ formData[m].inputs[j].label+": </label>"
+"<input type='text' id='"+formData[m].inputs[j].id+"' data-category='"
+formData[m]["category"]+"' data-key='"+formData[m].inputs[j].key+"' dat-subcat='"+
formData[m].subcategory
+"'onKeyUp='ZCWP.general.modify_chart(this,this.getAttribute(\"data-key\"),this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"))' value='"+defaultVal+"'><br>";
break;
case ('select'):
var options = ''
var optionLable = '';
for (var k=0; k<formData[m].inputs[j].values.length;k++) {
if (formData[m].inputs[j].labels) {
optionLable = formData[m].inputs[j].labels[k];
} else {
optionLable = formData[m].inputs[j].values[k];
}
options += "<option value='"+formData[m].inputs[j].values[k]+"'>"+optionLable +"</option>"
};
element[i].innerHTML += linebreak
+"<label>"+ formData[m].inputs[j].label+": </label>"
+"<select id='"+formData[m].inputs[j].id+"' data-category='"+formData[m]["category"]
+"' data-key='"+formData[m].inputs[j].key+"' dat-subcat='"+
formData[m].subcategory
+"'onchange='ZCWP.general.modify_chart(this,this.getAttribute(\"data-key\"),this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"))'><option></option> "+options+"</select><br>";
break;
case ("range") :
//oninput is for IE compatibility.
element[i].innerHTML += linebreak
+"<label>"+ formData[m].inputs[j].label+": </label>"
+"<input type='range' id='"+formData[m].inputs[j].id+"' data-category='"
+formData[m]["category"]+"' data-key='"+formData[m].inputs[j].key+"' dat-subcat='"+
formData[m].subcategory
+"' min='"+formData[m].inputs[j].min+"' max='"+formData[m].inputs[j].max+"' step='"+formData[m].inputs[j].step
+"' onchange='ZCWP.general.modify_chart(this,this.getAttribute(\"data-key\"),this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"))'"
+" oninput='ZCWP.general.modify_chart(this,this.getAttribute(\"data-key\"),this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"))'><br>";
break;
case ("bgcolor") :
element[i].innerHTML += linebreak +"<label> Background :</label>";//ID here represents category
element[i].innerHTML += "<select id='backgroundType"+formData[m].inputs[j].id+"' data-category ='"+formData[m]["category"]+"' dat-subcat='"+
formData[m]["subcategory"]+"'onchange='ZCWP.general.set_bg_type(this,this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"))'>"
+"<option value='solid'>Solid</option><option value='gradiant'>Gradiant</option></select><br>"
+"<label> Background color 1 : </label> <input type='color' id='backgroundColor1"+formData[m].inputs[j].id+"' data-category ='"+formData[m]["category"]
+"' dat-subcat='"+formData[m]["subcategory"]+"' data-bgtype='solid' onchange='ZCWP.general.set_bg_color(this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"))'><br>"
+"<label style='visibility :hidden'> Background color 2 : </label> <input type='color' id='backgroundColor2"+formData[m].inputs[j].id+"' data-category ='"+formData[m]["category"]
+"' dat-subcat='"+formData[m]["subcategory"]+"' onchange='ZCWP.general.set_bg_color(this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"))' style='visibility :hidden'><br>";
break;
case ("line") :
element[i].innerHTML += linebreak + "<label>Line color :</lable>";
element[i].innerHTML += "<input type='color' id='lineColor"+formData[m].inputs[j].id+"' data-category ='"+formData[m]["category"]+"' dat-subcat='"+formData[m]["subcategory"]+"' onchange='ZCWP.general.set_line(this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"))' value='#000000'><br>";
element[i].innerHTML += "<label>Line width :</lable> <input type='text' id='lineWidth"+formData[m].inputs[j].id+"' data-category ='"+formData[m]["category"]+"' dat-subcat='"+formData[m]["subcategory"]+"' onKeyUp='ZCWP.general.set_line(this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"))' value='2px'><br>";
element[i].innerHTML += "<lable> Line style :</lable>"
+"<select id='lineStyle"+formData[m].inputs[j].id+"' data-category ='"+formData[m]["category"]+"' dat-subcat='"+formData[m]["subcategory"]+"' onchange='ZCWP.general.set_line(this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"))'>"
+"<option></option>"
+"<option value='solid'> Solid</option>"
+"<option value='dotted'> Dotted</option>"
+"<option value='dashed'> Dashed</option>"
+"</select><br>";
element[i].innerHTML +="<label>Line gap size :</lable> <input type='text' id='lineGapSize"+formData[m].inputs[j].id+"' data-category ='"+formData[m]["category"]+"' dat-subcat='"+formData[m]["subcategory"]+"' onKeyUp='ZCWP.general.set_line(this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"))' value='2px' ><br>";
element[i].innerHTML +="<label>Line segment size :</lable> <input type='text' id='lineSegmentSize"+formData[m].inputs[j].id+"' data-category ='"+formData[m]["category"]+"' dat-subcat='"+formData[m]["subcategory"]+"' onKeyUp='ZCWP.general.set_line(this.getAttribute(\"data-category\"),this.getAttribute(\"dat-subcat\"))' value='2px' ><br>";
break;
};
};
};
};
};
};
|
var variables________________e________8js____8js__8js_8js =
[
[ "variables________e____8js__8js_8js", "variables________________e________8js____8js__8js_8js.html#aee90cf4cb6b04e64329466aa87eb7136", null ]
]; |
/**
* Created by Cjy on 2017/6/1.
*/
Ext.define('Admin.view.pictureHandpick.PictureHandpick', {
extend: 'Ext.Panel',
xtype: 'pictureHandpick',
title: 'ไธๅ็ฒพ้ๅพๅบ(<font color="red">ๅๅปๆฅ็ๅพ้</font>)',
requires: [
'Admin.view.pictureHandpick.PictureHandpickController'
],
tbar:[{
xtype: 'textfield',
id:'coreword',
emptyText:'ๅ
ณ้ฎๅญๆ็ดข',
enableKeyEvents:true,
listeners:{
keydown:'keywordSearch'
}
},'->',{
xtype: 'button',
text: 'ๆฅ่ฏข' ,
handler:'search'
}],
controller: "pictureHandpick",
layout:'fit',
start:20,
pageIndex:2,
preserveScrollOnRefresh: true,
scrollable: "y",
listeners:{
render:'panelRender'
},
items: [{
xtype: 'dataview',
store: 'pictureHandpick.PictureHandpick',
reference: 'dataview',
tpl:new Ext.XTemplate(
'<div id="container"><tpl for=".">',
'<div style="margin-bottom: 10px;" class="thumb-wrap">',
'<img alt="ๅๅปๆฅ็่ฎขๅๅพ้" src="http://img.bingzhiyi.com/{thumbnail}?x-oss-process=image/resize,w_350" />',
'<br/><span><i class="order">่ฎขๅ็ผๅท๏ผ</i><i>{orderNumber}</i></span> <span><i class="speci">็ฑป็ฎ๏ผ</i><i>{category1}-{category2}-{category3}</i></span>',
'</div>',
'</tpl></div>'
),
itemSelector: '#container .thumb-wrap',
emptyText: '่ฏทๆ นๆฎๆฅ่ฏขๆกไปถๆ็ดขๅพ็',
listeners: {
beforerender: 'viewBeforeRender',
render: 'search',
refresh:'resetComposing',
itemclick:'showAllPicture'
}
}]
}); |
import React from 'react'
const Header = () => {
return (
<header className="header">
<div>
<h1 id="header-h1">Lightsaber Builder</h1>
</div>
<div>
<nav id="header-nav">MENU ☰</nav>
</div>
</header>
)
}
export default Header |
class State{
constructor( svc, id ){
this._svc = svc;
this.id = id;
}
destroy(){
delete this._svc.states[ this.id ];
this._svc.msg({ id:this.id, cmd:"destroy" });
}
}
class AtcoreService {
constructor( path="./atcore.worker.js" ){
this.cbmap = {};
this.nextCBID = 0;
this.states = {};
this.worker = new Worker( path );
this.worker.onmessage = this._onmsg.bind(this);
this.queue = [];
}
create( url, periferals, cb ){
this.msg({
cmd:"create",
periferals,
url,
MID:({status})=>{
if( status ){
var state = new State( this, status );
this.states[ status ] = state;
cb( state );
}
else cb();
}
});
}
msg( data ){
if( typeof data.MID == "function" ){
this.cbmap[ ++this.nextCBID ] = data.MID;
data.MID = this.nextCBID;
}
if( this.queue )
this.queue.push( data );
else
this.worker.postMessage( data );
}
_onmsg( evt ){
if( evt.data.info == "ready" ){
for( var i=0; i<this.queue.length; ++i )
this.worker.postMessage( this.queue[i] );
this.queue = null;
return;
}
if( evt.data.MID ){
var cb = this.cbmap[ evt.data.MID ];
delete this.cbmap[ evt.data.MID ];
if( cb )
cb( evt.data );
}else{
for( var k in evt.data ){
var diff = evt.data[k];
var cpu = this.states[k];
if( !cpu ) continue;
Object.assign( cpu, diff );
}
}
}
}
module.exports = AtcoreService; |
'use strict';
function characterCounter (target, limit, currentLength, minLength) {
/* Global character counter
*
* Parameters:
* - target: string of target selector
* - limit: integer of maximum character length
* - currentLength: integer value of keyed in content
* - minLength: integer of minimum character length (default = 0)
*
* Ex:
* {
* target: "#dc_title",
* charLength: 150,
* contentLength: $(this).val().length,
* minLength: 0
* }
*
* */
var length = limit - currentLength;
minLength = (typeof minLength !== 'undefined') ? minLength : 0;
var s = length === 1 ? '' : 's';
$(target).text(length + ' character' + s + ' remaining');
if (length == 0) {
$(target).css('color', 'red');
} else if (currentLength < minLength) {
$(target).css('color', 'red');
}
else {
$(target).css('color', 'black');
}
} |
import React, { useEffect, useState } from 'react';
import './App.css';
import { global } from './components/globalStyle';
import BeerCard from './components/BeerCard';
import Search from './components/Search';
import ClipLoader from 'react-spinners/ClipLoader';
const styles = {
content: {
display: 'flex',
margin: '10px',
backgroundColor: '#ffff',
padding: '10px',
flexDirection: 'row',
justifyContent: 'center',
flexWrap: 'wrap',
marginTop: '0px',
},
title: {
color: '#ac3f21',
textAlign: 'center',
marginTop: 0,
marginBottom: 0,
padding: 20,
fontSize: 52,
fontFamily: 'Love Ya Like A Sister, cursive',
},
desc: {
textAlign: 'center',
color: '#ffff',
fontFamily: 'Arial, cursive',
fontSize: 14,
},
disc: {
textAlign: 'center',
color: '#f3cf7a',
},
imgContainer: {
img: { height: 300, width: 'auto' },
display: 'flex',
justifyContent: 'center',
},
};
function App() {
const [data, setData] = useState([]);
const [state, setState] = useState('');
const [isLoading, setIsLoading] = useState(true);
const handleSelect = (event) => {
setState(event.target.value);
};
if (isLoading) {
<div className='full-page-loader'>
<ClipLoader sizeUnit={'px'} size={150} color={'#fc1303'} loading={true} />
</div>;
}
useEffect(() => {
fetch(`https://api.openbrewerydb.org/breweries?by_state=${state}`, {
method: 'GET',
})
.then((res) => res.json())
.then((response) => {
setData(response);
setIsLoading(false);
})
.catch((e) => console.log(e));
}, [state]);
return (
<div style={global}>
<h1 style={styles.title}>Beer Brewery Bible</h1>
<div style={styles.imgContainer}>
<img src='/beerImg.png' alt='Beer' style={styles.imgContainer.img}/>
</div>
<p style={styles.disc}>
Disclosure: Some of the websites may no longer be available or
incorrect. Data is updated and maintained through OpenBreweryDB API.
</p>
<p style={styles.desc}>
{' '}
Instructions: Select a state from the dropdown for a list of beer
breweries!
</p>
<Search state={state} stateSet={handleSelect} />
<div style={styles.content}>
<BeerCard beer={data} />
</div>
</div>
);
}
export default App;
|
var express = require('express');
const { body, validationResult } = require('express-validator');
const { error } = require('console');
var admindb = require.main.require('./models/admin');
var router = express.Router();
router.get('/', function(req, res){
if(req.cookies['type'] == 'admin'){
admindb.getAllEmp(function(result){
console.log(result);
res.render('admin/index',{emp:result});
});
}
else{
res.redirect('/employee');
}
});
router.get('/addemployee', function(req, res){
if(req.cookies['type'] == 'admin'){
var value = {
name: req.body.name,
username: req.body.username,
phone: req.body.phone,
gender: req.body.gender,
designation: req.body.designation,
};
var valueCheck = [];
var data ={
value : value,
errors : valueCheck
}
res.render('admin/addEmployee',data);
}
else{
res.redirect('/employee');
}
});
router.post('/addemployee', [
body('name','Name required!').notEmpty(),
body('username').notEmpty().withMessage('Username required!').isLength({min: 9}).withMessage('Username must be greater than 8 characters!'),
body('password').notEmpty().withMessage('Password required!').isLength({min: 8}).withMessage('Password must be atleast 8 characters!').custom((value,{req}) => {
if (value != req.body.cPassword) {
throw new Error("Passwords don't match");
} else {
return value;
}
}),
body('phone').notEmpty().withMessage('Phone number required!').isNumeric().withMessage('Phone number must be numeric!').isLength({min: 11, max: 11}).withMessage('Phone number must be 11 characters!'),
body('gender','Gender required!').notEmpty(),
], function(req, res){
if(req.cookies['type'] == 'admin'){
var value = {
name: req.body.name,
phone: req.body.phone,
username: req.body.username,
gender: req.body.gender,
designation: req.body.designation,
password:req.body.password
};
var valueCheck = [];
validationResult(req).errors.forEach(error => {
valueCheck.push(error.msg);
});
var data ={
value : value,
errors : valueCheck
}
if(valueCheck.length > 0){
res.render('admin/addemployee',data);
} else {
admindb.addEmployee(value, function(result){
console.log(result);
res.redirect('/admin/');
});
}
}
else{
res.redirect('/employee');
}
});
router.get('/update/:id', function (req, res){
if(req.cookies['type'] == 'admin'){
id = req.params.id;
admindb.getEmployee(id, function (result){
var data = {
name: result.name,
phone: result.phone,
gender: result.gender,
designation: result.designation,
};
console.log(data);
var valueCheck = [];
res.render('admin/updateEmployee',{data, errors:valueCheck});
});
}
else{
res.redirect('/employee');
}
});
router.post('/update/:id',[
body('name','Name required!').notEmpty(),
body('phone').notEmpty().withMessage('Phone number required!').isNumeric().withMessage('Phone number must be numeric!').isLength({min: 11, max: 11}).withMessage('Phone number must be 11 characters!'),
body('gender','Gender required!').notEmpty(),
], function (req, res){
id= req.params.id;
admindb.getEmployee(id, function (result){
var data = {
name: result.name,
phone: result.phone,
gender: result.gender,
designation: result.designation,
};
var valueCheck = [];
validationResult(req).errors.forEach(error => {
valueCheck.push(error.msg);
});
if (valueCheck.length > 0){
res.render('admin/updateEmployee',{data,errors: valueCheck});
} else {
admindb.updateEmployee(id, req.body.name, req.body.phone, req.body.gender, req.body.designation, function(result1){
res.redirect('/admin/');
});
}
});
});
router.get('/delete/:id', function(req, res){
id= req.params.id;
admindb.getEmployee(id, function(result){
res.render('admin/deleteEmp',{employee: result});
});
});
router.post('/delete/:id', function(req, res){
id = req.params.id;
if(req.body.submit="Yes"){
console.log('yes');
admindb.deleteEmp(id, function(){
res.redirect('/admin/');
});
}
});
module.exports = router; |
var express = require('express');
var multer = require('multer');
var router = express.Router();
var uploadDoc = require('./ipfs')
router.post('/upload',uploadDoc);
router.get('/',(req,res)=>{
res.sendFile('upload.html',{root:__dirname});
});
module.exports = router; |
// pages/index/index-campus/index-campus.js
const APP = getApp()
const HTTP = require('../../../utils/http.js')
const CONST = require('../../../utils/const.js')
const UTIL = require('../../../utils/util.js')
const SHARE_UTIL = require('../../../utils/shareUtil.js')
const ALL_BRAND_URL = CONST.SERVER + '/positions/brand_list'
const SHARE_PREFIX = CONST.SERVER + '/campus/'
Page({
/**
* ้กต้ข็ๅๅงๆฐๆฎ
*/
data: {
allSubjects: [],
currentSubject: null,
shareImgPath: {},
showEditModal: false,
},
/**
* ็ๅฝๅจๆๅฝๆฐ--็ๅฌ้กต้ขๅ ่ฝฝ
*/
onLoad: function(options) {
this.parseQ(options)
// if (this.project_id) {
// this.setData({
// hideSearch: true
// })
// }
let that = this
wx.getSystemInfo({
success: function(res) {
var windowWidth = res.windowWidth
that.setData({
contentHeight: res.windowHeight
})
}
})
if (APP.globalData.isLogin) {
that.loadAllBrandData()
} else {
APP.authCallbacks.push({
authSuccess: function() {
console.log('auth success from callback')
that.loadAllBrandData()
}
})
}
},
parseQ(options) {
var q = options.q || ''
if (!q) {
if (options.brand) {
this.brand = options.brand
}
if (options.recommend_toc_uid) {
wx.setStorageSync('recommend_toc_uid', options.recommend_toc_uid)
}
if (options.project_id) {
this.project_id = options.project_id
}
return
}
q = decodeURIComponent(q)
var index = q.indexOf(SHARE_PREFIX)
if (index == -1) {
return
}
var params = q.substring(SHARE_PREFIX.length)
var kvs = params.split('&')
for (var i = 0; i < kvs.length; i++) {
var kv = kvs[i].split('=')
if (kv[0] == 'brand') {
this.brand = kv[1]
} else if (kv[0] == 'recommend_toc_uid' && kv[1]) {
wx.setStorageSync('recommend_toc_uid', kv[1])
} else if (kv[0] == 'project_id' && kv[1]) {
this.project_id = kv[1]
}
}
},
loadAllBrandData: function() {
var that = this
UTIL.showLoading()
HTTP.postRequest(ALL_BRAND_URL, {}, function(res) {
UTIL.dismissLoading()
var allSubjects = []
var currentSubject
if (that.brand) {
currentSubject = { id: that.brand }
if (that.project_id) {
currentSubject.project_id = that.project_id
}
}
Object.keys(res.data.results).forEach(function(key) {
var item = res.data.results[key]
var subject = new Object
subject.id = item.id
subject.name = item.name
subject.project_id = item.project_id
if (currentSubject && !currentSubject.project_id && currentSubject.id == subject.id) {
currentSubject.project_id == subject.project_id
}
allSubjects.push(subject)
})
if (!currentSubject) {
if (allSubjects.length > 0) {
currentSubject = allSubjects[0]
}
}
that.setData({
allSubjects: allSubjects,
currentSubject: currentSubject
})
if (currentSubject) {
that.callComponent(currentSubject)
}
}, function(errNo, errMsg) {
UTIL.dismissLoading()
wx.showToast({
title: errMsg ? errMsg : 'error',
icon: 'none'
})
})
},
onBrandName(event) {
var name = event.detail
if (!this.data.currentSubject.name && name) {
this.setData({
'currentSubject.name': name
})
}
},
callComponent: function(subject) {
let INDEX = this.selectComponent('#campus')
INDEX && INDEX.startLoadData(subject, subject.project_id)
},
onBrandSelect: function(event) {
var index = event.detail.value
var currentSubject = this.data.allSubjects[index]
this.project_id = ''
this.setData({
currentSubject: currentSubject,
hideSearch: false
})
this.callComponent(currentSubject)
},
goSearch: function() {
if (this.data.currentSubject) {
var goSearch = '../../search/search?channel=' + 1
goSearch = goSearch + '&brand=' + this.data.currentSubject.id
wx.navigateTo({
url: goSearch,
})
}
},
/**
* ็ๅฝๅจๆๅฝๆฐ--็ๅฌ้กต้ขๆพ็คบ
*/
onShow: function() {
},
showShare() {
var that = this
if (!that.data.currentSubject) {
return
}
var tobUid = ''
if (!tobUid) {
let INDEX = this.selectComponent('#campus')
tobUid = INDEX.tryFetchTobUid()
}
SHARE_UTIL.doShareProcess(this, tobUid)
},
changeShowModal() {
this.setData({
showEditModal: false
})
},
onSetUserName(e) {
var name = e.detail
if (name) {
var app = getApp()
app.saveUserName(name)
this.showShare()
}
},
dismissShareCircle() {
this.setData({
showCircleQR: false
})
},
onShareCircleClick() {
var qrCodeInfo = this.buildShareParams()
this.setData({
shareInfo: qrCodeInfo,
showCircleQR: true
})
},
buildShareParams() {
var that = this
var q = SHARE_PREFIX + 'channel=1&brand=' + (that.data.currentSubject ? that.data.currentSubject.id : that.brand)
var APP = getApp()
var tocUserInfo = APP.globalData.tocUserInfo
if (tocUserInfo && tocUserInfo.id) {
q = q + '&recommend_toc_uid=' + tocUserInfo.id
}
if (that.project_id) {
q = q + '&project_id=' + that.project_id
}
return q
},
/**
* ็จๆท็นๅปๅณไธ่งๅไบซ
*/
onShareAppMessage: function() {
var that = this
var titleSuffix = 'ๅๆจๅไบซไบไธๆน่ไฝ'
var title = ''
if (APP.getUserName()) {
title = APP.getUserName() + titleSuffix
} else {
title = 'ๆจ็ๅฅฝๅ' + titleSuffix
}
var q = that.buildShareParams()
q = encodeURIComponent(q)
var path = 'pages/index/index-campus/index-campus?q=' + q
var imageUrl
if (that.data.currentSubject && that.data.shareImgPath[that.data.currentSubject.id]) {
imageUrl = that.data.shareImgPath[that.data.currentSubject.id]
} else {
imageUrl = '../../../images/shareImg.jpg'
}
return {
title: title,
path: path,
imageUrl: imageUrl
}
},
createShareImg(canvasId, callback) {
var that = this
if (that.data.currentSubject && that.data.shareImgPath[that.data.currentSubject.id]) {
callback.success()
return
}
that.setData({
needDummy: true
})
var context = wx.createCanvasContext(canvasId)
var res = wx.getSystemInfoSync()
var windowWidth = res.windowWidth
var scale = windowWidth / 750
var imgWidth = 500 * scale
var imgHeight = 400 * scale
var positionNameTopMargin = 250 * scale
var positionNameFont = 36 * scale
var imgPath = '../../../images/wx_share_img_base.jpg'
context.clearRect(0, 0, imgWidth, imgHeight)
context.setFillStyle('#FFFFFF')
context.fillRect(0, 0, imgWidth, imgHeight)
context.drawImage(imgPath, 2, 2, imgWidth - 2, imgHeight - 2)
context.setFillStyle('#333333')
context.setFontSize(positionNameFont)
var positionName = that.data.currentSubject.name
// if (positionName.length > 12) {
// positionName = positionName.substring(0, 12) + 'โฆ'
// }
var names = []
var temp = ''
var maxWidth = imgHeight // 400 * scale
for (var k = 0; k < positionName.length; k++) {
temp = temp + positionName.charAt(k)
var textWidth = context.measureText(temp).width
if (textWidth < maxWidth) {
if (k == positionName.length - 1)
names.push(temp)
} else {
names.push(temp)
temp = ''
}
}
console.log('names: ' + names)
context.setTextBaseline('middle')
for (var k = 0; k < names.length; k++) {
var nameLength = context.measureText(names[k]).width
var positionNameX = (imgWidth - nameLength) / 2
var positionNameY = (150 + (175 - 50 * names.length) / 2 + 25 + 50 * k) * scale
console.log('positionNameX: ' + positionNameX)
console.log('positionNameY: ' + positionNameY)
console.log('names: ' + names[k])
context.fillText(names[k], positionNameX, positionNameY)
}
context.draw(true, function(res) {
console.log('draw canvas finish: ' + JSON.stringify(res))
setTimeout(function() {
wx.canvasToTempFilePath({
canvasId: canvasId,
success: res => {
var key = 'shareImgPath[' + that.data.currentSubject.id + ']'
that.setData({
[key]: res.tempFilePath
})
callback.success()
that.setData({
needDummy: false
})
},
fail: res => {
console.log('save fail: ' + JSON.stringify(res))
callback.fail()
that.setData({
needDummy: false
})
}
})
}, 500);
})
}
}) |
define(function(require, exports) {
exports.paint = function(insertedSeries) {
$('#you-strat').highcharts({
chart: { type: 'bar' },
title: { text: 'Your strategy vs the best' },
//subtitle: { text: 'bsaklรถdfsalรถf' },
xAxis: {
categories: ['Amortize house loan', 'Amortize consumption loans', 'Invest in stocks', 'Deposit to savings account', 'Deposit to checkings account', "Consumption" ],
title: {
text: null
}
},
yAxis: {
min: 0,
title: {
text: 'Spent salary on (SEK)',
align: 'high'
},
labels: {
overflow: 'justify'
}
},
tooltip: {
valueSuffix: ' SEK'
},
plotOptions: {
bar: {
dataLabels: {
enabled: true
}
}
},
legend: {
enabled: true,
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
reversed: true,
x: -40,
y: 100,
floating: true,
borderWidth: 1,
backgroundColor: ((Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'),
shadow: true
},
credits: {
enabled: false
},
series: insertedSeries
});
};
});
|
import './Nav.css';
const Nav = () => {
return (
<nav>
<span className='upper-container'>
<h1 className='nav-blue'>DEMO Streaming</h1>
<span>
<a href='#'>Login</a>
<button className='nav-btn'>Start your free trial</button>
</span>
</span>
<span className='blw-container'>
<h2 className='nav-dark-gray'>Popular Titles</h2>
</span>
</nav>
);
};
export default Nav;
|
import { test } from 'tape';
import canDivideIn from '../build/index.js';
test('A passing test', (assert) => {
assert.pass('This test will pass.');
assert.end();
});
test('Assertions with tape.', (assert) => {
assert.same(canDivideIn(3), [1, 3],
'Recibe different value');
assert.same(canDivideIn(4), [1, 2, 4],
'Recibe different value');
assert.same(canDivideIn(36), [1, 2, 3, 4, 6, 9, 12, 18, 36],
'Recibe different value');
assert.same(canDivideIn('a'), new Error('Only numbers'),
'Return error');
assert.end();
});
|
import React from 'react';
import { Helmet } from 'react-helmet';
const HeadSeo = props => {
const { name, address, description, image } = props;
return (
<Helmet>
<meta charSet='utf-8'/>
<title>{name ? `${name} - ` : ''}{process.env.APP_NAME}</title>
<link rel={'canonical'} href={process.env.SITE_DOMAIN + { address }}/>
<meta http-equiv='content-type' content='text/html; charset=UTF-8'/>
<meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'/>
{/* -- Meta -- */}
<meta name='copyright' content='Copyright ยฉ TorfehNegar Holding Company. All Rights Reserved.'/>
<meta name='author' content='Torfenegar developers (lead jafarRezaei : http://jrjs.ir)'/>
<meta name='robots' content='index, follow'/>
{/* -- Mobile -- */}
<meta name='viewport'
content='width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0'/>
<meta name='apple-mobile-web-app-capable' content='yes'/>
{/* -- Social tags -- */}
<meta name='description' content={description}/>
{/* -- Schema.org markup for Google+ -- */}
<meta itemProp='name' content={name}/>
<meta itemProp='description' content={description}/>
<meta itemProp='image' content={image}/>
{/* -- Twitter Card data -- */}
<meta name='twitter:card' content='summary_large_image'/>
<meta name='twitter:title' content={name}/>
<meta name='twitter:description' content={description}/>
<meta name='twitter:image' content={image}/>
{/* -- Open Graph data -- */}
<meta property='og:title' content={name}/>
<meta property='og:type' content='article'/>
<meta property='og:url' content={process.env.SITE_DOMAIN + address}/>
<meta property='og:image' content={image}/>
<meta property='og:description' content={description}/>
<meta property='og:site_name' content={process.env.APP_NAME}/>
{/* -- favIcon -- */}
<link rel='apple-touch-icon' sizes='57x57' href='/static/images/favicon/apple-icon-57x57.png'/>
<link rel='apple-touch-icon' sizes='60x60' href='/static/images/favicon/apple-icon-60x60.png'/>
<link rel='apple-touch-icon' sizes='72x72' href='/static/images/favicon/apple-icon-72x72.png'/>
<link rel='apple-touch-icon' sizes='76x76' href='/static/images/favicon/apple-icon-76x76.png'/>
<link rel='apple-touch-icon' sizes='114x114' href='/static/images/favicon/apple-icon-114x114.png'/>
<link rel='apple-touch-icon' sizes='120x120' href='/static/images/favicon/apple-icon-120x120.png'/>
<link rel='apple-touch-icon' sizes='144x144' href='/static/images/favicon/apple-icon-144x144.png'/>
<link rel='apple-touch-icon' sizes='152x152' href='/static/images/favicon/apple-icon-152x152.png'/>
<link rel='apple-touch-icon' sizes='180x180' href='/static/images/favicon/apple-icon-180x180.png'/>
<link rel='icon' type='image/png' sizes='192x192' href='/static/images/favicon/android-icon-192x192.png'/>
<link rel='icon' type='image/png' sizes='32x32' href='/static/images/favicon/favicon-32x32.png'/>
<link rel='icon' type='image/png' sizes='96x96' href='/static/images/favicon/favicon-96x96.png'/>
<link rel='icon' type='image/png' sizes='16x16' href='/static/images/favicon/favicon-16x16.png'/>
<link rel='manifest' href='/static/images/favicon/manifest.json'/>
<meta name='msapplication-TileColor' content='#ffffff'/>
<meta name='msapplication-TileImage' content='/static/images/favicon/ms-icon-144x144.png'/>
<meta name='theme-color' content='#ffffff'/>
</Helmet>
);
};
export default HeadSeo;
|
const max1 = 10;
const max2 = 10;
function getNumber1() {
return getRandom(0, max1);
}
function getNumber2() {
return getRandom(0, max2);
}
function isAnswerCorrect(input1, input2, output) {
return output == input1 * input2;
}
|
const http = require("http");
http.createServer((request,response)=>{
response.writeHead(200,{'Content-Type':'text/plain'});
response.end('I AM MASTER World\n');
}).listen(8081)
console.log('Server running at http://127.0.0.1:8081/ or localhost:') |
import _ from 'lodash'
import request from 'superagent'
import { getMeshbluConfig } from '../helpers/authentication'
import { getFriendlyName } from '../helpers/connector-metadata'
import { CONNECTOR_SERVICE_URI } from '../constants/config'
import {
getDevice,
} from '../services/device-service'
function generateKeyWrapper({ registryItem, connector, version, octoblu }, callback) {
return (error, device) => {
if (error) return callback(error)
const { uuid } = device
generateOtp({ uuid }, (error, response) => {
if (error) return callback(error)
const { key } = response || {}
return callback(null, { key, uuid })
})
}
}
function updateConnector({ uuid, properties }, callback) {
request
.put(`${CONNECTOR_SERVICE_URI}/users/${getMeshbluConfig().uuid}/connectors/${uuid}`)
.send(properties)
.auth(getMeshbluConfig().uuid, getMeshbluConfig().token)
.accept('application/json')
.set('Content-Type', 'application/json')
.end((error, response) => {
if (error) {
callback(error)
return
}
if (!response.ok) {
callback(new Error(_.get(response, 'body.error', 'Unable to update the connector')))
return
}
getDevice({ uuid }, callback)
})
}
function generateOtp({ uuid }, callback) {
request
.post(`${CONNECTOR_SERVICE_URI}/connectors/${uuid}/otp`)
.auth(getMeshbluConfig().uuid, getMeshbluConfig().token)
.accept('application/json')
.set('Content-Type', 'application/json')
.end((error, response) => {
if (error) {
callback(error)
return
}
if (!response.ok) {
callback(new Error(_.get(response, 'body.error', 'Unable to update the connector')))
return
}
const key = _.get(response, 'body.key')
if (!key) return callback(new Error('Unable to generate OTP'))
callback(null, { key })
})
}
function createConnector({ properties }, callback) {
request
.post(`${CONNECTOR_SERVICE_URI}/users/${getMeshbluConfig().uuid}/connectors`)
.send(properties)
.auth(getMeshbluConfig().uuid, getMeshbluConfig().token)
.accept('application/json')
.set('Content-Type', 'application/json')
.end((error, response) => {
if (error) {
callback(error)
return
}
if (!response.ok) {
callback(new Error(_.get(response, 'body.error', 'Unable to update the connector')))
return
}
callback(null, response.body)
})
}
export function upsertConnector({ uuid, registryItem, version, connector, octoblu }, callback) {
version = `v${version.replace('v', '')}`
const generateKey = generateKeyWrapper({ uuid, registryItem, version, connector, octoblu }, callback)
const properties = {
type: registryItem.type,
connector,
owner: getMeshbluConfig().uuid,
githubSlug: registryItem.githubSlug,
registryItem,
version,
}
if (uuid) {
return updateConnector({ uuid, properties }, generateKey)
}
_.set(properties, 'name', getFriendlyName(connector))
return createConnector({ properties }, generateKey)
}
|
import React, { useRef } from 'react';
import PropTypes from 'prop-types';
import DatePicker from '../DatePicker';
import TextInput from '../TextInput';
import { format } from 'date-fns';
import { IoMdCalendar } from 'react-icons/io'
import useClickOutside from '../../hooks/useClickOutside';
const DateInput = ({
defaultDate,
onSelect,
disabledPastDate,
title,
placeholder,
isOpenDatePicker,
onFocus,
onBlur,
switchHandler,
required,
}) => {
const dateInputRef = useRef();
useClickOutside(isOpenDatePicker, dateInputRef, () => switchHandler(false));
return (
<div className="DateInput" ref={dateInputRef}>
<TextInput
title={title}
text={format(defaultDate, 'yyyy/MM/dd')}
placeholder={placeholder}
onFocus={onFocus}
onBlur={onBlur}
icon={<IoMdCalendar />}
onChange={() => {}}
required={required}
/>
{isOpenDatePicker && (
<DatePicker
defaultDate={defaultDate}
onSelect={onSelect}
switchHandler={switchHandler}
disabledPastDate={disabledPastDate}
/>
)}
</div>
);
};
DateInput.propTypes = {
defaultDate: PropTypes.instanceOf(Date),
onSelect: PropTypes.func,
disabledPastDate: PropTypes.bool,
isOpenDatePicker: PropTypes.bool,
title: PropTypes.string,
placeholder: PropTypes.string,
required: PropTypes.bool,
};
DateInput.defaultProps = {
defaultDate: '',
onSelect: null,
disabledPastDate: true,
title: '',
placeholder: '',
isOpenDatePicker: false,
};
export default DateInput;
|
import React from 'react';
import ItemTitle from '../../../components/ItemTitle/index.js';
import ShopListItem from './ShopListItem';
import styles from './index.less';
import { Icon } from 'antd';
import { connect } from 'dva';
const ShopList = (props) => {
const { filterKey,clickFilterHandler } = props;
return (
<div className={styles.shopList}>
<ItemTitle title="ๆจ่ๅๅฎถ" />
<div className={styles.filter}>
<a onClick={()=>clickFilterHandler('sort')}>
<span className={styles.filterItem}>็ปผๅๆๅบ</span>
<Icon type="caret-down" style={{ width: '1.6vw', height: '1.0666vw', color: '#666' }} />
</a>
<a onClick={()=>clickFilterHandler('distance')}>
<span className={styles.filterItem} style={filterKey == 'distance' ? {fontWeight:700}:null}>่ท็ฆปๆ่ฟ</span>
</a>
<a onClick={()=>clickFilterHandler('quality')}>
<span className={styles.filterItem}>ๅ่ดจ่็</span>
<Icon type="caret-down" style={{ width: '1.6vw', height: '1.0666vw', color: '#666' }} />
</a>
<a onClick={()=>clickFilterHandler('filter')}>
<span className={styles.filterItem}>็ญ้</span>
<Icon type="filter" style={{ width: '1.6vw', height: '1.0666vw', color: '#666' }} />
</a>
</div>
<ShopListItem />
<ShopListItem />
<ShopListItem />
<ShopListItem />
</div>
)
}
export default ShopList;
|
const router = require('express').Router();
const bodyParser = require('body-parser');
const jwt = require('../util/jwtpromise');
const co = require('co');
const pages = require('../pages');
router.use(bodyParser.json());
router.get('/pages', (req, res) => {
pages.model.getAllPages()
.then((pages) => {
res.send(pages);
}).catch((err) => {
res.send('error');
console.log(err);
})
});
router.get('/pages/:url', (req, res) => {
var url = req.params.url;
// TODO: Validate
pages.model.getPage(url)
.then((page) => {
if(!page) {
res.send('not found');
return;
}
res.send(page);
}).catch((err) => {
res.send('error');
console.log(err);
});
});
router.post('/pages', (req, res) => {
let username = req.body.username;
let token = req.body.token;
co(function *() {
let token_username = yield jwt.verify(token, 'sss');
let page = yield pages.model.createPage(req.body.page);
console.log(token_username);
}).catch((err) => {
res.send('error');
console.log(err);
});
});
module.exports = router;
|
export const mockGet = jest.fn();
export const mockPost = jest.fn();
export const mockPut = jest.fn();
export const mockDelete = jest.fn();
export const mockInstaceGet = jest.fn();
export const mockInstacePost = jest.fn();
export const mockInstacePut = jest.fn();
export const mockInstaceDelete = jest.fn();
export const mockInstace = {
get: mockInstaceGet,
post: mockInstacePost,
put: mockInstacePut,
delete: mockInstaceDelete,
defaults: {
headers: {
common: {},
},
},
};
export default {
get: mockGet,
post: mockPost,
put: mockPut,
delete: mockDelete,
create: () => mockInstace,
};
|
const MongoClient = require('mongodb').MongoClient;
const dbUrl = 'mongodb://egursoy:Forever9@ds129030.mlab.com:29030/webscraper'
// const dbUrl = 'mongodb://localhost:27017/local';
var db;
export default function register(req) {
const user = {
name: req.body.userObj.name
};
// req.session.user = user;
// return Promise.resolve(req.body);
return new Promise((resolve, reject)=>{
// Use connect method to connect to the Server
MongoClient.connect(dbUrl, (err, database) => {
if (err) {
reject(err);
} else {
db = database;
db.collection('users').save(req.body.userObj, (err, result) => {
if (err){
reject(err);
}
else{
req.session.user = user;
resolve(user);
}
})
}
});
});
}
|
'use strict';
angular.module('app')
.controller('DeckController', function ($scope, $stateParams, $log, getData) {
var id = $stateParams.deckId;
getData($scope.flavor + '/' + id).then(function (data) {
$log.debug(data);
});
});
|
/**
Custom Routes
=============
You can create your own routing here.
This is prioritized over automatic controller routing.
**/
var routes = {
/** Example:
'/test' : function(req, res, next) { res.end('Hello World')}, //defaults to all GET, POST, DELETE, etc
'/sample' : {
//more specific
get: function(req, res, next) {
res.end('Hello Sample Get');
},
post: function(req, res, next) {
res.end('Hello Sample Post');
}
},
'/controller-sample' : includeController('/index.js'),
'/any-js-sample' : include('/web/controllers/index.js'),
// sample regex
'/^((?!\/static).)*$/' : {
isRegexp: true,
all: function(req, res, next) {
//do stuff here like authentication
next();
}
}
*/
}
module.exports = routes; |
// Positive integers that are divisible exactly by the sum of their digits are called Harshad numbers. The first few Harshad numbers are: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 18, ...
// We are interested in Harshad numbers where the product of its digit sum s and s with the digits reversed, gives the original number n. For example consider number 1729:
// its digit sum, s = 1 + 7 + 2 + 9 = 19
// reversing s = 91
// and 19 * 91 = 1729 --> the number that we started with.
// Complete the function which tests if a positive integer n is Harshad number, and returns True if the product of its digit sum and its digit sum reversed equals n; otherwise return False.
// Using .map()
const numberJoy = n => {
let digit = 0;
n.toString().split('').map(x => {
digit += parseInt(x);
});
return (digit * parseInt(digit.toString().split('').reverse().join(''))) === n;
};
// Using .reduce()
const numberJoy = n => {
const digit = n.toString().split('').reduce((sum, digit) => {
return sum + parseInt(digit);
}, 0);
return (digit * parseInt(digit.toString().split('').reverse().join(''))) === n;
};
console.log(numberJoy(1997)); // false
console.log(numberJoy(1998)); // false
console.log(numberJoy(1729)); // true
console.log(numberJoy(18)); // false
console.log(numberJoy(1)); // true
console.log(numberJoy(81)); // true
numberJoy(1458); //true
// See the code in action here: https://repl.it/@SterlingChin/EachSpitefulMonotone |
const isValidJSON = str => {
try {
JSON.parse(str);
return true;
} catch (e) {
return e;
}
};
module.exports = {
isValidJSON
}; |
const express = require('express') // declaring express as templating engine
const app = express()
require('dotenv').config({path: '.env-dev'}) // config .env file
const port = process.env.PORT || 3000 // declaring port
const TOKEN = process.env.TOKEN // importing API token from .env-dev file
const axios = require('axios') // importing axios
const cleanClubs = require('./modules/cleanClubs') // importing cleanClubs module
const cleanDate = require('./modules/cleanDate')// importing cleanDate module
// declaring empty arrays as global variables
let standingsPL = []
let logo = []
let matchDate = []
let homeTeam = []
let awayTeam = []
let scoreHome = []
let scoreAway = []
let cleanedStandings
let cleanedMatchDate
let cleanedHomeTeam
let cleanedAwayTeam
const main = () => {
app.use(express.static('static')) // declaring static as static folder
// importing the standings API
const configStandings = {
method: 'get',
url: 'https://api.football-data.org/v2/competitions/PL/standings',
headers: { 'X-Auth-Token': TOKEN },
}
let matchDay = 10 // declaring default round variable
// importing the matches API
const configScores = {
method: 'get',
url: `https://api.football-data.org/v2/competitions/PL/matches/?matchday=${matchDay}`,
headers: { 'X-Auth-Token': process.env.TOKEN },
}
// function to import and clean the standings and logo's
axios(configStandings)
.then(response => {
standingsPL = response.data.standings[0].table.map(item => item.team.name) // mapping all team names in new array
logo = response.data.standings[0].table.map(item => item.team.crestUrl) // mapping all team logos in new array
})
.then(() => cleanedStandings = cleanClubs(standingsPL)) // cleaning standingsPL by cleanClubs module and putting it in cleanedStandings
.catch((error) => console.log(error))
// function to import and clean dates, teams and scores
axios(configScores)
.then((response) => {
matchDate = response.data.matches.map(item => item.utcDate) // mapping all match dates in new array
homeTeam = response.data.matches.map(item => item.homeTeam.name) // mapping all home teams in new array
awayTeam = response.data.matches.map(item => item.awayTeam.name) // mapping all away teams in new array
scoreHome = response.data.matches.map(item => item.score.fullTime.homeTeam) // mapping all home scores in new array
scoreAway = response.data.matches.map(item => item.score.fullTime.awayTeam) // mapping all away scores in new array
})
.then(() => cleanedMatchDate = cleanDate(matchDate)) // cleaning matchDate by cleanDate module and putting it in cleanedMatchDate
.then(() => cleanedHomeTeam = cleanClubs(homeTeam)) // cleaning homeTeam by cleanClubs module and putting it in cleanedHomeTeam
.then(() => cleanedAwayTeam = cleanClubs(awayTeam)) // cleaning awayTeam by cleanClubs module and putting it in cleanedAwayTeam
.catch((error) => console.log(error))
// rendering all data to the index.ejs
app.get('/', (req, res) => res.render('index.ejs', {
dataPL: cleanedStandings,
date: cleanedMatchDate,
logo: logo,
homeTeam: cleanedHomeTeam,
awayTeam: cleanedAwayTeam,
scoreHome: scoreHome,
scoreAway: scoreAway,
}))
// console.log showing port
app.listen(port, () => {
console.log(`App listening at http://localhost:${port}`)
})
}
main()
|
import React, { Fragment } from 'react';
import { Subscribe } from 'unstated';
import SkillsInfoContainer from '../../../containers/SkillsInfo';
// Resume Editor Components
import Input from '../../Input';
// import Button from '../../Button';
// import ButtonWrapper from '../../ButtonWrapper';
// Styles
import styles from './styles.module.scss';
const ResumeEditorSkillsInfo = () => {
return (
<Subscribe to={[SkillsInfoContainer]}>
{(skillsInfo) => (
<Fragment>
{skillsInfo.state.skills.map((skill, skillIndex) => (
<form key={skillIndex}>
<Input
label={'Category'}
key={skillIndex}
value={skill.name}
type="text"
onChange={(event) =>
skillsInfo.handleChangeSkillName(event, skillIndex)
}
/>
{skill.keywords.map((keyword, keywordIndex) => (
<Input
sub={true}
key={keywordIndex}
value={keyword}
type="text"
onChange={(event) =>
skillsInfo.handleChange(event, skillIndex, keywordIndex)
}
/>
))}
<button
className={styles.addSkillSectionButton}
name={skill.name}
onClick={(event) => skillsInfo.addSkill(event, skillIndex)}
>
Add Skill
</button>
</form>
))}
{/* <ButtonWrapper>
<Button onClick={skillsInfo.addSkillSection}>Add Group</Button>
<Button onClick={skillsInfo.addSkillSection}>Add Group</Button>
</ButtonWrapper> */}
</Fragment>
)}
</Subscribe>
);
};
export default ResumeEditorSkillsInfo;
|
$(() => {
refreshList()
filldropbox();
$('#login').click(() => {
window.localStorage.clear();
window.location.href = '/';
})
$('#addproduct').click(() => {
x = $.trim($('#productname').val().length);
y = $.trim($('#productprice').val().length);
z = $.trim($('#productQ').val().length);
if (x == 0) {
alert('Product Name is Empty')
}
else if (y == 0) {
alert('Price is Empty')
}
else if (z == 0) {
alert('Quantity is Empty')
}
else {
$.post(
'/product',
{
name: $('#productname').val(),
price: $('#productprice').val(),
quantity: $('#productQ').val(),
vendorId: $('#vendorDropbox').val(),
},
(data) => {
if (data.success) {
alert('Data Entered Succesfully')
refreshList()
filldropbox()
$('#productname').val('');
$('#productprice').val('');
$('#productQ').val('');
}
else {
alert('Wrong Input data of Product')
}
}
)
}
})
$('#addVendor').click(() => {
window.location.href = './vendor.html';
})
})
function filldropbox() {
let dropbox = $('#vendorDropbox');
dropbox.empty();
$.get('/vendor', (data) => {
for (let d of data) {
dropbox.append(`<option value=${d.id}>${d.name}</option>`);
}
})
}
function refreshList() {
$.get('/product', (data) => {
$('#productlist').empty()
for (let product of data) {
$('#productlist').append(
`<li> ProductId : ${product.id} <br> Product Name : ${product.name} <br> Product Price : ${product.price} <br> Quantity : ${product.quantity} <br> VendorName : ${product.vendor.name} <br> Action : <button class="deletebutton" id="${product.id}" onClick='deleteProduct(${product.id})'>Delete</button><br><br> </li>`
)
}
})
}
function deleteProduct(id) {
$.post('/product/:id',
{
id: id
}, (data) => {
if (data.success) {
alert('Product Deleted')
refreshList()
filldropbox()
}
else {
alert('Error Occured On Server Side')
}
})
}
|
import Ember from 'ember';
import DS from 'ember-data';
const { Model, attr, belongsTo } = DS;
const { computed } = Ember;
export default Model.extend({
name: attr('string'),
time: attr('string'),
weekday: attr('string'),
studentGroup: belongsTo('student-group', { async: true }),
courseInfo: computed("time", "weekday", function() {
return `${this.get('name')} (${this.get('weekday')} ${this.get('time')})`;
})
});
|
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(['exports', './constants'], factory);
} else if (typeof exports !== "undefined") {
factory(exports, require('./constants'));
} else {
var mod = {
exports: {}
};
factory(mod.exports, global.constants);
global.utils = mod.exports;
}
})(this, function (exports, _constants) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.isArray = exports.toString = undefined;
exports.noop = noop;
exports.getLoggingName = getLoggingName;
exports.getNode = getNode;
exports.normEvents = normEvents;
exports.handlePreventDefault = handlePreventDefault;
exports.seqSlicer = seqSlicer;
exports.cloneArray = cloneArray;
exports.arrayCombinations = arrayCombinations;
exports.isFunction = isFunction;
exports.isString = isString;
exports.partial = partial;
exports.debounce = debounce;
exports.isEqual = isEqual;
exports.isUpper = isUpper;
exports.sortEvents = sortEvents;
exports.normCombo = normCombo;
exports.addListeners = addListeners;
exports.removeListeners = removeListeners;
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj;
};
// Utility functions
function noop(a) {
return a;
};
function getLoggingName(obj) {
// Try to get a usable name/prefix for the default logger
var name = '';
if (obj.name) {
name += " " + obj.name;
} else if (obj.id) {
name += " " + obj.id;
} else if (obj.nodeName) {
name += " " + obj.nodeName;
}
return '[HI' + name + ']';
};
function getNode(nodeOrSelector) {
if (typeof nodeOrSelector == 'string') {
var result = document.querySelector(nodeOrSelector);
return result;
}
return nodeOrSelector;
};
function normEvents(events) {
// Converts events to an array if it's a single event (a string)
if (isString(events)) {
return [events];
}
return events;
};
function handlePreventDefault(e, results) {
// Just a DRY method
// If any of the 'results' are false call preventDefault()
if (results.includes(false)) {
e.preventDefault();
return true; // Reverse the logic meaning, "default was prevented"
}
};
function seqSlicer(seq) {
/**:utils.seqSlicer(seq)
Returns all possible combinations of sequence events given a string of keys. For example::
'a b c d'
Would return:
['a b c d', 'b c d', 'c d']
.. note:: There's no need to emit 'a b c' since it would have been emitted before the 'd' was added to the sequence.
*/
var events = [],
i,
s,
joined;
// Split by spaces but ignore spaces inside quotes:
seq = seq.split(/ +(?=(?:(?:[^"]*"){2})*[^"]*$)/g);
for (i = 0; i < seq.length - 1; i++) {
s = seq.slice(i);
joined = s.join(' ');
if (!events.includes(joined)) {
events.push(joined);
}
}
return events;
};
function cloneArray(arr) {
// Performs a deep copy of the given *arr*
if (isArray(arr)) {
var copy = arr.slice(0);
for (var i = 0; i < copy.length; i++) {
copy[i] = cloneArray(copy[i]);
}
return copy;
} else {
return arr;
}
};
function arrayCombinations(arr, separator) {
var result = [];
if (arr.length === 1) {
return arr[0];
} else {
var remaining = arrayCombinations(arr.slice(1), separator);
for (var i = 0; i < remaining.length; i++) {
for (var n = 0; n < arr[0].length; n++) {
result.push(arr[0][n] + separator + remaining[i]);
}
}
return result;
}
};
var toString = exports.toString = Object.prototype.toString;
function isFunction(obj) {
return toString.call(obj) == '[object Function]';
};
function isString(obj) {
return toString.call(obj) == '[object String]';
};
var isArray = exports.isArray = Array.isArray;
function partial(func) {
var args = Array.from(arguments).slice(1);
return function () {
return func.apply(this, args.concat(Array.from(arguments)));
};
};
function debounce(func, wait, immediate) {
var timeout, result;
return function () {
var context = this;
var args = arguments;
var later = function later() {
timeout = null;
if (!immediate) {
result = func.apply(context, args);
}
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) {
result = func.apply(context, args);
}
return result;
};
};
function isEqual(x, y) {
return x && y && (typeof x === 'undefined' ? 'undefined' : _typeof(x)) === 'object' && (typeof y === 'undefined' ? 'undefined' : _typeof(y)) === 'object' ? Object.keys(x).length === Object.keys(y).length && Object.keys(x).reduce(function (equal, key) {
return equal && isEqual(x[key], y[key]);
}, true) : x === y;
};
function isUpper(str) {
if (str == str.toUpperCase() && str != str.toLowerCase()) {
return true;
}
};
function sortEvents(events) {
/**:utils.sortEvents(events)
Sorts and returns the given *events* array (which is normally just a copy of ``this.state.down``) according to HumanInput's event sorting rules.
*/
var priorities = _constants.MODPRIORITY;
// Basic (case-insensitive) lexicographic sorting first
events.sort(function (a, b) {
return a.toLowerCase().localeCompare(b.toLowerCase());
});
// Now sort by length
events.sort(function (a, b) {
return b.length - a.length;
});
// Now apply our special sorting rules
events.sort(function (a, b) {
a = a.toLowerCase();
b = b.toLowerCase();
if (a in priorities) {
if (b in priorities) {
if (priorities[a] > priorities[b]) {
return -1;
} else if (priorities[a] < priorities[b]) {
return 1;
} else {
return 0;
}
}
return -1;
} else if (b in priorities) {
return 1;
} else {
return 0;
}
});
return events;
}
function normCombo(event) {
/**:normCombo(event)
Returns normalized (sorted) event combos (i.e. events with '-'). When given things like, 'โ-Control-A' it would return 'ctrl-os-a'.
It replaces alternate key names such as 'โ' with their internally-consistent versions ('os') and ensures consistent (internal) ordering using the following priorities:
1. ctrl
2. shift
3. alt
4. os
5. length of event name
6. Lexicographically
Events will always be sorted in that order.
*/
var events = event.split('-'); // Separate into parts
var ctrlCheck = function ctrlCheck(key) {
if (key == 'control') {
// This one is simpler than the others
return _constants.ControlKeyEvent;
}
return key;
};
var altCheck = function altCheck(key) {
for (var j = 0; j < _constants.AltAltNames.length; j++) {
if (key == _constants.AltAltNames[j]) {
return _constants.AltKeyEvent;
}
}
return key;
};
var osCheck = function osCheck(key) {
for (var j = 0; j < _constants.AltOSNames.length; j++) {
if (key == _constants.AltOSNames[j]) {
return _constants.OSKeyEvent;
}
}
return key;
};
// First ensure all the key names are consistent
for (var i = 0; i < events.length; i++) {
events[i] = events[i].toLowerCase();
events[i] = ctrlCheck(events[i]);
events[i] = altCheck(events[i]);
events[i] = osCheck(events[i]);
}
// Now sort them
sortEvents(events);
return events.join('-');
};
function addListeners(elem, events, func, useCapture) {
/**:HumanInput.addListeners()
Calls ``addEventListener()`` on the given *elem* for each event in the given *events* array passing it *func* and *useCapture* which are the same arguments that would normally be passed to ``addEventListener()``.
*/
events.forEach(function (event) {
elem.addEventListener(event, func, useCapture);
});
}
function removeListeners(elem, events, func, useCapture) {
/**:HumanInput.removeListeners()
Calls ``removeEventListener()`` on the given *elem* for each event in the given *events* array passing it *func* and *useCapture* which are the same arguments that would normally be passed to ``removeEventListener()``.
*/
events.forEach(function (event) {
elem.removeEventListener(event, func, useCapture);
});
}
}); |
// Interfaces
const userInterface = require('./users');
const statisticsInterface = require('./statistics');
module.exports = { userInterface, statisticsInterface };
|
import React, { Component } from 'react';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {
toDoList: [],
input: ''
}
}
changeInput = (evt) => {
this.setState({ input: evt.target.value })
};
appendToList = () => {
const newList = this.state.toDoList.concat([this.state.input]);
this.setState({
input: '',
toDoList: newList
});
};
deleteItem = (selectedItem) => {
console.log(selectedItem);
const newList = this.state.toDoList.filter(item => selectedItem !== item );
console.log(newList);
this.setState({
toDoList: newList
})
}
render() {
return (
<div className="App">
<h1 className="App-title">To Do List</h1>
<Todolist list={this.state.toDoList} deleteItem={ this.deleteItem } />
<input value= {this.state.input} onChange={this.changeInput} />
<div onClick={this.appendToList}>Add Me</div>
</div>
);
}
}
//Child component
const Todolist = ({ list, deleteItem }) => {
return (
<ul>
{list.map((listItem, ind) => <li style={{ paddingTop: '6px', paddingBottom: '6px' }} key={ind} onClick={() => { deleteItem(listItem) } }> {listItem} </li>)}
</ul>
)
}
export default App;
// import React from 'react'
// const TodoItem = ({ todo }) => (
// <span>{todo.name}</span>
// )
// const TodoList = ({ todos, addTodo }) => (
// <ul>
// {todos.map(todo => <li><TodoItem todo={todo}/></li>)}
// </ul>
// )
// class TodoContainer extends React.Component {
// constructor() {
// super()
// this.state = { todos = [] }
// }
// addTodo = () => {
// }
// render() {
// return (
// <div>
// <button onClick={this.addTodo}>Add Todo</button>
// <TodoList todos={this.state.todos} />
// </div>
// )
// }
// }
// export default TodoContainer
|
//
// This application performs an HTTP Get on a number of given URLs
// passed in via command line. It collects the data
// before printing it AND prints out the data from the URLs
// in the same order they were passed in.
//
// Usage:
// nodejs Handling_Callbacks.js www.myurl.com
//
//
// Include the required modules.
var http = require("http");
var storage = [];
var urlList = [];
var asyncCounter = 0;
// Store all the URL's from the command line in an array
for(var i = 2; i < process.argv.length; i++){
urlList.push(process.argv[i]);
}
// This function prints out all the data in the storage array
// The storage array contains the data received from http.get
function AsyncComplete(){
for(var j = 0; j < storage.length; j++){
console.log(storage[j]);
};
};
// "Entry" function
function main(){
// Do an http get on each of the provided URL's
for(var i = 0; i < urlList.length; i++){
(function(i){
http.get(urlList[i], function(response){
var body = "";
// Got a chunk of data!
response.on("data", function(chunk){
body += chunk;
});
// All done with our request.
response.on("end", function (){
// Store the total response from the URL
storage[i] = body;
asyncCounter++;
// Check if we can print the results yet
// I want to wait for all the calls to complete so I am using a counter
if(asyncCounter == urlList.length){
AsyncComplete();
}
});
});
})(i);
};
};
main();
|
import React from 'react'
import {ImgBox} from './ShopCar.styled'
import emptyCar from '@a/images/iconku/emptycar.png'
import {useHistory} from 'react-router-dom'
export default function EmptyCar(){
const history = useHistory()
return(
<ImgBox>
<img src={emptyCar} alt=""/>
<p>่็ฏฎๅญ็ฉบ็ฉบๅฆไน</p>
<h5 onClick={()=>history.push("/home")}>ๅๅพๆข่ดญๅๅ</h5>
</ImgBox>
)
} |
'use strict';
class MsgStoreServiceMock {
constructor() {
this._messages = [];
}
add() {}
all() {}
}
export default new MsgStoreServiceMock; |
var Phaser = Phaser || {};
var GameTank = GameTank || {};
GameTank.BootState = function () {
"use strict";
GameTank.BaseState.call(this);
};
GameTank.BootState.prototype = Object.create(GameTank.BaseState.prototype);
GameTank.BootState.prototype.constructor = GameTank.BootState;
GameTank.BootState.prototype.preload = function () {
"use strict";
game.load.image('loading', 'assets/preloader.gif');
};
GameTank.BootState.prototype.create = function () {
"use strict";
game.state.start('PreloadState');
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.