text
stringlengths 7
3.69M
|
|---|
import PropTypes from 'prop-types';
import React, {Component} from 'react';
import {AsyncStorage} from 'react-native';
import {
Button,
DropDownMenu,
Image,
ListView,
View,
Tile,
Text,
Icon,
Card,
Title,
Caption,
GridRow,
Subtitle,
TouchableOpacity,
Screen,
Divider,
ImageBackground
} from '@shoutem/ui';
import {
NavigationBar,
} from '@shoutem/ui/navigation';
import {connect} from 'react-redux';
import {navigatePush} from '../redux';
// class rightButton extends React.Component {
// render() {
// return(
// <View styleName="container" virtual>
// <Button>
// <Icon name="cart"/>
// </Button>
// </View>
// );
// }
// }
const rightButton = () => {
const cars = require("../assets/data/menu");
let selectedCar = cars[0];
return (
<View styleName="container" virtual>
<DropDownMenu
options={cars}
selectedOption={cars[0]}
onOptionSelected={(car) => {
selectedCar = car;
console.log(car);
}}
titleProperty="title"
valueProperty="value"
/>
</View>
);
}
class RestaurantsGrid extends Component {
static propTypes = {
onButtonPress: PropTypes.func,
onDetailsButtonPress: PropTypes.func,
};
constructor(props) {
super(props);
this.renderRow = this.renderRow.bind(this);
this.state = {
restaurants: this.getRestaurants()
}
}
getRestaurants() {
return require('../assets/data/restaurants.json');
}
renderRow(restaurants, sectionId, index) {
const {onButtonPress, onDetailsButtonPress} = this.props;
if (index === '0') {
const restaurant = restaurants[0];
return (
<TouchableOpacity onPress={() => onButtonPress(restaurant)}>
<ImageBackground
styleName="large-banner"
source={{uri: restaurant.image.url}}
>
<Tile>
<Title styleName="md-gutter-bottom">{restaurant.name}</Title>
<Subtitle styleName="sm-gutter-horizontal">{restaurant.address}</Subtitle>
</Tile>
</ImageBackground>
<Divider styleName="line"/>
</TouchableOpacity>
);
}
const cellViews = restaurants.map((restaurant, id) => {
return (
<TouchableOpacity key={id} styleName="flexible" onPress={() => onDetailsButtonPress(restaurant)}>
<Card styleName="flexible">
<Image
styleName="medium-wide"
source={{uri: restaurant.image.url}}
/>
<View styleName="content">
<Subtitle numberOfLines={3}>{restaurant.name}</Subtitle>
<View styleName="horizontal">
<Caption styleName="collapsible" numberOfLines={2}>{restaurant.address}</Caption>
</View>
</View>
</Card>
</TouchableOpacity>
);
});
return (
<GridRow columns={2}>
{cellViews}
</GridRow>
);
}
render() {
// Group the restaurants into rows with 2 columns, except for the
// first article. The first article is treated as a featured article
let isFirstArticle = true;
const groupedData = GridRow.groupByRows(this.state.restaurants, 2, () => {
if (isFirstArticle) {
isFirstArticle = false;
return 2;
}
return 1;
});
return (
<Screen>
<NavigationBar
//renderLeftComponent={leftButton}
renderRightComponent={rightButton}
title="All Restaurants (Grid)"
/>
<ListView
data={groupedData}
renderRow={this.renderRow}
/>
</Screen>
);
}
}
const mapDispatchToProps = (dispatch) => ({
onButtonPress: (restaurant) => {
dispatch(navigatePush({
key: 'RestaurantsList',
title: 'Details',
}, {restaurant}));
},
onDetailsButtonPress: (restaurant) => {
dispatch(navigatePush({
key: 'RestaurantDetails',
title: 'Details',
}, {restaurant}));
},
});
export default connect(
undefined,
mapDispatchToProps
)(RestaurantsGrid);
|
/* eslint-disable unicorn/prevent-abbreviations */
async function checkAuth(request, res) {
if (!request.session.data) {
return res.status(401).json();
}
const {username} = request.session.data;
return res.status(200).json({username});
}
const mockRequest = (sessionData) => {
return {
session: {data: sessionData}
};
};
const mockResponse = () => {
const res = {};
res.status = jest.fn().mockReturnValue(res);
res.json = jest.fn().mockReturnValue(res);
return res;
};
test('should 401 if session data is not set', async () => {
const request = mockRequest();
const res = mockResponse();
await checkAuth(request, res);
expect(res.status).toHaveBeenCalledWith(401);
});
test('should 200 with username from session if session data is set', async () => {
const request = mockRequest({username: 'hugo'});
const res = mockResponse();
await checkAuth(request, res);
expect(res.status).toHaveBeenCalledWith(200);
expect(res.json).toHaveBeenCalledWith({username: 'hugo'});
});
|
(function(shoptet) {
function isTokenExpired() {
let t = new Date().getTime();
let ti = shoptet.csrf.tokenIssuedAt;
return t - ti > shoptet.csrf.tokenValidity;
}
function injectToken(f) {
let i = f.querySelector('[name=__csrf__]');
if (i) {
i.value = shoptet.csrf.token;
} else {
let i = document.createElement('input');
i.setAttribute('type', 'hidden');
i.setAttribute('name', '__csrf__');
i.setAttribute('value', shoptet.csrf.token);
f.appendChild(i);
}
}
function validateToken() {
var response;
$.ajax({
type: 'POST',
url: shoptet.csrf.validateURL,
data: {
__csrf__: shoptet.csrf.token
},
async: false
})
.done(function() {
response = true;
})
.fail(function() {
response = false;
});
return response;
}
if (shoptet.csrf.enabled) {
shoptet.csrf = shoptet.csrf || {};
shoptet.scripts.libs.csrf.forEach(function(fnName) {
var fn = eval(fnName);
shoptet.scripts.registerFunction(fn, 'csrf');
});
shoptet.csrf.tokenIssuedAt = new Date().getTime();
/*
The validity has to be synced with $csrf_window in cms/packages/Security/CSRFTrait.php
The maximum validity of the token is 6h 59m when it is generated right at the
top of the hour; so instead we have to count with 5h 59m and subtract five more
minutes just for sure.
*/
shoptet.csrf.tokenValidity = 1000 * 60 * 59 * 6;
document.addEventListener("DOMContentLoaded", function() {
var selector;
if (shoptet.csrf.formsSelector === '') {
selector = 'form';
} else {
selector = 'form' + '.' + shoptet.csrf.formsSelector;
}
document.querySelectorAll(selector).forEach(function(form) {
shoptet.csrf.injectToken(form);
});
});
if (shoptet.csrf.submitListener) {
document.addEventListener('submit', function(e) {
if (e.target && (shoptet.csrf.formsSelector === '' || e.target.classList.contains(shoptet.csrf.formsSelector))) {
var prevDefaultPrevented = e.defaultPrevented;
e.preventDefault();
e.stopPropagation();
shoptet.csrf.injectToken(e.target);
if (shoptet.csrf.isTokenExpired() && !shoptet.csrf.validateToken()) {
var modalContent = shoptet.csrf.invalidTokenModal;
shoptet.modal.open({
html: shoptet.content.colorboxHeader + modalContent + shoptet.content.colorboxFooter,
className: shoptet.modal.config.classMd,
width: shoptet.modal.config.widthMd
});
return false;
}
if (!prevDefaultPrevented) {
e.target.submit();
}
}
});
}
}
})(shoptet);
|
import React, { Component } from "react";
import "d3";
import * as d3Z from "d3-zoom";
import * as d3 from "d3-selection";
//import d3Scale from 'd3-scale'
import { geoMercator, geoPath } from "d3-geo";
import "./WorldMap.css";
import countries from "../resources/world-countries.json";
//
export default class WorldMap extends Component {
constructor(props) {
super(props);
this.width = 1300; //document.body.clientWidth,
this.height = 600; //document.body.clientHeight;
this.circleRadius = 2;
this.lstRadius = [7, this.circleRadius];
this.lstColor = ["green", "white"];
this.duration = parseInt(this.props.pulseDuration, 10); //500
this.visibilityHours=parseInt(this.props.maxVisibilityHours,10);
this.historicData=parseInt(this.props.historicData,10);
this.lstShots = [];
this.projection = geoMercator();
this.path = geoPath().projection(this.projection);
this.d3Zoom = d3Z.zoom();
this.getCirclePos = d => {
return "translate(" + this.projection([d.long, d.lat]) + ")";
};
this.svgObj = null;
this.feature = null;
this.circle = null;
this.componentDidMount = this.componentDidMount.bind(this);
this.componentDidUpdate = this.componentDidUpdate.bind(this);
}
componentDidMount() {
this.duration = parseInt(this.props.pulseDuration, 10); //500
this.visibilityHours==parseInt(this.props.maxVisibilityHours,10);
this.historicData=parseInt(this.props.historicData,10)
for (var i = 0; i < this.props.data.length; i++) {
this.lstShots.push(JSON.parse(JSON.stringify(this.props.data[i])));
}
this.svgObj = d3.select("#svgMap")
//responsive SVG needs these 2 attributes and no width and height attr
.attr("preserveAspectRatio", "xMinYMin meet")
.attr("viewBox", "0 0 1280 720")
//class to make it responsive
.classed("svg-content-responsive", true);
this.feature = this.svgObj
.selectAll("path.feature")
.data(countries.features)
.enter()
.append("path")
.attr("class", "feature");
this.projection
.scale(this.width / 6.5)
.translate([this.width / 2, this.height / 1.6]);
this.feature.attr("d", this.path);
const proj = this.projection;
const feat = this.feature;
const p = this.path;
this.zoom = this.d3Zoom.on("zoom", function() {
proj
.translate([d3.event.transform.x, d3.event.transform.y])
.scale(d3.event.transform.k);
feat.attr("d", p);
});
this.svgObj.call(this.zoom);
this.svgObj.call(
this.zoom.transform,
d3Z.zoomIdentity
.translate(
this.projection.translate()[0],
this.projection.translate()[1]
)
.scale(this.projection.scale())
);
}
componentDidUpdate() {
console.log(this.props.pulseDuration);
console.log("pulse value"+this.duration);
this.duration = parseInt(this.props.pulseDuration, 10); //500
this.visibilityHours==parseInt(this.props.maxVisibilityHours,10);
this.historicData=parseInt(this.props.historicData,10)
this.lstShots = [];
for (var i = 0; i < this.props.data.length; i++) {
this.lstShots.push(JSON.parse(JSON.stringify(this.props.data[i])));
}
this.svgObj.selectAll("circle").remove();
this.circle = this.svgObj
.selectAll("circle")
.data(this.lstShots)
.enter()
.append("circle")
.attr("r", this.circleRadius)
.attr("fill", "white")
//.attr("transform", this.getCirclePos)
.attr("node", function(d) {
return JSON.stringify(d);
})
.style("cursor", "pointer")
.on("click", function(d) {
var url =
"https://www.google.com/maps?t=k&q=loc:" + d.lat + "+" + d.long;
var win = window.open(url, "_blank");
win.focus();
});
this.lstRadius.forEach(function(d, i) {
this.svgObj
.selectAll("circle")
.filter(function(d) {
return d.isNew;
})
.transition()
.duration(this.duration)
.delay(i * this.duration)
.attr("r", d)
.attr("fill", this.lstColor[i]);
}, this);
const proj = this.projection;
const feat = this.feature;
const p = this.path;
const cir = this.circle;
const gcp = this.getCirclePos;
this.zoom = this.d3Zoom.on("zoom", function() {
proj
.translate([d3.event.transform.x, d3.event.transform.y])
.scale(d3.event.transform.k);
feat.attr("d", p);
cir.attr("transform", gcp);
});
this.svgObj.call(this.zoom);
this.svgObj.call(
this.zoom.transform,
d3Z.zoomIdentity
.translate(
this.projection.translate()[0],
this.projection.translate()[1]
)
.scale(this.projection.scale())
);
}
render() {
return (
<div className="svgMap svg-container">
<h1>{this.props.duration}</h1>
<svg id="svgMap" />
</div>
);
}
}
|
import { useEffect, useCallback } from 'react';
import LOCAL_STORAGE from '../constants/localStorage';
import helpers from '../utils/helpers';
import api from '../services/api';
import useLocalStorageReducer from './useLocalStorageReducer';
import tasks, { initState } from '../reducer/tasks';
import { fetchInit, fetchSuccess, fetchFailure } from '../actions/actionCreator';
const useFetchTaskList = () => {
const [state, dispatch] = useLocalStorageReducer(LOCAL_STORAGE.KEY, initState, tasks);
const fetchData = useCallback(async () => {
dispatch(fetchInit());
try {
const result = await api.getTasks();
const sortedTaskList = helpers.sortById(result);
dispatch(fetchSuccess(sortedTaskList));
} catch {
dispatch(fetchFailure());
}
}, [dispatch]);
useEffect(() => {
fetchData();
}, [fetchData]);
return [state, dispatch, fetchData];
};
export default useFetchTaskList;
|
import React, {Component} from 'react';
import { Link } from 'react-router-dom';
class Callout extends Component {
render() {
return (
<section className="parallax light bg-img-9" data-overlay-light="9">
<div className="background-image">
<img src="wunderkind/img/backgrounds/bg-5.jpg" alt="#"/>
</div>
<div className="container pt100 pb100">
<div className="row pt20">
<div className="col-md-12 text-center">
<h2>Ready to <span className="bold">Help</span> Your Single Friends ?</h2>
<p className="lead">
Use <span className="bold">HaveYouMet</span> to bring some more
<span className="color">Happiness</span> into their lives
</p>
<Link to="/register" className="btn btn-lg btn-primary btn-scroll">
<span>Start Now <i className="ion-checkmark"/></span>
</Link>
</div>
</div>
</div>
</section>
);
}
}
export default Callout;
|
import React,{Component} from 'react';
class Portfolio extends Component{
render(){
return(
<div>
<div className="container portfolio">
<h1 className="text-center">PORTFOLIO</h1>
<h2 className="text-center">My projects and works sample</h2>
<div className="row">
<a href="https://github.com/harryac07" target="_blank"><button className="more-project-button">More Projects</button></a>
<div className="col-sm-4 col-md-4 col-xs-12 animate-image">
<div>
<figure><img src="/images/gadget.jpg" className="img img-responsive image-portfolio" /></figure>
<div className="middle">
<a href="https://profinder1.herokuapp.com/#/" target="blank"><div className="text">visit me</div></a>
</div>
</div>
</div>
<div className="col-sm-4 col-md-4 col-xs-12 animate-image">
<div>
<figure><img src="/images/blog.png" className="img img-responsive image-portfolio" /></figure>
<div className="middle">
<a href="http://kathmandudaily.herokuapp.com/" target="blank"><div className="text">visit me</div></a>
</div>
</div>
</div>
<div className="col-sm-4 col-md-4 col-xs-12 animate-image">
<div>
<figure><img src="/images/codepen.png" className="img img-responsive image-portfolio" /></figure>
<div className="middle">
<a href="http://codepen.io/haria/" target="blank"><div className="text">visit me</div></a>
</div>
</div>
</div>
<div className="col-sm-4 col-md-4 col-xs-12 animate-image">
<div>
<figure><img src="/images/shivasai.jpg" className="img img-responsive image-portfolio" /></figure>
<div className="middle">
<a href="http://www.shivasaiconstruction.com/" target="blank"><div className="text">visit me</div></a>
</div>
</div>
</div>
<div className="col-sm-4 col-md-4 col-xs-12 animate-image">
<div>
<figure><img src="/images/github.jpg" className="img img-responsive image-portfolio" /></figure>
<div className="middle">
<a href="https://github.com/harryac07" target="blank"><div className="text">visit me</div></a>
</div>
</div>
</div>
<div className="col-sm-4 col-md-4 col-xs-12 animate-image">
<div>
<figure><img src="/images/tictactoe.jpg" className="img img-responsive image-portfolio" /></figure>
<div className="middle">
<a href="http://codepen.io/haria/full/qRQxQX" target="blank"><div className="text">visit me</div></a>
</div>
</div>
</div>
</div>
<div className="download">
<a href="/file/cv.pdf" download="cv_hari" className="text-center download-link">DOWNLOAD CV</a>
</div>
</div>
</div>
);
}
}
export default Portfolio;
|
import './App.css';
import { EOSIconsAbstract } from './components/index';
import Adapter from './components/adapter';
function App() {
return (
<div className="App">
<header className="App-header">
<p>
This app is using EOS Icons
</p>
<Adapter svg={EOSIconsAbstract} size={50}/>
</header>
</div>
);
}
export default App;
|
import React, {useState} from 'react'
import Button from '@material-ui/core/Button'
import Dialog from '@material-ui/core/Dialog'
import DialogTitle from '@material-ui/core/DialogTitle'
import DialogContent from '@material-ui/core/DialogContent'
import DialogActions from '@material-ui/core/DialogActions'
import TextField from '@material-ui/core/TextField'
import { makeStyles } from '@material-ui/core/styles'
import { OpenSeaPort, Network } from 'opensea-js'
const useStyles = makeStyles(theme => ({
input: {
marginBottom: theme.spacing(2)
}
}))
const MakeOfferForm = ({open, onClose, data}) => {
const classes = useStyles()
const [form, setForm] = useState({})
const handleChange = event => {
const name = event.target.name
const value = event.target.value
setForm({...form, [name]:value})
}
const handleSubmit = async () => {
const accounts = await window.ethereum.request({
method: 'eth_requestAccounts'
})
const seaport = new OpenSeaPort(window.ethereum, {
networkName: Network.Main
})
const referrerAddress = '0x9d280d898BcBfd84656c36d18a82D5BaeF54020C'
const offer = await seaport.createBuyOrder({
asset: {
tokenId: data.tokenId,
tokenAddress: data.tokenAddress,
schemaName: 'ERC1155'
},
accountAddress: accounts[0],
startAmount: form.price,
expirationTime: Math.round(Date.now()/1000 + 60*60*24),
referrerAddress
})
onClose()
}
return (
<Dialog open={open} onClose={onClose}>
<DialogTitle>Make Offer</DialogTitle>
<DialogContent>
{/*
<TextField fullWidth
className={classes.input}
variant="outlined"
label="Count"
name="count"
onChange={handleChange}
value={form.count}
/>*/}
<TextField fullWidth
className={classes.input}
variant="outlined"
label="Price"
name="price"
helperText="unit: ETH"
onChange={handleChange}
value={form.price}
/>
</DialogContent>
<DialogActions>
<Button onClick={onClose}>Cancel</Button>
<Button onClick={handleSubmit} color="primary">Submit</Button>
</DialogActions>
</Dialog>
)
}
export default MakeOfferForm
|
CheckBox = function (id,label,valueArray,tagCount,nVis,nEditable) {
this.id = id;
this.label = label;
this.valueArray = valueArray;
this.tagCount = tagCount;
this.nVis = nVis;
this.nEditable = nEditable;
CheckBox.baseConstructor.call(id,label,valueArray,tagCount);
};
CheckBox.prototype = {
generate: function () {
var htmlContent = "";
htmlContent = htmlContent+'<input style="font-size:11px;" id="value_id_'+this.tagCount+'" type="checkbox" name="'+this.label+'" onclick="onChecked(this)" ';
if(this.nEditable=='false'){
htmlContent = htmlContent+' disabled="disabled" ';
}
var style = ' style="width:50px; border:1px solid #0040FF;font-size:12px;';
if(this.nVis=='false'){
style = style + ' display:none ';
}
style=style+'"';
htmlContent+=style;
if(this.valueArray[0].Value==1 || this.valueArray[0].Value=='on'){
htmlContent+= " checked value='1' ";
}
else{
htmlContent+= " value='0'";
}
htmlContent+= '/>' ;
return htmlContent;
}
};
function onChecked(obj){
if(obj.checked){
obj.value="1";
}else {
obj.value="0";
}
}
|
const share = document.querySelector('.component-share');
const svg = document.querySelector('.component-share-icon path');
const popup = document.querySelector('.component-popup');
const popupMobile = document.querySelector('.component-popup-mobile');
let activated = false;
share.addEventListener('click', () => {
activated = !activated;
share.classList.toggle('active');
svg.classList.toggle('active-svg');
popup.classList.toggle('active-popup');
if(window.innerWidth <= 1120) {
popupMobile.classList.toggle('active-popup')
}
})
function disableStyles() {
if(window.innerWidth >= 1120 && activated){
activated = false;
share.classList.remove('active');
svg.classList.remove('active-svg');
popup.classList.remove('active-popup');
popupMobile.classList.remove('active-popup')
}
}
window.addEventListener('resize', disableStyles)
|
import _ from 'lodash';
import * as http from '@/http';
function list(state, data) {
if (data.count) {
state.total = data.count;
}
state.items = data.items;
}
function update(state, { id, data }) {
const items = state.items;
/* eslint no-underscore-dangle:0 */
const index = _.findIndex(items, item => item._id === id);
_.extend(items[index], data);
}
function add(state, data) {
state.items.push(data);
}
function createListAction(mutationType, url) {
return async ({ commit }, query) => {
const res = await http.get(url)
.query(query);
commit(mutationType, res.body);
};
}
function createAddAction(mutationType, url) {
return async ({ commit }, data) => {
const res = await http.post(url, data);
commit(mutationType, res.body);
};
}
function createUpdateAction(mutationType, url) {
return async ({ commit }, { id, data }) => {
await http.patch(`${url}/${id}`, data);
commit(mutationType, {
id,
data,
});
};
}
export function createMutation(type) {
const fns = {
list,
update,
add,
};
return fns[type] || _.noop;
}
export function createAction(type, mutationType, url) {
const fns = {
list: createListAction,
update: createUpdateAction,
add: createAddAction,
};
return (fns[type] || _.noop)(mutationType, url);
}
|
import React from 'react';
import PropTypes from 'prop-types';
import classes from '../index.module.css';
import {MDBListGroupItem} from 'mdbreact';
export const CompanyRadio = (props) => (
<MDBListGroupItem
className={classes.listGroupItems}
>
<p className={classes.listGroupItemsSecondTag}>前单位</p>
<form className={classes.radioForm}>
<div className="form-check">
<input type="radio" className="form-check-input" name="company" id="radioCmp1" defaultChecked={props.checked} />
<label className="form-check-label" htmlFor="radioCmp1">阿尔托大学(2,980)</label>
</div>
<div className="form-check">
<input type="radio" className="form-check-input" name="company" id="radioCmp2"/>
<label className="form-check-label" htmlFor="radioCmp2">华盛顿大学(986)</label>
</div>
<div className="form-check">
<input type="radio" className="form-check-input" name="company" id="radioCmp3"/>
<label className="form-check-label" htmlFor="radioCmp3">纽约大学(86)</label>
</div>
<div className="form-check">
<input type="radio" className="form-check-input" name="company" id="radioCmp4"/>
<label className="form-check-label" htmlFor="radioCmp4">哈佛大学(26)</label>
</div>
<div className="form-check">
<input type="radio" className="form-check-input" name="company" id="radioCmp5"/>
<label className="form-check-label" htmlFor="radioCmp5">伯克利加州分校(26)</label>
</div>
</form>
</MDBListGroupItem>
);
CompanyRadio.propTypes = {
checked: PropTypes.bool.isRequired
};
|
const config = require("../config.json")
var r = require('rethinkdbdash')({
db: config.rethinkdb.db
});
module.exports = r;
|
import React from 'react'
import { storiesOf } from '@storybook/react'
import { action } from '@storybook/addon-actions'
import PlayButton from './PlayButton'
storiesOf('PlayButton', module)
.add('with play icon', () => {
return <PlayButton onClick={action('onClick')} />
})
.add('with stop icon', () => {
return <PlayButton showStopIcon onClick={action('onClick')} />
})
|
/**
* The prime factors of 13195 are 5, 7, 13 and 29.
*
* What is the largest prime factor of the number 600851475143 ?
*/
var input = 600851475143;
function largestPrimeFactor (input) {
for (var i = 2; i <= input/2; i++) {
if (isPrime(input/i)) {
console.log('the largest prime is: ', input/i);
return;
}
}
}
function isPrime (factor) {
for (var i = 3; i <= factor/2; i++) {
if ((factor % 1) || factor % i === 0) {
return false;
}
}
return true;
}
largestPrimeFactor(input);
|
export const theme = {
primary: 'hsl( , , )',
white: 'hsl( , , )',
grey: 'hsl( , , )',
black: 'hsl( , , )',
font: {
size: {
xs: '.9rem',
s: '1.4rem',
m: '2.6rem',
l: '4.2rem',
xl: '7.2rem',
xxl: '9.4rem',
},
family: {
neuville:'"", ',
aktiv:'"", ',
}
}
}
|
let burger = document.querySelector('.icon-menu');
let headerMenu = document.querySelector('.menu__body');
burger.addEventListener('click', function() {
burger.classList.toggle('_active');
headerMenu.classList.toggle('_active');
});
|
const Sequelize = require('sequelize');
const userModel = require("../dao/sequelizeDao");
const Op = Sequelize.Op
const filecontroller = {
// //显示到页面
getany(req, res) {
userModel.findAll(
{
where: {
id: {
[Op.between]: [1, 10],
}
}
}
).then(data => {
console.log(data)
res.send(data)
})
},
//增加
addsome(req, res) {
userModel.create({
year: '2008-05-05',
name: '小明',
sex:1,
position:'前台',
Jurisdiction: '是',
Blacklist: '否'
}).then(data=>{
console.log(data)
}).catch( err =>{
console.log(err);
});
},
//删除
deltesome(req, res) {
userModel.destroy({
where:{
id:12
}
}).then( data=>{
console.log(data)
});
},
//查询
querysome(req, res) {
userModel.findAll({
where:{
name: 'duuliy',
}
}).then(data=>{
res.send(data)
}).catch( err =>{
console.log(err);
});
},
//修改
upsome(req, res) {
userModel.update({
name: '飞天禽兽',
},{
where:{
id:'2'
}
}).then(data=>{
res.send(data)
}).catch( err =>{
console.log(err);
});
}
};
module.exports = filecontroller;
|
/**
*
*/
function handleLoginRequest(xhr, status, args) {
if (args.loggedIn) {
try {
$("#div_login").hide("drop", {
direction : "up"
}, 1000);
setTimeout(function() {
$("#div_manager").show("drop", {
direction : "down"
}, 1000);
}, 1000);
;
} catch (err) {
}
}
}
function handleCloseRequest() {
try {
$("#div_manager").hide("drop", {
direction : "down"
}, 1000);
setTimeout(function() {
$("#div_login").show("drop", {
direction : "up"
}, 1000);
}, 1000);
} catch (err) {
}
}
function timer() {
}
function readOnly(element) {
element.readOnly = true;
}
function notReadOnly(element) {
element.readOnly = false;
}
|
import React, { PureComponent } from 'react'
import Box from 'grommet/components/Box'
import Title from 'grommet/components/Title'
import Header from 'grommet/components/Header'
import Table from 'grommet/components/Table'
import TableRow from 'grommet/components/TableRow'
export default class JobSidebar extends PureComponent {
renderRow = (key, value) => {
if (!value) return null
let cellValue
if (typeof value === 'string') {
cellValue = value
} else if (Array.isArray(value)) {
cellValue = []
value.forEach(v => cellValue.push(v, <br />))
}
return (
<TableRow key={key}>
<td style={{display: 'block'}}><b>{key}</b></td>
<td>{cellValue}</td>
</TableRow>
)
}
render () {
const {
name,
salaryRange,
automationRisk,
description,
otherJobs,
companies
} = this.props.info
return (
<Box>
<h2><b>{name}</b></h2>
<Table>
<thead>
<tr>
<th />
<th />
</tr>
</thead>
<tbody>
{this.renderRow('Salary Range', salaryRange)}
{this.renderRow('Automation Risk', automationRisk)}
{this.renderRow('Description', description)}
{this.renderRow('Other Jobs', otherJobs)}
{this.renderRow('Companies', companies)}
</tbody>
</Table>
</Box>
)
}
}
|
ko.bindingHandlers.jqmRefreshList = {
update: function(element, valueAccessor) {
ko.utils.unwrapObservable(valueAccessor());
$(element).listview("refresh");
}
};
$(document).on('pageinit', function(event) {
if(!location.hash) {
location.hash = '#home';
}
});
$(document).on('pageinit', '#home', function(event) {
$.ajax({
url: "api/home",
complete: function() {
console.log(arguments);
},
success: function(home) {
home.user.team = home.team;
ko.applyBindings(ko.mapping.fromJS(home.user, {
}), document.getElementById("home"));
}
});
});
$(document).on('pageinit', '#team', function(event) {
$.ajax({
url: "api/home",
success: function(team) {
ko.applyBindings(ko.mapping.fromJS(team.team, {
}), document.getElementById("team"));
}
});
});
$(document).on('pageinit', '#leaderboard', function(event) {
$.ajax({
url: "api/leaderboard.json",
success: function(leaderboard) {
ko.applyBindings(ko.mapping.fromJS(leaderboard, {
}), document.getElementById("leaderboard"));
$('#leaderboard div .category').collapsible({
collapsed: true
});
}
});
});
$(document).on('pageinit', '#leaderboard-team', function(event) {
$.ajax({
url: "api/leaderboard-team.json",
success: function(leaderboard) {
ko.applyBindings(ko.mapping.fromJS(leaderboard, {
}), document.getElementById("leaderboard-team"));
$('#leaderboard-team div .category').collapsible({
collapsed: true
});
}
});
});
$(document).on('pageinit', '#badges', function(event) {
$.ajax({
url: "api/reward",
success: function(rewards) {
ko.applyBindings(ko.mapping.fromJS(rewards, {
}), document.getElementById("badges"));
}
});
});
$(document).on('pageinit', '#badges-team', function(event) {
$.ajax({
url: "api/reward",
success: function(rewards) {
ko.applyBindings(ko.mapping.fromJS(rewards, {
}), document.getElementById("badges-team"));
}
});
});
$(document).on('pageinit', '#scoreboard', function(event) {
$.ajax({
url: "api/scoreboard.json",
success: function(scoreboard) {
ko.applyBindings(ko.mapping.fromJS(scoreboard, {
}), document.getElementById("scoreboard"));
$('#scoreboard div .category').collapsible({
collapsed: true
});
}
});
});
var chat = {
friends: ko.observableArray(),
friend: ko.observable()
};
chat.friends.push({
name: {
first: 'Matthew',
last: 'Murphy'
},
unread: ko.observable(1),
chat: ko.observableArray([{
content: 'Hello world!',
time: new Date
}]),
showChat: function() {
this.unread(0);
chat.friend(this);
},
message: ko.observable(),
send: function() {
var msg = {
content: chat.friend().message(),
time: new Date
};
chat.friend().chat.push(msg);
socket.emit('chat', msg);
chat.friend().message('');
}
});
$(document).on('pageinit', '#feed-chat', function(event) {
ko.applyBindings(chat, document.getElementById("feed-chat"));
});
var socket = io.connect('');
socket.on('chat', function (data) {
chat.friend().chat.push(data);
chat.friend().unread(chat.friend().unread() + 1);
$("#chat").trigger("updatelayout");
});
|
import headTpl from './head.html';
import { createModal, flatten } from '../../utils';
import editTpl from './edit.html';
import { RetryRequest } from '../../../../modules/gml-http-request';
import { Node } from '../../../../modules/gml-html';
function getValue(item, key, keyAppendix, what) {
return what === 'key' ? `${keyAppendix}${key}` || '' : item[key].toString();
}
function isObject(value) {
return value instanceof Object && !(value instanceof Array);
}
function reduceObject(item, what = 'value', keyAppendix = '') {
return Object.keys(item)
.filter(key => key !== 'id' && key !== '_id' && key !== 'activationCode' && key !== 'userAuth' && key !== 'hash' && key !== 'userId' && key !== '')
.map(key => isObject(item[key]) ? reduceObject(item[key], what, `${keyAppendix}${key}.`) : `${getValue(item, key, keyAppendix, what)}`);
}
function getColumnItem(item, col) {
const keys = col.split('.');
const value = keys.reduce((acc, key) => {
return acc[key] || {};
}, item);
return value instanceof Object ? '' : value;
}
export default function ({ template, itemTemplate, headerTemplate, filters }, data, tableName, Window, system) {
const obj = {};
let index = 0;
let content;
let head;
let filterText = '';
let table = data.slice(0);
let sort = {
field: '',
direction: 1,
type: 'text'
};
const sorters = {
text: (a, b) => sort.direction * (a.localeCompare(b)),
number: (a, b) => sort.direction * (a - b),
date: (a, b) => sort.direction * (new Date(a).getTime() - new Date(b).getTime())
};
function filter() {
const splitFilter = filterText.split(' ').map(i => i.trim());
table = data
.sort(function (a, b) {
if (!sort.field) return 1;
const a1 = sort.field.split('.').reduce((val, o) => val[o], a);
const b1 = sort.field.split('.').reduce((val, o) => val[o], b);
return sorters[sort.type](a1, b1);
})
.filter(i => {
return filters.reduce(function (acc, field) {
const ands = field.split('&').map(i => i.trim());
if (i[field] && i[field].indexOf(filterText) !== -1) return true;
const matches = ands.filter(function (and) {
const red = and.split('.').reduce((val, o) => val[o], i).toUpperCase();
return splitFilter.filter(f => red.indexOf(f.toUpperCase()) !== -1).length > 0;
});
return !filterText || acc || (matches.length === splitFilter.length);
}, false);
});
content.clear('items');
Window.loadContent();
}
obj.sort = function (e) {
const attribute = e.target.getAttribute('data-sort');
if (attribute) {
const [field, type] = attribute.split(':');
if (field === sort.field) sort.direction *= -1;
sort.field = field;
sort.type = type;
index = 0;
filter();
}
};
obj.start = function (search = '') {
content = Window.content(template, [], {});
head = Window.head(headerTemplate || headTpl, [], {});
Array.from(content.get().getElementsByTagName('th')).forEach(function (el) {
el.addEventListener('click', obj.sort);
el.style.cursor = 'pointer';
});
const form = Window.get();
form.block = function (bool) {
content.get().className = bool ? 'alternate-table blocks' : 'alternate-table';
};
form.search = function (value) {
index = 0;
filterText = value;
filter();
};
form.add = function (showDelete, id) {
if (tableName === 'equipements') {
const eq = system.db.equipements.find(i => i.id === id);
const { modalView, modal } = createModal(editTpl, Object.assign({ showDelete }, eq),
async function (close, isDeleted = false) {
if (!this.code.value) system.throw('custom', { message: 'MANCA IL CODICE' });
if (!this.name.value) system.throw('custom', { message: 'MANCA LA DESCRIZIONE' });
if (!this.constructorId.value) system.throw('custom', { message: 'MANCA IL COSTRUTTORE' });
if (!this.time.value) system.throw('custom', { message: 'MANCA IL TEMPO DI CONSEGNA' });
if (!this.priceReal.value) system.throw('custom', { message: 'MANCA IL PREZZO' });
const priceReal = Number(this.priceReal.value.replace(',', ''));
const res = await RetryRequest(id ? `/api/rest/equipments/${id}` : `/api/rest/equipments`,
{ headers: { 'Content-Type': 'application/json' } })
.send(id ? 'put' : 'post', JSON.stringify({
code: this.code.value,
name: this.name.value,
info: '',
notes: '',
image: '',
depliants: '',
priceReal: priceReal,
priceMin: priceReal,
priceOutsource: priceReal,
priceCGT: priceReal,
familys: [],
equipmentFamily: 'FUORI LISTINO',
constructorId: this.constructorId.value,
time: this.time.value,
compatibility: [],
isDeleted
}));
const item = JSON.parse(res.responseText);
Object.assign(item, { id: item._id });
if (id)
system.db.equipements.splice(system.db.equipements.indexOf(eq), 1);
if (!isDeleted)
system.db.equipements.push(item);
system.updateDb();
close();
index = 0;
filter();
});
}
};
form.save = function () {
const wb = XLSX.utils.book_new();
const flatten = JSON.parse(JSON.stringify(table));
flatten.forEach(item => {
Object.keys(item).forEach(key => {
if (item[key] instanceof Object) {
Object.keys(item[key]).forEach(key2 => {
if (item[key][key2])
item[`${key}.${key2}`] = item[key][key2];
});
}
});
});
XLSX.utils.book_append_sheet(wb, XLSX.utils.json_to_sheet(flatten), tableName);
XLSX.writeFile(wb, `ESTRAZIONE_${new Date().formatDay('dd_mm_yy', [])}.xlsx`);
};
form.get = function (url) {
window.open(url);
};
if (search) {
filterText = search;
filter();
form.block(true);
}
};
obj.destroy = function () {
Array.from(content.get().getElementsByTagName('th')).forEach(function (el) {
el.removeEventListener('click', obj.sort);
});
};
obj.loadContent = async function () {
const item = table[index];
if (content && item) {
content.appendTo('items', itemTemplate, [], Object.assign({}, item, {
showEdit: item.equipmentFamily === 'FUORI LISTINO' ? 'inline-block' : 'none',
name: filterText && item.name ?
item.name.replace(new RegExp(filterText, 'i'), `<strong style="color: green">${filterText}</strong>`) :
item.name
}));
index++;
}
await new Promise(r => setTimeout(r, 0));
};
return obj;
}
|
const path = require('path');
const dependencies = require('../lib/dependencies');
const fromBin = require('../lib/fromBin');
const runner = require('../lib/runner');
module.exports = () => {
runner.executeOrSkip({
fileCheck: fromBin('classes-dex2jar'),
fn() {
runner.runShellSync(
'Convert the dex to jar',
[
path.normalize(fromBin('dex-tools-2.0/dex2jar-2.0/d2j-dex2jar')),
fromBin('old-watchfaces/classes.dex'),
'-o',
fromBin('classes-dex2jar.jar'),
],
);
return dependencies.extractZip({
file: fromBin('classes-dex2jar.jar'),
destination: fromBin('classes-dex2jar'),
});
},
})
}
|
(() => {
const { remote } = require('electron');
const moment = remote.require('moment');
moment.locale('fr');
angular.module('Todos')
.filter('moment', () => {
return (date) => {
if (date !== undefined) {
const m = moment(date);
return m.isValid() ? m.format('ddd DD/MM, H:mm') : '';
}
}
})
.filter('sort', () => {
return (items) => {
const filtered = [];
for (let item of items) {
item.index = filtered.length;
filtered.push(item);
}
filtered.sort((a, b) => {
return (a.date.getTime() === b.date.getTime()) ? a.task.toLowerCase() - b.task.toLowerCase() : a.date.getTime() - b.date.getTime();
});
return filtered;
}
})
.filter('zpad', () => {
return (input, n) => {
if (input === undefined)
input = "";
if (input.length >= n)
return input;
const zeros = "0".repeat(n);
return (zeros + input).slice(-1 * n);
}
});
})();
|
// getter 和 setter
|
function runTest()
{
FBTest.openNewTab(basePath + "html/4826/issue4826.html", function(win)
{
FBTest.openFirebug(function()
{
var panel = FBTest.selectPanel("html");
FBTest.selectElementInHtmlPanel("testnode", function(node)
{
var idAttributeValue = node.getElementsByClassName("nodeValue").item(0);
FBTest.synthesizeMouse(idAttributeValue);
var editor = panel.panelNode.getElementsByClassName("textEditorInner").item(0);
if (FBTest.ok(editor, "Editor must be available now"))
{
FBTest.sendString("foo", editor);
FBTest.synthesizeMouse(panel.panelNode);
var chrome = FW.Firebug.chrome;
var elementPathItems = chrome.window.document.
getElementsByClassName("panelStatusLabel");
FBTest.compare("div#foo", elementPathItems.item(0).label,
"The label of the node inside the Element Path must now be 'div#foo'");
FBTest.synthesizeMouse(elementPathItems.item(1));
var selectedElement = panel.panelNode.getElementsByClassName("nodeBox selected").
item(0);
var selectedElementTagName = selectedElement.firstChild.
getElementsByClassName("nodeTag").item(0).textContent;
var selectedElementId = selectedElement.firstChild.
getElementsByClassName("nodeValue").item(0).textContent;
FBTest.compare(elementPathItems.item(1).label, selectedElementTagName+"#"+
selectedElementId, elementPathItems.item(1).label+" must now be selected");
FBTest.synthesizeMouse(idAttributeValue);
var editor = panel.panelNode.getElementsByClassName("textEditorInner").item(0);
if (FBTest.ok(editor, "Editor must be available now"))
{
FBTest.sendString("bar", editor);
FBTest.synthesizeMouse(panel.panelNode);
FBTest.compare("div#bar", elementPathItems.item(0).label,
"The label of the node inside the Element Path must now be 'div#bar'");
}
}
FBTest.testDone();
});
});
});
}
|
let tooltip = document.querySelector('.tooltip');
let shareIcons = document.querySelectorAll('.share__icon');
shareIcons.forEach(shareIcon => {
shareIcon.addEventListener('click', () => {
tooltip.classList.toggle('active');
})
})
|
Trello.Views.BoardNew = Backbone.CompositeView.extend({
template: JST['board_new'],
tagName: 'li',
events: {
"submit .form-new-board": "newBoardHandler"
},
render: function () {
this.$el.addClass('new-board-form');
this.$el.html(this.template({board: this.model}));
return this;
},
newBoardHandler: function (e) {
e.preventDefault();
var $form = this.$('.form-new-board');
var formdata = $form.serializeJSON();
var that = this;
this.model.save(formdata, {
success: function () {
that.collection.add(that.model);
Backbone.history.navigate("", {trigger: true});
},
error: function (model,response) {
$('.errors').empty();
response.responseJSON.forEach(function (error) {
var $li = $("<li>").text(error);
that.$(".errors").append($li);
Backbone.history.navigate("", {trigger: true});
});
}
});
}
});
|
app.controller('NavbarController', ['$rootScope', '$scope', '$location', 'databaseService', 'AuthorizationService', function($rootScope, $scope, $location, databaseService, AuthorizationService){
$scope.user = {};
$scope.init = function() {
//$scope.user = $rootScope.user;
console.log($scope.user);
};
$scope.status = {
isopen: false
};
$scope.toggled = function(open) {
$log.log('Dropdown is now: ', open);
};
$scope.toggleDropdown = function($event) {
$event.preventDefault();
$event.stopPropagation();
$scope.status.isopen = !$scope.status.isopen;
};
// function for processing user log out operation
$scope.processLogout = function(){
AuthorizationService.logout().then(function(result){
localStorage.setItem("idtfirebaseapp_username", "null")
localStorage.setItem("idtfirebaseapp_password", "null")
$location.path("/login");
}, function(error){
//console.log(error);
});
};
}]);
|
import React from 'react';
import { Link } from 'react-router-dom';
import SearchBarContainer from './containers/SearchBarContainer.js';
import popcornLogo from './popcorn.svg';
const Header = (props) => {
const styles = {
topBar: {
backgroundColor: 'rgb(43, 41, 37)',
},
logo: {
margin: '20px 10px 10px 20px',
},
logoName: {
display: 'inline-block',
color: 'rgb(255, 255, 255)',
verticalAlign: 'middle',
},
searchBarColumn: {
marginTop: '25px',
},
};
return (
<div className="row" style={styles.topBar}>
<div className="four columns">
<Link to="/" onClick={() => { props.resetMatches() }}>
<img src={popcornLogo} alt="Popcorn Now Logo" height="50" width="50" style={styles.logo}/>
<h5 style={styles.logoName}>Popcorn Now</h5>
</Link>
</div>
<div className="four columns" style={styles.searchBarColumn}>
<SearchBarContainer />
</div>
<div className="four columns"></div>
</div>
);
};
export default Header;
|
'use strict';
const chai = require('chai');
var chaiAsPromised = require("chai-as-promised");
chai.use(chaiAsPromised);
const expect = chai.expect;
var assert = require('assert');
var User = require('../../app/models/user');
const mongoose = require('mongoose')
describe('User', function() {
this.timeout(10000);
before(async function() {
await mongoose.connect('mongodb://localhost/test');
await mongoose.connection.db.dropDatabase();
});
it('Should create user successfully', async function() {
const user = await User.newLocalUser(
'username', 'email@gmail.com', 'password');
const foundUser = await User.findLocalUserByUsername('username');
assert(foundUser.local.password == 'password');
});
it('Should fail to create user with the same name', async function() {
await expect(User.newLocalUser('username', 'email@gmail.com', 'password'))
.to.eventually.be.rejectedWith('User: username already exists');
});
it.skip('Should be able to insert many users', async function() {
for (var i = 0; i < 3000; i++) {
if (i % 100 == 0) {
console.log(i + ' users created');
}
const user = await User.newLocalUser(
'username'+i, 'email@gmail.com', 'password');
const foundUser = await User.findLocalUserByUsername('username' + i);
assert(foundUser.local.password == 'password');
}
});
after(async function() {
await mongoose.connection.db.dropDatabase();
await mongoose.connection.close();
});
});
|
const gulp = require('gulp');
const request = require('request');
const fs = require('fs');
const cheerio = require('cheerio');
gulp.task('fetch-teaser', function(cb) {
const metaFile = 'data/meta.json';
fs.readFile(metaFile, 'utf8', function(err, data) {
var urls = JSON.parse(data).teasers;
if (urls.length) {
fetchAllTeasers(urls, cb);
} else {
cb();
}
});
});
const fetchAllTeasers = function(urls, cb) {
var data = [];
var fetchNext = function(index) {
fetchTeaser(urls[index], function(err, datum) {
if (!err && datum) {
data.push(datum);
}
index++;
if (index < urls.length) {
fetchNext(index);
} else {
writeData(data, cb);
}
});
};
fetchNext(0);
};
const fetchTeaser = function(url, cb) {
var datum = {};
request(url, function(err, response, body) {
if (!err && response.statusCode == 200) {
$ = cheerio.load(body);
var titleRaw = $('title').first().text();
var titleClean = titleRaw.split('- The Boston Globe')[0].trim();
datum.url = url;
datum.title = titleClean;
var meta = $('meta');
meta.each(function(i, el) {
if(el.attribs.property && el.attribs.property === 'og:image') {
var imageRaw = el.attribs.content;
var imageHttps = imageRaw.replace('http://', 'https://');
var imageFull = imageHttps.replace('image_585w', 'image_960w');
datum.image = imageFull;
}
});
cb(null, datum);
} else {
cb(true);
}
});
};
const writeData = function(data, cb) {
const teaserFile = 'data/teaser.json';
const str = JSON.stringify(data);
fs.writeFile(teaserFile, str, function(err) {
if (err) {
console.log(err);
}
cb();
});
};
|
// -----------------------
// Lazy loading - images
// -----------------------
echo.init({
offset: 100,
throttle: 250,
unload: false
});
// --------------------
// Global vars
// --------------------
var start = 0;
var count = 49; // number of items at first load
var step = 5; // number of items next to load
var windowWidth = $(window).width(); // sets window width
// --------------------
// Show next items
// --------------------
function retrieveContent() {
for( i = start; i <= count; i++) {
$(".item-note.item-" + i).css("display", "block");
start++;
}
count+= step;
$(".loading").css('display', 'none');
};
function scrollRetieveContent() {
if ($(window).scrollTop() === $(document).height() - $(window).height() ) {
setTimeout(function(){ retrieveContent(); }, 200);
}
}
function touchRetieveContent() {
if ($(window).scrollTop() >= $(document).height() - ( $(window).height() ) ) {
setTimeout(function(){ retrieveContent(); }, 500);
$('.loading').show();
}
}
// -------------------------
// Player Responsivo
// -------------------------
function resizePlayer() {
aspect = 16 / 9;
ancho = $("#ooyalaplayer").width();
alto = ancho / aspect;
$("#ooyalaplayer").height(alto);
}
// -------------------------
// Masonry, the Sussie way
// -------------------------
function acomodaNotas(){
if($(window).width()>=1000){
for(i=0; i<$('.item-note').length; i++){
n = (i % 3)+1;
$('#grid section.columna'+n).append($('.item-note.item-'+i));
}
}
else{
for(i=0; i<$('.item-note').length; i++){
$('.item-note.item-'+i).insertBefore($('#grid .loading'));
}
}
}
function refreshBanners () {
googletag.pubads().refresh();
}
// -------------------------
// Off-canvas navigation
// -------------------------
(function($) {
$(document).ready(function() {
$.slidebars({
scrollLock: true
});
});
}) (jQuery);
// -------------------------
// Responsive Ads
// -------------------------
function insertarBanners(numNotas){
var numIndex = numNotas;
$('.mix-banner').each(function(index){
$(this).insertAfter($('#grid .item-note:nth-child('+numIndex+')'));
$(this).insertAfter($('#grid-nota .item-note:nth-child('+numIndex+')'));
if($('#grid-nota a.item-note').length === 0 || $('#grid-nota .item-note').length < numIndex){
$(this).insertBefore($('#grid-nota .loading'));
}
numIndex = numIndex + (numNotas+1);
});
$('.item-note').each(function(index){
$(this).addClass('item-'+index);
});
}
// -------------------------
// Mostrar banner de "En vivo"
// -------------------------
var topBarLiveNews = $('<div class=top-live-news></div>');
function noticieros(){
var ruta = $(location).attr('href');
if(ruta.indexOf('en-vivo')=== -1){
var date = new Date();
var day = date.getDay();
if(day >= 1 && day <=5){
var hours = date.getHours();
var minutes = date.getMinutes();
if(minutes >= 30){hours += 0.5;}
if(hours>=14 && hours<15){
topBarLiveNews.html("<a class='container' href='http://www.unotv.com/en-vivo'><span>En vivo:</span><span>Uno Noticias</span><span>Ver</span></a>");
topBarLiveNews.insertAfter($('header'));
}else if(hours>=21.5 && hours<22.5){
topBarLiveNews.html("<a class='container' href='http://www.unotv.com/en-vivo'><span>En vivo:</span><span>Noticias en Claro</span><span>Ver</span></a>");
topBarLiveNews.insertAfter($('header'));
}else{
$('.top-live-news').remove();
}
}
}
}
// -------------------------
// Display Social Follow Module
// -------------------------
function displaySocialFollow () {
if($(window).width() > 767 ){
$('#socialFollow').insertAfter('header .logo');
} else {
$('#socialFollow').insertAfter('nav .logo');
}
}
// -------------------------
// Mover Fixed Elements para ver footer
// -------------------------
function moveFooterPosition(){
if($(window).width()>= 748){
$('.anchor-banner').css('bottom','65px');
}else{
$('.anchor-banner').css('bottom','100px');
}
$('#anchorShareButtons').css('bottom','65px');
$('.back-to-top').addClass('button-large');
}
// -------------------------
// Mover Fixed Elements a posicion original
// -------------------------
function moveDefaultPosition(){
if($(window).width()>= 748){
$('.anchor-banner').css('bottom','0px');
}else{
$('.anchor-banner').css('bottom','35px');
}
$('#anchorShareButtons').css('bottom','0px');
$('.back-to-top').removeClass('button-large');
}
// -------------------------
// Call functions
// -------------------------
$(document).ready(function() {
// Banners intercalados
// -------------------
insertarBanners(3);
// Banner del magazine
// -------------------
$('.magazine-banner').appendTo('.magazine-banner-slot');
// Load first set of items
// -------------------
retrieveContent();
// Hides Banner Carso
// -------------------
hayInfiniteSidebar = $('.infinite.sidebar').length;
if(hayInfiniteSidebar === 1){
$('.magazine-banner').css('display','none');
}
// Search
// -------------------
// Show
$('#show-search').click(function(event) {
event.preventDefault();
$('.top-content .search').addClass('search-visible');
$('.content-overlay').toggleClass('show-overlay');
$('.top-content .search input').focus();
});
// Close
$('.content-overlay').click(function(event) {
$('.search').removeClass('search-visible');
$(this).removeClass('show-overlay');
});
// Submenu
// -------------------
$('nav ul ul').find('span').click(function(event) {
if($(this).hasClass('selected')){
$('nav ul ul ul').slideUp('fast');
$('nav ul ul').find('span').removeClass('selected');
}
else{
$('nav ul ul').find('span').removeClass('selected');
$('nav ul ul ul').slideUp('fast');
$(this).next().slideDown('fast');
$(this).addClass('selected');
}
});
// Columns
// -------------------
for(i=3; i>=1; i--){
$("#grid").prepend("<section class='columna columna"+i+"'></section>");
}
if($(window).width()>=1000){
for(i=0; i<$('.item-note').length; i++){
n = (i % 3)+1;
$('#grid section.columna'+n).append($('.item-note.item-'+i));
}
}
// Responsive player
// -------------------
resizePlayer();
// Show: Live News
// -------------------
noticieros();
setInterval(function(){noticieros()},300000);
// Show: Social Follow
// -------------------
displaySocialFollow();
// Boton para regresar al top
// -------------------
var botonSubir = $("<div class='back-to-top'><div class='container'><div class='button-up'><span>Subir al inicio</span><i class='fa fa-chevron-up'></i></div></div></div>");
$('body').append(botonSubir);
$().showUp('.button-up');
});
$(window).resize(function(){
// Structure
// -------------------
if($(window).width() === windowWidth){ return; }
else{
acomodaNotas();
refreshBanners();
resizePlayer();
windowWidth = $(window).width();
}
// Show: Social Follow
// -------------------
displaySocialFollow();
// Mover Fixed Elements
// -------------------
moveDefaultPosition();
});
$(window).scroll(function(){
// Mostrar Footer
// -------------------
if($(this).scrollTop() + $(window).height() == $(document).height() && count > $('.item-note').length){
$('footer').show();
}
// Mover Fixed Elements
// -------------------
if($(this).scrollTop() + $(window).height() == $(document).height() && $('footer').css('display')== "block"){
moveFooterPosition();
}else{
moveDefaultPosition();
}
});
|
/* jshint indent: 2 */
module.exports = function(sequelize, DataTypes) {
return sequelize.define('acc_contract_product_discount', {
prd_product_ids: {
type: DataTypes.STRING(255),
allowNull: false
},
discount_ratio: {
type: DataTypes.DECIMAL,
allowNull: false
}
}, {
tableName: 'acc_contract_product_discount'
});
};
|
var searchData=
[
['vga_2eh',['vga.h',['../vga_8h.html',1,'']]],
['vga_5fcommands_2eh',['vga_commands.h',['../vga__commands_8h.html',1,'']]],
['vga_5fisr_2eh',['vga_isr.h',['../vga__isr_8h.html',1,'']]],
['vga_5fmonitor_2eh',['vga_monitor.h',['../vga__monitor_8h.html',1,'']]]
];
|
(function() {
'use strict';
/**
* @ngdoc object
* @name zamin.controller:AppCtrl
*
* @description
*
*/
angular
.module('zamin')
.controller('AppCtrl', AppCtrl);
function AppCtrl($scope, $location, $rootScope, $stateParams, $mdDialog, Login) {
$scope.contactUs = {
name: '',
email: ''
};
$scope.currentLocation = "";
$rootScope.currentUser = undefined;
$rootScope.showedRegDialog=0;
$rootScope.$on('$stateChangeStart',
function(event, toState, toParams, fromState, fromParams) {
$scope.currentLocation = toState.name;
});
//--------------------------------------login functions-----------------------------------------------
// $scope.login = function() {
// if ($scope.email === "" || $scope.password === "") {
// return;
// }
// showLoader();
// Login.login($scope.email, $scope.password).then(function(response) {
// $("#login-modal").modal("hide");
// $scope.logedIn = response.success;
// $scope.userName = response.userName;
// if (!$scope.logedIn) {
// $scope.showInvalidUserNameMessage = true;
// $scope.password = "";
// } else {
// $rootScope.$broadcast("userLogedIn", $scope.userName);
// $location.path("account");
// }
// hideLoader();
//
// });
// }
$scope.getCurrentUser = function() {
if (localStorage.getItem("loginToken") != undefined) {
Login.getCurrentUser(localStorage.getItem("loginToken")).then(function(response) {
$rootScope.currentUser = response.data;
});
}
}
//----------------------------------------------------------------------------------------------------------------
$scope.contactUsRequest = function() {
$scope.contactUsFormSubmitted = true;
if ($scope.contactUs.name === '' || $scope.contactUs.email === '') {
return;
}
userService.contactUsRequest($scope.contactUs).then(function(response) {
if (response === "true") {
$scope.contactUsThanks = true;
}
});
}
$scope.loginDialog = function() {
$scope.loginFailed = false;
$mdDialog.show({
templateUrl: 'dialogs/loginDialog.html',
scope: $scope,
preserveScope: true,
clickOutsideToClose: true
});
}
$scope.login = function(email, password) {
if (email === "" ||password === "") {
return;
}
showLoader();
Login.login(email, password).then(function(response) {
if (response.data.success) {
localStorage.setItem("loginToken", response.data.user.LoginToken);
$rootScope.currentUser = response.data.user;
$scope.loginFailed = false;
$scope.hideDialog();
$location.path("home");
}else{
$scope.loginFailed = true;
}
hideLoader();
});
}
$scope.logOut = function() {
window.location.href = "#";
$rootScope.currentUser = undefined;
localStorage.clear();
}
$scope.goTo = function(url) {
$location.path(url);
}
$scope.hideDialog = function() {
$mdDialog.hide();
}
$scope.getCurrentUser();
}
}());
|
import Ember from 'ember';
var BlogController = Ember.ArrayController.extend({
sortProperties: ['published'],
sortAscending: false
});
export default BlogController;
|
export const data = {
name: 'SvgLine'
};
export default data;
|
var _ = require('underscore');
var fn = require('../fn');
var datas = require('../datas');
var exports = {};
exports.init = function(userID) {}
exports.api = {
GetProfileList: function(req, res, userID) {
var $data = datas[userID].$data;
res.send(fn.result($data.GetProfileList, req.id));
},
AddNewProfile: function(req, res, userID) {
var $data = datas[userID].$data;
res.send(fn.result($data.SearchNetwork, req.id));
},
EditProfile: function(req, res, userID) {
var $data = datas[userID].$data;
res.send(fn.result($data.SearchNetworkResult, req.id));
},
DeleteProfile: function(req, res, userID) {
var $data = datas[userID].$data;
res.send(fn.result($data.RegisterNetwork, req.id));
},
SetDefaultProfile: function(req, res, userID) {
var $data = datas[userID].$data;
res.send(fn.result($data.GetNetworkRegisterState, req.id));
},
getCurrentProfile: function(req, res, userID) {
var $data = datas[userID].$data;
res.send(fn.result($data.getCurrentProfile, req.id));
},
setCurrentProfile: function(req, res, userID) {
var $data = datas[userID].$data;
res.send(fn.result());
}
}
module.exports = exports
|
/**
* Created by draqo on 22.08.2017.
*/
window.onload = function () {
alert("privet");
}
|
import styled from 'styled-components'
export const FormStyle = styled.table`
width: 100%;
border: 1px solid #D7D7D7;
border-collapse: separate;
border-spacing: 0;
border-radius: 4px;
thead{
width: 100%;
height: 40px;
tr{
width: 100%;
text-align: left;
border-radius: 4px 0 0 4px;
}
}
th{
font-size: 12px;
color: #333333;
text-align: left;
line-height: 40px;
border-bottom: 1px solid #EEEFEE;
}
tbody{
border-top: 1px solid #D6D6D6;
border-radius: 0 4px 4px 0;
}
`
|
app.controller('category' , ['$scope' , '$http' , '$route' , '$routeParams' ,'$location' , 'authen', 'localStorageService' , 'dateTime' , 'Category' , 'pageTitle', 'Upload', '$timeout', '$state', '$stateParams', '$modal', 'Status', function($scope, $http, $route, $routeParams, $location, authen, localStorageService, dateTime, Category, pageTitle, Upload, $timeout, $state, $stateParams, $modal, Status){
var storageType = localStorageService.getStorageType();
$scope.pagemode = "";
$scope.submitted =false;
$scope.options = {
language: 'en',
allowedContent: true,
entities: false
};
$scope.onReady = function () {
};
$scope.content = "";
$scope.timeformat = dateTime.showTime();
$scope.title = pageTitle;
Category.list($scope);
Status.statusdetail($scope);
$scope.addcategory = function(){
if(localStorageService.get('login')=="1" && localStorageService.get('usertype')=="admin"){
$scope.submitted = true;
if($scope.categoryform.$valid){
var data = {
parent_id:$scope.category.parent_category,
title:$scope.category.title,
description:$scope.category.description,
meta_tag:$scope.category.meta_tag,
meta_description:$scope.category.meta_description,
order:$scope.category.order,
status:$scope.category.status
};
var req = {
url:'category/add',
method:'POST',
data:data,
headers:{
'Content-Type': 'application/json'
}
};
$http(req).then(
function(response){
if(response.data['authen']=="1"){
if(response.data['success']=="1"){
$location.path("/category/index");
}
else if(response.data['success']=="0"){
if(response.data['error']!=""){
}
}
}
else {
localStorageService.remove("login");
$location.path("/login");
}
},
function(response){
}
);
}
}
else {
$location.path("/login");
}
};
$scope.viewcategory = function(){
};
if($state.current.name=="editcategory" || $state.current.name=="viewcategory"){
if(localStorageService.get('login')=="1" && localStorageService.get('usertype')=="admin"){
$http.get("category/view/"+$stateParams.id).then(
function(response){
if(response.data['authen']=="1"){
if(response.data['success']=="1"){
$scope.category = response.data['records'];
$scope.category.parent_category = response.data['records']['parent_id'];
}
}
},
function(response){
}
);
}
}
$scope.editcategory = function(id){
if(localStorageService.get('login')=="1" && localStorageService.get('usertype')=="admin"){
$scope.submitted = true;
if($scope.categoryform.$valid){
var data = {
parent_id:$scope.category.parent_category,
title:$scope.category.title,
description:$scope.category.description,
meta_tag:$scope.category.meta_tag,
meta_description:$scope.category.meta_description,
order:$scope.category.order,
status:$scope.category.status
};
var req = {
url:'category/edit/'+$stateParams.id,
method:'POST',
data:data,
header:{
'Content-Type':'application/json'
}
};
$http(req).then(function(response){
if(response.data['authen']=="1"){
if(response.data['success']=="1"){
$location.path("/category/index");
}
}
else {
$location.path("/login");
}
},
function(){
});
}
}
};
if($state.current.name=="listcategory"){
$http.get("category/index").then(
function(response){
if(response.data['authen']=="1"){
if(response.data['success']=="1"){
$scope.categorydetail = response.data['records'];
}
else {
$scope.categorydetail = [];
}
}
else {
$location.path("/login");
}
},
function(response){
}
);
};
$scope.removecategory = function(categoryid){
$http.delete("category/remove/"+categoryid).then(
function(response){
if(response.data['authen']=="1"){
if(response.data['success']=="1"){
$state.reload();
}
else {
$location.path("/login");
}
}
},
function(response){
}
);
}
}]);
|
import {create} from 'apisauce';
// import SERVICES_PATHS from 'services/login/constants';
const api = create({
baseURL: 'https://app-garage-back.herokuapp.com',
timeout: 3000,
headers: {
'Content-Type': 'application/json',
},
});
api.addRequestTransform(request => {
const persistedAuth = JSON.parse(window.localStorage.getItem('persist:root'));
const authtoken = JSON.parse(persistedAuth.authReducer).token;
request.headers['Authorization'] = authtoken;
})
export default api;
|
import React, { useState, useRef, useEffect } from 'react';
import AddIcon from '@material-ui/icons/Add';
import './NewProducts.css';
import { motion } from 'framer-motion';
import { useStateValue } from '../../../StateProvider/StateProvider';
import Service from '../../../services/services';
import Button from '../../../SharedComponents/UIElements/Buttons/Buttons';
import Preview from '../../../Resources/Picture/Products/preview.png';
const NewProduct = () => {
const [state, dispatch] = useStateValue();
const [name, setName] = useState('');
const [price, setPrice] = useState();
const [file, setFile] = useState();
const [image, setImage] = useState(Preview);
const [description, setDescription] = useState('');
const filePickerRef = useRef();
const pickImageHandler = () => {
filePickerRef.current.click();
};
useEffect(() => {
if (!file) {
return;
}
const fileReader = new FileReader();
fileReader.onload = () => {
setImage(fileReader.result);
};
fileReader.readAsDataURL(file);
}, [file]);
const handleName = (event) => {
setName(event.target.value);
};
const handlePrice = (event) => {
setPrice(event.target.value);
};
const handleImage = (event) => {
const pickedFile = event.target.files[0];
setFile(pickedFile);
//setImage(URL.createObjectURL(event.target.files[0]));
};
const handleDescription = (event) => {
setDescription(event.target.value);
};
const addProduct = (event) => {
event.preventDefault();
var data = {
name: name,
price: price,
image: image,
description: description,
};
Service.addNewProduct(data).then((response) => {
dispatch({
type: 'ADD_PRODUCT',
product: {
id: response.data.id,
name: response.data.name,
price: response.data.price,
image: response.data.image,
description: response.data.description,
},
});
});
setImage(Preview);
setName('');
setPrice();
setDescription('');
console.log('this is products');
console.log(state.products);
console.log(image);
};
return (
<div className='newProduct'>
<div className='newProduct__header'>ADD PRODUCT</div>
<form className='newProduct__form' onSubmit={addProduct}>
<div className='newProduct__inputSection'>
<label className='newProduct__inputLabel' htmlFor='name'>
Name
</label>
<input
type='text'
className='newProduct__input'
id='name'
name='name'
placeholder='Enter Product Name'
value={name}
onChange={handleName}
/>
</div>
<div className='newProduct__inputSection'>
<input
style={{ display: 'none' }}
ref={filePickerRef}
type='file'
className='newProduct__input'
id='image'
name='image'
placeholder='Choose the image'
accept='.jpg,.png,.jpeg'
onChange={handleImage}
/>
<div className='newProduct__imagePreview'>
<div className='newProduct__imagePreviewContainer'>
<img className='imagePreview' src={image} alt='Preview' />
</div>
<Button
type='default'
message='PICK IMAGE'
onClick={pickImageHandler}
/>
</div>
</div>
<div className='newProduct__inputSection'>
<label className='newProduct__inputLabel' htmlFor='price'>
Price
</label>
<input
type='number'
className='newProduct__input'
id='price'
name='price'
placeholder='Enter Product Price'
value={price}
onChange={handlePrice}
/>
</div>
<div className='newProduct__inputSection'>
<label className='newProduct__inputLabel' htmlFor='name'>
Description
</label>
<input
type='text'
className='newProduct__input'
id='description'
name='description'
placeholder='Enter Product Details'
value={description}
onChange={handleDescription}
/>
</div>
<div className='newProduct__formButtonSection'>
<motion.button
whileTap={{ scale: 0.85 }}
type='submit'
className='newProduct__addButton'>
<AddIcon />
</motion.button>
</div>
</form>
</div>
);
};
export default NewProduct;
|
exports.extensions = function (graphQL) {
return {
inputTypes: {
BooksInputFilter: {
description: "Books Input Filter",
fields: {
name: graphQL.GraphQLString,
startsWith: graphQL.GraphQLString,
endsWith: graphQL.GraphQLString,
contains: graphQL.GraphQLString,
customEnum: graphQL.reference('CustomEnum'),
}
}
},
enums: {
CustomEnum: {
description: "Custom Enum",
values: {
a: "A",
b: "B",
c: "C"
}
}
},
interfaces: {
CustomInterface: {
description: "Custom Interface",
fields: {
name: {
type: graphQL.GraphQLString,
args: {
filter: graphQL.reference('BooksInputFilter')
}
}
},
}
},
unions: {
CustomUnion: {
description: "Custom Union",
types: [graphQL.reference('GoogleBooks'), graphQL.reference('GoogleBooksAuthor')],
}
},
types: {
GoogleBooksAuthor: {
description: 'Google Books Author',
fields: {
name: {
type: graphQL.GraphQLString,
args: {
startsWith: graphQL.GraphQLString,
}
}
}
},
GoogleBooks: {
description: 'Google Books Type',
fields: {
title: {
type: graphQL.GraphQLString,
},
description: {
type: graphQL.GraphQLString,
},
author: {
type: graphQL.reference('GoogleBooksAuthor'),
args: {
filter: graphQL.reference('BooksInputFilter'),
}
}
}
},
CustomInterfaceImpl: {
description: 'CustomInterface Implementation',
interfaces: [graphQL.reference('CustomInterface')],
fields: {
name: {
type: graphQL.GraphQLString,
args: {
filter: graphQL.reference('BooksInputFilter')
}
},
extraField: {
type: graphQL.GraphQLString,
}
}
}
},
creationCallbacks: {
Query: function (params) {
params.addFields({
customField: {
type: graphQL.nonNull(graphQL.list(graphQL.GraphQLString)),
},
googleBooks: {
type: graphQL.list(graphQL.reference('GoogleBooks')),
},
testUnion: {
type: graphQL.reference('CustomUnion'),
},
testInterface: {
type: graphQL.reference('CustomInterface')
}
});
},
},
resolvers: {
Query: {
customField: function (env) {
return ["Value 1", "Value 2"];
},
googleBooks: function (env) {
return [{
title: "Title 1",
description: "Description 1",
author: {
name: "Author 1"
}
}, {
title: "Title 2",
description: "Description 2",
author: {
name: "Author 2"
}
}]
},
testUnion: function (env) {
return {
title: 'Title'
}
},
testInterface: function (env) {
return {
name: "First Name",
extraField: "Value",
}
}
},
GoogleBooksAuthor: {
name: function (env) {
return env.source.name;
}
},
CustomInterface: {
name: function (env) {
return 'No Name';
}
},
},
typeResolvers: {
CustomInterface: function (obj) {
return 'CustomInterfaceImpl';
},
CustomUnion: function (obj) {
if (obj.title) {
return 'GoogleBooks';
}
return 'GoogleBooksAuthor';
},
},
}
};
|
const APP_CONFIG = require('../config');
const jwt = require('jsonwebtoken');
const sha1 = require('sha1');
const atob = require('atob');
const userModel = require('../model/user');
const shared = require('../shared/sharedFunctions');
const securityController = {
AUTH,
VALIDATE,
middleware: {
MIDDLEWARE_ROLE
}
};
function findUserByEmailAndPassword(userName, password) {
return new Promise((resolve, reject) => {
userModel.findOne({ email: userName, password: password }, (err, document) => {
if (err) {
reject(err);
} else {
resolve(document);
}
});
});
}
function findUseByUserNameAndPassword(userName, password) {
return new Promise((resolve, reject) => {
userModel.findOne({ userName: userName, password: password }, (err, document) => {
if (err) {
reject(err);
} else {
resolve(document);
}
});
});
}
function getUserDataFromToken(token) {
return new Promise((resolve, reject) => {
try {
var decoded = jwt.verify(token, APP_CONFIG.keys.secret);
} catch (err) {
reject('badToken');
}
userModel.findOne({ email: decoded.email }, (err, document) => {
if (err) {
reject(err);
} else {
resolve(document);
}
});
});
}
function AUTH(request, response) {
let body = request.body;
if (!body.hasOwnProperty('userName')) {
return shared.response(response, 400, shared.message('model.security.auth.empty.userName'));
} else if (!body.userName.length > 0) {
return shared.response(response, 400, shared.message('model.security.auth.empty.userName'));
} else if (!body.hasOwnProperty('password')) {
return shared.response(response, 400, shared.message('model.security.auth.empty.password'));
} else if (!body.password.length > 0) {
return shared.response(response, 400, shared.message('model.security.auth.empty.password'));
} else {
let userName = body.userName;
let password = sha1(atob(body.password));
// find user
Promise.all([findUserByEmailAndPassword(userName, password), findUseByUserNameAndPassword(userName, password)])
.then((documents) => {
if (documents[0] === null && documents[1] === null) {
return shared.response(response, 400, shared.message('model.security.auth.error.noUser'));
}
// find the good document
var document;
for (let i = 0; i < documents.length; i++) {
if (documents[i] !== null) {
document = documents[i];
}
}
document.password = undefined;
// generate token
jwt.sign({
userName: document.userName,
email: document.email
}, APP_CONFIG.keys.secret, { expiresIn: '6h' }, (err, token) => {
return shared.response(response, 200, token);
});
}).catch((err) => {
console.log(err);
return shared.response(response, 500, shared.message('server.database.error'));
});
}
}
function VALIDATE(request, response) {
let body = request.body;
if (!body.hasOwnProperty('token')) {
return shared.response(response, 400, shared.message('model.security.validate.empty.token'));
}
if (!body.token.length > 0) {
return shared.response(response, 400, shared.message('model.security.validate.empty.token'));
}
getUserDataFromToken(body.token).then((document) => {
if (document === null) {
return shared.response(response, 400, shared.message('model.auth.validate.error.invalidToken'));
} else {
document.password = undefined;
return shared.response(response, 200, document);
}
}).catch((err) => {
if (err === 'badToken') {
return shared.response(response, 400, shared.message('model.security.validate.error.invalidToken'));
} else {
return shared.response(response, 500, shared.message('server.database.error'));
}
});
}
async function MIDDLEWARE_ROLE(request, response, next) {
// Get roles allowed for this url
let rolesAllowed = shared.rolesAllowedInRoute(request.url);
// If all users are allowed jump this process
if (rolesAllowed.includes('ALL')) {
next();
} else {
// get token from the headers
let token = request.headers.token || null;
if (!token) {
return shared.response(response, 401, shared.message('server.session.noToken'));
}
// get user info
getUserDataFromToken(token).then((document) => {
if (document === null) {
return shared.response(response, 401, shared.message('server.session.invalidToken'));
}
// Validate if the user are allowed here
if (rolesAllowed.includes(document.role)) {
next();
} else {
return shared.response(response, 401, shared.message('server.session.notAllowed'));
}
}).catch((err) => {
if (err === 'badToken') {
return shared.response(response, 400, shared.message('server.session.invalidToken'));
} else {
return shared.response(response, 500, shared.message('server.database.error'));
}
});
}
}
module.exports = securityController;
|
const path = require('path');
const HTMLWebpackPlugin = require('html-webpack-plugin');
const {CleanWebpackPlugin} = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin'); // плагин для копирования файлов с места на место
const MiniCssExtractPlugin = require('mini-css-extract-plugin'); // собирает отдельные файлы css
const CssMinimizerWebpackPlugin = require('css-minimizer-webpack-plugin'); // минимизация css
const TerserWebpackPlugin = require('terser-webpack-plugin');
const {BundleAnalyzerPlugin} = require('webpack-bundle-analyzer'); // для анализа размеров подключенных библиотек
const isDev = process.env.NODE_ENV === 'development'; // можно указать в каком режиме мы хотим работать
const isProd = !isDev;
console.log('IS DEV:', isDev);
console.log('IS PROD', isProd);
const optimization = () =>
{
const config = {
splitChunks: {
chunks: 'all'
}
}
if (isProd)
{
config.minimizer = [
new CssMinimizerWebpackPlugin(),
new TerserWebpackPlugin()
]
}
return config;
}
const filename = ext => isDev ? `[name].${ext}` : `[name].[hash].${ext}`
const plugins = () =>
{
const base = [
new HTMLWebpackPlugin({
//title: "Webpack App",
template: "./index.html", // копирует содержимое html файла
minify: {
collapseWhitespace: isProd // минификация
}
}),
new CleanWebpackPlugin(), // удаляет не актуальные файлы из папки сборки
new CopyWebpackPlugin({ // копирует файлы
patterns: [
{
from: path.resolve(__dirname, 'src/money.ico'),
to: path.resolve(__dirname, 'dist'),
}
]
}),
new MiniCssExtractPlugin({
//filename: "[name].[contenthash].css"
//filename: "[name].[hash].css"
filename: filename('css')
//filename:`./styles/${filename('css')}`,
})
]
if(isProd){
base.push(new BundleAnalyzerPlugin())
}
return base
}
// из package.json
/*"scripts": {
"dev": "webpack --mode development", // сборка в режиме development
"build": "webpack --mode production", // сборка в режиме production
"watch": "webpack --mode development --watch" // для отслеживания изменения файлов без выхода из процесса
},*/
module.exports = {
context: path.resolve(__dirname, 'src'), // указываем папку с исходниками, так можно указать относительный путь
mode: "development", // режим работы webpack. По-умолчанию 'production'
entry: // точка входа в наше приложение
{
main: ['@babel/polyfill', './index.js', './index.jsx'],
analytics: './JS/analytics.js',
analyticsTS: './JS/analyticsTS.ts',
},
output: // куда нужно складывать файлы
{
// в какой файл, [name] - это паттерн для названия собранных файлов (main.bundle.js, analytics.bundle.js)
//filename: "[name].bundle.js",
// [contenthash] - паттерн для создания названий исходя из содержимого файла (решается проблема с кешом)
//filename: "[name].[contenthash].js",
//filename: "[name].[hash].js",
filename: `./js/${filename('js')}`,
path: path.resolve(__dirname, 'dist') // __dirname - системная переменная. Указываем путь к папке
},
resolve: {
extensions: ['.js', '.ts', '.json', '.png'], // указываем расширения по-умолчанию (которые можно не указывать при импорте)
alias: // заменяем части относительных путей
{
'@models': path.resolve(__dirname, 'src/models'),
'@': path.resolve(__dirname, 'src'),
}
},
optimization: optimization(),
/*{
// для того чтобы несколько раз не подгружать одну и ту же библиотеку (jquery например,
// если она подключена в двух разных файлах)
splitChunks:
{
chunks: "all"
}
}*/
devServer: // запускает локальный сервер (обновление страницы происходит автоматически)
{
port: 4200,
hot: isDev
},
devtool: isDev ? 'source-map' : false,
plugins: plugins() /*[
new HTMLWebpackPlugin({
//title: "Webpack App",
template: "./index.html", // копирует содержимое html файла
minify: {
collapseWhitespace: isProd // минификация
}
}),
new CleanWebpackPlugin(), // удаляет не актуальные файлы из папки сборки
new CopyWebpackPlugin({ // копирует файлы
patterns: [
{
from: path.resolve(__dirname, 'src/money.ico'),
to: path.resolve(__dirname, 'dist'),
}
]
}),
new MiniCssExtractPlugin({
//filename: "[name].[contenthash].css"
//filename: "[name].[hash].css"
filename: filename('css')
})
]*/,
// подключение загрузчиков (loader) для работы с разными тапами файлов (не только js или json)
module:
{
rules: [
{
test: /\.css$/, // как только webpack встречает это регулярное выражение - будет запущен лоэдер
// этот загрузчик работает справа на лево (сначала 'css-loader', затем 'style-loader')
//use: ['style-loader', 'css-loader'] // подключение стилей прямо в html
//use: [MiniCssExtractPlugin.loader, 'css-loader'] // подключение стилей через отдельный файл css
use: [isDev ? 'style-loader' : MiniCssExtractPlugin.loader, 'css-loader'] // в продакшине стили встраиваются в html
/*use: [{
loader: MiniCssExtractPlugin.loader,
options: {
hmr: isDev,
reloadAll: true
}
}, 'css-loader']*/
},
{
test: /\.less$/, // как только webpack встречает это регулярное выражение - будет запущен лоэдер
// этот загрузчик работает справа на лево (сначала 'css-loader', затем 'style-loader')
//use: ['style-loader', 'css-loader'] // подключение стилей прямо в html
//use: [MiniCssExtractPlugin.loader, 'css-loader'] // подключение стилей через отдельный файл css
use: [isDev ? 'style-loader' : MiniCssExtractPlugin.loader, 'css-loader', 'less-loader'] // в продакшине стили встраиваются в html
/*use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
publicPath: (resourcePath, context) => {
return path.relative(path.dirname(resourcePath), context) + '/';
},
}
},
'css-loader',
'lass-loader'
],*/
},
{
test: /\.s[ac]ss$/, // как только webpack встречает это регулярное выражение - будет запущен лоэдер
// этот загрузчик работает справа на лево (сначала 'css-loader', затем 'style-loader')
//use: ['style-loader', 'css-loader'] // подключение стилей прямо в html
//use: [MiniCssExtractPlugin.loader, 'css-loader'] // подключение стилей через отдельный файл css
//use: [isDev ? 'style-loader' : MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'] // в продакшине стили встраиваются в html
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
publicPath: (resourcePath, context) => {
return path.relative(path.dirname(resourcePath), context) + '/';
},
}
},
'css-loader',
'sass-loader'
],
},
/*{
test: /\.(png|jpg|svg|gif)$/,
use: ['file-loader']
},*/
{
test: /\.(?:|gif|png|jpg|jpeg|svg)$/,
use: [{
loader: 'file-loader',
options: {
name: `./img/${filename('[ext]')}`
}
}],
},
/*{
test: /\.(ttf|woff|woff2|eot|otf)$/,
use: ['file-loader']
},*/
{
test: /\.(ttf|woff|woff2|eot|otf)$/,
use: [{
loader: 'file-loader',
options: {
name: `./fonts/${filename('[ext]')}`
}
}],
},
{
test: /\.xml$/,
use: ['xml-loader']
},
{
test: /\.csv$/,
use: ['csv-loader']
},
{ // лоэдер для бэйбла
test: /\.m?js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: ['@babel/preset-env'],
plugins: [
'@babel/plugin-proposal-class-properties'
]
}
}
},
{ // лоэдер для бэйбла
test: /\.m?ts$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: ['@babel/preset-env', '@babel/preset-typescript'],
plugins: [
'@babel/plugin-proposal-class-properties'
]
}
}
},
{ // лоэдер для бэйбла
test: /\.m?jsx$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: ['@babel/preset-env', '@babel/preset-react'],
plugins: [
'@babel/plugin-proposal-class-properties'
]
}
}
}
]
}
}
|
var apiKey = '180b1bf5a5f6f2399676fd9ad13fc2e9';
var allTags = [];
var allCameras = [];
var svg;
var bottomPadding = 50;
var w = 900;
var h = 400;
var currentDisplay = 'tags';
//get yesterday's date in yyyy-mm-dd format
function GetYestDate() {
// Yesterday's date time which will used to set as default date.
var yestDate = new Date();
yestDate = yestDate.getFullYear() + "-" +
("0" + (yestDate.getMonth() + 1)).slice(-2) + "-" +
("0" + (yestDate.getDate()-1)).slice(-2);
return yestDate;
}
$(document).ready(function() {
//form the URL for getting interestingness photos
var url='http://api.flickr.com/services/rest/?method=flickr.interestingness.getList&api_key=' + apiKey + '&date=' + GetYestDate() + '&extras=url_n&per_page=5&format=json&jsoncallback=?';
//call flickr API for getting ten interesting photos from yesterday
$.getJSON(url,function(data) {
var index=0;
$.each(data.photos.photo, function(key, value) {
if(index==0)
{
$(".carousel-inner").append('<div class="item active"><img src='+value.url_n+' alt="">');
}
else{
$(".carousel-inner").append('<div class="item"><img src='+value.url_n+' alt="">');
}
index++;
});
});
var totalMonths = 58;
var firstMonth = new Date(2009, 0, 1);
$( "#slider" ).slider({
min: 0,
max: totalMonths - 1,
step: 1,
value: totalMonths - 1,
slide: function( event, ui ) {
var selectedMonth = new Date(firstMonth.getTime());
selectedMonth.setMonth(selectedMonth.getMonth() + ui.value);
$('#sliderVal').text( selectedMonth.getFullYear() + '-' + zeroPad(selectedMonth.getMonth() + 1,2) );
clearSVG('instant');
getData();
}
});
var selectedMonth = new Date(firstMonth.getTime());
selectedMonth.setMonth(selectedMonth.getMonth() + (totalMonths-1));
$('#sliderVal').text( selectedMonth.getFullYear() + '-' + zeroPad(selectedMonth.getMonth() + 1,2) );
getData();
$('#show_viz').click(function() {
var month = $('#sliderVal').text();
if(!month) {
$('#error').fadeIn('fast');
} else if(currentDisplay == 'tags') {
// we're already on this mode. don't do anything.
return false;
} else {
// transitioning from camera to tags
currentDisplay = 'tags';
$('#criteria i').fadeTo('fast', 1.0);
$('#error').fadeOut('fast');
clearSVG();
window.setTimeout(showTagGraph, 1000);
}
return false;
});
$("#show_viz-camera").click(function() {
var month = $('#sliderVal').text();
if(!month) {
$('#error').fadeIn('fast');
} else if(currentDisplay == 'cameras') {
// we're already on this mode. don't do anything.
return false;
} else {
currentDisplay = 'cameras';
$('#criteria i').fadeTo('fast', 1.0);
$('#error').fadeOut('fast');
clearSVG();
window.setTimeout(showCameraGraph, 1000);
}
return false;
});
});
function clearSVG(instant) {
if(instant)
{
$("svg").children().each(function () {
$(this).remove();
});
} else {
var bars = svg.selectAll("rect.bar");
bars
.transition()
.duration (500)
.attr("height", 0)
.attr("y", h - bottomPadding);
window.setTimeout(hide, 500);
}
}
function hide() {
$("svg").children().each(function () {
$(this).fadeOut(250, function() {
$(this).remove();
});
});
}
function showTagGraph() {
showGraph(allTags, 'tags');
}
function showCameraGraph() {
showGraph(allCameras, 'cameras');
}
function getData() {
var month = $('#sliderVal').text();
var tagsFile = 'json/' + month + 'tags.json';
var camerasFile = 'json/' + month + 'cameras.json';
var ajaxConnections = 0;
if(!month) {
$('#error').fadeIn('fast');
} else {
$('#criteria i').fadeTo('fast', 1.0);
$('#error').fadeOut('fast');
// grab the three json arrays
// after grabbing all 2 json files,
// show the tag bar graph using tagsFile as input
ajaxConnections = 2;
// get tags
$.getJSON(tagsFile,
function (data) {
ajaxConnections--;
allTags = data;
if(ajaxConnections == 0) {
// all 3 have been retrieved
clearSVG('instant');
if(currentDisplay == 'cameras')
showCameraGraph();
else
showTagGraph();
}
})
.fail(function() {
console.log("getPhotos fail");
--ajaxConnections;
});
// get cameras
$.getJSON(camerasFile,
function (data) {
ajaxConnections--;
allCameras = data;
if(ajaxConnections == 0) {
// all 3 have been retrieved
clearSVG('instant');
if(currentDisplay == 'cameras')
showCameraGraph();
else
showTagGraph();
}
})
.fail(function() {
console.log("getPhotos fail");
--ajaxConnections;
});
} // end error checking if
}
// general graph. type is either tags or cameras
function showGraph(arr, type) {
var maxCount = d3.max(arr, function(d) {
return d.count;
});
var tickSpacing;
var barCount;
var barWidth;
var barSpacing; // total spacing between bars
switch(type) {
case "tags":
tickSpacing = 50;
barCount = 15;
barWidth = 30;
barSpacing = 50;
break;
case "cameras":
tickSpacing = 20;
barCount = 12;
barWidth = 30;
barSpacing = 65;
break;
}
var tickValues = [];
// generate ticks
for(var i = 0 ; i < maxCount ; i = i+tickSpacing) {
tickValues.push(i);
}
svg = d3.select("#viz");
svg.attr("width", w).attr("height", h);
// scaling the height of bar
var yScale = d3.scale.linear()
.domain([0, maxCount])
.range([0, h - bottomPadding]);
var yAxisScale = d3.scale.linear()
.domain([0, maxCount])
.range([h - bottomPadding, 0]);
var yAxis = d3.svg.axis()
.scale(yAxisScale)
.orient("left")
.tickValues(tickValues);
svg.append("g")
.attr("class", "axis")
.attr("transform", "translate(75, 0)")
.call(yAxis);
// grid lines
for (var j=0; j < tickValues.length; j++) {
svg.append("line")
.attr({
"x1": 80,
"x2": w,
"y1": yAxisScale(tickValues[j]),
"y2": yAxisScale(tickValues[j]),
"class": "grid"
});
};
// bars
var bars = svg.selectAll("rect")
.data(arr.slice(0,barCount))
.enter().append("rect")
.attr("x", function(d, i) {
return i * barSpacing + 80;
})
.attr("desc", function(d) {
return d.count;
})
.attr("width", barWidth)
.attr("height", 0)
.attr("y", h - bottomPadding)
.attr("class","bar")
.on("click",function(d){
// when clicking on a bar, populate the carousel with 5 photos from the interestingness list
$(".carousel-inner").empty();
var carouselConnections = 0;
for(var i = 0 ; i < 5 ; i++)
{
++carouselConnections;
var id = d.photoIDs[i];
//call flickr API for getting ten interesting photos from yesterday
$.getJSON('http://api.flickr.com/services/rest/?method=flickr.photos.getInfo&api_key=' + apiKey + '&photo_id=' + id + '&format=json&jsoncallback=?',function(data) {
// find the url information for this photo
--carouselConnections;
var t_url = "http://farm" + data.photo.farm + ".static.flickr.com/" + data.photo.server + "/" + data.photo.id + "_" + data.photo.secret + "_" + "z.jpg";
$(".carousel-inner").append('<div class="item"><img src='+t_url+' alt="">');
if(carouselConnections == 0) {
$('.carousel-inner .item:first-child').addClass('active');
}
});
}
})
.transition()
.duration (500)
.attr("height", function(d) {
return yScale(d.count);
})
.attr("y", function(d) {
return h - bottomPadding - yScale(d.count);
});
// onHover, show count
// hover event interaction
$("#viz rect").on("mouseenter", function() {
var self = $(this);
self.animate({"opacity": .8}, 100);
$("#count-popup")
.css({
"left": parseInt(self.position().left) - barWidth / 2 - 5,
"top": self.position().top + 5
})
.text(self.attr("desc"))
.fadeIn(50);
}).on("mouseleave", function() {
var self = $(this);
self.animate({"opacity": 1}, 100);
$("#count-popup").fadeOut(50);
});
// text labels
svg.selectAll("text.barLabel")
.data(arr.slice(0,barCount))
.sort()
.enter()
.append("text")
.text(function(d) {
var label;
switch(type) {
case "tags":
label = d.tag;
break;
case "cameras":
label = d.camera;
break;
}
return (label == "") ? '(none)' : label;
})
.attr("text-anchor", "middle")
.attr("x", function(d, i) {
return i * barSpacing + (barWidth / 2) + 80;
})
.attr("y", function(d, i) {
// stagger cameras because they're longer names
if(type == "cameras") {
return (i % 2 == 1) ? h - 10 : h - 25;
} else {
return h - 25;
}
})
.attr("class", "barLabel");
}
// flickr api expects date and month to be two digits. this function zero pads
function zeroPad(num, width) {
var n = Math.abs(num);
var zeros = Math.max(0, width - Math.floor(n).toString().length );
var zeroString = Math.pow(10,zeros).toString().substr(1);
if( num < 0 ) {
zeroString = '-' + zeroString;
}
return zeroString+n;
}
|
/*global alert: true, console: true, ODSA, PARAMS */
"use strict";
$(document).ready(function() {
// Process help button: Give a full help page for this activity
function help() {
window.open("btTravHelpPRO.html", "helpwindow");
}
// Process about button: Pop up a message with an Alert
function about() {
alert(ODSA.AV.aboutstring(interpret(".avTitle"), interpret("av_Authors")));
}
function comp(a, b) {
return a - b;
}
JSAV._types.ds.BinaryTree.prototype.insert = function(value) {
// helper function to recursively insert
var ins = function(node, insval) {
var val = node.value();
if (!val || val === "jsavnull") { // no value in node
node.value(insval);
} else if (comp(val, insval) > 0) { // go left
if (node.left()) {
ins(node.left(), insval);
} else {
node.left(insval);
}
} else { // go right
if (node.right()) {
ins(node.right(), insval);
} else {
node.right(insval);
}
}
};
if ($.isArray(value)) { // array of values
for (var i = 0, l = value.length; i < l; i++) {
ins(this.root(), value[i]);
}
} else {
ins(this.root(), value);
}
return this;
};
var postOrderTraversal = function() {
var i = 0,
av = this.jsav;
var postorderNode = function(node) {
if (node.left()) {
postorderNode(node.left());
}
if (node.right()) {
postorderNode(node.right());
}
node.highlight();
av.label(i + 1, {
relativeTo: node,
visible: true,
anchor: "right top"
});
av.stepOption("grade", true);
av.step();
i++;
};
postorderNode(this.root());
};
var preOrderTraversal = function() {
var i = 0,
av = this.jsav;
var preorderNode = function(node) {
node.highlight();
av.label(i + 1, {
relativeTo: node,
visible: true,
anchor: "right top"
});
i++;
av.stepOption("grade", true);
av.step();
if (node.left()) {
preorderNode(node.left());
}
if (node.right()) {
preorderNode(node.right());
}
};
preorderNode(this.root());
};
var inOrderTraversal = function() {
var i = 0,
av = this.jsav;
var inorderNode = function(node) {
if (node.left()) {
inorderNode(node.left());
}
node.highlight();
av.label(i + 1, {
relativeTo: node,
visible: true,
anchor: "right top"
});
i++;
av.stepOption("grade", true);
av.step();
if (node.right()) {
inorderNode(node.right());
}
};
inorderNode(this.root());
};
var levelOrderTraversal = function() {
var i = 0,
av = this.jsav,
queue = [this.root()],
curr;
while (queue.length > 0) {
curr = queue.shift();
curr.highlight();
av.label(i + 1, {
relativeTo: curr,
visible: true,
anchor: "right top"
});
av.stepOption("grade", true);
av.step();
i++;
if (curr.left()) {
queue.push(curr.left());
}
if (curr.right()) {
queue.push(curr.right());
}
}
};
JSAV._types.ds.BinaryTree.prototype.postOrderTraversal = postOrderTraversal;
JSAV._types.ds.BinaryTree.prototype.preOrderTraversal = preOrderTraversal;
JSAV._types.ds.BinaryTree.prototype.inOrderTraversal = inOrderTraversal;
JSAV._types.ds.BinaryTree.prototype.levelOrderTraversal = levelOrderTraversal;
JSAV._types.ds.BinaryTree.prototype.state = function(newState) {
var state,
i,
queue = [this.root()],
curr;
if (typeof newState === "undefined") { // return the state
// go through tree in levelorder and add true/false to the state
// array indicating whether the node is highlighted or not
state = [];
while (queue.length > 0) {
curr = queue.shift();
state.push(curr.isHighlight());
if (curr.left()) {
queue.push(curr.left());
}
if (curr.right()) {
queue.push(curr.right());
}
}
return state;
} else { // set the state
i = 0;
while (queue.length > 0) {
curr = queue.shift();
if (newState[i] && !curr.isHighlight()) {
curr.highlight();
} else if (!newState[i] && curr.isHighlight()) {
curr.unhighlight();
}
i++;
if (curr.left()) {
queue.push(curr.left());
}
if (curr.right()) {
queue.push(curr.right());
}
}
return this;
}
};
function modelWrapper(tt) {
return function model(modelav) {
var modelBst = modelav.ds.binarytree({
center: true,
nodegap: 15
});
modelBst.insert(tt.initData);
modelBst.layout();
modelav.displayInit();
tt.modelFunction.call(modelBst);
return modelBst;
};
}
var bt;
function initWrapper(tt) {
return function() {
var nodeNum = 9;
if (bt) {
bt.clear();
}
var dataTest = (function() {
return function(dataArr) {
var bst = tt.jsav.ds.binarytree();
bst.insert(dataArr);
var result = bst.height() <= 4;
bst.clear();
return result;
};
})();
tt.jsav.canvas.find(".jsavlabel").remove();
var initData = JSAV.utils.rand.numKeys(10, 100, nodeNum, {
test: dataTest,
tries: 30
});
bt = tt.jsav.ds.binarytree({
center: true,
visible: true,
nodegap: 15
});
bt.insert(initData);
bt.layout();
bt.click(tt.nodeClick(tt.exercise));
tt.bt = bt;
tt.initData = initData;
tt.jsav.displayInit();
return bt;
};
}
function fixFunction(modelTree) {
// get the highlight states in model tree (see state() above)
var modelState = modelTree.state(),
queue = [bt.root()],
curr,
i = 0;
// go through the tree in level order (like state does)
while (queue.length > 0) {
curr = queue.shift();
// check if a highlight is missing
if (modelState[i] && !curr.isHighlight()) {
// highlight the node
curr.highlight();
// add a label next to the just highlighted node
var pos = curr.jsav.canvas.find(".jsavlabel:visible").size();
curr.jsav.label(pos + 1, {
relativeTo: curr,
anchor: "right top"
});
} else if (!modelState[i] && curr.isHighlight()) {
// if we have additional highlight (shouldn't be possible due to
// how JSAV undo works)
curr.unhighlight();
}
i++;
if (curr.left()) {
queue.push(curr.left());
}
if (curr.right()) {
queue.push(curr.right());
}
}
}
function TreeTraversal(modelFunction) {
// Load the configuration created by odsaAV.js
var config = ODSA.UTILS.loadConfig({
"json_path": "btTravPRO.json",
"default_code": "none"
}),
code = config.code;
interpret = config.interpreter;
// Temporary fix for the animation timing bug that makes all answers be
// interpretted as wrong. To solve this, we want to set speed to max
JSAV.ext.SPEED = 0;
this.modelFunction = modelFunction;
var settings = config.getSettings();
this.jsav = new JSAV($(".avcontainer"), {
settings: settings
});
this.jsav.recorded();
if (code) {
switch (modelFunction) {
case inOrderTraversal:
code = code.inorder;
break;
case preOrderTraversal:
code = code.preorder;
break;
case postOrderTraversal:
code = code.postorder;
break;
case levelOrderTraversal:
code = code.levelorder;
break;
}
if (code !== config.code) {
this.jsav.code($.extend({
after: {
element: $(".instructions")
},
visible: true
}, code));
}
}
this.exercise = this.jsav.exercise(modelWrapper(this), initWrapper(this), {
compare: {
"css": "background-color"
},
controls: $(".jsavexercisecontrols"),
fix: fixFunction
});
this.exercise.reset();
}
TreeTraversal.prototype.nodeClick = function(exercise) {
return function() {
if (this.element.hasClass("jsavnullnode") || this.isHighlight()) {
return;
}
this.highlight();
var pos = exercise.jsav.canvas.find(".jsavlabel:visible").size();
exercise.jsav.label(pos + 1, {
relativeTo: this,
anchor: "right top"
});
exercise.gradeableStep();
};
};
// Set click handlers
$('#help').click(help);
$('#about').click(about);
//////////////////////////////////////////////////////////////////
// Global variables
//////////////////////////////////////////////////////////////////
var interpret;
window.TreeTraversal = TreeTraversal;
});
|
import _ from 'lodash'
import moment from 'moment'
import { ceilDate } from '../../utils/utils'
export const filteredParticipations = (state) => {
if (state.participations) {
let participations = state.participations
if(state.filters.tournamentIds.length) {
participations = _.filter(participations, (participation) => {
return state.filters.tournamentIds.includes(participation.tournament_id)
})
}
if(state.filters.createdAtMin) {
participations = _.filter(participations, (participation) => {
return moment(participation.created_at).unix() >= moment(state.filters.createdAtMin).startOf('day').unix()
})
}
if(state.filters.createdAtMax) {
participations = _.filter(participations, (participation) => {
return moment(participation.created_at).unix() <= moment(state.filters.createdAtMax).endOf('day').unix()
})
}
return participations
} else {
return []
}
return state.participations ? state.participations : []
}
export const itmParticipations = (state, getters) => {
return _.reject(getters.filteredParticipations, ['result_payout', 0])
}
export const countItmParticipations = (state, getters) => {
return getters.itmParticipations.length
}
export const countParticipations = (state, getters) => {
return getters.filteredParticipations.length
}
export const sumParticipationsResultPosition = (state, getters) => {
return _.sumBy(getters.filteredParticipations, 'result_position')
}
export const sumParticipationsParticipantTotal = (state, getters) => {
return _.sumBy(getters.filteredParticipations, 'participant_total')
}
export const turnOver = (state, getters) => {
return _.sumBy(getters.itmParticipations, 'result_payout') / 100
}
export const outgoings = (state, getters, rootState) => {
return _.reduce(getters.filteredParticipations, function(sum, participation) {
let tournament = _.find(rootState.tournaments.tournaments, ['id', participation.tournament_id])
return sum + (tournament ? tournament.buy_in : 0)
}, 0) / 100
}
export const euroProfit = (state, getters) => {
return getters.turnOver - getters.outgoings
}
export const buyInProfit = (state, getters) => {
return parseFloat((getters.euroProfit / getters.averageBuyIn).toFixed(2))
}
export const averageBuyIn = (state, getters) => {
return getters.outgoings / getters.countParticipations
}
export const itmPercentage = (state, getters) => {
return parseFloat(((getters.countItmParticipations * 100) / getters.countParticipations).toFixed(2))
}
export const resultPositionPercentage = (state, getters) => {
return parseFloat(((getters.sumParticipationsResultPosition * 100) / getters.sumParticipationsParticipantTotal).toFixed(2))
}
export const averageEuroProfitPerParticipation = (state, getters) => {
return parseFloat((getters.euroProfit / getters.countParticipations).toFixed(2))
}
export const averageBuyInProfitPerParticipation = (state, getters) => {
return parseFloat((getters.averageEuroProfitPerParticipation / getters.averageBuyIn).toFixed(2))
}
export const isProfitPositive = (state, getters) => {
return Math.sign(getters.euroProfit) >= 0
}
|
var { ipcMain } = require('electron');
//接收渲染进程广播的数据
ipcMain.on('toMain', (event, data) => {
console.log('1111')
console.log(data.toString());
})
|
// SetTimeout + closures
function x() {
const a = 10;
var b = 20;
return function () {
console.log(a, b);
};
}
// x()();
function a() {
const x = 10;
setTimeout(() => console.log(x), 2000);
}
// a();
function b() {
for (let i = 0; i <= 5; i++) {
setTimeout(() => console.log(i), i * 1000);
}
console.log("HI");
}
// b();
function c() {
for (var i = 0; i <= 5; i++) {
function close(x) {
setTimeout(() => console.log(x), x * 1000);
}
close(i);
}
console.log(close);
}
c();
{
// Overall Scope
let i = 0;
{
// Scope 0
let i = 0;
if (i <= 5) {
setTimeout(() => console.log(i), i * 1000);
}
// i++;
}
{
// Scope 1
let i = 0;
i++;
if (i <= 5) {
setTimeout(() => console.log(i), i * 1000);
}
} //......
}
|
import React from "react";
const Feed = props => {
const {tweets} = props;
return (
<ul>
{tweets.map( tweet => <li>{tweet}</li> )}
</ul>
);
};
export default Feed;
|
import React, { Component } from "react";
import "./styles.css";
import { Card, CountryPicker, Chart } from "./Components";
import { fetchData } from "./API";
import Image from "./Image/image.png";
class App extends Component {
state = {
data: [],
country: ""
};
async componentDidMount() {
const data = await fetchData();
this.setState({ data });
console.log(this.state.data);
}
handleCountryChange = async country => {
const data = await fetchData(country);
this.setState({ data, country: country });
console.log(this.state);
};
render() {
return (
<div className="container center container-1">
<div class="img-container">
<img src={Image} alt="" className="responsive-img center-align" />
</div>
<Card data={this.state.data} />
<CountryPicker
handleCountryChange={this.handleCountryChange}
data={this.state.data}
/>
<Chart data={this.state.data} country={this.state.country} />
</div>
);
}
}
export default App;
|
import React from 'react';
import { Media } from './ExampleMedia';
import imgIBM from '../../../images/example-channel-ibm.jpg';
import imgNASA from '../../../images/example-channel-nasa.jpg';
import imgTwit from '../../../images/example-channel-twit.png';
import imgCreativeLive from '../../../images/example-channel-creativelive.png';
const medias = [
{
title: 'creativeLIVE',
type: 'channel',
id: 4307895,
description:
'creativeLIVE provides the best free, live creative education on the web. We offer high-quality workshops in photography, business, video, web and graphic design, and more.',
imgUrl: imgCreativeLive,
},
{
title: 'IBM @ CES',
type: 'recorded',
id: 81056340,
description: 'IBM CEO Ginni Rometty 2016 CES Keynote.',
imgUrl: imgIBM,
},
{
title: 'TWiT Live',
type: 'channel',
id: 1524,
description:
'Live from the TWiT Brick House, non-stop technology news and conversation with Leo Laporte and friends.',
imgUrl: imgTwit,
},
{
title: 'NASA Public',
type: 'channel',
id: 6540154,
description:
'NASA TV airs a variety of regularly scheduled, pre-recorded educational and public relations programming 24 hours a day on its various channels.',
imgUrl: imgNASA,
},
];
export const MediaSwitcher = ({ onMediaChange }) => {
return medias.map((media) => (
<Media
title={media.title}
type={media.type}
description={media.description}
imgUrl={media.imgUrl}
id={media.id}
onClick={onMediaChange}
/>
));
};
|
import React,{useState,useEffect} from 'react'
import EditOutlinedIcon from '@material-ui/icons/EditOutlined';
import DeleteOutlineOutlinedIcon from '@material-ui/icons/DeleteOutlineOutlined';
import TextField from '@material-ui/core/TextField';
import FastfoodIcon from '@material-ui/icons/Fastfood';
import { DialogContent,DialogTitle,Typography,Button,makeStyles} from "@material-ui/core";
import inventory from '../../services/inventory';
import constants from "../../utils/constants";
import InputLabel from '@material-ui/core/InputLabel';
import MenuItem from '@material-ui/core/MenuItem';
import FormControl from '@material-ui/core/FormControl';
import Select from '@material-ui/core/Select';
import Loader from "../../common/Loader/Loader";
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableContainer from '@material-ui/core/TableContainer';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import Paper from '@material-ui/core/Paper';
import SaveOutlinedIcon from '@material-ui/icons/SaveOutlined';
import ReplayOutlinedIcon from '@material-ui/icons/ReplayOutlined';
import Fuse from 'fuse.js'
const { success, error } = constants.snackbarVariants;
const useStyles = makeStyles(theme => ({
formGroup: {
display: "flex",
justifyContent: "space-between",
alignItems: "center",
marginBottom: 20,
paddingRight: 20,
'& > div': {
margin: theme.spacing(1),
width: '25ch',
},
},
inputItems: {
width: "70%"
},
span: {
color: "#0088bc"
},
table: {
maxWidth:1400,
maxHeight: "70vh"
},
roomsDiv:{
display: "flex",
flexFlow: "row wrap",
alignItems: "flex-start",
justifyContent: "center"
}
}));
const FoodInventory = ({onSnackbarEvent}) => {
const classes = useStyles();
const [food,setFood] = useState({
item : '',
unit : '',
price: ''
})
const [foods,setFoods] = useState([])
const [loading, setLoading] = useState(false);
const [editingRow, setEditingRow] = useState({});
useEffect(() => {
setLoading(true);
fetchFoods()
}, [])
const fetchFoods = async () => {
const items = await inventory.getFoodItems();
if(items){
setFoods(items);
setLoading(false);
}
}
//Snackbar
const openSnackBar = (message, variant) => {
const snakbarObj = { open: true, message, variant, resetBookings: false };
onSnackbarEvent(snakbarObj);
};
//Handle Changes
const [unit, setUnit] = React.useState('');
const handleChange = (event) => {
setUnit(event.target.value);
setFood({
...food,unit:event.target.value
})
};
const handleEdit = (row) => {
setEditingRow(row)
}
const handleUndo = () => {
setEditingRow({})
}
const handleUpdateSelect=(event)=>{
setEditingRow({
...editingRow,
unit :event.target.value
})
}
const tablestyles={
color:'#0088bc',
fontWeight:"bold"
}
const handleUpdate = async () => {
setLoading(true);
const res = await inventory.updateFoodItem(editingRow);
setLoading(false);
if(res){
openSnackBar("Item Updated Successfully", success);
setEditingRow({})
setLoading(true);
fetchFoods()
}
}
const handleInputChange = (e) => {
setEditingRow({
...editingRow,
[e.target.name]:e.target.value
})
}
const handleDelete = async (row) => {
setLoading(true);
const res = await inventory.deleteFoodItem(row);
setLoading(false);
if(res){
openSnackBar("Item Deleted Successfully", success);
setLoading(true);
fetchFoods()
}
}
//handleSubmit
const handleSubmit = async(event)=>{
event.preventDefault();
if(food){
const options = {
includeScore: true,
threshold : 0.1,
keys: ['item']
}
const fuse = new Fuse(foods, options)
const result = fuse.search(food.item)
console.log("result of fuse",result)
if(result.length !== 0){
openSnackBar("Item Already Exist", error);
}
else{
console.log("BEFORE Response",food)
const response = await inventory.addFoodItem(food);
console.log("After Response",response)
if(response){
openSnackBar("Item Added Successfully", success);
setLoading(true);
fetchFoods()
}else {
openSnackBar("Error Occured", error);
}
}
}
}
return (
<div>
<DialogTitle><FastfoodIcon/> Add Menu</DialogTitle>
<DialogContent className={classes.roomsDiv}>
<form className={classes.formGroup} autoComplete="off">
<TextField required id="standard-required" label="Item Name" name="season" value={food.item}
onChange={(event)=>setFood({...food,item: event.target.value})} />
<FormControl>
<InputLabel id="demo-simple-select-label">Unit</InputLabel>
<Select
labelId="demo-simple-select-label"
id="demo-simple-select"
value={unit}
onChange={handleChange}
required
>
<MenuItem value="KG">KG</MenuItem>
<MenuItem value="GRAM">GRAM</MenuItem>
<MenuItem value="LTR">LTR</MenuItem>
<MenuItem value="ML">ML</MenuItem>
<MenuItem value="PIECE">PIECE</MenuItem>
<MenuItem value="PORTION">PORTION</MenuItem>
<MenuItem value="BOX">BOX</MenuItem>
</Select>
</FormControl>
<TextField required id="standard-required" label="Price" name="season"
value={food.price}
onChange={(event)=>setFood({...food,price: event.target.value})}/>
<Button
type="submit"
variant="contained"
style={{backgroundColor:"#0088bc",color:'white'}}
onClick={handleSubmit}
>
ADD ITEM
</Button>
</form>
{loading && <Loader color="#0088bc" />}
<TableContainer className={classes.table} component={Paper}>
<Table className={classes.table} size="small" stickyHeader aria-label="sticky table">
<TableHead>
<TableRow>
<TableCell style={tablestyles}>ID</TableCell>
<TableCell align="center" style={tablestyles}>ITEM</TableCell>
<TableCell align="center" style={tablestyles}>UNIT</TableCell>
<TableCell align="center" style={tablestyles}>PRICE</TableCell>
<TableCell align="center" style={tablestyles}>Edit</TableCell>
<TableCell align="center" style={tablestyles}>Delete</TableCell>
</TableRow>
</TableHead>
<TableBody>
{foods.map((row,i) => (
<TableRow key={row._id}>
<TableCell component="th" scope="row">
{i+1}
</TableCell>
{editingRow._id !== row._id && <TableCell align="center">{row.item}</TableCell>}
{editingRow._id === row._id && <TableCell align="center">
<TextField required id="standard-required" label="Item Name" name="item" value={editingRow.item} onChange={handleInputChange}/>
</TableCell>}
{editingRow._id !== row._id && <TableCell align="center">{row.unit}</TableCell>}
{editingRow._id === row._id &&<TableCell align="center">
<FormControl>
<InputLabel id="demo-simple-select-label">Unit</InputLabel>
<Select
labelId="demo-simple-select-label"
id="demo-simple-select"
value={editingRow.unit}
onChange={handleUpdateSelect}
required
>
<MenuItem value="KG">KG</MenuItem>
<MenuItem value="GRAM">GRAM</MenuItem>
<MenuItem value="LTR">LTR</MenuItem>
<MenuItem value="ML">ML</MenuItem>
<MenuItem value="PIECE">PIECE</MenuItem>
<MenuItem value="PORTION">PORTION</MenuItem>
<MenuItem value="BOX">BOX</MenuItem>
</Select>
</FormControl>
</TableCell>}
{editingRow._id !== row._id && <TableCell align="center">{row.price}</TableCell>}
{editingRow._id === row._id && <TableCell align="center">
<TextField required id="standard-required" label="price" name="price" value={editingRow.price} onChange={handleInputChange}/>
</TableCell>}
{editingRow._id !== row._id && <TableCell align="center">
{row._id!=="5d3edc251c9d4400006bc08e" && <EditOutlinedIcon style={{cursor:"pointer"}} onClick={()=>handleEdit(row)}/>}
</TableCell>}
{editingRow._id === row._id && <TableCell align="center">
<ReplayOutlinedIcon style={{cursor:"pointer"}} onClick={handleUndo}/>
<SaveOutlinedIcon style={{cursor:"pointer"}} onClick={handleUpdate}/>
</TableCell>}
<TableCell align="center">
{row._id!=="5d3edc251c9d4400006bc08e" && <DeleteOutlineOutlinedIcon style={{cursor:"pointer"}} onClick={()=>handleDelete(row)}/>}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
</DialogContent>
</div>
)
}
export default FoodInventory
|
self.__precacheManifest = [
{
"revision": "b6216d61c03e6ce0c9aea6ca7808f7ca",
"url": "/nem-wallet/robots.txt"
},
{
"revision": "8d4c5057882d6fa624c2",
"url": "/nem-wallet/js/chunk-vendors.4a78465f.js"
},
{
"revision": "513080c6cd83f3d92390",
"url": "/nem-wallet/js/app.c2415abc.js"
},
{
"revision": "d6712a9b771caccb9258f5d2ce711343",
"url": "/nem-wallet/index.html"
},
{
"revision": "8d4c5057882d6fa624c2",
"url": "/nem-wallet/css/chunk-vendors.ceb3e7dd.css"
},
{
"revision": "513080c6cd83f3d92390",
"url": "/nem-wallet/css/app.f01c8268.css"
}
];
|
$(function(){
var reg = new RegExp("[\\u4E00-\\u9FFF]+","g");
var spans = $(".stl_view span");
for (var i = 0; i < spans.length; i++) {
var span = spans[i];
var parentDiv = span.parentNode;
var divStyle = parentDiv.attributeStyleMap;
var divStyleLeft = divStyle.get("left").value;
var divStyleTop = divStyle.get("top").value;
if("4.3358"==divStyleLeft && parentDiv.childNodes.length == 1){
divStyle.set("top",(divStyleTop-0.06)+"em");
}
if ("." == span.innerText.trim()) {
span.classList.remove("stl_18");
divStyle.set("top",(divStyleTop-0.06)+"em");
if("7.9192" == divStyleLeft){
var sub1 = "7.7192em";
var sub2 = "0.6em";
var sub3 = "0.9em"
divStyle.set("left",sub1);
parentDiv.firstElementChild.attributeStyleMap.set("word-spacing",sub2);
parentDiv.childNodes[3].attributeStyleMap.set("word-spacing",sub3);
}
if("17.7525" == divStyleLeft){
divStyle.set("left","17.5525em");
}
if("20.8508" == divStyleLeft){
divStyle.set("left","20.6508em");
parentDiv.childNodes[3].attributeStyleMap.set("word-spacing","0.9em");
}
if("30.6" ==divStyleLeft ){
divStyle.set("left","30.4em");
}
if("40.3508" == divStyleLeft){
divStyle.set("left","40.1508em");
}
if("50.0175" == divStyleLeft){
divStyle.set("left","49.8175em");
}
if("60.2675"==divStyleLeft){
divStyle.set("left","60.0675em");
}
}
}
});
|
export const todoItemsSelector = (state) => state.todoItems.items;
|
var React = require('react'),
BookingActions = require('../../actions/booking_actions'),
LocationForm = require('./location_form'),
DescriptionForm = require('./description_form'),
TaskBanner = require('./task_banner'),
History = require('react-router').History,
BookingStore = require('../../stores/booking'),
TaskStore = require('../../stores/task'),
LinkedStateMixin = require('react-addons-linked-state-mixin');
module.exports = React.createClass({
mixins: [History, LinkedStateMixin],
getInitialState: function () {
return {
task: TaskStore.find(this.props.params.task_id),
address: this.getAddressFromStore(),
description: this.getDescriptionFromStore(),
errors: [],
focused: "location"
};
},
getAddressFromStore: function () {
return BookingStore.current().address;
},
getDescriptionFromStore: function () {
return BookingStore.current().description;
},
_proceedClick: function (value) {
BookingActions.updateBooking({description: value});
if (this.refs.loc.isValid()) {
this.props.history.push("book/" + this.props.params.task_id + "/taskers");
} else {
this.setState({
focused: "location"
});
}
},
_locationClick: function (value) {
this.setState({focused: "description"});
BookingActions.updateBooking({address: value});
},
componentDidMount: function() {
this.bookingListener = BookingStore.addListener(this._onBookingChange);
this.taskListener = TaskStore.addListener(this._onTasksChange);
BookingActions.fetchBooking();
},
componentWillUnmount: function() {
this.bookingListener.remove();
this.taskListener.remove();
},
_onBookingChange: function () {
this.setState({
booking: BookingStore.current()
});
},
_onTasksChange: function () {
this.setState({
task: TaskStore.find(this.props.params.task_id)
});
},
_onFormClick: function (clickSource) {
if (this.refs.loc.isValid()) {
this.setState({
focused: clickSource
});
}
},
render: function () {
return (
<div className="detail-main">
<TaskBanner task={this.state.task}/>
<div className="detail-container">
<LocationForm id="location_form" ref="loc" isFocused={this.state.focused === "location"} onComplete={this._locationClick} onFormClick={this._onFormClick}/>
<DescriptionForm id="description_form" ref="descr" isFocused={this.state.focused === "description"} onComplete={this._proceedClick} onFormClick={this._onFormClick}/>
</div>
</div>
);
}
});
|
import React from 'react'
const NoMatch = () => (
<div className='no-match'>
<h3>404! Cannot find this page at the moment.</h3>
</div>
);
export default NoMatch
|
import React from 'react'
import header from '../../images/header.jpg'
import './header.css'
function Header(props) {
return (
<div className="container-fluid header">
<img id="img1" src={header}/>
</div>
)
}
export default Header
|
({
openDetailsPage : function(component, event, helper) {
var navEvt = $A.get("e.force:navigateToSObject");
var oneField = component.get('v.oneField');
var recordId;
if (oneField.type === 'REFERENCE') {
recordId = oneField.value;
} else {
recordId = oneField.recordId;
}
//console.log('recordId ',recordId);
navEvt.setParams({
"recordId" : recordId
});
navEvt.fire();
}
})
|
var ZWL={};
ZWL.markAsReady=function(div) {
var tag=document.createComment("ZenReady");
div.insertBefore(tag,div.firstChild);
}
ZWL.isReady=function(div) {
var n=div.firstChild;
if (n==null) return(false);
if (n.nodeName!="#comment") return(false);
if (n.nodeValue!="ZenReady") return(false);
return(true);
}
//==================//
// TAB FRAME WIDGET //
//==================//
ZWL.handleTabFrame=function(tab) {
if (!tab.controller) alert("Steve screwed up again!")
tab.controller.giveFocus(tab);
tab.controller.refreshMenu();
}
ZWL.TabFrame=function(div) {
this.ADORNMENT_SIZE_Y=6;
this.ADORNMENT_SIZE_X=10;
this.TOP_PAD = 2;
div.controller=this;
if (ZLM.isZen()) { // In Zen, div will have a wrapper
//ZLM.cerr("Is Zen");
div.style.width="100%";
div.style.height="100%";
//ZLM.cerr("CH: "+div.clientHeight);
if (div.clientHeight>=0) {
//ZLM.cerr("Fixing parent nodes");
div.parentNode.style.width="100%";
div.parentNode.style.height="100%";
}
}
this.div = div;
//this.div.parentNode.style.border="3px solid red";
//this.div.parentNode.parentNode.style.border="3px solid green";
this.div.body = ZLM.simulateTag("div style='position:relative; top:0; left:0; width:100%; height:100%;'");
div.appendChild(this.div.body);
this.div.menu = ZLM.simulateTag("div class='tabMenu' style='position:absolute; top:0; left:0; width:100%; border:none;'");
this.div.body.appendChild(this.div.menu);
this.div.pageEdge = ZLM.simulateTag("div style='position:absolute; left:0; width:100%; height:2;'");
this.div.menu.appendChild(this.div.pageEdge);
// Start setting up basic geometry based on CSS preferences
this.fontHeight=parseInt(ZLM.getStringExtents("Hello world!",this.div.menu).split("X")[1]);
this.menuHeight=this.fontHeight+2*this.ADORNMENT_SIZE_Y+this.TOP_PAD;
if (this.div.menu.clientHeight>=this.menuHeight) {
this.menuOffset=this.div.menu.clientHeight-this.menuHeight;
}
else {
this.div.menu.style.height=this.menuHeight;
this.menuOffset=0;
}
this.div.page=ZLM.simulateTag("div style='position:absolute; left:0;'");
var tmpH = this.div.body.clientHeight-this.div.menu.offsetHeight;
if (tmpH<0) {
//ZLM.cerr("ARGGG "+tmpH);
tmpH=this.div.menu.offsetHeight;
}
//ZLM.cerr("ARGGG2 "+tmpH);
ZLM.setSize(this.div.page,"100%",tmpH,"none");
this.div.page.style.top=this.div.menu.offsetHeight;
this.div.body.appendChild(this.div.page);
// get color palette
this.LINE_COLOR=ZLM.toHTMLColorSpec(ZLM.getCSSBackgroundDefault("tabEdge",div));
this.RGB_FRAME_COLOR=ZLM.getRGBBackgroundColor(div);
this.FRAME_COLOR=ZLM.toHTMLColorSpec(this.RGB_FRAME_COLOR);
this.DARK_FRAME_COLOR=ZLM.toHTMLColorSpec(ZLM.averageColor("64,64,64",this.RGB_FRAME_COLOR));
this.BG_COLOR=ZLM.toHTMLColorSpec(ZLM.getRGBBackgroundColor(this.div.menu));
//ZLM.cerr("Line: "+this.LINE_COLOR+" Frame: "+this.FRAME_COLOR+" BG: "+this.BG_COLOR);
this.div.pageEdge.style.borderTop="2px solid "+this.LINE_COLOR;
this.div.pageEdge.style.background=this.FRAME_COLOR;
this.div.pageEdge.style.top=this.menuOffset+this.menuHeight-4;
if (ZLM.isInternetExplorer()) {
this.div.pageEdge.style.fontSize="0px";
this.div.pageEdge.style.top=this.menuOffset+this.menuHeight-4;
}
this.firstTop = new ZWL.TabTopper(this,this.div.menu,0,this.menuOffset-2);
this.firstTop.renderLeftEnd();
this.firstTop.div.style.display="none";
this.firstBase = new ZWL.TabBase(this,this.div.menu,0,this.menuOffset+this.menuHeight-8);
this.firstBase.renderRightOverlap();
this.firstBase.renderLeft("none");
this.firstBase.div.style.display="none";
this.tabs = new Array();
this.panes = new Array();
this.tabTops = new Array();
this.tabBase = new Array();
this.focusedTab = -1; // Nobody currently has the focus
this.firstTab = -1;
this.lastTab= -1;
this.makePrevTab("images/SmLeftArrow.png");
this.makeNextTab("images/SmRightArrow.png");
this.makeIndexTab("images/SmDownArrow.png");
// this.initTabs();
this.setTabVisibility();
ZLM.setLocalAttribute(div,"onresize","this.controller.resizeHandler();");
//ZLM.cerr("onresize set to: "+div.getAttribute("onresize"));
//ZLM.cerr("Page is now : "+this.div.page.clientWidth+"x"+this.div.page.clientHeight);
//ZLM.cerr("Body is now : "+this.div.page.parentNode.clientWidth+"x"+this.div.page.parentNode.clientHeight);
}
ZWL.TabFrame.prototype.resizeHandler=function() {
//ZLM.cerr("DIV "+this.div.clientHeight+" x "+this.div.clientWidth)
//ZLM.cerr("DIV P "+this.div.parentNode.clientHeight+" x "+this.div.parentNode.clientWidth)
//ZLM.cerr("DIV PP "+this.div.parentNode.parentNode.clientHeight+" x "+this.div.parentNode.parentNode.clientWidth)
//ZLM.cerr("BODY: "+this.div.body.clientHeight+" - "+this.div.menu.offsetHeight)
//ZLM.cerr("BODY P: "+this.div.body.parentNode.clientHeight+" x "+this.div.body.parentNode.clientWidth)
//ZLM.cerr("RESIZE HANDLER CALLED");
// ZLM.setSize(this.div.page,"100%",this.div.body.clientHeight-this.div.menu.offsetHeight,"none");
//ZLM.cerr(this.hey+"!!!");
this.div.page.style.width="100%";
//if (this.div.body.clientHeight<this.div.menu.offsetHeight) ZLM.setSize(this.div.body,"100%",this.div.menu.offsetHeight);
var fred = this.div.body.clientHeight-this.div.menu.offsetHeight;
//ZLM.cerr("IE hates this: "+fred+" body height is: "+this.div.body.clientHeight);
ZLM.setSize(this.div.page,"100%",this.div.body.clientHeight-this.div.menu.offsetHeight,"none");
//ZLM.cerr("BODY: "+this.div.body.clientHeight+" - "+this.div.menu.offsetHeight)
//ZLM.cerr("BODY P: "+this.div.body.parentNode.clientHeight+" x "+this.div.body.parentNode.clientWidth)
//ZLM.cerr("DIV "+this.div.clientHeight+" x "+this.div.clientWidth)
//ZLM.cerr("DIV P "+this.div.parentNode.clientHeight+" x "+this.div.parentNode.clientWidth)
//this.div.page.style.width="100%";
//ZLM.cerr("Page is now : "+this.div.page.clientWidth+"x"+this.div.page.clientHeight);
//ZLM.cerr("Body is now : "+this.div.page.parentNode.clientWidth+"x"+this.div.page.parentNode.clientHeight);
this.div.page.style.top=this.div.menu.offsetHeight;
this.refreshMenu();
}
ZWL.TabFrame.prototype.tallyTabWidth=function(start,end) {
if (end==-1) end = this.tabs.length-1;
var w=3; // MAGIC NUMBER: "margin" from refreshMenu - should symbolize
for (var i=start;i<=end;i++) {
w+=(this.tabs[i].width+2);
}
return(w);
}
ZWL.TabFrame.prototype.getFocusToEndWidth=function() {
if (this.focusedTab<0) { //focus (if any) is on index card, special case
}
else {
return(this.tallyTabWidth(this.focusedTab,-1));
}
return(0);
}
ZWL.TabFrame.prototype.setTabVisibility=function() {
// set the variables firstTab and lastTab accordingly
var workArea=this.div.menu.clientWidth;
var totalTabWidth=this.tallyTabWidth(0,-1);
//ZLM.cerr("Work area is: "+workArea+" Total tab width is: "+totalTabWidth);
if (totalTabWidth<workArea) {
this.firstTab=0;
this.lastTab=this.tabs.length-1;
this.showIndex=false;
return;
}
var toEnd = this.getFocusToEndWidth();
if (toEnd>workArea) { // list from focused frame to width of div is too big - Must compress somehow
//ZLM.cerr("Work area is: "+workArea+" Focus to end alone is: "+toEnd);
}
else { // list might fit, depending on where in list Focus is
//ZLM.cerr("POSSIBLE FIT! Work area is: "+workArea+" Focus to end alone is: "+toEnd);
}
}
ZWL.TabFrame.prototype.refreshMenu=function() {
// KEY VARIABLES CONTROLLING VISIBILITY
// this.firstTab : index of First tab of the tab array to display
// (if this is not 0, this.prevTab should be visible)
// this.lastTab : index of last tab of tab array to display
// (if this is not this.tabs.length-1 this.nextTab should be visible)
// this.showIndex: true if the index tab should be displayed (normally if there are more
// tabs to display than will fit on screen at once)
// this.focusedTab: index of tab with the current focus (-1 for none, -2 for index card)
var margin=3;
//ZLM.cerr("Page is now : "+this.div.page.clientWidth+"x"+this.div.page.clientHeight);
//ZLM.cerr("Body is now : "+this.div.page.parentNode.clientWidth+"x"+this.div.page.parentNode.clientHeight);
this.setTabVisibility();
if (this.firstTab!=0) margin+=(this.displayPrevTab("block")+2);
else this.displayPrevTab("none");
if (this.lastTab!=this.tabs.length-1) var last=this.nextTab;
else if (this.showIndex==true) var last=this.indexTab;
else var last=this.tabs[this.tabs.length-1];
//ZLM.cerr("First: "+this.firstTab+"Last: "+this.lastTab+" Index: "+this.showIndex);
//if (last==this.nextTab) alert("Next");
//if (last==this.indexTab) alert("Idx");
//if (last==this.tabs[this.tabs.length-1]) alert("Content");
var foundFocus=false;
for (var i=0;i<this.tabs.length;i++) {
if ((i<this.firstTab) || (i>this.lastTab)) {
this.tabs[i].style.display="none";
this.tabTops[i].div.style.display="none";
this.tabBase[i].div.style.display="none";
}
else {
this.tabs[i].style.display="block";
this.tabTops[i].div.style.display="block";
this.tabBase[i].div.style.display="block";
this.tabs[i].style.left=margin;
margin+=(this.tabs[i].width+2);
this.tabTops[i].div.style.left=(margin-4);
this.tabBase[i].div.style.left=(margin-4);
if (i==this.focusedTab) foundFocus=true;
else {
if (foundFocus) this.tabBase[i].renderLeftOverlap();
else if (i!=this.focusedTab-1) this.tabBase[i].renderRightOverlap();
}
if (this.tabs[i]==last) {
this.tabTops[i].renderRightEnd();
this.tabBase[i].renderRight("none");
}
else {
if (i==this.lastTab) {
this.tabTops[i].renderLeftOverlap();
if (!foundFocus) { // focus tab must not be visible at the moment
this.tabBase[i].renderLeftOverlap();
}
}
else this.tabTops[i].renderNormal();
}
}
}
if (this.showIndex) {
margin+=(this.displayIndexTab(margin,"block")+2);
}
else this.displayIndexTab(0,"none");
if (this.lastTab!=this.tabs.length-1) {
this.displayNextTab(margin,"block");
}
else this.displayNextTab(0,"none");
}
ZWL.TabFrame.prototype.giveFocus=function(tab) {
this.takeFocus();
var i=0;
while (i<this.tabs.length && this.tabs[i]!=tab) i++
if (i==this.tabs.length) return;
this.panes[i].style.display="block";
this.panes[i].style.width="100%";
this.panes[i].style.height="100%";
tab.style.background=this.FRAME_COLOR;
tab.style.borderBottomColor=this.FRAME_COLOR;
tab.close.closeColor="red";
tab.close.style.background="red";
this.tabTops[i].tintLeft(this.FRAME_COLOR);
this.tabBase[i].renderLeftFocused();
this.backtintCloseButton(i,this.FRAME_COLOR);
tab.hasFocus=true;
this.focusedTab=i;
// Few extra bookkeeping points
if (i==0) {
// NEED TO CHECK STUFF HERE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
this.firstTop.tintRight(this.FRAME_COLOR);
this.firstBase.renderRightFocused();
this.firstBase.renderLeft("none");
}
else {
this.tabTops[i-1].tintRight(this.FRAME_COLOR);
this.tabBase[i-1].renderRightFocused();
}
}
ZWL.TabFrame.prototype.takeFocus=function() {
var i=this.focusedTab;
if (i<0) return;
var t=this.tabs[i];
this.panes[i].style.display="none";
t.style.background=this.DARK_FRAME_COLOR;
t.style.borderBottomColor=this.LINE_COLOR;
t.close.closeColor=this.FRAME_COLOR;
t.close.style.background=this.FRAME_COLOR;
this.tabTops[i].tintLeft(this.DARK_FRAME_COLOR);
this.tabBase[i].renderLeftOverlap();
this.backtintCloseButton(i,this.DARK_FRAME_COLOR);
t.hasFocus=false;
if (i==0) { // used to be first tab
// NEED TO CHECK SCROLLING CONDITIONS HERE
this.firstTop.tintRight(this.DARK_FRAME_COLOR);
this.firstBase.renderRightOverlap();
this.firstBase.renderLeft("none");
}
else {
this.tabTops[i-1].tintRight(this.DARK_FRAME_COLOR);
this.tabBase[i-1].renderRightOverlap();
}
}
///
///
///
///
ZWL.TabFrame.prototype.makeArrowTab=function(url) {
var tabDiv = ZLM.simulateTag("div style='position:absolute;'");
tabDiv.width=15+12; // arrow div size+padding;
tabDiv.height=this.fontHeight+8;
tabDiv.style.background=this.DARK_FRAME_COLOR;
tabDiv.style.display="none";
tabDiv.style.top=this.menuOffset;
tabDiv.style.left=3; // MAGIC NUMBER AGAIN "margin" from refresh menu
ZLM.setSize(tabDiv,tabDiv.width,tabDiv.height,"2px solid "+this.LINE_COLOR);
var arrowDiv = ZLM.simulateTag("div style='position:absolute; left:4; cursor:pointer; background-image:url("+url+"); background-position:center center;' onclick='ZWL.handleTabFrame(this.parentNode);'");
arrowDiv.style.top=(tabDiv.height-15)/2; // center vertically
ZLM.setSize(arrowDiv,15,15,"none");
tabDiv.appendChild(arrowDiv);
tabDiv.controller=this;
this.div.menu.appendChild(tabDiv);
return(tabDiv);
}
ZWL.TabFrame.prototype.makeIndexTab=function(url) { // URL:images/SmRightArrow.png
this.indexTab=this.makeArrowTab(url);
this.indexTabTop = new ZWL.TabTopper(this,this.div.menu,0,this.menuOffset-2);
this.indexTabTop.div.style.display="none";
this.indexTabBase = new ZWL.TabBase(this,this.div.menu,0,this.menuOffset+this.menuHeight-8);
this.indexTabBase.div.style.display="none";
}
ZWL.TabFrame.prototype.makeNextTab=function(url) { // URL:images/SmRightArrow.png
this.nextTab=this.makeArrowTab(url);
this.nextTabTop = new ZWL.TabTopper(this,this.div.menu,0,this.menuOffset-2);
this.nextTabTop.renderRightEnd();
this.nextTabTop.div.style.display="none";
this.nextTabBase = new ZWL.TabBase(this,this.div.menu,0,this.menuOffset+this.menuHeight-8);
this.nextTabBase.renderLeftOverlap();
this.nextTabBase.renderRight("none");
this.nextTabBase.div.style.display="none";
}
ZWL.TabFrame.prototype.makePrevTab=function(url) { // URL:images/SmRightArrow.png
this.prevTab=this.makeArrowTab(url);
this.prevTabTop = new ZWL.TabTopper(this,this.div.menu,28,this.menuOffset-2);
this.prevTabTop.renderRightOverlap();
this.prevTabTop.div.style.display="none";
this.prevTabBase = new ZWL.TabBase(this,this.div.menu,28,this.menuOffset+this.menuHeight-8);
this.prevTabBase.renderRightOverlap();
this.prevTabBase.div.style.display="none";
}
ZWL.TabFrame.prototype.displayPrevTab=function(mode) {
this.prevTab.style.display=mode;
this.prevTabTop.div.style.display=mode;
this.prevTabBase.div.style.display=mode;
if (mode=="none") return(0);
if (this.firstTab==this.focusedTab) {
this.prevTabTop.tintRight(this.FRAME_COLOR);
this.prevTabBase.renderRightFocused();
}
else {
this.prevTabTop.tintRight(this.DARK_FRAME_COLOR);
this.prevTabBase.renderRightOverlap();
}
return(this.prevTab.width);
}
ZWL.TabFrame.prototype.displayNextTab=function(margin, mode) {
var m2=margin+this.nextTab.width-2;
this.nextTab.style.left=margin;
this.nextTab.style.display=mode;
this.nextTabTop.div.style.left=m2;
this.nextTabTop.div.style.display=mode;
this.nextTabBase.div.style.left=m2;
this.nextTabBase.div.style.display=mode;
if (mode=="none") return(0);
return(this.nextTab.width);
}
ZWL.TabFrame.prototype.displayIndexTab=function(margin, mode) {
this.indexTab.style.display=mode;
this.indexTabTop.div.style.display=mode;
this.indexTabBase.div.style.display=mode;
if (mode=="none") return(0);
var m2=margin+this.indexTab.width-2;
this.indexTab.style.left=margin;
this.indexTabTop.div.style.left=m2;
this.indexTabBase.div.style.left=m2;
if (this.lastTab!=this.tabs.length) { // next tab will be showing
this.indexTabTop.renderLeftOverlap();
this.indexTabBase.renderLeftOverlap();
}
else {
this.indexTabTop.renderRightEnd();
this.indexTabBase.renderRightOverlap();
this.indexTabBase.div.style.display="none";
}
return(this.indexTab.width);
}
////
////
ZWL.TabFrame.prototype.initTabs=function() {
var iKids=[];
for (var k=this.div.firstChild;k!=null;k=k.nextSibling) {
if (k.nodeType==1) iKids[iKids.length]=k;
}
for (var i=0;i<iKids.length;i++) {
this.addStaticTabs(iKids[i]);
iKids[i].style.display="none";
}
}
ZWL.TabFrame.prototype.addStaticTabs=function(root) {
if (root.nodeType==1) {
if (root.className=="tabRef") {
var lbl=root.getAttribute("caption");
if (lbl==null) lbl="(untitled)";
var src=root.getAttribute("src");
if (src!=null) this.addTab(lbl,src);
root.style.display="none";
}
else {
for (var k=root.firstChild;k!=null;k=k.nextSibling) this.addStaticTabs(k);
}
}
}
ZWL.TabFrame.prototype.addFrame=function(src) {
var idx = this.panes.length;
var fDiv = ZLM.simulateTag("iframe src='"+src+"' width='0' height='0' style='position:absolute; left:0; top:0; border:0px solid red; display:block;'");
this.div.page.appendChild(fDiv);
this.panes[idx]=fDiv;
}
ZWL.TabFrame.prototype.addTab=function(label,url) {
var idx = this.tabs.length;
if (idx==0) { // first tab, need to turn on starter adornments
this.firstTop.div.style.display="block";
this.firstBase.div.style.display="block";
}
var tabDiv = ZLM.simulateTag("div style='position:absolute;'");
tabDiv.style.background=this.DARK_FRAME_COLOR;
var txtDiv = ZLM.simulateTag("div style='display:inline; cursor:pointer;' onclick='ZWL.handleTabFrame(this.parentNode);'");
var txt = document.createTextNode(label);
txtDiv.appendChild(txt);
this.div.menu.appendChild(txtDiv);
tabDiv.txtW=txtDiv.offsetWidth;
tabDiv.txtH=txtDiv.offsetHeight;
this.div.menu.removeChild(txtDiv);
tabDiv.width=tabDiv.txtW+12+16;
tabDiv.height=tabDiv.txtH+8;
ZLM.setSize(tabDiv,tabDiv.width,tabDiv.height,"2px solid "+this.LINE_COLOR);
txtDiv.style.display="block";
txtDiv.style.position="absolute";
txtDiv.style.left=4;
txtDiv.style.top=4;
tabDiv.appendChild(txtDiv);
tabDiv.close=this.makeCloseButton();
tabDiv.close.style.top=(tabDiv.height-16)/2;
tabDiv.close.style.left=tabDiv.width-20;
tabDiv.appendChild(tabDiv.close);
tabDiv.style.top=this.menuOffset;
tabDiv.style.left=0;
tabDiv.hasFocus=false;
tabDiv.controller=this;
this.div.menu.appendChild(tabDiv);
this.tabTops[idx]=new ZWL.TabTopper(this,this.div.menu,0,this.menuOffset-2);
this.tabBase[idx]=new ZWL.TabBase(this,this.div.menu,0,this.menuOffset+this.menuHeight-8);
this.tabs[idx]=tabDiv;
this.addFrame(url);
this.giveFocus(this.tabs[idx]);
this.refreshMenu();
}
ZWL.TabFrame.prototype.makeCloseButton=function() {
var divStr="div style='position:absolute; width:";
var div=ZLM.simulateTag(divStr+"16; height:16;' onmouseover='this.style.background="+'"red";'+"' onmouseout='this.style.background=this.closeColor;'");
if (ZLM.isInternetExplorer()) div.style.fontSize="0px";
div.closeColor=this.FRAME_COLOR;
div.corner=new Array();
div.corner[0]=ZLM.simulateTag(divStr+"2; height:2; top:0; left:0;'");
div.corner[1]=ZLM.simulateTag(divStr+"2; height:2; top:0; left:14;'");
div.corner[2]=ZLM.simulateTag(divStr+"2; height:2; top:14; left:14;'");
div.corner[3]=ZLM.simulateTag(divStr+"2; height:2; top:14; left:0;'");
div.cap=ZLM.simulateTag(divStr+"16; height:16; background-image:url(tabClose.png);'");
for (var i=0;i<4;i++) {
div.appendChild(div.corner[i]);
div.corner[i].style.background=this.DARK_FRAME_COLOR;
}
div.appendChild(div.cap);
div.style.background=this.FRAME_COLOR;
return(div);
}
ZWL.TabFrame.prototype.backtintCloseButton=function(idx, color) {
for (var i=0; i<4; i++) {
this.tabs[idx].close.corner[i].style.background=color;
}
}
ZWL.TabTopper=function(controller,parent,x,y) {
this.boss=controller;
this.div=ZLM.simulateTag("div style='position:absolute; z-index:1;'");
ZLM.setSize(this.div,9,8,"none");
this.div.overlapBar=ZLM.simulateTag("div style='position:absolute; top:2; left:0;'");
ZLM.setSize(this.div.overlapBar,9,2,"none");
this.div.leftTab=ZLM.simulateTag("div style='position:absolute; top:4; left:0;'");
ZLM.setSize(this.div.leftTab,4,4,"none");
this.div.rightTab=ZLM.simulateTag("div style='position:absolute; top:4; left:5;'");
ZLM.setSize(this.div.rightTab,4,4,"none");
this.div.centerFill=ZLM.simulateTag("div style='position:absolute; top:4; left:4;'");
ZLM.setSize(this.div.centerFill,1,2,"none");
this.div.tabArcRight=new Array();
this.div.tabArcRight[0]=ZLM.simulateTag("div style='position:absolute; top:6; left:4;'");
ZLM.setSize(this.div.tabArcRight[0],2,2,"none");
this.div.tabArcRight[1]=ZLM.simulateTag("div style='position:absolute; top:4; left:5;'");
ZLM.setSize(this.div.tabArcRight[1],2,2,"none");
this.div.tabArcRight[2]=ZLM.simulateTag("div style='position:absolute; top:3; left:7;'");
ZLM.setSize(this.div.tabArcRight[2],2,2,"none");
this.div.tabArcRight[3]=ZLM.simulateTag("div style='position:absolute; top:2; left:8;'");
ZLM.setSize(this.div.tabArcRight[3],1,1,"none");
this.div.tabArcLeft=new Array();
this.div.tabArcLeft[0]=ZLM.simulateTag("div style='position:absolute; top:6; left:3;'");
ZLM.setSize(this.div.tabArcLeft[0],2,2,"none");
this.div.tabArcLeft[1]=ZLM.simulateTag("div style='position:absolute; top:4; left:2;'");
ZLM.setSize(this.div.tabArcLeft[1],2,2,"none");
this.div.tabArcLeft[2]=ZLM.simulateTag("div style='position:absolute; top:3; left:0;'");
ZLM.setSize(this.div.tabArcLeft[2],2,2,"none");
this.div.tabArcLeft[3]=ZLM.simulateTag("div style='position:absolute; top:2; left:0;'");
ZLM.setSize(this.div.tabArcLeft[3],1,1,"none");
// add and paint parts appropriately
parent.appendChild(this.div);
this.div.style.background=this.boss.BG_COLOR;
this.div.style.top=y;
this.div.style.left=x;
this.div.appendChild(this.div.overlapBar);
this.div.overlapBar.style.background=this.boss.LINE_COLOR;
this.div.appendChild(this.div.leftTab);
this.div.leftTab.style.background=this.boss.DARK_FRAME_COLOR;
this.div.appendChild(this.div.rightTab);
this.div.rightTab.style.background=this.boss.DARK_FRAME_COLOR;
this.div.appendChild(this.div.centerFill);
this.div.centerFill.style.background=this.boss.DARK_FRAME_COLOR;
for(var i=0;i<4;i++) {
this.div.appendChild(this.div.tabArcRight[i]);
this.div.tabArcRight[i].style.background=this.boss.LINE_COLOR;
}
for(var i=0;i<4;i++) {
this.div.appendChild(this.div.tabArcLeft[i]);
this.div.tabArcLeft[i].style.background=this.boss.LINE_COLOR;
}
this.render="";
}
ZWL.TabTopper.prototype.renderNormal=function() {
// "normal" means separate two tabs with no overlap
this.div.overlapBar.style.display="none";
this.div.centerFill.style.display="none";
this.displayLeftArc("block");
this.displayRightArc("block");
}
ZWL.TabTopper.prototype.renderRightOverlap=function() {
// render a tag with the right tab overlapping the left
this.div.overlapBar.style.display="block";
this.div.centerFill.style.display="block";
this.displayLeftArc("none");
this.displayRightArc("block");
this.div.leftTab.style.display="block";
}
ZWL.TabTopper.prototype.renderLeftOverlap=function() {
// render a tag with the left tab overlapping the right
this.div.overlapBar.style.display="block";
this.div.centerFill.style.display="block";
this.displayLeftArc("block");
this.displayRightArc("none");
this.div.rightTab.style.display="block";
}
ZWL.TabTopper.prototype.renderRightEnd=function() {
this.div.overlapBar.style.display="none";
this.div.centerFill.style.display="none";
this.displayLeftArc("block");
this.displayRightArc("none");
}
ZWL.TabTopper.prototype.renderLeftEnd=function() {
this.div.overlapBar.style.display="none";
this.div.centerFill.style.display="none";
this.displayLeftArc("none");
this.displayRightArc("block");
}
ZWL.TabTopper.prototype.tintRight=function(color) {
this.div.rightTab.style.background=color;
}
ZWL.TabTopper.prototype.tintLeft=function(color) {
this.div.leftTab.style.background=color;
}
ZWL.TabTopper.prototype.displayLeftArc=function(mode) {
for (var i=0;i<4;i++) this.div.tabArcLeft[i].style.display=mode;
this.div.leftTab.style.display=mode;
}
ZWL.TabTopper.prototype.displayRightArc=function(mode) {
for (var i=0;i<4;i++) this.div.tabArcRight[i].style.display=mode;
this.div.rightTab.style.display=mode;
}
//======================
ZWL.TabBase=function(controller,parent,x,y) {
this.boss=controller;
this.div=ZLM.simulateTag("div style='position:absolute; z-index:1;'");
ZLM.setSize(this.div,9,8,"none");
this.div.overlapBar=ZLM.simulateTag("div style='position:absolute; top:4; left:0;'");
ZLM.setSize(this.div.overlapBar,9,2,"none");
this.div.pageBar=ZLM.simulateTag("div style='position:absolute; top:6; left:0;'");
ZLM.setSize(this.div.pageBar,9,2,"none");
this.div.leftTab=ZLM.simulateTag("div style='position:absolute; top:0; left:0;'");
ZLM.setSize(this.div.leftTab,4,4,"none");
this.div.rightTab=ZLM.simulateTag("div style='position:absolute; top:0; left:5;'");
ZLM.setSize(this.div.rightTab,4,4,"none");
this.div.centerFill=ZLM.simulateTag("div style='position:absolute; top:2; left:4;'");
ZLM.setSize(this.div.centerFill,1,2,"none");
this.div.tabArcRight=new Array();
this.div.tabArcRight[0]=ZLM.simulateTag("div style='position:absolute; top:0; left:4;'");
ZLM.setSize(this.div.tabArcRight[0],2,2,"none");
this.div.tabArcRight[1]=ZLM.simulateTag("div style='position:absolute; top:2; left:5;'");
ZLM.setSize(this.div.tabArcRight[1],2,2,"none");
this.div.tabArcRight[2]=ZLM.simulateTag("div style='position:absolute; top:3; left:7;'");
ZLM.setSize(this.div.tabArcRight[2],2,2,"none");
this.div.tabArcRight[3]=ZLM.simulateTag("div style='position:absolute; top:4; left:8;'");
ZLM.setSize(this.div.tabArcRight[3],1,1,"none");
this.div.tabArcLeft=new Array();
this.div.tabArcLeft[0]=ZLM.simulateTag("div style='position:absolute; top:0; left:3;'");
ZLM.setSize(this.div.tabArcLeft[0],2,2,"none");
this.div.tabArcLeft[1]=ZLM.simulateTag("div style='position:absolute; top:2; left:2;'");
ZLM.setSize(this.div.tabArcLeft[1],2,2,"none");
this.div.tabArcLeft[2]=ZLM.simulateTag("div style='position:absolute; top:3; left:0;'");
ZLM.setSize(this.div.tabArcLeft[2],2,2,"none");
this.div.tabArcLeft[3]=ZLM.simulateTag("div style='position:absolute; top:5; left:0;'");
ZLM.setSize(this.div.tabArcLeft[3],1,1,"none");
// add and paint parts appropriately
parent.appendChild(this.div);
this.div.style.background=this.boss.BG_COLOR;
this.div.style.top=y;
this.div.style.left=x;
this.div.appendChild(this.div.overlapBar);
this.div.overlapBar.style.background=this.boss.LINE_COLOR;
this.div.appendChild(this.div.pageBar);
this.div.pageBar.style.background=this.boss.FRAME_COLOR;
this.div.appendChild(this.div.leftTab);
this.div.leftTab.style.background=this.boss.DARK_FRAME_COLOR;
this.div.appendChild(this.div.rightTab);
this.div.rightTab.style.background=this.boss.DARK_FRAME_COLOR;
this.div.appendChild(this.div.centerFill);
this.div.centerFill.style.background=this.boss.DARK_FRAME_COLOR;
for(var i=0;i<4;i++) {
this.div.appendChild(this.div.tabArcRight[i]);
this.div.tabArcRight[i].style.background=this.boss.LINE_COLOR;
}
for(var i=0;i<4;i++) {
this.div.appendChild(this.div.tabArcLeft[i]);
this.div.tabArcLeft[i].style.background=this.boss.LINE_COLOR;
}
this.render="";
}
ZWL.TabBase.prototype.renderRightOverlap=function() {
this.displayLeftArc("block");
this.displayRightArc("none");
this.div.leftTab.style.display="block";
this.div.rightTab.style.display="block";
this.div.overlapBar.style.background=this.boss.LINE_COLOR;
this.div.centerFill.style.background=this.boss.DARK_FRAME_COLOR;
this.div.rightTab.style.background=this.boss.DARK_FRAME_COLOR;
this.div.leftTab.style.background=this.boss.DARK_FRAME_COLOR;
}
ZWL.TabBase.prototype.renderRightFocused=function() {
this.displayLeftArc("block");
this.displayRightArc("none");
this.div.leftTab.style.display="block";
this.div.rightTab.style.display="block";
this.div.overlapBar.style.background=this.boss.FRAME_COLOR;
this.div.centerFill.style.background=this.boss.FRAME_COLOR;
this.div.rightTab.style.background=this.boss.FRAME_COLOR;
this.div.leftTab.style.background=this.boss.DARK_FRAME_COLOR;
}
ZWL.TabBase.prototype.renderLeftOverlap=function() {
this.div.overlapBar.style.display="block";
this.displayLeftArc("none");
this.displayRightArc("block");
this.div.leftTab.style.display="block";
this.div.rightTab.style.display="block";
this.div.overlapBar.style.background=this.boss.LINE_COLOR;
this.div.centerFill.style.background=this.boss.DARK_FRAME_COLOR;
this.div.rightTab.style.background=this.boss.DARK_FRAME_COLOR;
this.div.leftTab.style.background=this.boss.DARK_FRAME_COLOR;
}
ZWL.TabBase.prototype.renderLeftFocused=function() {
this.displayLeftArc("none");
this.displayRightArc("block");
this.div.leftTab.style.display="block";
this.div.rightTab.style.display="block";
this.div.overlapBar.style.background=this.boss.FRAME_COLOR;
this.div.centerFill.style.background=this.boss.FRAME_COLOR;
this.div.leftTab.style.background=this.boss.FRAME_COLOR;
this.div.rightTab.style.background=this.boss.DARK_FRAME_COLOR;
}
ZWL.TabBase.prototype.renderLeft=function(mode) {
this.div.leftTab.style.display=mode;
}
ZWL.TabBase.prototype.renderRight=function(mode) {
this.div.rightTab.style.display=mode;
}
ZWL.TabBase.prototype.displayLeftArc=function(mode) {
for (var i=0;i<4;i++) this.div.tabArcLeft[i].style.display=mode;
}
ZWL.TabBase.prototype.displayRightArc=function(mode) {
for (var i=0;i<4;i++) this.div.tabArcRight[i].style.display=mode;
}
//==============
ZWL.initTabFrame=function() {
var f = ZLM.getElementsByClassPrefix("tabFrame",document.body);
for (var i=0;i<f.length;i++) {
if (f[i].className=="tabFrame" && !ZWL.isReady(f[i])) {
var tmp=new ZWL.TabFrame(f[i]);
ZWL.markAsReady(f[i]);
}
}
}
//==============//
// GRID WIDGET //
//==============//
ZWL.createGrid=function(g) {
// GRID DATA
// nRows : number of actual rows
// nCols : number of actual columns
// rHeader : binary flag to turn off header row
// cHeader : binary flag to turn off header column
// rResize : binary flag to allow user to resize row heights interactively
// cResize : binary flag to allow user to resize column widths interactively
// rHeight : default height of rows (in pixels)
// cWidth : default width of cols (in pixels)
// cA : multidimensional cell array
// rH : array of row adjust handles
// cH : array of column adjust handles
// gridArea: div containing the actual array of cells and adjustment handles
// parse and store base attributes
g.nRows = g.getAttribute("nRows");
g.nCols = g.getAttribute("nCols");
if (g.getAttribute("rowHeader")=="false") g.rHeader=0;
else g.rHeader=1;
if (g.getAttribute("colHeader")=="false") g.cHeader=0;
else g.cHeader=1;
if (g.getAttribute("rowResize")=="false") g.rResize=0;
else g.rResize=1;
if (g.getAttribute("colResize")=="false") g.cResize=0;
else g.cResize=1;
g.cWidth=ZWL.initAttribute(g,"colWidth",100);
g.rHeight=ZWL.initAttribute(g,"rowHeight",25);
if (g.cHeader) g.nCols++; // tack on room for a header
if (g.rHeader) g.nRows++; // tack on room for a header
g.gridArea = ZLM.simulateTag("div style='position:relative; top:0; left:0;'");
g.gridArea.style.width=g.nCols*g.cWidth;
g.gridArea.style.height=g.nRows*g.rHeight;
g.style.width=g.nCols*g.cWidth;
g.style.height=g.nRows*g.rHeight;
g.style.border="2px outset red";
g.appendChild(g.gridArea);
var style="style='border:1px solid black; position:absolute; fontSize:0px; overflow:hidden;'";
g.cA=new Array(g.nRows);
for (var r=0;r<g.nRows;r++) {
g.cA[r]=new Array(g.nCols);
for (var c=0;c<g.nCols;c++) {
g.cA[r][c]=ZLM.simulateTag("div "+style);
if (r==0 && c>0) {
var lbl=ZLM.simulateTag("div className='zenGridHeader'");
lbl.appendChild(document.createTextNode(c));
lbl.style.width=g.cWidth-4;
lbl.style.position="relative";
lbl.style.left=2;
lbl.style.fontSize="14px";
lbl.style.fontFamily="Arial Black";
lbl.style.align="center";
lbl.style.zIndex= "-5";
lbl.style.textAlign="center";
lbl.style.background="yellow";
g.cA[r][c].appendChild(lbl);
}
g.cA[r][c].style.top=r*g.rHeight;
g.cA[r][c].style.left=c*g.cWidth;
g.gridArea.appendChild(g.cA[r][c]);
ZLM.setWidth(g.cA[r][c],g.cWidth);
ZLM.setHeight(g.cA[r][c],g.rHeight);
}
}
if (!ZWL.resizeMgr) ZWL.resizeMgr=new ZWL.ResizeManager();
g.cH=new Array(g.nCols);
style="style='width:5; height:"+g.rHeight+"; position:absolute; cursor:col-resize; z-index:10;'";
for (var c=0;c<g.nCols; c++) {
g.cH[c]=ZLM.simulateTag("div "+style+" onmousedown='ZLM.drag(this,event);'");
g.cH[c].style.top="0";
g.cH[c].style.left=(c+1)*g.cWidth-3;
g.cH[c].baseGrid=g;
ZLM.registerDragItem(g.cH[c],ZWL.resizeMgr);
g.gridArea.appendChild(g.cH[c]);
}
g.rH=new Array(g.nRows);
style="style='width:"+g.cWidth+"; height:5; position:absolute; cursor:row-resize; z-index:1;'";
for (var r=0;r<g.nRows; r++) {
g.rH[r]=ZLM.simulateTag("div "+style+" onmousedown='ZLM.drag(this,event);'");
g.rH[r].style.top=(r+1)*g.rHeight-3;
g.rH[r].style.left=0;
g.rH[r].baseGrid=g;
ZLM.registerDragItem(g.rH[r],ZWL.resizeMgr);
g.gridArea.appendChild(g.rH[r]);
}
}
ZWL.setGridColumnWidth=function(grid, colIdx, width) {
// adjusting the width of a column consists of
// 1) making the actual column wider
// 2) moving all the other columns over
// 3) moving all the adjustment handlers over
// 4) resizing the overall grid container
if (width<4) width=4;
var delta = width - grid.cA[0][colIdx].clientWidth;
//ZLM.cerr("new width: "+width+" Delta of "+delta);
//ZLM.getClientWidth(grid.cA[0][colIdx]);
for (var r=0;r<grid.nRows;r++) {
// grid.cA[r][colIdx].style.width=width;
ZLM.setWidth(grid.cA[r][colIdx],width);
for (var c=colIdx+1; c<grid.nCols; c++) grid.cA[r][c].style.left=grid.cA[r][c].offsetLeft+delta;
}
for (var c=colIdx;c<grid.nCols;c++) grid.cH[c].style.left=grid.cH[c].offsetLeft+delta;
grid.gridArea.style.width=grid.gridArea.clientWidth+delta;
grid.style.width=grid.gridArea.offsetWidth;
}
ZWL.setGridRowHeight=function(grid, rowIdx, height) {
if (height<4) height=4;
var delta = height - grid.cA[rowIdx][0].clientHeight;
for (var c=0;c<grid.nCols;c++) {
// grid.cA[rowIdx][c].style.height=height;
ZLM.setHeight(grid.cA[rowIdx][c],height);
for (var r=rowIdx+1; r<grid.nRows; r++) grid.cA[r][c].style.top=grid.cA[r][c].offsetTop+delta;
}
for (var r=rowIdx;r<grid.nRows;r++) grid.rH[r].style.top=grid.rH[r].offsetTop+delta;
grid.gridArea.style.height=grid.gridArea.clientHeight+delta;
grid.style.height=grid.gridArea.offsetHeight;
}
ZWL.initGrids=function() {
var grids = ZLM.getElementsByClassPrefix("csGrid",document.body);
for (var i=0;i<grids.length;i++) {
if (grids[i].className=="csGrid") {
ZWL.createGrid(grids[i]);
}
}
}
//# HELPER CLASS #
ZWL.ResizeManager=function() {}
ZWL.ResizeManager.prototype.startDrag=function(mgr, wrapper) {
this.who = wrapper.node;
this.baseGrid = this.who.baseGrid;
if (this.who.offsetTop==0) { // column adjustor
for (var i=0;i<this.baseGrid.nCols;i++) {
if (this.baseGrid.cH[i]==this.who) {
this.idx=i;
}
}
}
else {
for (var i=0;i<this.baseGrid.nRows;i++) {
if (this.baseGrid.rH[i]==this.who) {
this.idx=i;
}
}
}
}
/// Move the dragAvatar over by 2 pixels to prevent overlap with the crosshair cursor.
ZWL.ResizeManager.prototype.constrainDragX=function(mgr, wrapper, intendedX) {
var n = wrapper.node;
if (n.offsetLeft==0) return(0); // lateral move of row adjuster
//n.style.background="red";
var newWidth = this.baseGrid.cA[0][this.idx].clientWidth+intendedX-n.offsetLeft;
ZWL.setGridColumnWidth(this.baseGrid,this.idx,newWidth);
return(n.offsetLeft);
}
/// Like constrainDragX, we're moving the dragAvatar down by 2 pixels to
/// prevent overlap with the crosshair cursor.
ZWL.ResizeManager.prototype.constrainDragY=function(mgr, wrapper, intendedY) {
var n=wrapper.node;
if (n.offsetTop==0) return(0); // vertical move of column adjuster
var newHeight = this.baseGrid.cA[this.idx][0].clientHeight+intendedY-n.offsetTop;
ZWL.setGridRowHeight(this.baseGrid,this.idx,newHeight);
return(n.offsetTop);
}
ZWL.ResizeManager.prototype.endDrag=function(mgr, wrapper){
}
//# HELPER CLASS #
ZWL.SliderManager=function() {
this.SLIDER=1;
this.RANGE_SLIDER=2;
this.SCROLLBAR=3;
}
ZWL.SliderManager.prototype.startDrag=function(mgr, wrapper) {
this.who = wrapper.node;
this.baseObj= wrapper.node.baseObj;
this.vert = wrapper.node.baseObj.vert;
this.ilk = this.SLIDER;
if (wrapper.node.baseObj.className=="ZEN_RANGE_SLIDER") this.ilk=this.RANGE_SLIDER;
this.pxMin=wrapper.node.baseObj.getMinPxPosition(this.who);
this.pxMax=wrapper.node.baseObj.getMaxPxPosition(this.who);
this.pxInset=wrapper.node.baseObj.getStaticPxInset(this.who);
}
ZWL.SliderManager.prototype.constrainDragX=function(mgr, wrapper, intendedX) {
if (this.vert) return(this.pxInset); // No lateral movements of V sliders
if (this.ilk==this.RANGE_SLIDER) wrapper.node.baseObj.updateRange(wrapper.node)
else wrapper.node.baseObj.updateValue();
if (intendedX<this.pxMin) return(this.pxMin);
if (intendedX>this.pxMax) return(this.pxMax);
return(intendedX);
}
ZWL.SliderManager.prototype.constrainDragY=function(mgr, wrapper, intendedY) {
if (!this.vert) return(this.pxInset); // No vertical movements of H sliders
if (this.ilk==this.RANGE_SLIDER) wrapper.node.baseObj.updateRange(wrapper.node)
else wrapper.node.baseObj.updateValue();
if (intendedY<this.pxMin) return(this.pxMin);
if (intendedY>this.pxMax) return(this.pxMax);
return(intendedY);
}
ZWL.SliderManager.prototype.endDrag=function(mgr, wrapper){
wrapper.node.baseObj.snapToValue();
}
//########################################################
ZWL.initSliders=function() {
// if (!ZWL.sliderMgr) ZWL.sliderMgr=new ZWL.SliderManager();
var sliders = ZLM.getElementsByClassPrefix("slider",document.body);
for (var i=0;i<sliders.length;i++) {
if (sliders[i].className=="slider" && !ZWL.isReady(sliders[i])) {
var s=new ZWL.Slider(sliders[i]);
ZWL.markAsReady(sliders[i]);
}
}
var sliders = ZLM.getElementsByClassPrefix("rangeSlider",document.body);
for (var i=0;i<sliders.length;i++) {
if (sliders[i].className=="rangeSlider" && !ZWL.isReady(sliders[i])) {
var s=new ZWL.RangeSlider(sliders[i]);
ZWL.markAsReady(sliders[i]);
}
}
var sliders = ZLM.getElementsByClassPrefix("scrollbar",document.body);
for (var i=0;i<sliders.length;i++) {
if (sliders[i].className=="scrollbar" && !ZWL.isReady(sliders[i])) {
var s=new ZWL.Scrollbar(sliders[i]);
ZWL.markAsReady(sliders[i]);
}
}
}
ZWL.initAttribute=function(div,attrName,defaultValue) {
var val = div.getAttribute(attrName);
if (val==null || val=="") val=defaultValue;
return(val);
}
//
// AUTOFIRE SYSTEM FOR PRESS & HOLD BUTTONS
//
ZWL.autofireFlag=0;
ZWL.autofireWidget=null;
ZWL.autofireEventX=0;
ZWL.autofireEventY=0;
ZWL.autofire=function(fn,delay) {
if (ZWL.autofireFlag!=1) return;
var widget=ZWL.autofireWidget;
eval(fn);
setTimeout("ZWL.autofire('"+fn+"',"+delay+");",delay);
}
ZWL.autofireCB=function(who,event,fn,delay) {
ZWL.autofireFlag=1;
ZWL.autofireWidget=who;
ZWL.autofireEventX=event.clientX;
ZWL.autofireEventY=event.clientY;
ZWL.autofire(fn,delay);
}
ZWL.cancelAutofireCB=function(widget,fn) {
eval(fn);
ZWL.autofireFlag=0;
}
//########################################################
ZWL.Scrollbar =function(div) {
// scrollbars are defined by
// orientation: horizontal or vertical;
// pageSize : max extent of virtual page (in generic units)
// viewSize : how much of the virtual page (in generic units) is visible
// viewHome : location (in generic units) of the Home position of the view
// unitScrollDelay : scrolling speed for up and down arrows
// pageScrollDelay : scrolling speed for page flips
//
// callbacks:
// onpageup: response to autofire above scrollbar handle
// onunitup: response to autofire on up arrow
// onscroll: response to drag of scrollbar handle
// onunitdown: response to autofire on down arrow
// onpagedown: response to autofire below scrollbar
this.SLIDER_SPAN=19;
this.SLIDER_ICON_LEFT_EDGE="hSliderTabLeft.png";
this.SLIDER_ICON_RIGHT_EDGE="hSliderTabRight.png";
this.SLIDER_ICON_H_FILL="hSliderTabFill.png";
this.SLIDER_ICON_H_GRIP="hSliderTabGrip.png";
this.SLIDER_ICON_TOP="vSliderTabTop.png";
this.SLIDER_ICON_BOTTOM="vSliderTabBottom.png";
this.SLIDER_ICON_V_FILL="vSliderTabFill.png";
this.SLIDER_ICON_V_GRIP="vSliderTabGrip.png";
this.SLIDER_ICON_UP="images/SmUpArrow.png";
this.SLIDER_ICON_DOWN="images/SmDownArrow.png";
this.SLIDER_ICON_LEFT="images/SmLeftArrow.png";
this.SLIDER_ICON_RIGHT="images/SmRightArrow.png";
this.className="ZEN_SCROLLBAR";
this.div = div;
div.controller = this;
this.minValue = 0;
this.maxValue = ZWL.initAttribute(div,"pageSize",100);
this.value= ZWL.initAttribute(div,"viewHome",0);
this.extent = ZWL.initAttribute(div,"viewSize",this.maxValue);
this.usDelay = ZWL.initAttribute(div,"unitScrollDelay",100);
this.psDelay = ZWL.initAttribute(div,"pageScrollDelay",250);
if (div.getAttribute("orientation")=="vertical") this.vert=1;
else this.vert=0;
this.onPageUpCB = ZWL.initAttribute(div,"onpageup",null);
this.onUnitUpCB = ZWL.initAttribute(div,"onunitup",null);
this.onScrollCB = ZWL.initAttribute(div,"onscroll",null);
this.onUnitDownCB = ZWL.initAttribute(div,"onunitdown",null);
this.onPageDownCB = ZWL.initAttribute(div,"onpagedown",null);
this.createAvatar();
}
ZWL.Scrollbar.prototype.createAvatar=function() {
var w = this.div.clientWidth;
var h = this.div.clientHeight;
var bSz = this.SLIDER_SPAN-4;
if (this.vert) {
if (w>this.SLIDER_SPAN) var offset=(w-this.SLIDER_SPAN)/2;
else var offset=0;
var tH = this.div.clientHeight-2*this.SLIDER_SPAN-2;
this.div.body=ZLM.simulateTag("div style='width:"+this.SLIDER_SPAN+"; height:100%; position:relative; top:0; left:"+offset+";'");
if (ZLM.isIE) this.div.body.style.fontSize="0pt";
this.div.appendChild(this.div.body);
this.div.upButton=ZLM.simulateTag("div style='position:absolute; top:0; left:0; border:2px outset #a0a0a0; background-image:url("+this.SLIDER_ICON_UP+");'");
this.div.upButton.controller=this;
ZLM.setLocalAttribute(this.div.upButton,"onmousedown","ZWL.autofireCB(this,event,'widget.controller.upCB();',"+this.usDelay+");");
ZLM.setLocalAttribute(this.div.upButton,"onmouseup","ZWL.cancelAutofireCB(this,'widget.controller.normalCB();');");
this.div.body.appendChild(this.div.upButton);
ZLM.setSize(this.div.upButton,bSz,bSz);
this.div.trough=ZLM.simulateTag("div style='border:1px solid gray; position:absolute; top:"+this.SLIDER_SPAN+"; left:0;'");
this.div.trough.controller=this;
ZLM.setLocalAttribute(this.div.trough,"onmousedown","ZWL.autofireCB(this,event,'widget.controller.pageCB();',"+this.usDelay+");");
ZLM.setLocalAttribute(this.div.trough,"onmouseup","ZWL.cancelAutofireCB(this,'widget.controller.endPageCB();');");
this.div.body.appendChild(this.div.trough);
ZLM.setSize(this.div.trough,this.SLIDER_SPAN-2,tH);
this.div.tab=ZLM.simulateTag("div class='sliderTab'; style='width:"+this.SLIDER_SPAN+"; height:"+this.SLIDER_SPAN+"; position:absolute; top:0; left:0; cursor:n-resize;' onmousedown='ZLM.drag(this,event);'");
this.div.tab.baseObj=this;
this.div.body.appendChild(this.div.tab);
this.div.tabTop = ZLM.simulateTag("div style='width:19; height:4; position:absolute; top:0; left:0; background-image:url("+this.SLIDER_ICON_TOP+");'");
this.div.tabFill = ZLM.simulateTag("div style='width:19; height:11; position:absolute; top:4; left:0; background-image:url("+this.SLIDER_ICON_V_FILL+"); background-repeat:repeat-y;'");
this.div.tabBottom = ZLM.simulateTag("div style='width:19; height:4; position:absolute; top:15; left:0; background-image:url("+this.SLIDER_ICON_BOTTOM+");'");
this.div.tabGrip = ZLM.simulateTag("div style='width:19; height:19; position:absolute; top:0; left:0; z-index:1; background-image:url("+this.SLIDER_ICON_V_GRIP+");'");
this.div.tab.appendChild(this.div.tabTop);
this.div.tab.appendChild(this.div.tabFill);
this.div.tab.appendChild(this.div.tabBottom);
this.div.tab.appendChild(this.div.tabGrip);
this.div.downButton=ZLM.simulateTag("div style='position:absolute; top:"+(this.div.body.clientHeight-this.SLIDER_SPAN)+"; left:0; border:2px outset #a0a0a0; background-image:url("+this.SLIDER_ICON_DOWN+");'");
this.div.downButton.controller=this;
ZLM.setLocalAttribute(this.div.downButton,"onmousedown","ZWL.autofireCB(this,event,'widget.controller.downCB();',"+this.usDelay+");");
ZLM.setLocalAttribute(this.div.downButton,"onmouseup","ZWL.cancelAutofireCB(this,'widget.controller.normalCB();');");
this.div.body.appendChild(this.div.downButton);
ZLM.setSize(this.div.downButton,bSz,bSz);
}
else {
if (h>this.SLIDER_SPAN) var offset=(h-this.SLIDER_SPAN)/2;
else var offset=0;
var tW = this.div.clientWidth-2*this.SLIDER_SPAN-2;
this.div.body=ZLM.simulateTag("div style='width:100%; height:"+this.SLIDER_SPAN+"; position:relative; top:"+offset+"; left:0;'");
if (ZLM.isIE) this.div.body.style.fontSize="0pt";
this.div.appendChild(this.div.body);
this.div.upButton=ZLM.simulateTag("div style='position:absolute; top:0; left:0; border:2px outset #a0a0a0; background-image:url("+this.SLIDER_ICON_LEFT+");'");
this.div.upButton.controller=this;
ZLM.setLocalAttribute(this.div.upButton,"onmousedown","ZWL.autofireCB(this,event,'widget.controller.upCB();',"+this.usDelay+");");
ZLM.setLocalAttribute(this.div.upButton,"onmouseup","ZWL.cancelAutofireCB(this,'widget.controller.normalCB();');");
this.div.body.appendChild(this.div.upButton);
ZLM.setSize(this.div.upButton,bSz,bSz);
this.div.trough=ZLM.simulateTag("div style='border:1px solid gray; position:absolute; left:"+this.SLIDER_SPAN+"; top:0;'");
this.div.trough.controller=this;
ZLM.setLocalAttribute(this.div.trough,"onmousedown","ZWL.autofireCB(this,event,'widget.controller.pageCB();',"+this.usDelay+");");
ZLM.setLocalAttribute(this.div.trough,"onmouseup","ZWL.cancelAutofireCB(this,'widget.controller.endPageCB();');");
this.div.body.appendChild(this.div.trough);
ZLM.setSize(this.div.trough,tW,this.SLIDER_SPAN-2);
this.div.tab=ZLM.simulateTag("div class='sliderTab'; style='width:"+this.SLIDER_SPAN+"; height:"+this.SLIDER_SPAN+"; position:absolute; top:0; left:0; cursor:e-resize;' onmousedown='ZLM.drag(this,event);'");
this.div.tab.baseObj=this;
this.div.body.appendChild(this.div.tab);
this.div.tabLeft = ZLM.simulateTag("div style='width:4; height:19; position:absolute; top:0; left:0; background-image:url("+this.SLIDER_ICON_LEFT_EDGE+");'");
this.div.tabFill = ZLM.simulateTag("div style='width:11; height:19; position:absolute; top:0; left:4; background-image:url("+this.SLIDER_ICON_H_FILL+"); background-repeat:repeat-x;'");
this.div.tabRight = ZLM.simulateTag("div style='width:4; height:19; position:absolute; top:0; left:15; background-image:url("+this.SLIDER_ICON_RIGHT_EDGE+");'");
this.div.tabGrip = ZLM.simulateTag("div style='width:19; height:19; position:absolute; top:0; left:0; z-index:1; background-image:url("+this.SLIDER_ICON_H_GRIP+");'");
this.div.tab.appendChild(this.div.tabLeft);
this.div.tab.appendChild(this.div.tabFill);
this.div.tab.appendChild(this.div.tabRight);
this.div.tab.appendChild(this.div.tabGrip);
this.div.downButton=ZLM.simulateTag("div style='position:absolute; left:"+(this.div.body.clientWidth-this.SLIDER_SPAN)+"; top:0; border:2px outset #a0a0a0; background-image:url("+this.SLIDER_ICON_RIGHT+");'");
this.div.downButton.controller=this;
ZLM.setLocalAttribute(this.div.downButton,"onmousedown","ZWL.autofireCB(this,event,'widget.controller.downCB();',"+this.usDelay+");");
ZLM.setLocalAttribute(this.div.downButton,"onmouseup","ZWL.cancelAutofireCB(this,'widget.controller.normalCB();');");
this.div.body.appendChild(this.div.downButton);
ZLM.setSize(this.div.downButton,bSz,bSz);
}
var sliderColor = ZLM.toHTMLColorSpec(ZLM.getRGBBackgroundColor(this.div.tab));
this.div.downButton.style.backgroundColor=sliderColor;
this.div.upButton.style.backgroundColor=sliderColor;
ZLM.cerr("registering tab: "+ZWL.sliderMgr);
ZLM.registerDragItem(this.div.tab,ZWL.sliderMgr);
this.snapToValue();
}
ZWL.Scrollbar.prototype.normalCB=function() {
this.div.upButton.style.border="2px outset gray";
this.div.downButton.style.border="2px outset gray";
}
ZWL.Scrollbar.prototype.upCB=function() {
this.div.upButton.style.border="2px inset gray";
eval(this.onUnitUpCB);
}
ZWL.Scrollbar.prototype.downCB=function() {
this.div.downButton.style.border="2px inset gray";
eval(this.onUnitDownCB);
}
ZWL.Scrollbar.prototype.pageCB=function() {
if (this.vert) {
var b=this.div.tab.offsetTop-this.SLIDR_SPAN;
var e=b+this.div.tab.offsetHeight;
var y=ZWL.autofireEventY-ZLM.getRelativeOffsetTop(this.div.trough,document.body);
}
else {
var b=this.div.tab.offsetLeft-this.SLIDER_SPAN;
var e=b+this.div.tab.offsetWidth;
var y=ZWL.autofireEventX-ZLM.getRelativeOffsetLeft(this.div.trough,document.body);
}
if (y<b) eval(this.onPageUpCB);
else if (y>e) eval(this.onPageDownCB);
else ZWL.cancelAutofireCB(this,null);
}
ZWL.Scrollbar.prototype.endPageCB=function() {
ZLM.cerr("Whoa!");
}
ZWL.Scrollbar.prototype.getMinPxPosition=function(tab) {
return(this.SLIDER_SPAN);
}
ZWL.Scrollbar.prototype.getMaxPxPosition=function(tab) {
if (this.vert) return(this.div.clientHeight-this.SLIDER_SPAN-this.div.tab.offsetHeight);
return(this.div.clientWidth-this.SLIDER_SPAN-this.div.tab.offsetWidth);
}
ZWL.Scrollbar.prototype.getStaticPxInset=function(tab) {
return(0);
}
ZWL.Scrollbar.prototype.updateValue=function() {
if (this.vert) {
var offset = this.div.tab.offsetTop-this.SLIDER_SPAN;
var span = this.div.trough.offsetHeight-this.div.tab.offsetHeight;
}
else {
var offset = this.div.tab.offsetLeft-this.SLIDER_SPAN;
var span = this.div.trough.offsetWidth-this.div.tab.offsetWidth;
}
var range = this.maxValue-this.minValue;
this.value=Math.round(range*(offset/span))+this.minValue;
eval(this.onScrollCB);
}
ZWL.Scrollbar.prototype.snapToValue=function() {
var homePercent = this.value/this.maxValue;
var sizePercent = this.extent/this.maxValue;
if (this.vert) {
var tabSize=this.div.trough.offsetHeight*sizePercent;
if (tabSize<this.SLIDER_SPAN) tabSize=this.SLIDER_SPAN;
this.div.tab.style.height=tabSize;
this.div.tabFill.style.height=tabSize-8;
this.div.tabBottom.style.top=tabSize-4;
this.div.tabGrip.style.top=(tabSize-this.SLIDER_SPAN)/2;
var homePx = homePercent*(this.div.trough.offsetHeight-tabSize);
homePx+=this.SLIDER_SPAN;
this.div.tab.style.top=homePx;
}
else {
var tabSize=this.div.trough.offsetWidth*sizePercent;
if (tabSize<this.SLIDER_SPAN) tabSize=this.SLIDER_SPAN;
this.div.tab.style.width=tabSize;
this.div.tabFill.style.width=tabSize-8;
this.div.tabRight.style.left=tabSize-4;
this.div.tabGrip.style.left=(tabSize-this.SLIDER_SPAN)/2;
var homePx = homePercent*(this.div.trough.offsetWidth-tabSize);
homePx+=this.SLIDER_SPAN;
this.div.tab.style.left=homePx;
}
}
// Scrollbar API
ZWL.Scrollbar.prototype.resize=function(newW, newH) {
ZLM.setSize(this.div,newW,newH);
// enforce base constriants
if (this.vert) {
if (newW>this.SLIDER_SPAN) var offset=(newW-this.SLIDER_SPAN)/2;
else var offset=0;
this.div.body.style.left=offset;
this.div.downButton.style.top=newH-this.div.downButton.offsetHeight;
ZLM.setSize(this.div.trough,this.SLIDER_SPAN-2,newH-2*this.SLIDER_SPAN-2);
}
else {
if (newH>this.SLIDER_SPAN) var offset=(newH-this.SLIDER_SPAN)/2;
else var offset=0;
this.div.body.style.top=offset;
this.div.downButton.style.left=newW-this.div.downButton.offsetWidth;
ZLM.setSize(this.div.trough,newW-2*this.SLIDER_SPAN-2,this.SLIDER_SPAN-2);
}
this.snapToValue();
}
ZWL.Scrollbar.prototype.setViewSize=function(newMin) {
this.extent=newMin;
this.snapToValue();
}
ZWL.Scrollbar.prototype.setPageSize=function(newMax) {
this.maxValue=newMax;
this.snapToValue();
}
ZWL.Scrollbar.prototype.setViewHome=function(newValue) {
if (newValue<0) newValue=0;
if (newValue>this.maxValue) newValue=this.maxValue;
this.value=newValue;
this.snapToValue();
}
ZWL.Scrollbar.prototype.getValue=function() {
return(this.value);
}
//####################################################
ZWL.Slider =function(div) {
this.SLIDER_SPAN=19;
this.SLIDER_ICON_LEFT="hSliderTabLeft.png";
this.SLIDER_ICON_RIGHT="hSliderTabRight.png";
this.SLIDER_ICON_H_FILL="hSliderTabFill.png";
this.SLIDER_ICON_H_GRIP="hSliderTabGrip.png";
this.SLIDER_ICON_TOP="vSliderTabTop.png";
this.SLIDER_ICON_BOTTOM="vSliderTabBottom.png";
this.SLIDER_ICON_V_FILL="vSliderTabFill.png";
this.SLIDER_ICON_V_GRIP="vSliderTabGrip.png";
this.className="ZEN_SLIDER";
this.div = div;
div.controller = this;
this.minValue = div.getAttribute("minValue");
if (this.minValue==null || this.minValue=="") this.minValue=0;
this.maxValue = div.getAttribute("maxValue");
if (this.maxValue==null || this.maxValue=="") this.maxValue=100;
this.value = div.getAttribute("value");
if (this.value==null||this.value=="") this.value=this.minValue;
if (div.getAttribute("orientation")=="vertical") this.vert=1;
else this.vert=0;
this.createAvatar();
}
ZWL.Slider.prototype.createAvatar=function() {
var w = this.div.clientWidth;
var h = this.div.clientHeight;
if (this.vert) {
if (w>this.SLIDER_SPAN) var offset=(w-this.SLIDER_SPAN)/2;
else var offset=0;
this.div.body=ZLM.simulateTag("div style='width:"+this.SLIDER_SPAN+"; height:100%; position:relative; top:0; left:"+offset+";'");
if (ZLM.isIE) this.div.body.style.fontSize="0pt";
this.div.appendChild(this.div.body);
this.div.trough=ZLM.simulateTag("div style='width:1; height:"+(h-10)+"; border:3px inset gray; background:#505050; position:absolute; top:2; left:7;'");
this.div.body.appendChild(this.div.trough);
this.div.tab=ZLM.simulateTag("div class='sliderTab'; style='width:"+this.SLIDER_SPAN+"; height:"+this.SLIDER_SPAN+"; position:absolute; top:0; left:0; cursor:n-resize;' onmousedown='ZLM.drag(this,event);'");
this.div.tab.baseObj=this;
this.div.body.appendChild(this.div.tab);
var tabTop = ZLM.simulateTag("div style='width:19; height:4; position:absolute; top:0; left:0; background-image:url("+this.SLIDER_ICON_TOP+");'");
var tabFill = ZLM.simulateTag("div style='width:19; height:11; position:absolute; top:4; left:0; background-image:url("+this.SLIDER_ICON_V_FILL+"); background-repeat:repeat-y;'");
var tabBottom = ZLM.simulateTag("div style='width:19; height:4; position:absolute; top:15; left:0; background-image:url("+this.SLIDER_ICON_BOTTOM+");'");
var tabGrip = ZLM.simulateTag("div style='width:19; height:19; position:absolute; top:0; left:0; z-index:1; background-image:url("+this.SLIDER_ICON_V_GRIP+");'");
this.div.tab.appendChild(tabTop);
this.div.tab.appendChild(tabFill);
this.div.tab.appendChild(tabBottom);
this.div.tab.appendChild(tabGrip);
}
else {
if (h>this.SLIDER_SPAN) var offset=(h-this.SLIDER_SPAN)/2;
else var offset=0;
this.div.body=ZLM.simulateTag("div style='width:100%; height:"+this.SLIDER_SPAN+"; position:relative; top:"+offset+"; left:0;'");
if (ZLM.isIE) this.div.body.style.fontSize="0pt";
this.div.appendChild(this.div.body);
this.div.trough=ZLM.simulateTag("div style='width:"+(w-10)+"; height:1; border:3px inset gray; background:#505050; position:absolute; top:7; left:2;'");
this.div.body.appendChild(this.div.trough);
this.div.tab=ZLM.simulateTag("div class='sliderTab'; style='width:"+this.SLIDER_SPAN+"; height:"+this.SLIDER_SPAN+"; position:absolute; top:0; left:0; cursor:e-resize;' onmousedown='ZLM.drag(this,event);'");
this.div.tab.baseObj=this;
this.div.body.appendChild(this.div.tab);
var tabLeft = ZLM.simulateTag("div style='width:4; height:19; position:absolute; top:0; left:0; background-image:url("+this.SLIDER_ICON_LEFT+");'");
var tabFill = ZLM.simulateTag("div style='width:11; height:19; position:absolute; top:0; left:4; background-image:url("+this.SLIDER_ICON_H_FILL+"); background-repeat:repeat-x;'");
var tabRight = ZLM.simulateTag("div style='width:4; height:19; position:absolute; top:0; left:15; background-image:url("+this.SLIDER_ICON_RIGHT+");'");
var tabGrip = ZLM.simulateTag("div style='width:19; height:19; position:absolute; top:0; left:0; background-image:url("+this.SLIDER_ICON_H_GRIP+");'");
this.div.tab.appendChild(tabLeft);
this.div.tab.appendChild(tabFill);
this.div.tab.appendChild(tabRight);
this.div.tab.appendChild(tabGrip);
}
ZLM.registerDragItem(this.div.tab,ZWL.sliderMgr);
this.snapToValue();
}
ZWL.Slider.prototype.getMinPxPosition=function(tab) {
return(0);
}
ZWL.Slider.prototype.getMaxPxPosition=function(tab) {
if (this.vert) return(this.div.clientHeight-this.div.tab.offsetHeight);
return(this.div.clientWidth-this.div.tab.offsetWidth);
}
ZWL.Slider.prototype.getStaticPxInset=function(tab) {
return(0);
}
ZWL.Slider.prototype.updateValue=function() {
if (this.vert) {
var offset = this.div.tab.offsetTop;
var span = this.div.clientHeight-this.div.tab.clientHeight;
}
else {
var offset = this.div.tab.offsetLeft;
var span = this.div.clientWidth-this.div.tab.clientWidth;
}
var range = this.maxValue-this.minValue;
this.value=Math.round(range*(offset/span))+this.minValue;
}
ZWL.Slider.prototype.snapToValue=function() {
var percentage = (this.value-this.minValue)/(this.maxValue-this.minValue);
if (this.vert) {
this.div.tab.style.top=percentage*(this.div.clientHeight-this.div.tab.offsetHeight);
}
else {
this.div.tab.style.left=percentage*(this.div.clientWidth-this.div.tab.offsetWidth);
}
}
// SLIDER API
ZWL.Slider.prototype.resize=function(newW, newH) {
this.div.parentNode.style.width=newW;
this.div.parentNode.style.height=newH;
// enforce base constriants
if (this.vert) {
if (newW>this.SLIDER_SPAN) var offset=(newW-this.SLIDER_SPAN)/2;
else var offset=0;
this.div.body.style.left=offset;
this.div.trough.style.height=(newH-10);
}
else {
if (newH>this.SLIDER_SPAN) var offset=(newH-this.SLIDER_SPAN)/2;
else var offset=0;
this.div.body.style.top=offset;
this.div.trough.style.width=(newW-10);
}
this.snapToValue();
}
ZWL.Slider.prototype.setMinValue=function(newMin) {
this.minValue=newMin;
if (newMin>this.maxValue)this.maxValue=newMin;
this.snapToValue();
}
ZWL.Slider.prototype.setMaxValue=function(newMax) {
this.maxValue=newMax;
if (newMax<this.minValue) this.minValue=newMax;
this.snapToValue();
}
ZWL.Slider.prototype.setValue=function(newValue) {
if (newValue<this.minValue) newValue=this.minValue;
if (newValue>this.maxValue) newValue=this.maxValue;
this.value=newValue;
this.snapToValue();
}
ZWL.Slider.prototype.getValue=function() {
return(this.value);
}
//################################################################
ZWL.RangeSlider =function(div) {
this.SLIDER_SPAN=19;
this.SLIDER_TAB_SPAN=8;
this.SLIDER_ICON_LEFT="hSliderTabLeft.png";
this.SLIDER_ICON_RIGHT="hSliderTabRight.png";
this.SLIDER_ICON_H_GRIP="hSliderTabGrip.png";
this.SLIDER_ICON_TOP="vSliderTabTop.png";
this.SLIDER_ICON_BOTTOM="vSliderTabBottom.png";
this.SLIDER_ICON_V_GRIP="vSliderTabGrip.png";
this.className="ZEN_RANGE_SLIDER";
this.div = div;
div.controller = this;
this.minValue = div.getAttribute("minValue");
if (this.minValue==null || this.minValue=="") this.minValue=0;
this.maxValue = div.getAttribute("maxValue");
if (this.maxValue==null || this.maxValue=="") this.maxValue=100;
this.value = div.getAttribute("rangeMin");
if (this.rangeMin==null||this.rangeMax=="") this.rangeMin=this.minValue;
this.value = div.getAttribute("rangeMax");
if (this.rangeMax==null||this.rangeMax=="") this.rangeMax=this.minValue;
if (div.getAttribute("orientation")=="vertical") this.vert=1;
else this.vert=0;
this.createAvatar();
}
ZWL.RangeSlider.prototype.createAvatar=function() {
var w = this.div.clientWidth;
var h = this.div.clientHeight;
if (this.vert) {
if (w>this.SLIDER_SPAN) var offset=(w-this.SLIDER_SPAN)/2;
else var offset=0;
this.div.body=ZLM.simulateTag("div style='width:"+this.SLIDER_SPAN+"; height:100%; position:relative; top:0; left:"+offset+";'");
if (ZLM.isIE) this.div.body.style.fontSize="0pt";
this.div.appendChild(this.div.body);
this.div.trough=ZLM.simulateTag("div style='width:1; height:"+(h-10)+"; border:3px inset gray; background:#505050; position:absolute; top:2; left:7;'");
this.div.body.appendChild(this.div.trough);
this.div.minTab=ZLM.simulateTag("div class='sliderTab'; style='width:"+this.SLIDER_SPAN+"; height:"+this.SLIDER_TAB_SPAN+"; position:absolute; top:0; left:0; cursor:n-resize;' onmousedown='ZLM.drag(this,event);'");
this.div.minTab.baseObj=this;
this.div.body.appendChild(this.div.minTab);
var tabTop = ZLM.simulateTag("div style='width:19; height:4; position:absolute; top:0; left:0; background-image:url("+this.SLIDER_ICON_TOP+");'");
var tabBottom = ZLM.simulateTag("div style='width:19; height:4; position:absolute; top:4; left:0; background-image:url("+this.SLIDER_ICON_BOTTOM+");'");
this.div.minTab.appendChild(tabTop);
this.div.minTab.appendChild(tabBottom);
this.div.maxTab=ZLM.simulateTag("div class='sliderTab' style='width:"+this.SLIDER_SPAN+"; height:"+this.SLIDER_TAB_SPAN+"; position:absolute; top:0; left:0; cursor:n-resize;' onmousedown='ZLM.drag(this,event);'");
this.div.maxTab.baseObj=this;
this.div.body.appendChild(this.div.maxTab);
var tabTop = ZLM.simulateTag("div style='width:19; height:4; position:absolute; top:0; left:0; background-image:url("+this.SLIDER_ICON_TOP+");'");
var tabBottom = ZLM.simulateTag("div style='width:19; height:4; position:absolute; top:4; left:0; background-image:url("+this.SLIDER_ICON_BOTTOM+");'");
this.div.maxTab.appendChild(tabTop);
this.div.maxTab.appendChild(tabBottom);
this.div.bodyTab=ZLM.simulateTag("div class='sliderTab' style='width:11; position:absolute; top:0; left:5; border:1px solid gray;' onmousedown='ZLM.drag(this,event);'");
this.div.bodyTab.baseObj=this;
this.div.bodyTabGrip= ZLM.simulateTag("div style='width:19; height:19; position:absolute; top:0; left:-4; z-index:1; display:none; background-image:url("+this.SLIDER_ICON_V_GRIP+");'");
this.div.appendChild(this.div.bodyTab);
this.div.bodyTab.appendChild(this.div.bodyTabGrip);
}
else {
if (h>this.SLIDER_SPAN) var offset=(h-this.SLIDER_SPAN)/2;
else var offset=0;
this.div.body=ZLM.simulateTag("div style='width:100%; height:"+this.SLIDER_SPAN+"; position:relative; top:"+offset+"; left:0;'");
if (ZLM.isIE) this.div.body.style.fontSize="0pt";
this.div.appendChild(this.div.body);
this.div.trough=ZLM.simulateTag("div style='width:"+(w-10)+"; height:1; border:3px inset gray; background:#505050; position:absolute; top:7; left:2;'");
this.div.body.appendChild(this.div.trough);
this.div.minTab=ZLM.simulateTag("div class='sliderTab'; style='width:"+this.SLIDER_TAB_SPAN+"; height:"+this.SLIDER_SPAN+"; position:absolute; top:0; left:0; cursor:e-resize;' onmousedown='ZLM.drag(this,event);'");
this.div.minTab.baseObj=this;
this.div.body.appendChild(this.div.minTab);
var tabTop = ZLM.simulateTag("div style='width:4; height:19; position:absolute; top:0; left:0; background-image:url("+this.SLIDER_ICON_LEFT+");'");
var tabBottom = ZLM.simulateTag("div style='width:4; height:19; position:absolute; top:0; left:4; background-image:url("+this.SLIDER_ICON_RIGHT+");'");
this.div.minTab.appendChild(tabTop);
this.div.minTab.appendChild(tabBottom);
this.div.maxTab=ZLM.simulateTag("div class='sliderTab' style='width:"+this.SLIDER_TAB_SPAN+"; height:"+this.SLIDER_SPAN+"; position:absolute; top:0; left:0; cursor:e-resize;' onmousedown='ZLM.drag(this,event);'");
this.div.maxTab.baseObj=this;
this.div.body.appendChild(this.div.maxTab);
var tabTop = ZLM.simulateTag("div style='width:4; height:19; position:absolute; top:0; left:0; background-image:url("+this.SLIDER_ICON_LEFT+");'");
var tabBottom = ZLM.simulateTag("div style='width:4; height:19; position:absolute; top:0; left:4; background-image:url("+this.SLIDER_ICON_RIGHT+");'");
this.div.maxTab.appendChild(tabTop);
this.div.maxTab.appendChild(tabBottom);
this.div.bodyTab=ZLM.simulateTag("div class='sliderTab' style='height:11; position:absolute; top:5; left:0; border:1px solid gray;' onmousedown='ZLM.drag(this,event);'");
this.div.bodyTab.baseObj=this;
this.div.bodyTabGrip= ZLM.simulateTag("div style='width:19; height:19; position:absolute; top:-4; left:0; z-index:1; display:none; background-image:url("+this.SLIDER_ICON_H_GRIP+");'");
this.div.appendChild(this.div.bodyTab);
this.div.bodyTab.appendChild(this.div.bodyTabGrip);
}
ZLM.registerDragItem(this.div.minTab,ZWL.sliderMgr);
ZLM.registerDragItem(this.div.maxTab,ZWL.sliderMgr);
ZLM.registerDragItem(this.div.bodyTab,ZWL.sliderMgr);
this.snapToValue();
}
ZWL.RangeSlider.prototype.getMinPxPosition=function(tab) {
if (tab==this.div.minTab) return(0);
if (this.vert) return(this.div.minTab.offsetHeight);
return(this.div.minTab.offsetWidth);
}
ZWL.RangeSlider.prototype.getMaxPxPosition=function(tab) {
if (this.vert) {
if (tab==this.div.minTab) return(this.div.clientHeight-this.div.minTab.offsetHeight-this.div.maxTab.offsetHeight);
if (tab==this.div.bodyTab) return(this.div.clientHeight-this.div.maxTab.offsetHeight-this.div.bodyTab.offsetHeight);
return(this.div.clientHeight-this.div.maxTab.offsetHeight);
}
if (tab==this.div.minTab) return(this.div.clientWidth-this.div.minTab.offsetWidth-this.div.maxTab.offsetWidth);
if (tab==this.div.bodyTab) return(this.div.clientWidth-this.div.maxTab.offsetWidth-this.div.bodyTab.offsetWidth);
return(this.div.clientWidth-this.div.maxTab.offsetWidth);
}
ZWL.RangeSlider.prototype.getStaticPxInset=function(tab) {
if (tab==this.div.bodyTab) return(5);
return(0);
}
ZWL.RangeSlider.prototype.resizeRange=function() {
if (this.vert) {
this.div.bodyTab.style.top=this.div.minTab.offsetTop+this.div.minTab.offsetHeight;
var h =this.div.maxTab.offsetTop-this.div.minTab.offsetHeight-this.div.minTab.offsetTop-1;
if (h<=0) {
this.div.bodyTab.style.display="none";
}
else {
//ZLM.cerr(h+" v. "+this.SLIDER_SPAN+"-"+this.div.minTab.offsetHeight);
this.div.bodyTab.style.height=h;
this.div.bodyTab.style.display="block";
}
if (h<this.SLIDER_SPAN-this.div.minTab.offsetHeight) {
//ZLM.cerr("Too short");
this.div.bodyTabGrip.style.display="none";
}
else {
var gp=h/2-this.SLIDER_SPAN/2+1;
this.div.bodyTabGrip.style.display="block";
this.div.bodyTabGrip.style.top=gp;
}
}
else {
this.div.bodyTab.style.left=this.div.minTab.offsetLeft+this.div.minTab.offsetWidth;
var w =this.div.maxTab.offsetLeft-this.div.minTab.offsetWidth-this.div.minTab.offsetLeft-1;
if (w<=0) {
this.div.bodyTab.style.display="none";
}
else {
this.div.bodyTab.style.width=w;
this.div.bodyTab.style.display="block";
}
if (w<this.SLIDER_SPAN-this.div.minTab.offsetWidth) {
this.div.bodyTabGrip.style.display="none";
}
else {
var gp=w/2-this.SLIDER_SPAN/2+1;
this.div.bodyTabGrip.style.display="block";
this.div.bodyTabGrip.style.left=gp;
}
}
}
ZWL.RangeSlider.prototype.updateRange=function(tab) {
//ZLM.cerr("end of drag");
//update range bounds and visual indicators based on the graphical motion of the given tab
var span=this.getMaxPxPosition(tab);
if (tab==this.div.minTab) {
if (this.vert) {
var offset = this.div.minTab.offsetTop;
if (offset+this.div.minTab.offsetHeight>this.div.maxTab.offsetTop) {
this.div.maxTab.style.top=offset+this.div.minTab.offsetHeight;
this.updateRange(this.div.maxTab);
}
}
else {
var offset = this.div.minTab.offsetLeft;
if (offset+this.div.minTab.offsetWidth>this.div.maxTab.offsetLeft) {
this.div.maxTab.style.left=offset+this.div.minTab.offsetWidth;
this.updateRange(this.div.maxTab);
}
}
var range = this.maxValue-this.minValue;
this.rangeMin=Math.round(range*(offset/span))+this.minValue;
}
if (tab==this.div.maxTab) {
if (this.vert) {
var offset = this.div.maxTab.offsetTop;
if (offset<this.div.minTab.offsetTop+this.div.minTab.offsetHeight) {
this.div.minTab.style.top=offset-this.div.minTab.offsetHeight;
this.updateRange(this.div.minTab);
}
}
else {
var offset = this.div.maxTab.offsetLeft;
if (offset<this.div.minTab.offsetLeft+this.div.minTab.offsetWidth) {
this.div.minTab.style.left=offset-this.div.minTab.offsetWidth;
this.updateRange(this.div.minTab);
}
}
var range = this.maxValue-this.minValue;
this.rangeMax=Math.round(range*(offset/span))+this.minValue;
}
if (tab==this.div.bodyTab) {
if (this.vert) {
var offset=this.div.bodyTab.offsetTop;
var oMn = offset-this.div.minTab.offsetHeight;
var oMx = offset+this.div.bodyTab.offsetHeight-1;
this.div.minTab.style.top=oMn;
this.div.maxTab.style.top=oMx;
}
else {
var offset=this.div.bodyTab.offsetLeft;
var oMn = offset-this.div.minTab.offsetWidth;
var oMx = offset+this.div.bodyTab.offsetWidth-1;
this.div.minTab.style.left=oMn;
this.div.maxTab.style.left=oMx;
}
var range = this.maxValue-this.minValue;
var rangeSpan = this.rangeMax-this.rangeMin;
this.rangeMin=Math.round(range*(oMn/span))+this.minValue;
if (this.rangeMin+rangeSpan>this.maxValue) this.rangeMin=this.maxValue-rangeSpan;
this.rangeMax=rangeSpan+this.rangeMin;
}
else this.resizeRange();
}
ZWL.RangeSlider.prototype.snapToValue=function() {
//ZLM.cerr("Snap to :"+this.rangeMin+" and "+this.rangeMax+" within "+this.minValue+" and "+this.maxValue);
var percentage = (this.rangeMin-this.minValue)/(this.maxValue-this.minValue);
if (this.vert) {
this.div.minTab.style.top=percentage*(this.div.clientHeight-this.div.minTab.offsetHeight-this.div.maxTab.offsetHeight);
}
else {
this.div.minTab.style.left=percentage*(this.div.clientWidth-this.div.minTab.offsetWidth-this.div.maxTab.offsetWidth);
}
var percentage = (this.rangeMax-this.minValue)/(this.maxValue-this.minValue);
if (this.vert) {
this.div.maxTab.style.top=percentage*(this.div.clientHeight-this.div.minTab.offsetHeight-this.div.maxTab.offsetHeight)+this.div.minTab.offsetHeight;
}
else {
this.div.maxTab.style.left=percentage*(this.div.clientWidth-this.div.minTab.offsetWidth-this.div.maxTab.offsetWidth)+this.div.minTab.offsetWidth;
}
this.resizeRange();
}
//#########################
// RANGE SLIDER API
ZWL.RangeSlider.prototype.resize=function(newW, newH) {
this.div.parentNode.style.width=newW;
this.div.parentNode.style.height=newH;
// enforce base constriants
if (this.vert) {
if (newW>this.SLIDER_SPAN) var offset=(newW-this.SLIDER_SPAN)/2;
else var offset=0;
this.div.body.style.left=offset;
this.div.trough.style.height=(newH-10);
}
else {
if (newH>this.SLIDER_SPAN) var offset=(newH-this.SLIDER_SPAN)/2;
else var offset=0;
this.div.body.style.top=offset;
this.div.trough.style.width=(newW-10);
}
this.snapToValue();
}
ZWL.RangeSlider.prototype.setMinValue=function(newMin) {
this.minValue=newMin;
if (newMin>this.maxValue)this.maxValue=newMin;
this.snapToValue();
}
ZWL.RangeSlider.prototype.setMaxValue=function(newMax) {
this.maxValue=newMax;
if (newMax<this.minValue) this.minValue=newMax;
this.snapToValue();
}
ZWL.RangeSlider.prototype.setRangeMin=function(newValue) {
if (newValue<this.minValue) newValue=this.minValue;
if (newValue>this.maxValue) newValue=this.maxValue;
this.rangeMin=newValue;
this.snapToValue();
}
ZWL.RangeSlider.prototype.setRangeMax=function(newValue) {
if (newValue<this.minValue) newValue=this.minValue;
if (newValue>this.maxValue) newValue=this.maxValue;
this.rangeMax=newValue;
this.snapToValue();
}
ZWL.RangeSlider.prototype.getRangeMin=function() {
return(this.rangeMin);
}
ZWL.RangeSlider.prototype.getRangeMax=function() {
return(this.rangeMax);
}
//################################################################
ZWL.initScrollAreas = function() {
var s=ZLM.getElementsByClassPrefix("scrolledArea",document.body);
for (var i=0;i<s.length;i++) {
if (!ZWL.isReady(s[i])) {
var sa=new ZWL.ScrolledArea(s[i]);
ZWL.markAsReady(s[i]);
}
}
}
ZWL.ScrolledArea=function(div) {
// A scrolled area is a manually controlled window onto a virtual space
// defined by:
// resize: true/false (outer window can be resized)
// vPolicy: always|auto|never (policy for showing vertical scrollbars)
// hPolicy: always|auto|never (policy for showing horizontal scrollbars)
// pageWidth: width of virtual space (in generic units)
// pageHeight: height of virtual spase (in generic units)
// windowWidth: width of viewing window (in generic units)
// windowHeight: height of viewing window (in generic units)
// unitScrollDelay: scrolling speed for buttons
// pageScrollDelay: scrolling speed for page flips
//
// callbacks:
// onUnitUp
// onUnitDown
// onUnitLeft
// onUnitRight
// onPageUp
// onPageDown
// onPageRight
// onPageLeft
// onHScroll
// onVScroll
// onResize
// onShowScrollbar
// onHideScrollbar
//
// In the base HTML specification a div of class scrolledArea has one or more children
// that define the contents of the virtual space. OnLoadPage takes these children and
// reparents them to be children of a workArea div that is a new child of the base div.
// Other new children include the matteArea, hScroll, vScroll and resizeDiv.
this.SB_SIZE=21; // base thickness of scrollbar elements
this.div = div;
this.setAttributes(div);
this.createAvatar();
}
ZWL.ScrolledArea.prototype.setAttributes=function(div) {
this.resizable=ZWL.initAttribute(div,"resize",false);
this.vPolicy=ZWL.initAttribute(div,"vPolicy","auto");
this.hPolicy=ZWL.initAttribute(div,"hPolicy","auto");
this.pageWidth=ZWL.initAttribute(div,"pageWidth",div.offsetWidth);
this.pageHeight=ZWL.initAttribute(div,"pageHeight",div.offsetWidth);
this.windowWidth=ZWL.initAttribute(div,"windowWidth",div.offsetWidth);
this.windowHeight=ZWL.initAttribute(div,"windowHeight",div.offsetWidth);
this.usDelay=ZWL.initAttribute(div,"unitScrollDelay",100);
this.psDelay=ZWL.initAttribute(div,"pageScrollDelay",250);
this.onUnitUpCB=ZWL.initAttribute(div,"onUnitUp",null);
this.onUnitDownCB=ZWL.initAttribute(div,"onUnitDown",null);
this.onUnitLeftCB=ZWL.initAttribute(div,"onUnitLeft",null);
this.onUnitRightCB=ZWL.initAttribute(div,"onUnitRight",null);
this.onPageUpCB=ZWL.initAttribute(div,"onPageUp",null);
this.onPageDownCB=ZWL.initAttribute(div,"onPageDown",null);
this.onPageLeftCB=ZWL.initAttribute(div,"onPageLeft",null);
this.onPageRightCB=ZWL.initAttribute(div,"onPageRight",null);
this.onHScrollCB=ZWL.initAttribute(div,"onHScroll",null);
this.onVScrollCB=ZWL.initAttribute(div,"onVScroll",null);
this.onResizeCB=ZWL.initAttribute(div,"onResize",null);
this.onShowScrollbarCB=ZWL.initAttribute(div,"onShowScrollbar",null);
this.onHideScrollbarCB=ZWL.initAttribute(div,"onHideScrollbar",null);
}
ZWL.ScrolledArea.prototype.createAvatar=function() {
var w = this.div.clientWidth;
if (w<3*this.SB_SIZE) {
w=3*this.SB_SIZE;
this.div.style.width=w;
}
var h = this.div.clientHeight;
if (h<3*this.SB_SIZE) {
h=3*this.SB_SIZE;
this.div.style.height=h;
}
var wW=w-this.SB_SIZE;
var wH=h-this.SB_SIZE;
this.div.body=ZLM.simulateTag("div style='width:100%; height:100%; position:relative; top:0; left:0; overflow:hidden;'");
this.div.port=ZLM.simulateTag("div style='position:absolute; top:0; left:0; overflow:hidden;'");
this.div.body.appendChild(this.div.port);
this.div.matte=ZLM.simulateTag("div class='matteArea' style='position:absolute; top:0; left:0; width:100%; height:100%; z-index:-10;'");
this.div.port.appendChild(this.div.matte);
this.div.workArea=ZLM.simulateTag("div style='position:relative; top:0; left:0;'");
this.div.port.appendChild(this.div.workArea);
this.div.hScroll=ZLM.simulateTag("div class='scrollbar' style='width:"+wW+"; height:"+this.SB_SIZE+"; position:absolute; top:"+wH+"; left:0;'");
this.div.body.appendChild(this.div.hScroll);
this.div.vScroll=ZLM.simulateTag("div class='scrollbar' orientation='vertical' style='width:"+this.SB_SIZE+"; height:"+wH+"; position:absolute; top:0; left:"+wW+";'");
this.div.body.appendChild(this.div.vScroll);
this.div.workArea.style.width=300;
this.div.workArea.style.height=300;
this.div.workArea.style.background="green";
this.div.appendChild(this.div.body);
this.hsControl=new ZWL.Scrollbar(this.div.hScroll);
ZWL.markAsReady(this.div.hScroll);
this.vsControl=new ZWL.Scrollbar(this.div.vScroll);
ZWL.markAsReady(this.div.vScroll);
ZLM.cerr("real width: "+this.div.workArea.clientWidth);
ZLM.cerr("real height: "+this.div.workArea.clientHeight);
this.updateGeometry();
}
ZWL.ScrolledArea.prototype.updateGeometry=function() {
var sbSize=this.div.vScroll.offsetWidth; // size taken up by scrollbar
var w = ZLM.getClientWidth(this.div);
var h = ZLM.getClientHeight(this.div);
var wW=w-sbSize;
var wH=h-sbSize;
ZLM.setSize(this.div.port,wW,wH);
ZLM.setPosition(this.div.vScroll,wW,0);
ZLM.setPosition(this.div.hScroll,0,wH);
this.hsControl.resize(wW-2,this.SB_SIZE);
this.hsControl.setViewSize(wW);
this.hsControl.setPageSize(this.div.workArea.offsetWidth);
this.vsControl.resize(this.SB_SIZE,wH-2);
this.vsControl.setViewSize(wH);
this.vsControl.setPageSize(this.div.workArea.offsetHeight);
// this.div.port.style.width=wW;
// this.div.port.style.height=wH;
// this.div.vScroll.style.height=wH-2;
// this.div.hScroll.style.width=wW-2;
}
//################################################################
function newWidgetInit() {
if (!ZWL.sliderMgr) ZWL.sliderMgr=new ZWL.SliderManager();
ZWL.isIE = ZLM.isInternetExplorer();
ZWL.initGrids();
ZWL.initScrollAreas();
ZWL.initSliders();
}
|
import React, { Component} from 'react';
import { connect } from 'react-redux';
import { selectBook } from '../actions/index';
import { bindActionCreators } from 'redux';
import south from './south.jpg';
type Props = {
pageTitle: string,
}
class BookList extends React.Component<Props> {
renderList() {
return this.props.books.map((book) => {
return (
<li
key={book.title}
onClick={() => this.props.selectBook(book)}
className="list-group-item">
<img className="list_img" src={book.image} alt="" />
{book.title}
</li>
);
});
}
render() {
return (
<div className="book_list">
<h1>{this.props.pageTitle}</h1>
<ul className="list-group col-sm-4">
{this.renderList()}
</ul>
</div>
)
}
}
export default BookList
|
import React from "react";
import styled from "styled-components";
import { Icon, Divider, Rating } from "semantic-ui-react";
const Container = styled.div`
&&& {
display: flex;
flex-direction: column;
margin-top: 0;
padding: 24px;
border: 1px solid rgb(228, 228, 228);
}
`;
const Box = styled.div`
&&& {
display: flex;
flex-direction: column;
}
`;
const Item = styled.div`
&&& {
display: flex;
align-items: center;
padding-bottom: 6px;
}
`;
const ItemText = styled.p`
&&& {
font-size: 16px;
font-weight: 400;
line-height: 1.28em;
color: #4f4b65;
margin: 0;
margin-bottom: 2px;
}
`;
const PostTitle = styled.p`
&&& {
font-size: 18px;
font-weight: 600;
line-height: 1.28em;
margin: 0;
color: #4f4b65;
margin-bottom: 6px;
}
`;
const StyledIcon = styled(Icon)`
&&& {
font-size: 16px;
margin-right: 8px;
color: #4f4b65;
align-self: flex-start;
height: 100%;
&::before {
height: 100%;
}
}
`;
const StyledRating = styled(Rating)`
&&& {
display: block;
font-size: 16px;
height: 100%;
&::before {
height: 100%;
}
margin-bottom: 6px;
}
`;
const ImageBox = styled.div`
&&& {
height: 94px;
width: 60px;
display: flex;
max-width: 100%;
max-height: 100%;
}
`;
const Image = styled.img`
object-fit: cover;
object-position: 50% 50%;
width: 100%;
height: 100%;
border-radius: 2px !important;
`;
const CardSummary = ({ post, date, startTimeValue, endTimeValue }) => (
<Container>
<Item style={{ padding: 0, justifyContent: "space-between" }}>
<Box style={{ marginTop: 0 }}>
<PostTitle>{post.title}</PostTitle>
<StyledRating icon="star" disabled defaultRating={5} maxRating={5} />
<ItemText>154 evaluaciones</ItemText>
</Box>
<ImageBox>
<Image src="https://resources.premierleague.com/photos/2019/03/24/cb91e149-7607-4cd6-ba9b-2eb821ed33ca/Totenham-Hotspur-open-new-stadium-action.jpg?width=860&height=573" />
</ImageBox>
</Item>
<Divider style={{ margin: "16px 0" }} />
<Item>
<StyledIcon name="map marker alternate" />
<ItemText>{post.address}</ItemText>
</Item>
<Item>
<StyledIcon name="phone" />
<ItemText>(304) 545-4488</ItemText>
</Item>
<Divider style={{ margin: "16px 0" }} />
<Item>
<StyledIcon name="shower" />
<ItemText>Regaderas</ItemText>
<ItemText style={{ marginLeft: "auto", maxWidth: "130px" }}>Sí</ItemText>
</Item>
<Item>
<StyledIcon name="food" />
<ItemText>Cafetería</ItemText>
<ItemText style={{ marginLeft: "auto", maxWidth: "130px" }}>Sí</ItemText>
</Item>
<Item>
<StyledIcon name="car" />
<ItemText>Parqueadero</ItemText>
<ItemText style={{ marginLeft: "auto", maxWidth: "130px" }}>Sí</ItemText>
</Item>
<Divider style={{ margin: "16px 0" }} />
<Item>
<Box style={{ padding: 0 }}>
<ItemText style={{ marginBottom: "6px" }}>{date}</ItemText>
<ItemText style={{ marginBottom: "6px" }}>
{startTimeValue} - {endTimeValue}
</ItemText>
</Box>
</Item>
<Divider style={{ margin: "16px 0" }} />
<Item>
<ItemText>${post.price} por 1 hora</ItemText>
<ItemText style={{ marginLeft: "auto" }}>${post.price}</ItemText>
</Item>
<Divider style={{ margin: "16px 0" }} />
<Item>
<ItemText style={{ fontWeight: "800" }}>Total (COP)</ItemText>
<ItemText style={{ marginLeft: "auto", fontWeight: "800" }}>
${post.price}
</ItemText>
</Item>
<Divider style={{ margin: "16px 0" }} />
<Item>
<Box>
<ItemText style={{ color: "#483df6", marginBottom: "8px" }}>
Politica de cancelación
</ItemText>
<ItemText style={{ fontSize: "14px" }}>
Obtén un reembolso completo si cancelas durante las 2 horas siguientes
al pago.
</ItemText>
</Box>
</Item>
</Container>
);
export default CardSummary;
|
import React, { Component } from "react";
import NavBar from "../../../shared/components/Navbar";
import { connect } from "react-redux";
import { getNotificationsFromDB } from "./../../../database/dal/firebase/studentDal";
//import { getNotifications } from './actions';
class NotificationFullDetails extends Component {
state = {};
componentDidMount = () => {
getNotificationsFromDB().onSnapshot(querySnapshot => {
let notifyData = [];
querySnapshot.forEach(doc => {
notifyData.push(doc.data());
});
if (notifyData.length > 0) {
this.setState({
notificationslistNewlyItems: notifyData
});
}
notifyData = [];
});
};
render() {
const { notificationslistNewlyItems } = this.state;
console.log("notificationslistNewlyItems", notificationslistNewlyItems);
return (
<div className="container-fluid">
<NavBar />
<div className="row margin-bottom">
<div className="col-12 col-md-12 col-xl-12 col-sm-12 col-lg-12">
<div className="card">
<div className="card-body">
<div className="modal-content">
<div className="modal-header">
<button
type="button"
className="close"
data-dismiss="modal"
aria-hidden="true"
/>
<h4 className="modal-title" id="myModalLabel">
More About Joe Notification
</h4>
</div>
<div className="modal-body">
<center>
<img
alt=""
src="../Assets/hdpi/avatar.png"
name="aboutme"
width="140"
height="140"
border="0"
className="img-circle"
/>
<h3 className="media-heading">
Kately <small>USA</small>
</h3>
</center>
<span>
<strong>Date: </strong>
</span>
<span className="label label-warning">4/22/2019</span>{" "}
<span>
<strong>Timing: </strong>
</span>
<span className="label label-info">9:00 AM</span>
<span>
<strong>Duration: </strong>
</span>
<span className="label label-info">30 Min</span>
<p className="text-left">
<strong>Message: </strong>
Hey Michal, I just want a discssion on following topic.
Please schedule a chat meeting. Waiting for you.
</p>
</div>
<div className="modal-footer">
<button
type="button"
className="btn btn-success"
data-dismiss="modal"
>
Accept
</button>
<button
type="button"
className="btn btn-danger"
data-dismiss="modal"
>
Reject
</button>
<button
type="button"
className="btn btn-warning"
data-dismiss="modal"
>
Discuss on Time
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
}
const mapStateToProps = state => {
return {};
};
const mapDispatchToProps = dispatch => {
return {
//getNotifications: () => dispatch(getNotifications()),
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(NotificationFullDetails);
|
/* For API calls */
const BASE_URL = 'https://thinkful-list-api.herokuapp.com/Ron';
function listApiFetch(...args) {
let error = null;
return fetch(...args)
.then(resp => {
if(!resp.ok) { //Valid HTTP response, but non-2XX status
error = {code: resp.status};
}
return resp.json();
})
.then(data => {
if(error) {
error.message = data.message;
return Promise.reject(error);
}
return data;
});
}
function getBookmarks() {
return listApiFetch(`${BASE_URL}/bookmarks`);
}
// Expects an OBJECT Should be passed through as {title: Yahoo, url: http://yahoo.com, desc: blah blah, rating: 2}
// desc and rating are optional
function createBookmark(bookmarkObj) {
const newItem = JSON.stringify(bookmarkObj);
return listApiFetch(`${BASE_URL}/bookmarks`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: newItem
});
}
/*
@params updateData will be an OBJECT
the object should be passed as {property : value} */
function updateBookmark(id, updateData) {
const newData = JSON.stringify( updateData );
return listApiFetch(`${BASE_URL}/bookmarks/${id}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json'
},
body: newData
});
}
function deleteBookmark (id) {
return listApiFetch(BASE_URL + '/bookmarks/' + id, {
method: 'DELETE'
});
}
export default {
getBookmarks,
createBookmark,
updateBookmark,
deleteBookmark
};
|
import React, { Component } from "react";
import ButtonPanel from "./ButtonPanel/ButtonPanel";
import Step from "./Step/Step";
import "./Counter.css";
class Counter extends Component {
constructor(props) {
super(props);
let initValue = 0;
if (!isNaN(this.props.initValue)) {
initValue = parseInt(this.props.initValue, 10);
}
this.state = {
counterValue: initValue,
step: 5,
};
}
changeValue = () => {
this.setState((prevValue) => {
return { counterValue: prevValue.counterValue + 1 };
});
};
resetCounter = (resetCounter) => {
let initValue = 0;
if (!resetCounter) {
if (!isNaN(this.props.initValue)) {
initValue = parseInt(this.props.initValue, 10);
}
}
this.setState({
counterValue: initValue,
});
};
changeStep = (num) => {
num = parseInt(num, 10);
this.setState((prevValue) => {
return {
counterValue: prevValue.counterValue + num,
step: num,
};
});
};
render() {
return (
<div className="CounterPanel">
<div className="Counter">
Licznik:
<span className="CounterValue">
{this.state.counterValue}
</span>
</div>
<ButtonPanel
changeCounterValue={this.changeValue}
resetCounterValue={this.resetCounter}
/>
<Step step={this.state.step} change={this.changeStep} />
</div>
);
}
}
export default Counter;
|
angular.module('projectWeb').directive('ngTranslateLanguageSelect',
function (rivalWarLayoutService) {
'use strict';
return {
restrict: 'A',
replace: true,
template: ''
+ '<div ng-if="visible" class="form-group">'
+ '<select class="form-control select2" ng-model="currentLocaleDisplayName"'
+ 'ng-options="localesDisplayName for localesDisplayName in localesDisplayNames" ng-change="changeLanguage(currentLocaleDisplayName)" style="width: 100%;">'
+ '</select>' + '</div>'
+ '<!-- /.form-group -->',
controller: function ($scope) {
$scope.currentLocaleDisplayName = rivalWarLayoutService.getLocaleDisplayName();
$scope.localesDisplayNames = rivalWarLayoutService.getLocalesDisplayNames();
$scope.visible = $scope.localesDisplayNames && $scope.localesDisplayNames.length > 1;
$scope.changeLanguage = function (locale) {
rivalWarLayoutService.setLocaleByDisplayName(locale);
};
}//controller end
};//return end
}//function end
);
|
const express = require('express');
const body = require('body-parser');
const mongoose = require('mongoose');
const cors = require('cors');
const dotenv = require('dotenv');
const userRouter = require('./routes/user')
const portfolioRouter = require('./routes/portfolio')
const app = express();
// use .env file
dotenv.config();
// body-parser
app.use(body.json({ limit: "30mb", extended: true }));
app.use(cors());
app.get('/',(req, res) => {
res.send('Hello to portfolio API')
})
// use router
app.use('/user', userRouter);
app.use('/portfolio', portfolioRouter);
// Connecting to MongoDB
const PORT = process.env.PORT || 5000;
mongoose.connect(process.env.CONNECTION_URL, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => app.listen(PORT, () => console.log(`Server runnin on port: ${PORT}`)))
.catch((error) => console.log(error.message));
//make sure that we dont get any warning in the console.
mongoose.set('useFindAndModify', false);
|
const dbpool=require("../config/dbpoolConfig.js");
const jpShowModel={
jpShow(){
return new Promise((resolve,reject)=>{
let sql="SELECT custom_img_path FROM yd_custom_made";
dbpool.connect(sql,[],
(err,data)=>{
if(!err){
resolve(data);
}else{
reject(err);
}
}
)
})
},
buyGoods(params){
return new Promise((resolve,reject)=>{
let sql="SELECT NAME,info,price FROM yd_goods WHERE NAME=?";
dbpool.connect(sql,params,
(err,data)=>{
if(!err){
resolve(data);
}else{
reject(err);
}
}
)
})
},
actionGoods(params){
return new Promise((resolve,reject)=>{
let sql="SELECT act_name FROM yd_action WHERE act_id IN(SELECT act_id FROM yd_goods_action WHERE goods_id=(SELECT goods_id FROM yd_goods WHERE NAME=?))";
dbpool.connect(sql,params,
(err,data)=>{
if(!err){
resolve(data);
}else{
reject(err);
}
}
)
})
},
colorGoods(params){
return new Promise((resolve,reject)=>{
let sql="SELECT NAME FROM yd_color WHERE color_id IN(SELECT color_id FROM yd_goods_color WHERE goods_id=(SELECT goods_id FROM yd_goods WHERE NAME=?))";
dbpool.connect(sql,params,
(err,data)=>{
if(!err){
resolve(data);
}else{
reject(err);
}
}
)
})
},
sizeGoods(params){
return new Promise((resolve,reject)=>{
let sql="SELECT notice FROM yd_size WHERE size_id IN(SELECT size_id FROM yd_goods_size WHERE goods_id=(SELECT goods_id FROM yd_goods WHERE NAME=?))";
dbpool.connect(sql,params,
(err,data)=>{
if(!err){
resolve(data);
}else{
reject(err);
}
}
)
})
},
balanceGoods(params){
return new Promise((resolve,reject)=>{
let sql="SELECT consi_name,consi_phone,state,city,district,address FROM yd_user_address WHERE user_id=(SELECT user_id FROM yd_user WHERE u_name=?)";
dbpool.connect(sql,params,
(err,data)=>{
if(!err){
resolve(data);
}else{
reject(err);
}
}
)
})
}
}
module.exports=jpShowModel;
|
const express = require("express");
const router = express.Router();
const Cliente = require("../../models/Cliente");
const { validEmail } = require("../../functions/misc");
// Tarjetas:
// DNI
// Correo_electrónico
// Operador
// Número_Celular
router.post("/", async (req, res) => {
const operadores = ["MOVISTAR", "ENTEL", "CLARO"];
const { dni, celular, email, edad, operador } = req.body;
if (!dni || !celular || !email || !edad || !operador) {
res.status(400).json({ error: "Debe llenar todos los campos" });
return;
}
const operadorUpper = operador.toUpperCase();
if (dni.length !== 8) {
res.status(400).json({ error: "Ingrese un número de DNI válido" });
}
if (celular.length !== 9) {
res.status(400).json({ error: "Ingrese un número de Celular válido" });
}
if (edad < 18) {
res.status(400).json({ error: "Debe cumplir con la mayoría de edad para tramitar un seguro" });
}
if (!validEmail(email)) {
res.status(400).json({ error: "Ingrese un email válido" });
}
if (!operadores.includes(operadorUpper)) {
res.status(400).json({ error: "Su operadora no está disponible (MOVISTAR, ENTEL, CLARO)" });
}
const newCliente = new Cliente({
dni: dni,
email: email,
celular: celular,
edad: edad,
operador: operador,
});
const newProducto = {
nombreProcuto: "Tarjeta",
};
try {
const encontrarCliente = await Cliente.findOne({ dni: dni });
if (encontrarCliente) {
res.status(400).json({ error: "Ya existe un prestamo solicitado bajo este DNI" });
return;
}
//Crear nuevo cliente sobre dni
await newCliente.save();
const newProducto = {
nombreProducto: "Tarjeta",
};
//Agregar producto a nuevo cliente
const cliente = await Cliente.findOne({ dni: dni });
cliente.productos.unshift(newProducto);
await cliente.save();
res.status(200).json({ cliente: cliente, msg: `Tarjeta solicitada exitosmanete al cliente ${dni}` });
} catch (err) {
res.status(500).json({ error: "Error de servidor" });
console.log(err);
}
});
module.exports = router;
|
//callbacks
const getUser = function(fnCallback) { //function passed as an argument
setTimeout(function(){
fnCallback({name: 'max'});
}, 2000);
};
getUser(
function(user) {
console.log(user.name);
}
);
// Alternatively, use a named function:
const handleUser = function(user){
console.log("user handled :> ", user.name);
}
getUser(handleUser);
//la ejecución del código no para mientras espera que se ejecute el temporizador.
console.log('Se imprime antes de que "max" sea imprimido!');
|
import React, { Component } from "react";
import Header from "./Header";
import BannerInner from "./BannerInner";
import Navbar from "./Navbar";
import Footer from "./Footer";
import axios from "axios";
import Card from "./Card";
// import { Link } from "react-router-dom";
import Cookies from "universal-cookie";
const cookies = new Cookies();
class Menu extends Component {
constructor() {
super();
this.state = {
menu: [],
success_flag: 0,
login: true,
};
}
authLogin() {
let jwtToken = cookies.get("jwtToken");
if (jwtToken === undefined) {
this.setState({
login: false,
});
}
}
componentWillMount() {
this.authLogin();
}
componentDidMount() {
console.log("START GET A");
axios.get("http://localhost:3002/menu").then((result) => {
this.setState(
{
menu: result.data.return,
},
console.log("result.data.result")
);
});
console.log("START GET B");
}
render() {
return (
<div>
<Header />
<BannerInner />
<Navbar />
<br></br>
{this.state.menu.map((val) => (
<Card menu={val} />
))}
<Footer />
</div>
);
}
}
export default Menu;
|
import { Component } from 'react';
import styled from 'styled-components';
import Input from './../Input'
class tags extends Component {
constructor(props) {
super(props);
this.state = {
tagValue: "",
tags: props.tags ? props.tags : []
};
}
onEnter = (e) => {
var tags = this.state.tags;
if (e.key === "Enter" && this.state.tagValue !== " ") {
var id = this.state.tagValue
.split(/[ ,]+/)
.join("_")
.toUpperCase();
var tag = { name: this.state.tagValue.toUpperCase(), id: id };
var x =
tags.length === 0
? tags.push(tag)
: tags.find(t => {
return tag.id === t.id;
})
? null
: tags.push(tag);
this.setState({ tags: tags, tagValue: "" });
return x;
}
if (e.key === "Backspace" && this.state.tagValue === "") {
tags.pop();
this.setState({ tags: tags });
}
this.props.onChangeTag(tags)
}
onChange = (e) => {
const { target } = e;
const { name, value } = target;
this.setState({ [name]: value });
}
removeTag = (i) => {
const tags = this.state.tags.filter(t => {
return t.id !== i ? t : null;
});
this.setState({ tags: tags });
this.props.onChangeTag(tags)
}
render() {
return (
<div style={{ display: "flex", flexDirection: "column" }}>
{this.state.tags ? (
<TagsUL>
{
this.state.tags.map((t, i) => (
<Tag key={i}>
<span>{t.name}</span>
<TabIndicator
selected={true}
onClick={() => {
this.removeTag(t.id);
}}
/>
</Tag>
))}
</TagsUL>
) : null}
<Input
name="tagValue"
placeholder="Add new Tag"
type="text"
style={{ flex: 1, padding: "5px",background:'transparent' }}
onKeyDown={this.onEnter}
onChange={this.onChange}
value={this.state.tagValue}
/>
</div>
);
}
}
export default tags;
const TagsUL = styled.ul`
display: flex;
flex-direction: row;
flex-wrap: wrap;
padding: 0;
margin: 2px;
`;
// #080a0b
const Tag = styled.li`
display: flex;
flex-direction: row;
background:${props => props.theme.secondary};
border-radius: 0.5em;
margin: 0.3em;
span{
padding:0.5em;
flex:1
}
`;
const TabIndicator = styled.i`
display: block;
height: 0.5em;
width: 0.5em;
margin: 0.5em;
border-radius: 0.3em;
cursor: pointer;
background: ${props => (props.selected ? props.theme.accent : "transparent")};
`;
// "#87C895"
|
import {apiRequest} from "../services/api";
export const postQuestion = async (id, idExercice, question) => {
return await apiRequest(`exams/${id}/exercices/${idExercice}/questions`, 'post', {
...question
});
};
export const deleteQuestion = async (idExam, idExercice, idQuestion, question) => {
return await apiRequest(`exams/${idExam}/exercices/${idExercice}/questions/${idQuestion}`, 'delete', {
...question
});
};
export const patchQuestion = async (idExam, idExercice, idQuestion, question) => {
return await apiRequest(`exams/${idExam}/exercices/${idExercice}/questions/${idQuestion}`, 'patch', {
...question
});
};
|
import {Component} from "react";
const Case = class extends Component{
constructor(props){
super(props);
this.state = {
index : this.props.index,
href : this.props.href,
backgroundImage : this.props.backgroundImage
}
}
render(){
return (
<a href={this.state.href} style={
{
backgroundImage : `url(${this.state.backgroundImage})`
}
}></a>
);
}
};
const Banner = class extends Component{
constructor(props){
super(props);
this.state = {
index : 0,
data : this.props.data
};
}
render(){
let lists = [],
data = this.state.data;
data.map((list, index) => {
lists.push(
<Case index={index} href={list.href} backgroundImage={list.imgSrc} key={index} />
);
});
lists.push(
<Case index={0} href={data[0].href} backgroundImage={data[0].imgSrc} key={data.length} />
);
return (
<header>
<div className="container">
{lists}
</div>
</header>
);
}
};
export default Banner;
|
import React, {Component} from "react";
import PropTypes from "prop-types";
import {View} from "react-native";
import {Text} from "react-native-elements";
class SimpleTable extends Component {
constructor(props) {
super(props);
console.log(this.props);
}
renderRow(cells=[]) {
return (
<View style={{ flex: 1, alignSelf: 'stretch', flexDirection: 'row' }}>
{
cells.map((cell, i) => (
<View style={{ flex: 1, alignSelf: 'stretch' }} key={i}>
<Text>{cell}</Text>
</View>
))
}
</View>
);
}
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
{
this.props.data.map((datum) => {
return this.renderRow(datum);
})
}
</View>
);
}
}
SimpleTable.propTypes = {
data: PropTypes.array
}
export default SimpleTable;
|
import React, { createContext } from 'react';
// import useTodoState from '../hooks/useTodoState';
import { useLocalStorageReducer } from '../hooks/useLocalStorageReducer';
import todoReducer from '../reducer/todoReducer';
import uuid from 'uuid/v4';
export const defaultTodos = [
{ id: uuid(), task: 'Now is the Time to Change', completed: false },
{ id: uuid(), task: 'Release lady Dugs into garden', completed: true },
{ id: uuid(), task: 'Walk the Talk', completed: true }
];
export const TodoContext = createContext();
export const DispatchContext = createContext();
export const TodoProvider = (props) => {
// const todoStaff = useTodoState(defaultTodos);
//const [ state, dispatch ] = useReducer(todoReducer, defaultTodos);
const [ state, dispatch ] = useLocalStorageReducer('Todo', defaultTodos, todoReducer);
// return <TodoContext.Provider value={todoStaff}>{props.children}</TodoContext.Provider>;
return (
<TodoContext.Provider value={state}>
<DispatchContext.Provider value={dispatch}>{props.children} </DispatchContext.Provider>
</TodoContext.Provider>
);
};
|
import Vue from 'vue';
var app = new Vue({
el: '#app',
data: {
newTodo: '',
todoList:[]
},
methods:{
addTodo:function(){
let now_data = new Date();
this.todoList.push({
title:this.newTodo,
createdAt: this.format(now_data,"yyyy-MM-dd hh:mm:ss"),
done:false
})
this.newTodo = ''
},
removeTodo:function(todo){
let index = this.todoList.indexOf(todo);
this.todoList.splice(index,1)
},
format:function(data,fmt){
var o = {
"M+" : data.getMonth()+1, //月份
"d+" : data.getDate(), //日
"h+" : data.getHours(), //小时
"m+" : data.getMinutes(), //分
"s+" : data.getSeconds(), //秒
"q+" : Math.floor((data.getMonth()+3)/3), //季度
"S" : data.getMilliseconds() //毫秒
};
if(/(y+)/.test(fmt)){
fmt=fmt.replace(RegExp.$1, (data.getFullYear()+"").substr(4 - RegExp.$1.length));
};
for(var k in o){
if(new RegExp("("+ k +")").test(fmt)){
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
}
}
return fmt;
}
},
created: function(){
window.onbeforeunload = ()=>{
let todoString = JSON.stringify(this.todoList);
let inputString = JSON.stringify(this.newTodo);
window.localStorage.setItem('myTodos', todoString)
window.localStorage.setItem('myInput',inputString)
}
let oldTodoString = window.localStorage.getItem('myTodos');
let oldInputString = window.localStorage.getItem('myInput');
let oldTodo = JSON.parse(oldTodoString);
let oldInput = JSON.parse(oldInputString);
this.todoList = oldTodo || [];
this.newTodo = oldInput || "";
}
})
var app1 = new Vue({
el:"#app1",
data:{
checked:""
}
})
|
/*
* @lc app=leetcode.cn id=39 lang=javascript
*
* [39] 组合总和
*/
// @lc code=start
/**
* @param {number[]} candidates
* @param {number} target
* @return {number[][]}
*/
var combinationSum = function (candidates, target) {
const res = [], solution = [];
let backTrack = (targetT, begin) => {
if (targetT <= 0) {
if (targetT === 0) {
res.push([...solution]);
}
return;
} else {
for (let i = begin; i < candidates.length; i++) {
targetT = targetT - candidates[i];
solution.push(candidates[i]);
backTrack(targetT, i);
let num = solution.pop();
targetT = targetT + num;
}
}
}
backTrack(target, 0);
return res;
};
// @lc code=end
|
const Store = require('flux/utils').Store;
const dispatcher = require('../dispatcher/dispatcher');
const DrinkConstants = require('../constants/drink_constants');
const hashHistory = require('react-router').hashHistory;
let _drinks = {};
const DrinkStore = new Store(dispatcher);
DrinkStore.all = function () {
return Object.keys(_drinks).map(drink => {
return _drinks[drink];
});
};
DrinkStore.resetAllDrinks = function(drinks) {
_drinks = {};
drinks.forEach(drink => {
_drinks[drink.id] = drink;
});
this.__emitChange();
};
DrinkStore.addDrink = function(drink){
_drinks[drink.id] = drink;
hashHistory.push(`drinks/${drink.id}`);
this.__emitChange();
};
DrinkStore.find = function(id){
return _drinks[id];
};
DrinkStore.__onDispatch = function(payload) {
switch (payload.actionType) {
case DrinkConstants.DRINKS_RECEIVED:
this.resetAllDrinks(payload.drinks);
break;
case DrinkConstants.DRINK_RECEIVED:
this.addDrink(payload.drink);
break;
}
};
module.exports = DrinkStore;
|
import React from "react";
import { shallow } from "enzyme";
import {
ACTIVATEACCOUNT_ERROR_MESSAGE,
ACTIVATEACCOUNT_SUCCES_MESSAGE
} from "../../../constants";
import { activateAccount } from "../../../apiCalls/auth/activateAccountActions";
jest.mock("../../../apiCalls/auth/activateAccountActions");
import ActivateAccountContainer from "../../auth/ActivateAccountContainer";
describe("ActivateAccountContainer handleActivateAccount", () => {
const uid = "some-uid";
const token = "some-token";
let wrapper;
beforeEach(() => {
wrapper = shallow(
<ActivateAccountContainer match={{ params: { uid, token } }} />
);
});
it("sets the state of success message when fetch is successful", async () => {
await activateAccount.mockImplementationOnce(() => {
return Promise.resolve();
});
expect.assertions(2);
await wrapper.instance().handleActivateAccount(uid, token);
expect(wrapper.state().success_message).toBe(
ACTIVATEACCOUNT_SUCCES_MESSAGE
);
expect(wrapper.state().err).toBeNull();
});
it("calls activateAccount with the correct parameters", async () => {
await activateAccount.mockImplementationOnce(() => {
return Promise.resolve();
});
expect.assertions(1);
await wrapper.instance().handleActivateAccount(uid, token);
expect(activateAccount).toHaveBeenCalledWith(uid, token);
});
it("sets the state to Error after erroneous fetch", async () => {
expect.assertions(2);
await activateAccount.mockImplementationOnce(() => {
throw new Error(ACTIVATEACCOUNT_ERROR_MESSAGE);
});
await wrapper.instance().handleActivateAccount(uid, token);
expect(wrapper.state().success_message).toBe("");
expect(wrapper.state().err.message).toBe(ACTIVATEACCOUNT_ERROR_MESSAGE);
});
});
|
var crypto = require('crypto'),
User = require('../models/user.js');
var express = require('express');
var router = express.Router();
/* GET home page. */
// router.get('/', function(req, res, next) {
// res.render('index', { title: 'Express' });
// });
// module.exports = router;
module.exports = function(app){
app.get('/',function(req,res){
res.render('index',{
title:'主页',
user:req.session.user,
success:req.flash('success').toString(),
error:req.flash('error').toString()
})
});
app.get('/reg',function(req,res){
console.log(req.session)
res.render('reg',{
title:'注册',
user:req.session.user,
success:req.flash('success').toString(),
error:req.flash('error').toString()
});
});
app.post('/reg',function(req,res){
var name = req.body.name,
password = req.body.password,
password_re = req.body['password-repeat'],
email = req.body.email;
console.log('姓名为:%s,密码为:%s,确认密码:%s',name,password,password_re);
if( password_re != password ){
req.flash('error','两次输入的密码不一致!');
return res.redirect('/reg');
}
var md5 = crypto.createHash('md5'),
password = md5.update(password).digest('hex');
var newUser = new User({
name:name,
password:password,
email:email
});
newUser.get(newUser.name, function(err, user){
if( err ){
req.flash('error',err);
return res.redirect('/')
}
if( user ){
req.flash('error','用户已存在!');
return res.redirect('/reg');
}
newUser.save(function(err, user){
if(err){
req.flash('error',err);
return res.redirect('/reg');
}
req.session.user = user;
req.flash('success','注册成功!');
res.redirect('/');
});
});
});
app.get('/login',function(req,res){
console.log("this")
res.render('login',{
title:'登陆',
user:req.session.user,
success:req.flash('success').toString(),
error:req.flash('error').toString()
})
});
app.post('/login',function(req,res){
});
app.get('/post',function(req,res){
res.render('post',{title:'发表'})
});
app.post('/post',function(req,res){
});
app.get('/logout',function(req,res){
})
}
|
$(document).ready(function(){
// Initialize Firebase
var config = {
apiKey: "AIzaSyD_7Wg45B52ObBgEemV4cF5_ikfQxzCvRE",
authDomain: "traintime-8c069.firebaseapp.com",
databaseURL: "https://traintime-8c069.firebaseio.com",
projectId: "traintime-8c069",
storageBucket: "traintime-8c069.appspot.com",
messagingSenderId: "1051000597889"
};
firebase.initializeApp(config);
var database = firebase.database();
//Button for adding train times
$("#add-train-btn").on("click", function(event) {
event.preventDefault();
//Grab user input
var trnName = $("#train-name-input").val().trim();
var trnDestination = $("#destination-input").val().trim();
var frstTrain = moment($("#start-input").val().trim(), "HH:mm").format("X");
var frequency = $("#frequency-input").val().trim();
//"Temporary" object for holding train data
var newTrain = {
name: trnName,
destination: trnDestination,
firstTrain: frstTrain,
tfrequency: frequency
}
//Uploads train data to the database
database.ref().push(newTrain);
//Log to console
console.log(newTrain.name);
console.log(newTrain.destination);
console.log(newTrain.firstTrain);
console.log(newTrain.tfrequency);
alert("Train time successfully loaded");
//Clear all of the text-boxes
$("#train-name.input").val("");
$("#destination-input").val("");
$("#start-input").val("");
$("#frequency-input").val("");
return false;
});
database.ref().on("child_added", function(childSnapshot, preChildKey) {
console.log(childSnapshot.val());
//Firebase variables to snapshots.
var fbTrnName = childSnapshot.val().name;
var fbTrnDestination = childSnapshot.val().destination;
var fbFrstTrain = childSnapshot.val().firstTrain;
var fbFrequency = childSnapshot.val().tfrequency;
console.log(fbTrnName);
console.log(fbTrnDestination);
console.log(fbFrstTrain);
console.log(fbFrequency);
//First time converted and pushed back 1 year
var frstTrnConverted = moment(fbFrstTrain, "HH:mm").subtract(1, "years");
var trnStartPretty = moment.unix(fbFrstTrain).format("HH:mm");
//Calculation of next train arrival
var timeDiff = moment().diff(moment.unix(frstTrnConverted), "minutes");
var tRemainder = timeDiff % fbFrequency;
var minsAway = fbFrequency - tRemainder;
var nextTrain = moment().add(minsAway, "minutes");
var nextTrainConverted = moment(nextTrain).format("HH:mm a");
$("#train-table > tbody").append("<tr><td>" + fbTrnName + "</td><td>" + fbTrnDestination + "</td><td>" + fbFrequency + "</td><td>" + nextTrainConverted + "</td><td>" + minsAway + "</td><td>");
});
});
|
let input=document.getElementById("input")
let link = document.getElementById('link')
let list = document.getElementById('list')
let del = document.getElementById('delete')
let i=1
function add_value(){
input_val=input.value
console.log(input_val)
let item = document.createElement('li');
item.innerHTML = input_val;
item.setAttribute('onclick', 'strike('+i+')')
item.setAttribute('id', 'content'+i)
i++
list.appendChild(item)
input.value=""
}
function strike(k){
let attr="nothing"
let strike="text-decoration:line-through"
let li = document.getElementById("content"+k)
attr+=li.getAttribute("style")
if(attr.indexOf(strike)===-1)
{
console.log("strike"+k)
li.setAttribute('style', 'text-decoration:line-through')
}
else{
console.log("unstrike"+k)
li.setAttribute('style', 'text-decoration:none')
}
}
function delete_striked(){
let ol = document.getElementById('list')
let strike="text-decoration:line-through"
let arr=[]
let j=0
let f=i
let g=i
for(let k=1;k<i;k++){
let attr="nothing"
let li = document.getElementById("content"+k)
attr+=li.getAttribute("style")
console.log(attr)
if(attr.indexOf(strike)!==-1)
{
arr[j]=k
j++
ol.removeChild(li)
console.log("removed"+k)
f--
}
}
i=f
console.log(arr)
j=1
for(let k=1;k<g;k++){
if(arr.indexOf(k)===-1){
let li = document.getElementById("content"+k)
li.setAttribute("id","content"+j)
li.setAttribute("onclick","strike("+j+")")
console.log(k+"changed to "+j)
j++
}
}
}
|
import { renderString } from '../../src/index';
describe(`Calculates the time between two datetime objects`, () => {
it(`unnamed case 0`, () => {
const html = renderString(`{% set begin = "2018-07-14T14:31:30+0530"|strtotime("yyyy-MM-dd'T'HH:mm:ssZ") %}{% set end = "2018-07-20T14:31:30+0530"|strtotime("yyyy-MM-dd'T'HH:mm:ssZ") %}{{ begin|between_times(end, 'days') }}`);
expect(html).toBe('6')
});
});
|
const router = require('express').Router()
const bcrypt = require('bcrypt')
// https://github.com/kelektiv/node.bcrypt.js/issues/16
// if bcrypt gives you grief, you just give em onna these: npm rebuild bcrypt --build-from-source
const jwt = require('jsonwebtoken')
// more rounds more secure - lol
const SALT_ROUNDS = 1
// not creating records yet - just send back a web-token
// i didnt have to write this.. i should really just mock something on the front end to check out hooks
router.post('/register', async (req, res, next) => {
try {
const hash = await bcrypt.hash(req.body.not_a_password, SALT_ROUNDS)
// create user here
// is sync
const token = jwt.sign({
email: req.body.email,
// id: createdUser.id
// hash // i defs shouldnt send the hash back to the client LOL, even tokenized
}, process.env.AUTH_SECRET, {expiresIn: '1d'})
res.status(200).send(token)
} catch (err) {
console.log(err)
res.status(500).send(err)
}
})
module.exports = router
// curl -X POST -H 'Content-Type:application/json' --data '{"email": "hi", "not_a_password": "stu"}' http://localhost:3000/api/auth/register
|
'use strict';
angular.module('projetCineFilms')
.directive('detailsMovieDir', function(){
return {
restrict: 'E',
templateUrl: 'app/details/directive/movie-template.html',
controller: function($scope, Movies, $routeParams) {
Movies.getMovie($routeParams.id).then(function(movie) {
$scope.movie = movie[0];
});
}
}
});
|
import React, { useEffect, useState, useRef } from "react";
import { useDispatch, useSelector } from "react-redux";
import {
// Button,
Table,
InputGroup,
FormControl,
Row,
Col,
} from "react-bootstrap";
import {
deleteTicket,
createTicketHeading,
createTicketHeading2,
deleteTicketHeading,
deleteTicketHeading2,
createTicket,
duplicateTicket,
} from "../../actions/ticketActions.js";
import axios from "axios";
import "./ticket.css";
import { makeStyles } from "@material-ui/core/styles";
import Button from "@material-ui/core/Button";
import { Card } from "@material-ui/core";
const useStyles = makeStyles((theme) => ({
root: {
margin: theme.spacing(0, 1, 0),
},
edit: {
backgroundColor: "#21b6ae",
margin: theme.spacing(0, 1, 0),
},
}));
const Ticket = ({ ticket }) => {
const classes = useStyles();
const [input, setInput] = useState(false);
const [input1, setInput1] = useState(false);
const [input2, setInput2] = useState(false);
const [input3, setInput3] = useState(false);
const [button, setButton] = useState(false);
const [button1, setButton1] = useState(false);
const [button2, setButton2] = useState(false);
const [response, setResponse] = useState(false);
const editResponse = () => {
const getresponse = localStorage.getItem("response");
if (getresponse) {
setResponse(true);
}
};
const [button3, setButton3] = useState(false);
const [allbuttons, setAllbuttons] = useState(false);
const [headingName, setHeadingName] = useState(ticket.heading);
const [bodyName, setBodyName] = useState(ticket.body);
const [bodyName2, setBodyName2] = useState(ticket.body2);
const [headingName2, setheadingName2] = useState(ticket.heading2);
const [data, setData] = useState(ticket.heading);
const [copySuccess, setCopySuccess] = useState("");
if (ticket.body2[0] == "check.com") {
console.log(<a href="clickhere to reveal link"></a>);
} else {
console.log(ticket.body2[0]);
}
const dispatch = useDispatch();
const deleteheading = (id) => {
ticket.heading.pop();
ticket.body.pop();
dispatch(deleteTicketHeading(ticket._id, {}));
};
const deleteheading2 = (id) => {
ticket.heading2.pop();
ticket.body2.pop();
dispatch(deleteTicketHeading2(ticket._id, {}));
};
const deleteHandler = (id) => {
if (window.confirm("Are you sure")) {
dispatch(deleteTicket(id));
}
};
const submitHandler = (e) => {
const head = "sample name";
ticket.heading.push(head);
ticket.body.push(head);
dispatch(createTicketHeading(ticket._id, {}));
};
const submitHand = (e) => {
const head = "sample name";
ticket.heading2.push(head);
ticket.body2.push(head);
dispatch(createTicketHeading2(ticket._id, {}));
};
const handleChange = (e, i) => {
const clonedData = [...headingName];
ticket.heading[i] = e.target.value;
};
const updateTicke = (e, i) => {
ticket.heading[i] = headingName;
axios.post(
`https://ticketupdater.herokuapp.com/api/tickets/${ticket._id}/heading`,
ticket.heading
);
};
const testfunction = (e, i) => {
e.persist();
handleChange(e, i);
};
const testbody = (e, i) => {
e.persist();
handleBody(e, i);
};
const updateBody = (e, i) => {
ticket.body[i] = bodyName;
axios.post(
`https://ticketupdater.herokuapp.com/api/tickets/${ticket._id}/body`,
ticket.body
);
};
const handleBody = (e, i) => {
const clonedData = [...bodyName];
ticket.body[i] = e.target.value;
};
const testHeading = (e, i) => {
e.persist();
handleHeading2(e, i);
};
const updateHeading2 = (e, i) => {
ticket.heading2[i] = headingName2;
axios.post(
`https://ticketupdater.herokuapp.com/api/tickets/${ticket._id}/heading2`,
ticket.heading2
);
};
const handleHeading2 = (e, i) => {
const clonedData = [...headingName2];
ticket.heading2[i] = e.target.value;
};
const testBody2 = (e, i) => {
e.persist();
handleBody2(e, i);
};
const updateBody2 = (e, i) => {
ticket.body2[i] = bodyName2;
axios.post(
`https://ticketupdater.herokuapp.com/api/tickets/${ticket._id}/body2`,
ticket.body2
);
};
const handleBody2 = (e, i) => {
const clonedData = [...bodyName2];
ticket.body2[i] = e.target.value;
};
const handleUpdated = () => {
if (localStorage.getItem("response")) {
updateTicke();
} else {
alert("You must be admin to update");
}
};
const handleBod = () => {
if (localStorage.getItem("response")) {
updateBody();
} else {
alert("You must be admin to update");
}
};
const handleHead = () => {
if (localStorage.getItem("response")) {
updateHeading2();
} else {
alert("You must be admin to update");
}
};
const handleBodyyy2 = () => {
if (localStorage.getItem("response")) {
updateBody2();
} else {
alert("You must be admin to update");
}
};
const handleDuplicate = () => {
dispatch(duplicateTicket(ticket));
};
return (
<div id="stats">
<Row>
<Button
variant="contained"
color="primary"
size="small"
onClick={handleDuplicate}
>
Duplicate
</Button>
{allbuttons == false ? (
<Button
variant="contained"
color="secondary"
size="small"
className={classes.edit}
onClick={() => {setAllbuttons(true);
setInput(true)}
}
>
Edit
</Button>
) : (
<Button
variant="contained"
color="secondary"
size="small"
className={classes.edit}
onClick={() => {setAllbuttons(false);
setInput(false)}
}
>
Update
</Button>
)}
<Button
variant="contained"
color="secondary"
size="small"
className={classes.root}
onClick={() => deleteHandler(ticket._id)}
>
Delete
</Button>
<Table className="table table-borderless" variant="dark">
<thead>
<tr>
{ticket &&
ticket.heading.map((head, i) => (
<th key={i}>
{" "}
{input == false ? (
<h6 className="head">{head}</h6>
) : (
<InputGroup className="mb-3">
<FormControl
placeholder={head}
name={head.headingName}
value={head.headingname}
defaultValue={head}
onChange={(e) => testfunction(e, i)}
// onChange={set}
// value={hea d && head.name}
// onChange={(e) => {
// console.log(head._id);
// setArr(e.target.value);
// // ticket.heading[i].name = e.target.value
// console.log(e.target.name)
// }}
/>
</InputGroup>
)}
</th>
))}
<td>
{allbuttons == true ? (
<Button
variant="contained"
color="secondary"
size="small"
onClick={() => deleteheading(ticket._id)}
>
<i className="fas fa-minus"></i>
</Button>
) : (
""
)}
{allbuttons == true ? (
<Button
variant="contained"
color="primary"
size="small"
onClick={() => submitHandler(ticket._id)}
>
<i className="fas fa-plus"></i>
</Button>
) : (
""
)}
</td>
{/* <th>
<div className="edit">
{ticket.heading.length == 0 ? (
""
) : button == false ? (
<Button
variant="contained"
color="primary"
onClick={() => {
// key = product;
setInput(true);
setButton(true);
}}
>
<i className="fas fa-edit"></i>
</Button>
) : (
<Button
variant="contained"
color="primary"
onClick={() => {
// submitHandle();
handleUpdated();
// key = product;
setButton(false);
setInput(false);
}}
>
Update
</Button>
)}
</div>
</th> */}
</tr>
</thead>
<tbody>
<tr>
{ticket.body.map((body, i) => (
<td key={i}>
{}
{input == false ? (
<div className="body"> {body}</div>
) : (
<InputGroup className="mb-3">
<FormControl
placeholder={body}
name={body.bodyName}
value={body.bodyName}
defaultValue={body}
onChange={(e) => testbody(e, i)}
/>
</InputGroup>
)}
</td>
))}
{/* <td>
{" "}
{ticket.body.length == 0 ? (
""
) : button1 == false ? (
<Button
variant="contained"
color="primary"
onClick={() => {
// key = product;
setInput1(true);
setButton1(true);
}}
>
<i className="fas fa-edit"></i>
</Button>
) : (
<Button
variant="contained"
color="primary"
onClick={() => {
handleBod();
setButton1(false);
setInput1(false);
}}
>
Update
</Button>
)}
</td> */}
</tr>
<tr>
{ticket.heading2.map((head2, i) => (
<td key={i}>
{input == false ? (
<h6 className="head">
<b>{head2}</b>
</h6>
) : (
<InputGroup className="mb-3">
<FormControl
placeholder={head2}
name={head2.bodyName}
value={head2.bodyName}
defaultValue={head2}
onChange={(e) => testHeading(e, i)}
/>
</InputGroup>
)}
</td>
))}
<td>
{allbuttons == true ? (
<Button
variant="contained"
color="primary"
size="small"
onClick={() => submitHand(ticket._id)}
>
<i className="fas fa-plus"></i>
</Button>
) : (
""
)}
{allbuttons == true ? (
<Button
variant="contained"
color="secondary"
size="small"
onClick={() => deleteheading2(ticket._id)}
>
<i className="fas fa-minus"></i>
</Button>
) : (
""
)}
</td>
{/* <td>
{" "}
{ticket.heading2.length == 0 ? (
""
) : button2 == false && localStorage.getItem("response") ? (
<Button
variant="contained"
color="primary"
onClick={() => {
// key = product;
setInput2(true);
setButton2(true);
}}
>
<i className="fas fa-edit"></i>
</Button>
) : (
<Button
variant="contained"
color="primary"
onClick={() => {
handleHead();
setButton2(false);
setInput2(false);
}}
>
Update
</Button>
)}
</td> */}
</tr>
<tr>
{ticket.body2.map((body2, i) => (
<td key={i}>
{input == false ? (
<div className="body"> {body2}</div>
) : (
<InputGroup className="mb-3">
<FormControl
placeholder={body2}
name={body2.bodyName}
value={body2.bodyName}
defaultValue={body2}
onChange={(e) => testBody2(e, i)}
/>
</InputGroup>
)}
</td>
))}
{/* <td>
{" "}
{ticket.body2.length == 0 ? (
""
) : button3 == false ? (
<Button
variant="contained"
color="primary"
onClick={() => {
// key = product;
setInput3(true);
setButton3(true);
}}
>
<i className="fas fa-edit"></i>
</Button>
) : (
<Button
variant="contained"
color="primary"
onClick={() => {
handleBodyyy2();
setButton3(false);
setInput3(false);
}}
>
Update
</Button>
)}
</td> */}
</tr>
<tr></tr>
<tr></tr>
</tbody>
</Table>
</Row>
</div>
);
};
export default Ticket;
|
const { deepEqual, ok } = require('assert')
const { MOCK_CARD_CREATE, MOCK_CARD_UPDATE } = require('./mocks')
const api = require('../api')
let app = {}
let MOCK_ID = null
const TOKEN = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IllPdXNzZWZNdWhhbWFkIiwiaWQiOjEsImlhdCI6MTU2NTY2NTM2NH0.kfYNb8FzQ_QUleI4-nn63ewPIydcXOdhpu8h4_YdVjw'
const headers = {
Authorization: TOKEN
}
describe('API Cards', function () {
this.beforeAll(async () => {
app = await api
await app.inject({ method: 'POST', url: '/cards', payload: JSON.stringify(MOCK_CARD_CREATE), headers })
const res = await app.inject({ method: 'POST', url: '/cards', payload: JSON.stringify(MOCK_CARD_UPDATE), headers })
const data = JSON.parse(res.payload)
MOCK_ID = data._id
})
it('Should list all cards in /cards', async () => {
const res = await app.inject({
method: 'GET',
url: '/cards',
headers
})
const statusCode = res.statusCode
const data = JSON.parse(res.payload)
deepEqual(statusCode, 200)
ok(Array.isArray(data))
})
it('should list only a limited number of typles, by pagination GET /cards?...', async () => {
const LIMIT = 3
const res = await app.inject({
method: 'GET',
url: `/cards?skip=0&limit=${LIMIT}`,
headers
})
const statusCode = res.statusCode
const data = JSON.parse(res.payload)
deepEqual(statusCode, 200)
ok(data.length === LIMIT)
})
it('Should read by name and limit by 2 GET /cards?...', async () => {
const NAME = 'Obelisk The Tormentor'
const res = await app.inject({
method: 'GET',
url: `/cards?skip=0&limit=2&name=${NAME}`,
headers
})
const statusCode = res.statusCode
const data = JSON.parse(res.payload)
ok(statusCode === 200)
deepEqual(data[0].name, NAME)
deepEqual(data[1].name, NAME)
})
it('Should read a card just by a word in the name GET /cards?name...', async () => {
const NAME = 'The'
const res = await app.inject({
method: 'GET',
url: `/cards?name=${NAME}`,
headers
})
const statusCode = res.statusCode
const data = JSON.parse(res.payload)
ok(data[0].name, NAME)
})
it('Should create a card POST /cards', async () => {
const res = await app.inject({
method: 'POST',
url: '/cards',
payload: MOCK_CARD_CREATE,
headers
})
const statusCode = res.statusCode
const { message } = JSON.parse(res.payload)
ok(statusCode === 200)
deepEqual(message, "The card was created with success :)")
})
it('Should update a card PATCH - /cards/:id', async () => {
const expected = { atk: '2000', def: '1200' }
const res = await app.inject({
method: 'PATCH',
url: `/cards/${MOCK_ID}`,
payload: JSON.stringify(expected),
headers
})
const statusCode = res.statusCode
const data = JSON.parse(res.payload)
ok(statusCode === 200)
deepEqual(data.message, 'The card was updated with success :)')
})
it('Should delete a card DELETE - /cards/:id', async () => {
const _id = MOCK_ID
const res = await app.inject({
method: 'DELETE',
url: `/cards/${_id}`,
headers
})
const statusCode = res.statusCode
const data = JSON.parse(res.payload)
ok(statusCode === 200)
deepEqual(data.message, 'The card was deleted with success :)')
})
})
|
const concat = require('lodash/concat')
const isFunction = require('lodash/isFunction')
const isObject = require('lodash/isObject')
const isString = require('lodash/isString')
/**
* Simulate UI Event
* REF: https://www.w3.org/TR/uievents/
*/
const TYPE = Symbol('type')
const TARGET = Symbol('target')
const SUPEREVENT = Symbol('superEvent')
// const NONE = 0
// const CAPTURING_PHASE = 1
// const AT_TARGET = 2
// const BUBBLING_PHASE = 3
const PropertiesInspectEventAlias = [
['type', 'typeEvent'],
['target', 'targetEvent']
]
const PropertiesInspectEvent = [
'currentTarget',
'eventPhase',
'bubbles',
'cancelable',
'defaultPrevented',
'composed',
'isTrusted',
'timeStamp',
'composedPath',
'stopPropagation',
'stopImmediatePropagation',
'preventDefault'
]
function WrapperUIEvents (thisArg, typeArg, superEventArg) {
if (!(this instanceof WrapperUIEvents)) return new WrapperUIEvents(thisArg, typeArg, superEventArg)
if (!isObject(thisArg)) throw new TypeError('Failed to constructor \'WrapperUIEvents\': parameter 1 (\'thisArg\') is not a object.')
if (!isString(typeArg)) throw new TypeError('Failed to constructor \'WrapperUIEvents\': parameter 2 (\'typeArg\') is not a string.')
this[TYPE] = typeArg
this[Symbol.toStringTag] = 'WrapperUIEvents(' + typeArg + ')'
this[TARGET] = thisArg
this[SUPEREVENT] = superEventArg
if (isObject(superEventArg)) {
PropertiesInspectEvent.forEach((propName) => {
if ((propName in superEventArg)) {
const description = {}
if (isFunction(superEventArg[propName])) {
description.get = () => superEventArg[propName].bind(superEventArg)
} else {
description.get = () => superEventArg[propName]
}
Object.defineProperty(this, propName, description)
}
})
PropertiesInspectEventAlias.forEach(([propName, propAliasName]) => {
if ((propName in superEventArg)) {
const description = {}
if (isFunction(superEventArg[propName])) {
description.get = () => superEventArg[propName].bind(superEventArg)
} else {
description.get = () => superEventArg[propName]
}
Object.defineProperty(this, propAliasName, description)
}
})
}
Object.defineProperty(this, 'type', {
get: () => this[TYPE]
})
Object.defineProperty(this, 'target', {
get: () => this[TARGET]
})
Object.defineProperty(this, 'superEvent', {
get: () => this[SUPEREVENT]
})
this.toString = Object.prototype.toString.bind(this)
}
WrapperUIEvents.parse = function (thisArg, ...events) {
return concat(...events).map((event) => {
if (isObject(event) && isString(event.type)) {
return new WrapperUIEvents(thisArg, event.type, event)
} else {
return event
}
})
}
// WrapperUIEvents.NONE = NONE
// WrapperUIEvents.CAPTURING_PHASE = CAPTURING_PHASE
// WrapperUIEvents.AT_TARGET = AT_TARGET
// WrapperUIEvents.BUBBLING_PHASE = BUBBLING_PHASE
exports = module.exports
exports.default = WrapperUIEvents
exports.WrapperUIEvents = WrapperUIEvents
|
const { schema } = require('normalizr');
const { get } = require('lodash');
const counterPartyConnectionTypes = new schema.Entity(
'counterPartyConnections',
{},
{
idAttribute: (data) => {
const {
counterPartyId: { id },
} = data;
return id;
},
},
);
const getCurrentPage = (paging) => {
let currentPage;
const nextPageKeyInt = parseInt(get(paging, 'nextPageKey', -1), 10);
const previousPageKeyInt = parseInt(get(paging, 'previousPageKey', -1), 10);
if (nextPageKeyInt === -1 && previousPageKeyInt === -1) {
currentPage = 1;
} else if (nextPageKeyInt === -1) {
currentPage = previousPageKeyInt + 1;
} else {
currentPage = nextPageKeyInt - 1;
}
return currentPage;
};
const paging = new schema.Entity(
'paging',
{},
{
idAttribute: (paging) => getCurrentPage(paging),
processStrategy: (paging) => {
const result = {
id: getCurrentPage(paging),
total: Math.ceil(paging.count / paging.pageSize),
pageSize: paging.pageSize,
count: paging.count,
};
return result;
},
},
);
const counterPartySchemaArray = new schema.Array(counterPartyConnectionTypes);
const counterPartyConnectionTypesSchema = new schema.Entity('parentj', {});
module.exports = {
counterPartyConnections: [counterPartyConnectionTypes],
paging: paging,
};
|
(function () {
'use strict';
var gulp = require('gulp'),
del = require('del'),
sass = require('gulp-sass'),
sourcemaps = require('gulp-sourcemaps'),
cleanCSS = require('gulp-clean-css'),
autoprefixer = require('gulp-autoprefixer'),
minify = require('gulp-minify'),
browserSync = require('browser-sync').create(),
include = require("gulp-include"),
imagemin = require('gulp-imagemin'),
http = require('http'),
st = require('st');
// PATHS
var path = __dirname;
var src = path + '/src/',
dist = path + '/dist/';
gulp.task('default', ['styles', 'scripts', 'images', 'html']);
gulp.task('clean', function () {
// Remove everything from dist folder
del([ dist + '/**/*', dist + '/.*' ]);
});
gulp.task('build', ['clean', 'default'] , function(){
// Clean everything, then reBuild everything
// @todo: default has to run after clean
});
gulp.task('styles', function () {
gulp.src( src + 'scss/**/*.scss' )
.pipe(sourcemaps.init())
.pipe(sass().on('error', sass.logError))
.pipe(cleanCSS())
.pipe(sourcemaps.write())
.pipe(autoprefixer())
.pipe(gulp.dest( dist + 'css' ))
.pipe(browserSync.stream({match: '**/*.css'}));
});
gulp.task('scripts', function() {
// Main.js
gulp.src( src + 'js/main.js')
.pipe(include()).on('error', console.log)
.pipe(minify({
ext:{
src:'-debug.js',
min:'.min.js'
}
}))
.pipe(gulp.dest(dist + 'js' ));
// Copy the rest but exclude main.js and includes starting with an underscore.
gulp.src([
src + 'js/**/*.js',
'!' + src + 'js/main.js',
'!' + src + 'js/**/_*.js'
]).pipe(gulp.dest(dist + 'js'))
.pipe(browserSync.stream({match: '**/*.js'}));
});
gulp.task('images', function() {
gulp.src( src +'img/**/*')
.pipe(imagemin())
.pipe(gulp.dest( dist + 'img'))
.pipe(browserSync.stream());
});
gulp.task('html', function() {
gulp.src( [src + 'html/**/*', src + 'html/**/.*'])
.pipe(gulp.dest( dist ))
.pipe(browserSync.stream({match: '**/*.html'}));
});
gulp.task('server', function(done) {
http.createServer(
st({
path: dist,
index: 'index.html',
cache: false
})
).listen(8080, done);
});
gulp.task('watch', ['default', 'server'] ,function () {
browserSync.init({
server: {
baseDir: dist
}
});
gulp.watch( src + 'scss/**/*.scss' , ['styles'] );
gulp.watch( src + 'js/**/*.js' , ['scripts'] );
gulp.watch( src + 'html/**/*.html' , ['html'] );
gulp.watch( src + 'img/**/*' , ['images'] );
});
}());
|
/**
* 1) Open a new tab and Firebug on it.
* 2) Disable Console panel
* 3) Verify visibility of the command line (must be collapsed).
*/
function runTest()
{
FBTest.openNewTab(basePath + "firebug/OpenFirebugOnThisPage.html", function(win)
{
FBTest.openFirebug(function()
{
FBTest.selectPanel("console");
FW.Firebug.Console.setDefaultState(true);
FW.Firebug.Console.setDefaultState(false);
var cmdBox = FW.Firebug.chrome.$("fbCommandBox");
var splitter = FW.Firebug.chrome.$("fbPanelSplitter");
var sidePanel = FW.Firebug.chrome.$("fbSidePanelDeck");
FBTest.ok(cmdBox.collapsed, "Command line must be hidden");
FBTest.ok(splitter.collapsed, "Splitter must be hidden");
FBTest.ok(sidePanel.collapsed, "Large command line must be hidden");
FBTest.testDone();
});
});
}
|
import reduce from "../reduce.js";
import { items } from "../dataset/dataset.js";
export function cb(accumulator, value) {
// return accumulator + value; // for testing purpose
/* ADD YOUR CODE HERE */
}
const result = reduce(items, cb);
console.log(result);
|
import router from './Task6.js';
const square = require('./app.js');
const calculate = (a) =>{
console.log('The Area is ' +square.area(a));
console.log('The Perimeter is ' + square.perimeter(a));
}
console.log(__filename)
console.log(__dirname)
calculate(5)
router.post("/page", (req, res, next) => {
var skip = req.body.page
const limit = 50
skip = (skip - 1)*limit
var fromDate = new Date(req.body.fromDate)
var toDate = new Date(req.body.toDate)
var url = req.body.url
var currency = req.body.currency
var queryObject = {type:{$ne:"debit" }}
if(fromDate) {
queryObject.createdAt = {
$gte: fromDate,
$lte: toDate
}
}
if(url){
queryObject = url
}
if(currency){
queryObject = currency
}
async.parallel({
data: function(callback){
Transaction.find(queryObject,{
"game.id":1,
"transaction.id":1,
url:1,
currency:1,
userId:1,
winLoseAmt:1
}).exec(callback)
},
total: function(callback){
Transaction.aggregate([{
$match: queryObject
},{
$group:{
_id:null,
totalAmt:{$sum:"$winLoseAmt"}
}}]).exec(callback)
}
},res.callback)
})
export default router
|
class Game{
constructor(){
}
//To update the state in the other player's device
getState(){
var getstateInfo=database.ref('gameState')
getstateInfo.on("value",(data)=>{
gameState=data.val();
})
}
//To update the gamestate in the database
updateState(state){
database.ref('/').update({
gameState:state
})
}
async start(){
if(gameState===0){
var playerCountRef= await database.ref('playerCount').once("value");
player=new Player;
if(playerCountRef.exists()){
playerCount=playerCountRef.val();
player.getPlayerNumber();
player.getPlayerCount();
}
form= new Form;
form.display();
}
bike1=createSprite(100,200);
bike1.addImage("bike1",bike1Img);
bike2=createSprite(300,200);
bike2.addImage("bike2",bike2Img);
bike3=createSprite(500,200);
bike3.addImage("bike3",bike3Img);
bike4=createSprite(700,200);
bike4.addImage("bike4",bike4Img);
bikes=[bike1,bike2,bike3,bike4];
}
play(){
form.hide();
Player.playerInfo();
if(playerInfo!==undefined){
background(rgb(193,135,105));
image(track,0,-displayHeight*4,displayWidth,displayHeight*5);
var index=0;
var x=175;
var y;
for(var i in playerInfo){
index=index+1;
x=x+200;
y= displayHeight-playerInfo[i].distance;
bikes[index-1].x=x
bikes[index-1].y=y
if(player.index===index){
stroke(10);
ellipse(x,y,80,80);
bikes[index-1].shapeColor="red";
camera.position.x=displayWidth/2;
camera.position.y=car[index-1].y;
}
}
}
if(player.index!==null && keyIsDown(UP_ARROW)){
player.distance=player.distance+10;
if(playerCount===1){
bike2.speed=random(5,20);
bike3.speed=random(5,20);
bike4.speed=random(5,20);
}
if(playerCount===2){
bike3.speed=random(5,20);
bike4.speed=random(5,20);
}
if(playerCount===3){
bike4.speed=random(5,20);
}
player.update();
}
drawSprites();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.