text
stringlengths 7
3.69M
|
|---|
import React from 'react';
const SEO = ({ config }) => {
const {
title, description, keywords, author, copyright, imgLink, link,
} = config;
return (
<div>
<title>{title}</title>
<meta name="description" content={description} />
<link rel="icon" href="/favicon.ico" />
<meta name="description" content={description} />
<meta name="keywords" content={keywords} />
<meta name="author" content={author} />
<meta name="copyright" content={copyright} />
<meta name="thumbnail" content={imgLink} />
<meta itemProp="name" content={title} />
<meta itemProp="url" content={link} />
<meta itemProp="description" content={description} />
<meta itemProp="about" content={description} />
<meta itemProp="abstract" content={description} />
<meta itemProp="image" content={imgLink} />
<meta itemProp="keywords" content={keywords} />
<meta itemProp="author" content={author} />
<meta itemProp="copyrightHolder" content={copyright} />
{/* Open Graph data */}
<meta property="og:title" content={title} />
<meta property="og:description" content={description} />
<meta property="og:url" content={link} />
<meta property="og:ttl" content="345600" />
<meta property="og:site_name" content={title} />
<meta property="og:type" content="website" />
<meta property="og:image" content={imgLink} />
<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" />
{/* Link relationship */}
<link rel="author" href={link} />
<link rel="publisher" href={link} />
{/* Twitter Card data */}
<meta name="twitter:title" content={title} />
<meta name="twitter:description" content={description} />
<meta name="twitter:site" content="綠球藻遊戲工作室" />
<meta name="twitter:creator" content={author} />
<meta name="twitter:card" content={imgLink} />
<meta name="twitter:image:src" content={imgLink} />
</div>
);
};
export default SEO;
|
import React, { useReducer } from 'react'
import axios from 'axios'
import CartContext from './cartContext'
import CartReducer from './CartReducer'
import {
NEW_CART_ITEM,
ADD_TO_CART_ERROR,
GET_CART_ITEMS,
CART_LOAD_ERR,
CART_ITEM_DELETED,
CART_DELETE_ERROR,
CLIENT_TOKEN,
CLIENT_TOKEN_FAIL,
PROCCESS_PAYMENT,
PAYMENT_ERR,
EMPTY_CART,
EMPTY_CART_ERR,
} from '../types'
import setAuthToken from '../../utills/setAuthToken'
const CartState = props => {
let initialState = {
cart: [],
err: null,
message: null,
clientToken: null,
paymentSuccess: false,
}
const [state, dispatch] = useReducer(CartReducer, initialState)
//setting auth token for headers
if (localStorage.token) {
setAuthToken(localStorage.token)
}
const addItem = (item, next) => {
let cart = []
try {
if (typeof window !== undefined) {
if (localStorage.getItem('cart')) {
cart = JSON.parse(localStorage.getItem('cart'))
}
cart.push({
...item,
count: 1
})
// remove duplicates
// build an Array from new Set and turn it back into array using Array.from
// so that later we can re-map it
// new set will only allow unique values in it
// so pass the ids of each object/product
// If the loop tries to add the same value again, it'll get ignored
// ...with the array of ids we got on when first map() was used
// run map() on it again and return the actual product from the cart
cart = Array.from(new Set(cart.map(p => p._id))).map(id => {
return cart.find(p => p._id === id);
});
localStorage.setItem('cart', JSON.stringify(cart))
next()
}
dispatch({
type: NEW_CART_ITEM,
payload: 'New item in cart'
})
} catch (err) {
dispatch({
type: ADD_TO_CART_ERROR,
payload: err
})
}
}
const getCart = async () => {
if (typeof window !== undefined) {
try {
if (localStorage.getItem('cart')) {
let cart = JSON.parse(localStorage.getItem('cart'))
dispatch({
type: GET_CART_ITEMS,
payload: cart
})
}
}
catch (err) {
dispatch({
type: CART_LOAD_ERR,
payload: err,
})
}
}
}
const removeItem = (productId) => {
let cart = []
try {
if (typeof window !== undefined) {
if (localStorage.getItem('cart')) {
cart = JSON.parse(localStorage.getItem('cart'))
}
cart.map((product, i) => {
if (product._id === productId) {
cart.splice(i, 1)
}
})
localStorage.setItem('cart', JSON.stringify(cart))
dispatch({
type: CART_ITEM_DELETED,
payload: 'Item deleted'
})
}
} catch (err) {
dispatch({
type: CART_DELETE_ERROR,
payload: err
})
}
}
const getBraintreeClientToken = async (userId) => {
const config = {
headers: {
"Content-Type": "application/json"
},
}
try {
const res = await axios.get(`/braintree/getToken/${userId}`, config)
dispatch({
type: CLIENT_TOKEN,
payload: res.data
})
} catch (err) {
dispatch({
type: CLIENT_TOKEN_FAIL,
payload: err.response.data.msg,
})
}
}
const proccessPayment = async (userId ,paymentData) => {
const config = {
headers: {
"Content-Type": "application/json"
},
}
try {
const res = await axios.post(`/braintree/payment/${userId}`, JSON.stringify(paymentData), config)
emptyCart()
dispatch({
type: PROCCESS_PAYMENT,
payload: res.data
})
return res.data
} catch (err) {
dispatch({
type: PAYMENT_ERR,
payload: err.response.data.msg,
})
}
}
const emptyCart = async () => {
if (typeof window !== undefined) {
try {
localStorage.removeItem('cart')
dispatch({
type: EMPTY_CART
})
} catch (error) {
dispatch({
type: EMPTY_CART_ERR
})
}
}
}
return (
<CartContext.Provider
value={{
cart: state.cart,
err: state.err,
message: state.message,
clientToken: state.clientToken,
paymentSuccess: state.paymentSuccess,
addItem,
getCart,
removeItem,
getBraintreeClientToken,
proccessPayment,
emptyCart,
}}
>
{props.children}
</CartContext.Provider>
)
}
export default CartState
|
var Phaser = Phaser || {};
var GameTank = GameTank || {};
GameTank.LevelManager = function(gameState) {
"use strict";
Object.call(this);
this.gameState = gameState;
this.keyMap = {
1: "brick",
2: "iron",
3: "grass",
4: "waterv",
5: "waterh"
}
this.map = [];
for(var i=0; i<26; i++) {
this.map[i] = [];
}
};
GameTank.LevelManager.prototype = Object.create(Object.prototype);
GameTank.LevelManager.prototype.constructor = GameTank.LevelManager;
GameTank.LevelManager.prototype.load = function(level) {
this.levelJSON = game.cache.getJSON(level);
for(var i=0; i<this.levelJSON.length; i++) {
for(var j=0; j<this.levelJSON[0].length; j++) {
if(this.levelJSON[i][j]) {
var tile = this.gameState.groups.map[this.keyMap[this.levelJSON[i][j]]].getFirstExists(false);
tile.body.immovable = true;
tile.reset(j * TILE_WIDTH, i * TILE_HEIGHT);
tile.xIndex = j;
tile.yIndex = i;
tile.type = this.levelJSON[i][j];
this.map[j][i] = tile;
} else {
this.map[j][i] = undefined;
}
}
}
}
GameTank.LevelManager.prototype.updateMap = function(x, y) {
this.map[x][y] = undefined;
}
GameTank.LevelManager.prototype.getShovel = function() {
var indexes = [{x:11, y:25},{x:11, y:24},{x:11, y:23},{x:12, y:23},{x:13, y:23},{x:14, y:23},{x:14, y:24},{x:14, y:25},{x:14, y:26}];
if(this.shovelTimer) {
this.gameState.game.time.events.remove(this.shovelTimer);
this.shovelTimer = null;
}
for(var i=0; i<indexes.length; i++) {
if(this.map[indexes[i].x][indexes[i].y]) {
this.map[indexes[i].x][indexes[i].y].kill();
this.map[indexes[i].x][indexes[i].y] = undefined;
}
var tile = this.gameState.groups.map['iron'].getFirstExists(false);
tile.body.immovable = true;
tile.reset(indexes[i].x * TILE_WIDTH, indexes[i].y * TILE_HEIGHT);
tile.xIndex = indexes[i].x;
tile.yIndex = indexes[i].y;
tile.type = 2;
this.map[indexes[i].x][indexes[i].y] = tile;
}
this.shovelTimer = this.gameState.game.time.events.add(Phaser.Timer.SECOND * 8, function() {
for(var i=0; i<indexes.length; i++) {
if(this.map[indexes[i].x][indexes[i].y]) {
this.map[indexes[i].x][indexes[i].y].kill();
this.map[indexes[i].x][indexes[i].y] = undefined;
}
var tile = this.gameState.groups.map['brick'].getFirstExists(false);
tile.body.immovable = true;
tile.reset(indexes[i].x * TILE_WIDTH, indexes[i].y * TILE_HEIGHT);
tile.xIndex = indexes[i].x;
tile.yIndex = indexes[i].y;
tile.type = 1;
this.map[indexes[i].x][indexes[i].y] = tile;
}
this.shovelTimer = null;
}, this);
}
|
import constant from "crocks/combinators/constant"
import curry from "crocks/helpers/curry"
import mapStateProp from "./mapStateProp"
// setStateProp :: String -> a -> State AppState ()
const setStateProp = curry((key, val) => mapStateProp(key, constant(val)))
export default setStateProp
|
import React from "react";
import {Link} from "react-router-dom";
import {Avatar, Box, Button, Container, Divider, Grid, Typography} from "@material-ui/core";
import {makeStyles} from "@material-ui/styles";
import {
Close,
CreditCard,
Dashboard,
DeleteForever,
Edit,
ExitToApp,
LockOpen,
MonetizationOn,
Receipt,
ShoppingBasket,
VerifiedUser
} from "@material-ui/icons";
const DrawerContent = ({handleDrawerClose}) => {
const useStyles = makeStyles(theme => {
return {
divider: {
marginTop: 8,
marginBottom: 8
},
link: {
textDecoration: 'none'
},
button: {
paddingTop: 8,
paddingBottom: 8,
textTransform: 'capitalize'
},
container: {
paddingTop: 16,
paddingBottom: 16
},
accordion: {
marginLeft: -16
},
closeIcon: {
cursor: 'pointer'
},
deleteButton: {
color: 'white',
backgroundColor: '#DC2626',
paddingTop: 8,
paddingBottom: 8
},
logo: {
width: 120,
height: 120
},
box: {
paddingBottom: 32
},
title: {
fontWeight: 'bold',
color: theme.palette.text.primary,
textTransform: 'uppercase'
},
image: {
maxHeight: '100%',
maxWidth: '100%',
objectFit: 'cover',
objectPosition: 'center'
},
}
});
const classes = useStyles();
return (
<React.Fragment>
<Container className={classes.container}>
<Grid container={true} justifyContent="flex-end">
<Grid item={true}>
<Close className={classes.closeIcon} onClick={handleDrawerClose}/>
</Grid>
</Grid>
<Grid container={true} justifyContent="center">
<Grid item={true}>
<Avatar className={classes.logo} variant="rounded">
<img className={classes.image} alt="logo" src="/images/logo.png"/>
</Avatar>
</Grid>
</Grid>
<Box className={classes.box}>
<Typography className={classes.title} gutterBottom={true} variant="body2">Main</Typography>
<Divider variant="fullWidth" className={classes.divider}/>
<Link className={classes.link} to="/">
<Button
className={classes.button}
startIcon={<Dashboard/>}
fullWidth={false}
size="small">
Dashboard
</Button>
</Link>
<Divider variant="fullWidth" className={classes.divider}/>
<Link className={classes.link} to="/funds">
<Button
className={classes.button}
startIcon={<MonetizationOn/>}
fullWidth={false}
size="small">
Funds
</Button>
</Link>
<Divider variant="fullWidth" className={classes.divider}/>
<Link className={classes.link} to="/products">
<Button
startIcon={<CreditCard/>}
size="small"
className={classes.button}
fullWidth={false}
variant="text">
Bank Logs & CC Dumps
</Button>
</Link>
<Divider variant="fullWidth" className={classes.divider}/>
<Link className={classes.link} to="/cheques">
<Button
className={classes.button}
startIcon={<Receipt/>}
size="small"
variant="text">Cheques</Button>
</Link>
<Divider variant="fullWidth" className={classes.divider}/>
<Link className={classes.link} to="/orders">
<Button
startIcon={<ShoppingBasket/>}
className={classes.button}
fullWidth={false}
size="small">
Orders
</Button>
</Link>
</Box>
<Box>
<Typography className={classes.title} gutterBottom={true} variant="body2">Account</Typography>
<Divider variant="fullWidth" className={classes.divider}/>
<Link className={classes.link} to="/profile">
<Button
startIcon={<VerifiedUser/>}
className={classes.button}
fullWidth={false}
size="small">
Profile
</Button>
</Link>
<Divider variant="fullWidth" className={classes.divider}/>
<Link className={classes.link} to="/edit-profile">
<Button
variant="text"
startIcon={<Edit/>}
className={classes.button}
fullWidth={false}
size="small">
Edit Profile
</Button>
</Link>
<Divider variant="fullWidth" className={classes.divider}/>
<Link
className={classes.link}
to="/auth/change-password">
<Button
variant="text"
startIcon={<LockOpen/>}
className={classes.button}
fullWidth={false}
size="small">
Change Password
</Button>
</Link>
<Divider variant="fullWidth" className={classes.divider}/>
<Link
className={classes.link}
to="/auth/login">
<Button
variant="text"
startIcon={<ExitToApp/>}
className={classes.button}
fullWidth={false}
size="small">
Logout
</Button>
</Link>
<Divider variant="fullWidth" className={classes.divider}/>
<Button
variant="outlined"
startIcon={<DeleteForever/>}
className={classes.deleteButton}
fullWidth={true}
size="small">
Delete Account
</Button>
</Box>
</Container>
</React.Fragment>
)
}
export default DrawerContent;
|
import React from 'react';
import './CommentDetails.css';
const CommentDetails = (props) => {
const {img, name, designation, company, comment} = props.comment;
const active = props.index === 0 ? 'active' : '';
return (
<div class={`carousel-item ${active}`}>
<div class="card single-comment">
<div class="commenter-pic d-flex justify-content-center">
<img src={`data:${img.contentType};base64,${img.image}`} alt="" />
</div>
<div class="comment-quote px-3">
<p><q>{comment}</q></p>
<p> — {name}, <cite>{designation}, {company}</cite></p>
</div>
</div>
</div>
);
};
export default CommentDetails;
|
import styled from 'styled-components';
import ProfPic from '../svg/user-solid.svg';
import Icons from './Icons';
import React from 'react';
import TwitterIcon from '../svg/twitter.svg';
import WhatsApp from '../svg/WhatsApp.svg';
import Instagram from '../svg/instagram.svg';
const Card = ({ profile }) => {
return (
<CardContainer>
<Picture>
<ProfPicWrapper>
<ProfPic />
</ProfPicWrapper>
</Picture>
<UserNameContainer>{profile.fullName}</UserNameContainer>
<hr />
<InputFields>
<p>المدينة: {profile.city}</p>
<p>المنطقة: {profile.district}</p>
</InputFields>
<Contact>تواصل معي</Contact>
<IconsWrapper>
{profile.twitterAcc !== null ? (
<a
href={`https://twitter.com/${profile.twitterAcc}`}
target="_blank"
rel="noopener noreferrer"
>
<Icons icon={<TwitterIcon />} />{' '}
</a>
) : null}
{profile.whatsappAcc !== null ? (
<a
href={`https://wa.me/${profile.whatsappAcc}`}
target="_blank"
rel="noopener noreferrer"
>
<Icons icon={<WhatsApp />} />{' '}
</a>
) : null}
{profile.instagramAcc !== null ? (
<a
href={`https://www.instagram.com/${profile.instagramAcc}`}
target="_blank"
rel="noopener noreferrer"
>
<Icons icon={<Instagram />} />
</a>
) : null}
</IconsWrapper>
</CardContainer>
);
};
const CardContainer = styled.div`
width: 407px;
min-height: 586px;
background: #fff;
border-radius: 50px;
filter: drop-shadow(1px 2px 3px rgba(102, 102, 102, 0.15));
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
hr {
width: 90%;
}
@media screen and (max-width: 700px) {
width: 350px;
}
`;
const Picture = styled.div`
width: 181px;
height: 181px;
background: #dbdbd7;
border-radius: 50%;
filter: drop-shadow(2px 4px 3px rgba(102, 102, 102, 0.15));
display: flex;
justify-content: center;
align-items: center;
overflow: hidden;
margin-bottom: 30px;
`;
const ProfPicWrapper = styled.div`
width: 100px;
`;
const UserNameContainer = styled.div`
width: 100%;
height: 47px;
text-align: center;
font-size: 1.7rem;
`;
const InputFields = styled.div`
width: 100%;
text-align: right;
padding: 22px;
font-size: 1.2rem;
`;
const Contact = styled.div`
width: 100%;
height: 30px;
text-align: center;
font-size: 1.3rem;
margin-bottom: 20px;
`;
const IconsWrapper = styled.div`
display: flex;
width: 50%;
justify-content: space-evenly;
align-items: center;
`;
export default Card;
|
import React from 'react'
import issueimg from '../../images/download.svg'
import './FeedBack.css'
export default function FeedBack() {
return (
<div className="container-fluid feedback">
<div >
<h2>Raise An Issue</h2>
<p>Raise an issue or get solutions to<br></br> your CovaInfo account and Information provided by us related issues instantly..</p>
<p id="mail"><a href="mailto:akshitbatra222@gmail.com">Send email</a></p>
</div>
<img src={issueimg}/>
</div>
)
}
|
// const webpack = require('webpack')
const path = require('path')
// const HtmlWebpackPlugin = require('html-webpack-plugin')
const {CleanWebpackPlugin} = require('clean-webpack-plugin')
const outputDirectory = 'dist'
const LOCAL_PORT = 3000
module.exports = {
entry: ['@babel/polyfill', './src/index.js'],
output: {
path: path.join(__dirname, outputDirectory),
filename: 'bundle.js',
// // publicPath allows you to specify the base path for all the assets within your application (compile proper path to dynamic index.html file)
// publicPath: '.' or outputDirectory...,
// // Keeps path name in bundle.js comments
// pathinfo: true,
},
// set default options for webpack-dev-server mode
devServer: {
// hot update
hot: true,
// refresh app automatically after update
inline: true,
// prevent removing bundle.js on development mode run => available for local compilation (e.g. we can check whether paths in dynamic index.html are correct).
writeToDisk: true,
// The contentBase in devServer represents the location where the server is told to provide content.
// contentBase: '.', // works with src="bundle.js" in root
port: LOCAL_PORT,
// historyAPIFallback will redirect 404s to /index.html => fix a problem (works only for local dev-server) with "cannot GET /URL" error on refresh with React Router https://tylermcginnis.com/react-router-cannot-get-url-refresh/, ALTERNATIVE method (hack): HashRouter
// historyApiFallback: true,
},
// keep local production mode hot
watch: true,
devtool: 'inline-source-map',
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader'],
},
{
test: /\.s[ac]ss$/i,
use: [
// Creates `style` nodes from JS strings
'style-loader',
// Translates CSS into CommonJS
{loader: 'css-loader', options: {sourceMap: true}},
// Compiles Sass to CSS
{loader: 'sass-loader', options: {sourceMap: true}},
],
},
{
test: /\.(png|woff|woff2|eot|ttf|svg|jpg)$/,
loader: 'url-loader?limit=100000',
},
],
},
plugins: [
new CleanWebpackPlugin(),
// // Dynamic index.html generator
// // Beware: github-pagres doesn't like index.html in different dir than root (static needed)
// new HtmlWebpackPlugin({
// template: 'index.html', // pointing to base html for minified html.index creation (with auto injected bundle.js script) - default 'index.html'
// title: 'Kreator Fałszywych Cytatów', // 'template' prop will override 'title' prop
// }),
],
}
|
var mongoose = require('../connectdb'),
Schema = mongoose.Schema;
var Card = require('./card');
var AccountSchema = new Schema ({
account_id : {type : String,index: true},
time : {type : String},
money : {type : Number},
merchant : {type : String},
merchant_id : {type : String},
pos_id : {type : String},
detail : {type : String},
type : {type : String},
consum_card : {type : mongoose.SchemaTypes.ObjectId, ref:'Card'},
owner_card : {type : mongoose.SchemaTypes.ObjectId, ref:'Card'},
comment : {type : Number}
});
module.exports = mongoose.model('Account',AccountSchema);
|
/**
* Common mixin which is merged into client and server model code
*/
class CommonApple {
myCommonFunction(){
return 'foobar';
}
}
|
import React from 'react';
import './avatar.css';
import axios from 'axios';
import person from '../assets/person.png';
import person2 from '../assets/person2.png';
import iconAdd from '../assets/iconAdd.png';
import Alert from './alert';
export default class Avatar extends React.Component{
state = {
img: '',
alerts: []
}
componentDidMount(){
/*axios.get(`http://localhost:4000/imgUser/${this.props.tokenUser}`).then(res => {
console.log(res);
if(res.status === 200){
this.setState({img: res.data});
}
});*/
}
hideAlert = (number) => {
var alerts = this.state.alerts;
alerts.indexOf(alert => alert.number === number);
alerts.splice(0, 1);
this.setState({
alerts
});
}
showAlert = (typeAlert, positionAlert, textAlert) => {
var alert = {
typeAlert: typeAlert,
positionAlert: positionAlert,
textAlert: textAlert,
number: (this.state.alerts.length)+1
}
var alerts = this.state.alerts;
alerts.push(alert);
this.setState({alerts});
setTimeout(function(){ this.hideAlert(alert.number) }.bind(this), 5010);
}
file = (value) => {
var reader = new FileReader();
reader.onloadend = () => {
var imgUser = {
UserId: this.props.tokenUser,
Img: reader.result
};
/*axios.post(`http://localhost:4000/imgUser/`, imgUser).then(res => {
if(res.status === 201){
this.setState({img: imgUser.Img});
}else{
}
});*/
}
reader.readAsDataURL(document.querySelector('input[type=file]').files[0]);
}
render(){
var imgPerson = this.props.inverted ? person2 : person;
var imgUser = this.state.img === '' ? imgPerson : this.state.img;
return(
<div className="circle" style={{width: this.props.width, height: this.props.height}}><img src={imgUser} style={{width: this.props.width, height: this.props.height}} /><div className={"iconAdd "+this.props.viewIconEdit}><img src={iconAdd} /><input type="file" className="inputHidden" onChange={(value) => this.file(value)} /></div></div>
);
}
}
|
// Isometric Renderer creates an HTML5 canvas with render output upon it which can be
// given to Display object to draw.
function IsometricRender(schematic) {
this.targetSchematic = schematic;
this.rotation = 0;
this.cutoff = this.targetSchematic.height;
this.outputImage = document.createElement('canvas');
this.tileSheet = document.createElement('canvas');
this.tempCanvas = document.createElement('canvas');
this.tileSize = 50;
this.blockImage = [];
//this.loadBlockImages();
}
IsometricRender.prototype.setBlockImages = function(images) {
this.blockImage = images;
}
// create render method called when block image is loaded or when schematic
// palette is updated and tilesheet needs to be re-populated.
IsometricRender.prototype.createRender = function() {
this.createTileSheet();
this.updateRender();
}
IsometricRender.prototype.resizeTileSize = function(width, height) {
var model = this.targetSchematic;
var maxXSize = (2*width)/(model.width+model.depth+2);
var maxYSize = (4*height)/(model.width+model.depth+2*model.height+4);
this.tileSize = Math.floor(Math.min(maxXSize,maxYSize));
this.createRender();
}
// creates a tilesheet with default block image adjusted to match each
// colouration present in schematic palette.
IsometricRender.prototype.createTileSheet = function (sourceImage) {
var palette = this.targetSchematic.palette;
this.tileSheet.width = palette.length*this.tileSize;
this.tileSheet.height = this.tileSize;
var ctx = this.tileSheet.getContext("2d");
this.tempCanvas.width = this.tileSize;
this.tempCanvas.height = this.tileSize;
var tempCtx = this.tempCanvas.getContext("2d");
//clear temp canvas to be used after each tile is drawn
var clearRect = tempCtx.createImageData(this.tileSize, this.tileSize);
for (var i=0; i<clearRect.data.length; i++) {
clearRect.data[i] = 0;
}
for (var i=0; i<palette.length; i++) {
var textureIndex = textureID[palette[i].texture];
tempCtx.drawImage(this.blockImage[textureIndex], 0, 0, this.tileSize, this.tileSize);
var imageData = tempCtx.getImageData(0, 0, this.tileSize, this.tileSize);
// wipe initial tile for next
tempCtx.putImageData(clearRect,0,0);
var data = imageData.data;
var blockColour = colourComponents("#ffffff");
if (palette[i].customColour) {
blockColour = colourComponents(palette[i].colour);
}
var oldData = [];
for (var j=0; j<data.length; j++) {
oldData[j] = data[j];
}
for (var j=0; j<data.length; j += 4) {
var oldRed = data[j];
var oldGreen = data[j+1];
var oldBlue = data[j+2];
var red = (blockColour[0] * oldRed)/255;
var green = (blockColour[1] * oldGreen)/255;
var blue = (blockColour[2] * oldBlue)/255;
data[j] = Math.floor(red);
data[j+1] = Math.floor(green);
data[j+2] = Math.floor(blue);
}
ctx.putImageData(imageData, i*this.tileSize, 0);
for (var j=0; j<data.length; j++) {
data[j] = oldData[j];
}
}
}
// redraws isometric render, to be called when contents of schematic block array changes.
IsometricRender.prototype.updateRender = function() {
var rotationTransforms = [ [[1,0],[0,1]], [[0,-1],[1,0]], [[-1,0],[0,-1]], [[0,1],[-1,0]] ];
var size = this.tileSize;
var half = Math.floor(size/2);
var quarter = Math.floor(size/4);
var model = this.targetSchematic;
this.outputImage.width = model.width*half + model.depth*half + size;
this.outputImage.height = model.width*quarter + model.height*half + model.depth*quarter + size;
var ctx = this.outputImage.getContext("2d");
ctx.fillStyle= model.palette[0].colour;
ctx.fillRect(0,0,this.outputImage.width,this.outputImage.height)
var nx, nz;
var xxcomp = rotationTransforms[this.rotation][0][0];
var xzcomp = rotationTransforms[this.rotation][0][1];
var zxcomp = rotationTransforms[this.rotation][1][0];
var zzcomp = rotationTransforms[this.rotation][1][1];
var longestAxis = Math.max(model.width, model.depth);
for (var i=0; i<longestAxis; i++) {
for (var k=0; k<longestAxis; k++) {
for (var j=0; j<model.height; j++) {
nx = xxcomp<0 ? model.width - (1+i) : i*xxcomp;
nx += xzcomp<0 ? model.width - (1+k) : k*xzcomp;
nz = zxcomp<0 ? model.depth - (1+i) : i*zxcomp;
nz += zzcomp<0 ? model.depth - (1+k) : k*zzcomp;
// Temporary bugfix!
if (nx < model.width && nz < model.depth && nx >= 0 && nz >= 0) {
var id = model.block[nx][j][nz];
var material = model.palette[id].model;
if ( !(material == "none") ) {
if (model.visible[nx][j][nz] || j == this.cutoff) {
if (material == "transparent") ctx.globalAlpha=0.7;
var tx = id*size;
var ty = 0;
var x = model.depth*half + i*half -k*half;
var y = model.height*half + i*quarter + k*quarter - j*half;
ctx.drawImage(this.tileSheet,tx,ty,size,size, x,y,size,size);
if (material == "transparent") ctx.globalAlpha=1;
}
}
}
}
}
}
}
|
const koa = require('koa');
const router = require('koa-router');
const app = new koa();
const route = new router();
const koaBetterBody = require('koa-better-body');
const bodyParser = require('koa-bodyparser');
const jwt = require('./middlewares/jwt');
const authenticate = require('./middlewares/authenticate');
const customerService = require('./services/customer.service');
app.use(bodyParser());
route.get('/customers', async(ctx, next) => {
ctx.body = await customerService.getCustomers();
});
route.get('/customers/:id', async(ctx, next) => {
const id = ctx.params.id;
const customerData = await customerService.getCustomer(id);
if (customerData) {
ctx.body = customerData;
} else {
ctx.status = 404;
ctx.body = { message: '유효하지 않은 ID입니다.' };
}
});
route.post('/customers', jwt, async(ctx, next) => {
ctx.body = await customerService.postCustomer(ctx.request.body);
});
route.post('/login', async(ctx, next) => {
authenticate(ctx);
});
app
.use(route.routes())
.use(route.allowedMethods());
app.listen(3000);
|
export const toggleButtonMixin = {
data: function() {
return {
toggleButtonWidth: 170,
toggleButtonHeight: 25,
}
},
created() {
const vGeo = getViewportDimensions();
if (vGeo.width < 480) {
this.toggleButtonWidth = 270;
}
}
};
|
var URL = require('url'),
fs = require('fs'),
$ = require('jQuery'),
urlParser = URL.parse;
var urlget = require('./httpUtil').urlget;
function matchLink(url, res, selector, cb){
$(selector, res.body.toString()).each(function(){
console.log($(this).text(), $(this).attr('href'))
});
cb();
}
/*
用node-jquery根据给出的选择器,选出a元素,并输出链接到queue
*/
exports.matchLink = matchLink;
function matchLinkTest(){
var url = 'http://127.0.0.1/test.htm';
urlget(url,function(err, res){
if(err)throw err;
var handler = matchLink;
handler(url,res, '.clearfix a', function(){
console.log(url, 'handled.');
//self.emit('doWork');
});
})
}
matchLinkTest();
|
import React, { Component } from 'react';
import * as api from '../api';
import moment from 'moment';
import { Link } from '@reach/router';
class Comment extends Component {
constructor(props) {
super(props)
this.state = {
// article: props.article,
// comments: {},
hidden: false
}
}
render() {
if (this.state.hidden) {
return null;
}
return (
<div>
{/* <button className="voteButton upVote" onClick={this.handleUpVote.bind(this, comments.comment_id)}>⬆</button>
<span className="voteCount">{comments.votes}</span> */}
{/* <button className="voteButton downVote" onClick={this.handleDownVote.bind(this, comments.comment_id)}>⬇</button> */}
{/* {" | "} */}
<span className="commentHeader"><Link to={`/users/${this.props.comment.author}`}>{this.props.comment.author}</Link>{" | "}{moment(this.props.comment.created_at).fromNow()}
{" | "}
<button className="deleteButton" onClick={this.handleDelete.bind(this)}>🗑</button>
</span>
<p className="commentBody">{this.props.comment.body}</p>
</div>
);
}
// handleUpVote = (comment_id) => {
// console.log(comment_id)
// api.voteComment(comment_id, 1, article_id).then(() => {
// const newComment = this.state.comments;
// newComment.votes += 1;
// this.setState({ comment: newComment })
// })
// }
// handleDownVote = (comment_id) => {
// api.voteComment(comment_id, -1, article_id).then(() => {
// const newComment = this.state.comments;
// newComment.votes += -1;
// this.setState({ comment: newComment })
// })
// }
handleDelete() {
api.deleteComment(this.props.comment.comment_id, this.props.article_id).then(() => {
this.setState({ hidden: true })
})
}
}
export default Comment;
|
$('document').ready(()=>{
let counter = 0
$('#dec').attr('disabled',true)
// change background-color
if( counter%2 == 0){
$('.main').css('background-color','lightblue')
$('.counter').css('color','white')
}
else{
$('.main').css('background-color','grey')
$('.counter').css('color','red')
}
// decrement function
$('#dec').click(()=>{
if(counter <= 1){
counter--;
$('#dec').attr('disabled',true)
}
else if(counter <= 10){
counter--;
$('#inc').attr('disabled',false)
}
else {
counter --;
}
if( counter%2 == 0){
$('.main').css('background-color','lightblue')
$('.counter').css('color','white')
}
else{
$('.main').css('background-color','grey')
$('.counter').css('color','red')
}
$('.counter').text(counter)
})
// reset function
$('#reset').click(()=>{
counter = 0;
$('#dec').attr('disabled',true)
$('#inc').attr('disabled',false)
$('.counter').text(counter)
if( counter%2 == 0){
$('.main').css('background-color','lightblue')
$('.counter').css('color','white')
}
else{
$('.main').css('background-color','grey')
$('.counter').css('color','red')
}
})
// increment function
$('#inc').click(()=>{
if(counter >= 9){
counter++;
$('#inc').attr('disabled',true)
}
else if(counter >= 0){
counter++;
$('#dec').attr('disabled',false)
}
else{
counter++;
}
if( counter%2 == 0){
$('.main').css('background-color','lightblue')
$('.counter').css('color','white')
}
else{
$('.main').css('background-color','grey')
$('.counter').css('color','red')
}
$('.counter').text(counter)
})
})
|
const express = require("express");
const router = express.Router();
const dev = require("./dev");
// router.get("/", (req, res) => {
// res.send("<h1>API</h1>");
// });
router.use("/dev", dev);
module.exports = router;
|
import React, { useState , useEffect } from 'react';
import Header from './components/ui/Header'
import CharactersGrid from './components/characters/CharactersGrid'
import Search from './components/ui/Search'
import './App.css';
const App = () => {
const [items, setItems] = useState([]);
const [isLoading, setIsLoading] = useState(true);
const [query, setQuery] = useState('');
useEffect(() => {
fetch(`https://www.breakingbadapi.com/api/characters?name=${query}`)
.then(res => {
if(!res.ok){
throw new Error('Response not correct');
}else{
return res.json();
}
})
.then(data => {
setItems(data);
setIsLoading(false);
})
.catch(err => console.log(err));
}, [query]);
return (
<div className="container">
<Header />
<Search getQuery={ (q) => setQuery(q) }/>
<CharactersGrid isLoading={isLoading} items={items} />
</div>
);
}
export default App;
|
angular.module('ngApp.payment')
.directive('isNumber', function () {
return {
require: 'ngModel',
link: function (scope) {
scope.$watch('Pv_Amount', function (newValue, oldValue) {
if (newValue === undefined) { return;}
var arr = String(newValue).split("");
if (arr.length === 0) { return; }
if (arr.length === 1 && (arr[0] === '.')) { return; }
if (arr.length === 2 && newValue === '-.') { return; }
if (isNaN(newValue)) {
scope.Pv_Amount = oldValue;
}
});
scope.$watch('PaymentPaypal.TotalAmount', function (newValue, oldValue) {
if (newValue === undefined) { return; }
var arr = String(newValue).split("");
if (arr.length === 0) { return; }
if (arr.length === 1 && (arr[0] === '.')) { return; }
if (arr.length === 2 && newValue === '-.') { return; }
if (isNaN(newValue)) {
scope.PaymentPaypal.TotalAmount = oldValue;
}
});
}
};
})
.directive('aDisabled', function () {
return {
compile: function (tElement, tAttrs, transclude) {
//Disable ngClick
tAttrs["ngClick"] = "!(" + tAttrs["aDisabled"] + ") && (" + tAttrs["ngClick"] + ")";
//Toggle "disabled" to class when aDisabled becomes true
return function (scope, iElement, iAttrs) {
scope.$watch(iAttrs["aDisabled"], function (newValue) {
if (newValue !== undefined) {
iElement.toggleClass("disabled", newValue);
}
});
//Disable href on click
iElement.on("click", function (e) {
if (scope.$eval(iAttrs["aDisabled"])) {
e.preventDefault();
}
});
};
}
};
});
|
const { MessageSender } = require('ffc-messaging')
const msgCfg = require('../config/messaging')
const { log } = require('../services/logger')
const agreementSender = new MessageSender(msgCfg.updateAgreementQueue)
const createMsg = (agreementData) => {
const msgBase = {
type: msgCfg.updateAgreementMsgType,
source: msgCfg.msgSrc
}
return { ...agreementData, ...msgBase }
}
async function stop () {
await agreementSender.closeConnection()
}
process.on('SIGTERM', async () => {
await stop()
process.exit(0)
})
process.on('SIGINT', async () => {
await stop()
process.exit(0)
})
module.exports = {
updateAgreement: async function (agreementData) {
const msg = createMsg(agreementData)
log('sending message', msg)
await agreementSender.sendMessage(msg)
}
}
|
window.onload=manejarClics;
var cifra1="";
function manejarClics() {
var mas =document.getElementById("mas");
mas.addEventListener("click",function() {
operacion("+");
});
var menos=document.getElementById("menos");
menos.addEventListener("click",function() {
operacion("-");
});
var por=document.getElementById("por");
por.addEventListener("click",function() {
operacion("*");
});
var division=document.getElementById("dividido");
division.addEventListener("click",function() {
operacion("/");
});
var numero1=document.getElementById("1");
numero1.addEventListener("click",function() {
operacion("1");
});
var numero2=document.getElementById("2");
numero2.addEventListener("click",function() {
operacion("2");
});
var numero3=document.getElementById("3");
numero3.addEventListener("click",function() {
operacion("3");
});
var numero4=document.getElementById("4");
numero4.addEventListener("click",function() {
operacion("4");
});
var numero5=document.getElementById("5");
numero5.addEventListener("click",function() {
operacion("5");
});
var numero6=document.getElementById("6");
numero6.addEventListener("click",function() {
operacion("6");
});
var numero7=document.getElementById("7");
numero7.addEventListener("click",function() {
operacion("7");
});
var numero8=document.getElementById("8");
numero8.addEventListener("click",function() {
operacion("8");
});
var numero9=document.getElementById("9");
numero9.addEventListener("click",function() {
operacion("9");
});
var numero0=document.getElementById("0");
numero0.addEventListener("click",function() {
operacion("0");
});
var igual=document.getElementById("igual");
igual.addEventListener("click",calcular);
var punto=document.getElementById("punto");
punto.addEventListener("click",function() {
operacion(".");
});
var elimina=document.getElementById("on");
elimina.addEventListener("click",eliminar);
}
function operacion(num){
cifra1+=num;
var pan=document.getElementById("display");
pan.innerHTML=cifra1;
}
function calcular() {
var rta=eval(cifra1);
var pan=document.getElementById("display");
var conDecimal = rta.toFixed(2);
console.log(conDecimal);
pan.innerHTML=conDecimal;
}
function eliminar(){
var total= eval(cifra1="0")
var pan=document.getElementById("display");
pan.innerHTML=0;
}
|
const sdk = require('@defillama/sdk');
const {staking} = require('../helper/staking')
const {pool2} = require('../helper/pool2')
const cdsAddress = '0x3c48Ca59bf2699E51d4974d4B6D284AE52076e5e';
const lpWethCds = '0x0be902716176d66364f1c2ecf25829a6d95c5bee';
const stakingAddress = '0x0a6bfa6aaaef29cbb6c9e25961cc01849b5c97eb';
async function tvl(timestamp, block) {
let balances = {};
const results = await sdk.api.abi.multiCall({
block,
abi: 'erc20:balanceOf',
calls: [
{
target: cdsAddress,
params: [lpWethCds]
},
{
target: cdsAddress,
params: [stakingAddress]
}
]
})
sdk.util.sumMultiBalanceOf(balances, results);
return balances
}
module.exports = {
methodology: "TVL includes all farms in staking and swap contract",
staking:{
tvl: staking(stakingAddress, cdsAddress)
},
pool2:{
tvl: pool2(stakingAddress, lpWethCds)
},
tvl: async ()=>({})
}
|
var express = require('express');
var router = express.Router();
var User = require('../model/User');
//var session = require('client-sessions');
/* GET home page. */
router.get('/', function(req, res, next) {
//disallow robots
if('/robots.txt'==req.url)res.render('robots.txt');
//res.render('index', { title: 'Express' });
//res.sendfile('views/index.html');
//res.sendFile('index.html',{"root":'views'});
if('/images/leo.jpg'==req.url){
res.end('Hmm');
}
res.render( 'index', { name : 'Hi Liang' });
});
//Search
router.get('/search?'),(req,res)=>{
/*var search = req....
File.find({'filename':search},(err,file)=>{
if(!file){
res.end('Find not found');
}else{
//show file
}
}
});*/
res.end('file not found');
}
//login
router.post('/login',(req,res)=>{
var email = req.body.email;
var password = req.body.password
//Not validtae input yet
User.findOne({'email' : email},(err,user)=>{
if(!user){
res.end('User not found');
}
else if(password===user.password){
req.session_notesource.user = user;
res.redirect('/users');
/*res.cookie('session_id' , email,{ httpOnly: true })//encrypt cookie
.status(200).render('user',{ name : user.fname });
res.redirect('/users');*/
}
});
});
//register
router.post('/register',(req,res)=>{
var email = req.body.email;
var password = req.body.password;
var fname = req.body.fname;
var lname = req.body.lname;
var university = req.body.university;
var faculty = req.body.faculty;
var newuser = new User();
newuser.email = email;
newuser.password = password;
newuser.fname= fname;
newuser.lname = lname;
newuser.university = university;
newuser.faculty = faculty;
User.count({'email':email},(err,num)=>{//check duplicate users
if(err)res.sendFile('error.html',{"root":'views'});
if(num)res.end('This email is already use');
else{
newuser.save((err,newuser)=>{//add user
if(err){
console.log(err);
res.status(500).send();
}
/*
res.cookie('session_id' , email,{ httpOnly: true })//encrypt cookie
.status(200).render('user',{ name : fname });*/
req.session_notesource.user = newuser;
res.redirect('/users');
});
}
});
});
module.exports = router;
|
const machine = {
// Complete here
litersOfCoffee : 0,
fillWithLitersOfCoffee: function (litersOfCoffee){
this.litersOfCoffee = this.litersOfCoffee + litersOfCoffee;
},
expresso: function (){
if (this.litersOfCoffee >=0.08){
console.log(this.litersOfCoffee = this.litersOfCoffee-0.08);
return true;
} else {
return false; }
},
longCoffee: function () {
if (this.litersOfCoffee>=0.15){
console.log(this.litersOfCoffee = this.litersOfCoffee-0.15);
return true;
} else {
return false; }
},
};
module.exports = machine;
// je remplis la machine de 10 litre et j'affiche les litres
// je m'assure qu'en fonction de la quantité dans la machine, je peux avoir un expresso et je retourne true
// j'affiche la quantité restante
// je m'assure qu'en fonction de la quantité dans la machine, je peux avoir un café long et je retourne true
// j'affiche la quantité restante
// et à la fin j'affiche la quantité à O,02
// je souhaite un expresso mais comme la quantité n'est pas suffisante, il affiche false
// --------------------------
//machine.fillWithLitersOfCoffee(10);
//console.log(machine.litersOfCoffee); // => 10
//console.log(machine.expresso()); // => true
//console.log(machine.litersOfCoffee); // => 9.92
//console.log(machine.longCoffee()); // => true
//console.log(machine.litersOfCoffee); // => 9.77
//// some more people ordering coffee here
// ...
//console.log(machine.litersOfCoffee); // => 0.02
//console.log(machine.expresso()); // => false
|
const snu = {
delay(ms = 1000) {
return new Promise((res, rej) => {
setTimeout(() => {
res();
}, ms);
});
}
};
const isUndefined = (value) => {
if (value === undefined) {
return true;
}
return false;
}
export { snu, isUndefined };
|
const nodemailer = require('nodemailer');
const sendEmail = options => {
//1 Create a transporter
const reansporter = nodemailer.createTransport({
service: "Gmail",
auth: {
user: process.env.EMAIL_USERNAME,
pass: process.env.EMAIL_PASSWORD
}
})
//2 Define the email options
//3 Actually send the email
}
|
import React, { Component } from "react";
import {
Container,
Header,
Title,
Content,
Button,
Icon,
Left,
Right,
Body,
DatePicker
} from "native-base";
class NHDatePicker extends Component {
render() {
return (
<Container>
<Header>
<Left>
<Button
transparent
onPress={() => this.props.navigation.navigate("DrawerOpen")}
>
<Icon name="ios-menu" />
</Button>
</Left>
<Body>
<Title>Date Picker</Title>
</Body>
<Right />
</Header>
<Content padder style={{ backgroundColor: "#fff" }}>
<DatePicker
defaultDate={new Date(2018, 4, 4)}
minimumDate={new Date(2018, 1, 1)}
maximumDate={new Date(2018, 12, 31)}
locale={"en"}
timeZoneOffsetInMinutes={undefined}
modalTransparent={false}
animationType={"fade"}
androidMode={"default"}
placeHolderText="Select date"
/>
</Content>
</Container>
);
}
}
export default NHDatePicker;
|
import React, { useEffect } from "react";
import { connect } from "react-redux";
import { fetchClothes, onItemSelected, searchClothes } from "../../actions";
import ErrorIndicator from "../error-indicator";
import GoodsItem from "../goods-item";
import { withModnikkyService } from "../hoc";
import Spinner from "../spinner";
import "./goods.css";
const Goods = ({ clothes, loading, error, onItemSelected, fetchClothes }) => {
useEffect(() => {
fetchClothes();
}, []);
if (loading) {
return <Spinner />;
}
if (error) {
return <ErrorIndicator />;
}
return (
<div>
<div className="goods-item-container">
{clothes.map((cloth) => {
return (
<GoodsItem
cloth={cloth}
key={cloth.id}
onItemSelected={() => onItemSelected(cloth.id)}
/>
);
})}
</div>
</div>
);
};
const mapStateToProps = ({ clothes, loading, error }) => {
return { clothes, loading, error };
};
const mapDispatchToProps = (dispatch, ownProps) => {
const { modnikkyService } = ownProps;
return {
fetchClothes: fetchClothes(modnikkyService, dispatch),
onItemSelected: (id) => dispatch(onItemSelected(id)),
///search fillter
searchClothes: searchClothes,
};
};
export default withModnikkyService()(
connect(mapStateToProps, mapDispatchToProps)(Goods)
);
|
TQ.unsettledPopulationList = function (dfop){
function search(orgId){
var condition = $("#searchByCondition").val();
if(condition == '请输入姓名或身份证号码') return;
var initParam = {
"orgId": orgId,
"unsettledPopulationCondition.logOut":0,
"unsettledPopulationCondition.isDeath":0,
"unsettledPopulationCondition.fastSearchKeyWords":condition
}
$("#unsettledPopulationList").setGridParam({
url:PATH+'/baseinfo/unsettledPopulationSearch/fastSearchUnsettledPopulation.action',
datatype: "json",
page:1
});
$("#unsettledPopulationList").setPostData(initParam);
$("#unsettledPopulationList").trigger("reloadGrid");
}
$(document).ready(function(){
function clickDisabled(name){
var id="#"+name;
var isDisabled=$(id).attr("disabled");
if(isDisabled=="disabled"){
return true;
}
}
$("#add").click(function(event){
if(!isGrid()){
$.messageBox({level:"warn",message:"请先选择网格级别组织机构进行新增!"});
return;
}
$("#unsettledPopulationMaintanceDialog").createTabDialog({
title:"新增未落户人口",
width: dialogWidth,
height: dialogHeight,
postData:{
mode:'add',
imageType:"population",
type:"unsettledPopulation"
},
tabs:dfop.addTabs,
close : function(){
$("#unsettledPopulationList").trigger("reloadGrid");
}
});
});
$("#refreshSearchKey").click(function(event){
$("#searchByCondition").attr("value","请输入姓名或身份证号码");
});
$("#reload").click(function(event){
onOrgChanged(getCurrentOrgId(),isGrid());
$("#searchByCondition").attr("value","请输入姓名或身份证号码");
});
$("#searchByConditionButton").click(function(){
search(getCurrentOrgId());
});
$("#isLogOut").click(function(){
if(clickDisabled("isLogOut")){
return;
}
var allValue = getSelectedIds();
var logOut=new Array();
var temp=new Array();
if(allValue.length ==0){
$.messageBox({level:'warn',message:"请选择一条或多条数据进行注销!"});
return;
}
for(var i=0;i<allValue.length;i++){
var rowData=$("#unsettledPopulationList").getRowData(allValue[i]);
if(rowData.logOut==0 || rowData.logOut=='0'){
logOut.push(allValue[i]);
}else{
temp.push(allValue[i]);
}
}
allValue=logOut;
if(allValue==null||allValue.length==0){
$.messageBox({level:'warn',message:"没有可注销的数据"});
return;
}
var encryptIds=deleteOperatorByEncrypt("unsettledPopulation",allValue,"encryptId");
$("#unsettledPopulationDialog").createDialog({
width:450,
height:210,
title:'注销提示',
modal:true,
url:PATH+'/baseinfo/commonPopulation/populationEmphasiseConditionDlg.jsp?populationIds='+encryptIds+'&isEmphasis=1&lowerCaseModuleName=unsettledPopulation&type=actualPopulation&temp='+temp+"&orgId="+getCurrentOrgId(),
buttons: {
"保存" : function(event){
$("#populationEmphasisForm").submit();
},
"关闭" : function(){
$(this).dialog("close");
}
}
});
});
$("#cancelLogOut").click(function(){
if(clickDisabled("cancelLogOut")){
return;
}
var allValue = getSelectedIds();
var cancelLogOut=new Array();
var temp=new Array();
if(allValue.length ==0){
$.messageBox({level:'warn',message:"请选择一条或多条数据进行取消注销!"});
return;
}
for(var i = 0;i<allValue.length;i++){
var row=$("#unsettledPopulationList").getRowData(allValue[i]);
if((row.logOut==1||row.logOut=='1')&&(row.death!=true&&row.death!='true')){
$.ajax({
async: false ,
url:PATH+"/baseinfo/householdStaff/findHouseholdStaffByIdCardNoAndOrgIdEncrypt.action",
data:{
"population.idCardNo":row.encryptId,
"population.organization.id":row["organization.id"]
},
success:function(population){
if(population!=null&&population.logOut==0){
temp.push(row.id);
$.messageBox({message:"已经落户且在户籍人口中为关注状态不允许重新关注!",level:"warn"});
}else{
cancelLogOut.push(row.id);
}
}
});
}else{
temp.push(allValue[i]);
}
}
allValue=cancelLogOut;
if(allValue==null||allValue.length==0){
$.messageBox({level:'warn',message:"没有可取消注销的数据"});
return;
}
var encryptIds=deleteOperatorByEncrypt("unsettledPopulation",allValue,"encryptId");
$.confirm({
title:"确认取消注销",
message:"确定要取消注销吗?",
okFunc: function(){
$.ajax({
url:PATH+"/baseinfo/unsettledPopulationManage/updateEmphasiseByEncryptId.action?population.logoutDetail.logout=0&populationIds="+encryptIds+"&orgId="+getCurrentOrgId(),
success:function(datas){
if(null==temp||temp.length==0){
$.messageBox({message:"已经成功取消注销该"+title+"信息!"});
}else{
$.messageBox({level:'warn',message:"除选中的红色数据外,已经成功取消注销该"+title+"信息!"});
}
notExecute=temp;
$("#unsettledPopulationList").trigger("reloadGrid");
disableButtons();
checkExport();
}
});
}
});
});
$("#cancelDeath").click(function(){
if(clickDisabled("cancelDeath")){
return;
}
var allValue = getSelectedIds();
var cancelDeath=new Array();
var temp=new Array();
if(allValue.length ==0){
$.messageBox({level:'warn',message:"请选择一条或多条数据进行取消死亡!"});
return;
}
for(var i = 0;i<allValue.length;i++){
var row=$("#unsettledPopulationList").getRowData(allValue[i]);
if(row.death==true||row.death=='true'){
cancelDeath.push(allValue[i]);
}else{
temp.push(allValue[i]);
}
}
allValue=cancelDeath;
if(allValue==null||allValue.length==0){
$.messageBox({level:'warn',message:"没有可取消死亡的数据"});
return;
}
var encryptIds=deleteOperatorByEncrypt("unsettledPopulation",allValue,"encryptId");
$.confirm({
title:"确认取消死亡",
message:"确定要取消死亡吗?",
okFunc: function(){
$.ajax({
url:PATH+"/baseinfo/unsettledPopulationManage/updateDeathOfUnsettledPopulationByEncryptId.action?unsettledPopulation.death=false&unsettledPopulationIds="+encryptIds,
success:function(datas){
for(var i = 0;i<datas.length;i++){
var responseData = datas[i];
if(($("#isLock").val()=='2'&&$("#isDeath").val()=="0")){
$("#unsettledPopulationList").delRowData(responseData.id);
}else{
$("#unsettledPopulationList").setRowData(responseData.id,responseData);
$("#unsettledPopulationList").setSelection(responseData.id);
}
}
if(null==temp||temp.length==0){
$.messageBox({message:"已经成功取消死亡该"+title+"信息!"});
}else{
$.messageBox({level:'warn',message:"除选中的红色数据外,已经成功取消死亡该"+title+"信息!"});
}
notExecute=temp;
$("#unsettledPopulationList").trigger("reloadGrid");
disableButtons();
checkExport();
}
});
}
});
});
$("#delete").click(function(){
var allValue = getSelectedIds();
if(allValue.length ==0){
$.messageBox({level:'warn',message:"请选择一条或多条记录,再进行删除!"});
return;
}
var encryptIds = deleteOperatorByEncrypt("unsettledPopulation",allValue,"encryptId");
var str = "确定删除吗?一经删除无法恢复 ";
$.confirm({
title:"确认删除",
message:str,
okFunc: function() {
$.ajax({
url:PATH+"/baseinfo/unsettledPopulationManage/deleteUnsettledPopulation.action",
type:"post",
data:{
"unsettledPopulationIds":encryptIds
},
success:function(data){
$("#unsettledPopulationList").trigger("reloadGrid");
$.messageBox({message:"已经成功删除该"+title+"信息!"});
disableButtons();
checkExport();
}
});
}
});
});
$("#view").click(function(){
if(clickDisabled("view")){
return;
}
var selectedId =getSelectedIdLast();
if(selectedId==null){
return;
}
viewDialog(event,selectedId);
});
$("#search").click(function(event){
$("#unsettledPopulationMaintanceDialog").createDialog({
width:650,
height:320,
title:title+'查询-请输入查询条件',
url:PATH+'/baseinfo/unsettledPopulationManage/dispatchOperate.action?mode=search',
buttons: {
"查询" : function(event){
searchUnsettledPopulation();
$(this).dialog("close");
},
"关闭" : function(){
$(this).dialog("close");
}
}
});
});
$("#import").click(function(event){
$("#unsettledPopulationMaintanceDialog").createDialog({
width: 400,
height: 230,
title:'数据导入',
url:PATH+'/common/import.jsp?isNew=1&dataType=unsettledPopulationData&dialog=unsettledPopulationMaintanceDialog&startRow=6&templates='+dfop.templates+'&listName=unsettledPopulationList',
buttons: {
"导入" : function(event){
$("#mForm").submit();
},
"关闭" : function(){
$(this).dialog("close");
}
},
shouldEmptyHtml:false
});
});
$("#export").click(function(event){
if ($("#unsettledPopulationList").getGridParam("records")>0){
$("#unsettledPopulationMaintanceDialog").createDialog({
width: 250,
height: 200,
title:'导出'+title+'信息',
url:PATH+'/common/exportExcel.jsp',
postData:{
gridName:'unsettledPopulationList',
downloadUrl:PATH+'/baseinfo/unsettledPopulationSearch/downloadUnsettledPopulation.action'
},
buttons: {
"导出" : function(event){
exceldownloadSubmitForm();
$(this).dialog("close");
},
"关闭" : function(){
$(this).dialog("close");
}
},
shouldEmptyHtml:false
});
}else{
$.messageBox({level:"warn",message:"列表中没有数据,不能导出!"});
}
});
$("#isDeath").change(function(){
onOrgChanged(getCurrentOrgId(),isGrid());
});
$("#settle").click(function(event){
if(!isGrid()){
$.messageBox({level:"warn",message:"请先选择网格级别组织机构进行落户!"});
return;
}
var selectedId =getSelectedIds();
if(selectedId==undefined||selectedId.length>1||selectedId.length==0){
$.messageBox({level:"warn",message:"请先选择一条记录,再进行落户!"});
return;
}
var rowData = $("#unsettledPopulationList").getRowData(selectedId);
var idCardNo = rowData.idCardNo;
if(rowData.death=="true"){
$.messageBox({message:"该未落户人口已死亡不能进行落户!",level:"warn"});
return;
}
if(rowData.logOut==1||rowData.logOut=='1'){
$.messageBox({message:"该未落户人口已注销不能进行落户!",level:"warn"});
return;
}
if(idCardNo==null||idCardNo==""){
$.messageBox({message:"该未落户人口没有身份证号码不能进行落户!",level:"warn"});
return;
}
if(!isHouseHoldStaff(idCardNo ,rowData["organization.id"])){
$.confirm({
title:"落户提示",
message:"是否把“未落户人口:<u>"+rowData.name+","+idCardNo+"</u> 落户为户籍人口?",
okFunc: function(){
$("#unsettledPopulationMaintanceDialog").createTabDialog({
title:"未落户人口-落户",
width: dialogWidth,
height: dialogHeight,
postData:{
type:"unsettledPopulation"
},
tabs:dfop.settleTabs(idCardNo),
close : function(){
$("#unsettledPopulationList").trigger("reloadGrid");
}
});
}
});
}
});
$("#transfer").click(function(e){
//获取需要转移的id
var allValue = getSelectedIds();
if(allValue.length ==0){
$.messageBox({level:'warn',message:"请选择一条或多条记录,再进行转移!"});
return;
}
for(var i=0;i<allValue.length;i++){
var rowData_Popu=$("#unsettledPopulationList").getRowData(allValue[i]);
if(rowData_Popu.logOut==1||rowData_Popu.death=="true"){
$.messageBox({level:'warn',message:"所选记录中存在已注销(或死亡)记录,无法转移!"});
return;
}
}
//get current orgid
var orgid= getCurrentOrgId();
if(orgid==""||orgid==null){
$.messageBox({level:'warn',message:"没有获取到当前的组织机构id"});
return;
}
moveOperator(e,allValue,orgid);
});
$("#updateIdCardNo").click(function(event){
if(!isGrid()){
$.messageBox({level:"warn",message:"请先选择网格级别组织机构进行修改!"});
return;
}
var selectedId =getSelectedIds();
if(selectedId==undefined||selectedId.length==0){
$.messageBox({level:"warn",message:"请先选择一条记录,再进行操作!"});
return;
}
if(selectedId.length>1){
$.messageBox({level:"warn",message:"只能选择一条记录进行操作!"});
return;
}
var rowData = $("#unsettledPopulationList").getRowData(selectedId);
var idCardNo = rowData.idCardNo;
var orgId=rowData["organization.id"];
if(idCardNo==null || idCardNo=="" || typeof(idCardNo)=="undefined"){
$.messageBox({level:"warn",message:"身份证号未录入不能修改"});
return;
}
updateIdCardNo(selectedId,idCardNo,orgId);
});
function moveOperator(event,allValue,orgid){
var encryptIds = deleteOperatorByEncrypt("unsettledPopulation",allValue,"encryptId");
var allOrgId = getOrgIdsByIds("unsettledPopulation",allValue,"organization.id");
$("#moveDataDialog").createDialog({
width: 400,
height: 230,
title:"数据转移",
url:PATH+"/transferManage/transferDispatchByEncryptId.action?orgId="+orgid+"&Ids="+encryptIds+"&type=unsettledPopulation&orgIds="+allOrgId,
buttons: {
"保存" : function(event){
$("#maintainShiftForm").submit();
},
"关闭" : function(){
$(this).dialog("close");
}
}
});
var evt = event || window.event;
if (window.event) {
evt.cancelBubble=true;
} else {
evt.stopPropagation();
}
}
function isHouseHoldStaff(idCardNo ,orgId){
var isHouseHoldStaff;
$.ajax({
async: false ,
url:PATH+"/baseinfo/householdStaff/findHouseholdStaffByIdCardNoAndOrgId.action",
data:{
"population.idCardNo":idCardNo,
"population.organization.id":orgId
},
success:function(population){
if(population!=null&&population.logOut==0){
isHouseHoldStaff=true;
$.messageBox({message:"已经落户且在户籍人口中为关注状态不允许重新关注!",level:"warn"});
}else{
isHouseHoldStaff=false;
}
}
});
return isHouseHoldStaff;
}
function householdRegisterFormatter(el, options, rowData){
var str = "";
if(rowData.province != null)
str += rowData.province;
if(rowData.city != null)
str += rowData.city
if(rowData.district != null)
str += rowData.district;
return str;
}
$("#unsettledPopulationList").jqGridFunction({
datatype: "local",
colModel:[
{name:"id",index:"id",hidden:true,sortable:false,frozen:true},
{name:"encryptId",index:"id",sortable:false,hidden:true,frozen:true},
{name:'organization.id',index:'organization.id',hidden:true,hidedlg:true,sortable:false,frozen:true},
{name:"operator",label:"操作",index:'id',width:90,formatter:operateFormatter,sortable:false,frozen:true,align:"center"},
{name:"name",index:'name',label:'姓名',sortable:false,width:80,formatter:nameFont,frozen:true},
{name:"gender",label:'性别',sortable:false,width:50,align:'center',formatter : genderFormatter },
{name:'idCardNo',label:'身份证号码',sortable:false,width:160,align:'center',frozen:true},
{name:'organization.orgName',index:'orgInternalCode',label:'所属网格',width:150,sortable:false,hidden:true},
{name:'usedName',label:'曾用名',sortable:false,width:100,hidden:true},
{name:'mobileNumber',label:'联系手机',sortable:false,width:100,align:'center',hidden:true},
{name:'telephone',label:'固定电话',sortable:false,width:120,align:'center',hidden:true},
{name:"birthday",label:"出生日期", width:80,align:'center',sortable:false,hidden:true},
{name:'nation',label:'民族',formatter:nationFormatter,sortable:false,width:80,hidden:true},
{name:'politicalBackground',label:'政治面貌',formatter:politicalBackgroundFormatter,sortable:false,width:150,hidden:true},
{name:'schooling',label:'文化程度',formatter:schoolingFormatter,sortable:false,width:100,hidden:true},
{name:'career',label:'职业',formatter:careerFormatter,sortable:false,width:100,hidden:true},
{name:'workUnit',label:'工作单位或就读学校',sortable:false, width:200},
{name:'maritalState',label:'婚姻状况',formatter:maritalStateFormatter,sortable:false,align:'center',width:80,hidden:true},
{name:'stature',label:'身高(cm)',sortable:false,width:80,align:'center',hidden:true},
{name:'bloodType',label:'血型',formatter:bloodTypeFormatter,sortable:false,width:100,hidden:true},
{name:'faith',label:'宗教信仰',formatter:faithFormatter,sortable:false,width:80,hidden:true},
{name:'email',label:'电子邮箱',sortable:false,width:120,hidden:true},
{name:'unSettedTime',label:'未落户时间',sortable:false,align:'center',width:90,hidden:true},
{name:'unSettedReason',label:'未落户原因',formatter:unSettedReasonFormatter,align:'center',sortable:false,width:90},
{name:'certificateType',label:'持证种类',formatter:certificateTypeFormatter,align:'center',sortable:false,width:80,hidden:true},
{name:'certificateNo',label:'持证编号',sortable:false,width:100,hidden:true},
{name:"province",label:"户籍地", width:120,sortable:false,formatter:householdRegisterFormatter, hidden:true},
{name:'nativePlaceAddress',label:'户籍地详址',sortable:false,width:100,hidden:true},
{name:'currentAddress',label:'常住地址',sortable:false,width:200},
{name:'otherAddress',label:'临时居所',sortable:false,width:100,hidden:true},
{name:'sourcesState',index:'sourcesState',label:"数据来源",sortable:false,hidden:true,formatter:sourceStateFormatter,width:80,align:'center'},
{name:'updateDate', sortable:false, label:'数据更新时间',align:'center', width:160},
//{name:'mobileNumber',label:'联系手机',sortable:true,width:100,align:'center',hidden:true},
// {name:'telephone',label:'固定电话',sortable:true,width:120,align:'center',hidden:true},
{name:'death',sortable:false,hidden:true,hidedlg:true,width:80},
{name:'logOut',sortable:false,hidden:true,hidedlg:true,width:80}
],
onSelectAll:function(aRowids,status){},
loadComplete: afterLoad,
multiselect:true,
ondblClickRow: function (rowid){
if(dfop.hasViewUnsettledPopulation == 'true'){
viewDialogs(rowid);
}
},
onSelectRow:selectRow
});
if (getCurrentOrgId()!=null && getCurrentOrgId()!=""){
onOrgChanged(getCurrentOrgId(),isGrid());
}
});
jQuery("#unsettledPopulationList").jqGrid('setFrozenColumns');
function afterLoad(){
logOutFormatter();
disableButtons();
checkExport();
changeColor();
}
function changeColor(){
if(notExecute==null||notExecute.length==0){
return;
}
for(var i=0;i<notExecute.length;i++){
var rowData=$("#unsettledPopulationList").getRowData(notExecute[i]);
$("#"+notExecute[i]).css('background','red');
$("#unsettledPopulationList").setSelection(notExecute[i])
}
notExecute.splice(0,notExecute.length);
}
function logOutFormatter(){
var idCollection = new Array();
idCollection=$("#unsettledPopulationList").getDataIDs();
for(var i=0;i<idCollection.length;i++){
var ent = $("#unsettledPopulationList").getRowData(idCollection[i]);
if(ent.logOut==1||ent.logOut=='1'){
$("#"+idCollection[i]+"").css('color','#778899');
}
}
}
function selectRow(){
var selectedCounts = getActualjqGridMultiSelectCount("unsettledPopulationList");
var count = $("#unsettledPopulationList").jqGrid("getGridParam","records");
if(selectedCounts == count){
jqGridMultiSelectState("unsettledPopulationList", true);
}else{
jqGridMultiSelectState("unsettledPopulationList", false);
}
}
function viewDialogs(rowid){
if(rowid==null){
return;
}
var unsettledPopulation = $("#unsettledPopulationList").getRowData(rowid);
$("#unsettledPopulationMaintanceDialog").createDialog({
width:dialogWidth,
height:dialogHeight,
title:'查看'+title+'信息',
url:PATH+'/baseinfo/unsettledPopulationManage/dispatchOperateByEncrypt.action?mode=view&id='+unsettledPopulation.encryptId,
buttons: {
"打印" : function(){
printChoose(unsettledPopulation.id);
},
"关闭" : function(){
$(this).dialog("close");
}
}
});
var evt = event || window.event;
if(typeof evt!="object"){return false;}
if (window.event) {
evt.cancelBubble=true;
} else {
evt.stopPropagation();
}
}
function searchUnsettledPopulation(){
var conditionName=$("#conditionName").val();
var conditionUsedName=$("#conditionUsedName").val();
var conditionGender=$("#conditionGender").val();
var conditionIdCardNo=$("#conditionIdCardNo").val();
var conditionCertificateType=$("#conditionCertificateType").val();
var conditionCertificateNo=$("#conditionCertificateNo").val();
var conditionNativePlaceAddress=$("#conditionNativePlaceAddress").val();
var conditionCurrentAddress=$("#conditionCurrentAddress").val();
var conditionWorkUnit=$("#conditionWorkUnit").val();
var conditionTelephone=$("#conditionTelephone").val();
var conditionMobileNumber=$("#conditionMobileNumber").val();
var conditionBirthdayStart=$("#conditionBirthdayStart").val();
var conditionBirthdayEnd=$("#conditionBirthdayEnd").val();
var conditionUnsettedTimeStart=$("#conditionUnsettedTimeStart").val();
var conditionUnsettedTimeEnd=$("#conditionUnsettedTimeEnd").val();
var conditionUnSettedReason=$("#conditionUnSettedReason").val();
var conditionProvince=$("#conditionProvince").val();
var conditionCity=$("#conditionCity").val();
var conditionDistrict=$("#conditionDistrict").val();
var conditionNativePlaceAddress=$("#conditionNativePlaceAddress").val();
var conditionPoliticalBackground=$("#conditionPoliticalBackground").val();
var conditionMaritalState=$("#conditionMaritalState").val();
var conditionNation=$("#conditionNation").val();
var conditionFaith=$("#conditionFaith").val();
var conditionSchooling=$("#conditionSchooling").val();
var conditionBloodType=$("#conditionBloodType").val();
var conditionEmail=$("#conditionEmail").val();
var conditionRemark=$("#conditionRemark").val();
var conditionStature=$("#conditionStature").val();
var conditionOtherAddress=$("#conditionOtherAddress").val();
var conditionCareer=$("#conditionCareer").val();
var initParam = {
"orgId": getCurrentOrgId()
}
if($("#logOut").val()=="-1"){
if($("#isDeath").val()=="-1"){
initParam = {
"isSearch":"1",
"orgId":getCurrentOrgId(),
"unsettledPopulationCondition.name":conditionName,
"unsettledPopulationCondition.usedName":conditionUsedName,
"unsettledPopulationCondition.gender.id":conditionGender,
"unsettledPopulationCondition.idCardNo":conditionIdCardNo,
"unsettledPopulationCondition.certificateType.id":conditionCertificateType,
"unsettledPopulationCondition.certificateNo":conditionCertificateNo,
"unsettledPopulationCondition.nativePlaceAddress":conditionNativePlaceAddress,
"unsettledPopulationCondition.politicalBackground.id":conditionPoliticalBackground,
"unsettledPopulationCondition.currentAddress":conditionCurrentAddress,
"unsettledPopulationCondition.otherAddress":conditionOtherAddress,
"unsettledPopulationCondition.workUnit":conditionWorkUnit,
"unsettledPopulationCondition.telephone":conditionTelephone,
"unsettledPopulationCondition.mobileNumber":conditionMobileNumber,
"unsettledPopulationCondition.birthdayStart":conditionBirthdayStart,
"unsettledPopulationCondition.birthdayEnd":conditionBirthdayEnd,
"unsettledPopulationCondition.unSettedReason.id":conditionUnSettedReason,
"unsettledPopulationCondition.unsettedTimeStart":conditionUnsettedTimeStart,
"unsettledPopulationCondition.unsettedTimeEnd":conditionUnsettedTimeEnd,
"unsettledPopulationCondition.province":conditionProvince,
"unsettledPopulationCondition.city":conditionCity,
"unsettledPopulationCondition.district":conditionDistrict,
"unsettledPopulationCondition.maritalState.id":conditionMaritalState,
"unsettledPopulationCondition.nation.id":conditionNation,
"unsettledPopulationCondition.faith.id":conditionFaith,
"unsettledPopulationCondition.schooling.id":conditionSchooling,
"unsettledPopulationCondition.bloodType.id":conditionBloodType,
"unsettledPopulationCondition.email":conditionEmail,
"unsettledPopulationCondition.remark":conditionRemark,
"unsettledPopulationCondition.stature":conditionStature,
"unsettledPopulationCondition.career.id":conditionCareer
}
}else{
initParam = {
"isSearch":"1",
"orgId":getCurrentOrgId(),
"unsettledPopulationCondition.name":conditionName,
"unsettledPopulationCondition.usedName":conditionUsedName,
"unsettledPopulationCondition.gender.id":conditionGender,
"unsettledPopulationCondition.idCardNo":conditionIdCardNo,
"unsettledPopulationCondition.certificateType.id":conditionCertificateType,
"unsettledPopulationCondition.certificateNo":conditionCertificateNo,
"unsettledPopulationCondition.nativePlaceAddress":conditionNativePlaceAddress,
"unsettledPopulationCondition.politicalBackground.id":conditionPoliticalBackground,
"unsettledPopulationCondition.currentAddress":conditionCurrentAddress,
"unsettledPopulationCondition.otherAddress":conditionOtherAddress,
"unsettledPopulationCondition.workUnit":conditionWorkUnit,
"unsettledPopulationCondition.telephone":conditionTelephone,
"unsettledPopulationCondition.mobileNumber":conditionMobileNumber,
"unsettledPopulationCondition.birthdayStart":conditionBirthdayStart,
"unsettledPopulationCondition.birthdayEnd":conditionBirthdayEnd,
"unsettledPopulationCondition.unSettedReason.id":conditionUnSettedReason,
"unsettledPopulationCondition.unsettedTimeStart":conditionUnsettedTimeStart,
"unsettledPopulationCondition.unsettedTimeEnd":conditionUnsettedTimeEnd,
"unsettledPopulationCondition.province":conditionProvince,
"unsettledPopulationCondition.city":conditionCity,
"unsettledPopulationCondition.district":conditionDistrict,
"unsettledPopulationCondition.maritalState.id":conditionMaritalState,
"unsettledPopulationCondition.nation.id":conditionNation,
"unsettledPopulationCondition.faith.id":conditionFaith,
"unsettledPopulationCondition.schooling.id":conditionSchooling,
"unsettledPopulationCondition.bloodType.id":conditionBloodType,
"unsettledPopulationCondition.email":conditionEmail,
"unsettledPopulationCondition.remark":conditionRemark,
"unsettledPopulationCondition.stature":conditionStature,
"unsettledPopulationCondition.career.id":conditionCareer,
"unsettledPopulationCondition.isDeath":$("#isDeath").val()
}
}
}else{
if($("#isDeath").val()=="-1"){
initParam = {
"isSearch":"1",
"orgId":getCurrentOrgId(),
"unsettledPopulationCondition.name":conditionName,
"unsettledPopulationCondition.usedName":conditionUsedName,
"unsettledPopulationCondition.gender.id":conditionGender,
"unsettledPopulationCondition.idCardNo":conditionIdCardNo,
"unsettledPopulationCondition.certificateType.id":conditionCertificateType,
"unsettledPopulationCondition.certificateNo":conditionCertificateNo,
"unsettledPopulationCondition.nativePlaceAddress":conditionNativePlaceAddress,
"unsettledPopulationCondition.politicalBackground.id":conditionPoliticalBackground,
"unsettledPopulationCondition.currentAddress":conditionCurrentAddress,
"unsettledPopulationCondition.otherAddress":conditionOtherAddress,
"unsettledPopulationCondition.workUnit":conditionWorkUnit,
"unsettledPopulationCondition.telephone":conditionTelephone,
"unsettledPopulationCondition.mobileNumber":conditionMobileNumber,
"unsettledPopulationCondition.birthdayStart":conditionBirthdayStart,
"unsettledPopulationCondition.birthdayEnd":conditionBirthdayEnd,
"unsettledPopulationCondition.unSettedReason.id":conditionUnSettedReason,
"unsettledPopulationCondition.unsettedTimeStart":conditionUnsettedTimeStart,
"unsettledPopulationCondition.unsettedTimeEnd":conditionUnsettedTimeEnd,
"unsettledPopulationCondition.province":conditionProvince,
"unsettledPopulationCondition.city":conditionCity,
"unsettledPopulationCondition.district":conditionDistrict,
"unsettledPopulationCondition.maritalState.id":conditionMaritalState,
"unsettledPopulationCondition.nation.id":conditionNation,
"unsettledPopulationCondition.faith.id":conditionFaith,
"unsettledPopulationCondition.schooling.id":conditionSchooling,
"unsettledPopulationCondition.bloodType.id":conditionBloodType,
"unsettledPopulationCondition.email":conditionEmail,
"unsettledPopulationCondition.remark":conditionRemark,
"unsettledPopulationCondition.stature":conditionStature,
"unsettledPopulationCondition.career.id":conditionCareer,
"unsettledPopulationCondition.logOut":$("#logOut").val()
}
}else{
initParam = {
"isSearch":"1",
"orgId":getCurrentOrgId(),
"unsettledPopulationCondition.name":conditionName,
"unsettledPopulationCondition.usedName":conditionUsedName,
"unsettledPopulationCondition.gender.id":conditionGender,
"unsettledPopulationCondition.idCardNo":conditionIdCardNo,
"unsettledPopulationCondition.certificateType.id":conditionCertificateType,
"unsettledPopulationCondition.certificateNo":conditionCertificateNo,
"unsettledPopulationCondition.nativePlaceAddress":conditionNativePlaceAddress,
"unsettledPopulationCondition.politicalBackground.id":conditionPoliticalBackground,
"unsettledPopulationCondition.currentAddress":conditionCurrentAddress,
"unsettledPopulationCondition.otherAddress":conditionOtherAddress,
"unsettledPopulationCondition.workUnit":conditionWorkUnit,
"unsettledPopulationCondition.telephone":conditionTelephone,
"unsettledPopulationCondition.mobileNumber":conditionMobileNumber,
"unsettledPopulationCondition.birthdayStart":conditionBirthdayStart,
"unsettledPopulationCondition.birthdayEnd":conditionBirthdayEnd,
"unsettledPopulationCondition.unSettedReason.id":conditionUnSettedReason,
"unsettledPopulationCondition.unsettedTimeStart":conditionUnsettedTimeStart,
"unsettledPopulationCondition.unsettedTimeEnd":conditionUnsettedTimeEnd,
"unsettledPopulationCondition.province":conditionProvince,
"unsettledPopulationCondition.city":conditionCity,
"unsettledPopulationCondition.district":conditionDistrict,
"unsettledPopulationCondition.maritalState.id":conditionMaritalState,
"unsettledPopulationCondition.nation.id":conditionNation,
"unsettledPopulationCondition.faith.id":conditionFaith,
"unsettledPopulationCondition.schooling.id":conditionSchooling,
"unsettledPopulationCondition.bloodType.id":conditionBloodType,
"unsettledPopulationCondition.email":conditionEmail,
"unsettledPopulationCondition.remark":conditionRemark,
"unsettledPopulationCondition.stature":conditionStature,
"unsettledPopulationCondition.career.id":conditionCareer,
"unsettledPopulationCondition.logOut":$("#logOut").val(),
"unsettledPopulationCondition.isDeath":$("#isDeath").val()
}
}
}
$("#unsettledPopulationList").setGridParam({
url:PATH+'/baseinfo/unsettledPopulationSearch/searchUnsettledPopulation.action',
datatype: "json",
page:1
});
$("#unsettledPopulationList").setPostData(initParam);
$("#unsettledPopulationList").trigger("reloadGrid");
}
function getSelectedIds(){
var selectedIds = $("#unsettledPopulationList").jqGrid("getGridParam", "selarrrow");
return selectedIds;
}
function getSelectedIdLast(){
var selectedId;
var selectedIds = $("#unsettledPopulationList").jqGrid("getGridParam", "selarrrow");
for(var i=0;i<selectedIds.length;i++){
selectedId = selectedIds[i];
}
return selectedId;
}
function getIdCardNo(idCardNo,logOut){
var actualIdCardNo;
if(logOut==1||logOut=='1'){
actualIdCardNo = idCardNo.substring(22).split("</font>")[0];
}else{
actualIdCardNo = idCardNo.substring(19).split("</font>")[0];
}
return actualIdCardNo;
}
function updateIdCardNo(rowId,idCardNo,orgId){
$("#unsettledPopulationDialog").createDialog({
width:320,
height:150,
title:'修改身份证号码',
url:PATH+'/baseinfo/common/commonUpdateIdCardNoDlg.jsp?listTable=unsettledPopulationList&dialog=unsettledPopulationDialog&countrymenId='+rowId+'&orgId='+orgId+'&idCardNo='+idCardNo+'&actualPopulationType='+dfop.actualPopulationType,
buttons: {
"保存" : function(event){
$("#updateIdCardNoForm").submit();
},
"关闭" : function(){
$(this).dialog("close");
}
}
});
}
}
|
import axios from 'util/axios'
const methods = {};
/**
* 查询房源列表
*/
methods.filterHouse = params => axios.post(`web/manager/house/findByWeb`, Object.assign({
name: '',
page: 0,
pageSize: 5
}, params));
/**
* 添加房源项目
*/
methods.addHouseProject = params => axios.post(`web/manager/addDevelopersAudit`, Object.assign({
developersId: '',
houseName: '',
houseId: '',
cityId: '1'
}, params));
/**
* 删除房源项目
*/
methods.deleteHouseProject = aid => axios.get(`web/manager/deleteDevelopersAudit/${aid}`);
/**
* 查询房源项目
*/
methods.queryHouseProject = (mid, cityId = -1) => axios.post(`web/manager/findDevelopersAudit/${mid}/${cityId}`);
/**
* 查询已添加的房源项目id列表
*/
methods.queryMyProjectId = mid => axios.get(`web/manager/findDevelopershouseIDbyhDID/${mid}`);
/**
* 最近开盘数
*/
methods.queryNewKPCounts = () => axios.get(`web/manager/house/findNewKPCounts`);
export default methods
|
function Lpersegi() {
let a, Lp
a=Number(document.formscript.asisi.value);
Lp = a * a;
document.formscript.luaspersegi.value=Lp
}
function Kpersegi() {
let K, b
b=Number(document.formscript.bsisi.value);
K = 4 * b;
document.formscript.kelilingpersegi.value=K
}
function Lpersegipanjang() {
let L, p, l
p=Number(document.formscript.panjang.value);
l=Number(document.formscript.lebar.value);
L = p * l;
document.formscript.luaspersegipanjang.value=L;
}
|
var ajaxTabSelTabIds = new Hash;
var ajaxTabAjaxStatus = new Hash;
var authenticityToken;
function select_tab(name, tabid, url)
{
var previousTab, currentTab;
if(ajaxTabSelTabIds[name] == undefined)
{
ajaxTabSelTabIds[name] = -1;
}
if(ajaxTabAjaxStatus[name + '_tab_' + tabid] == undefined)
{
ajaxTabAjaxStatus[name + '_tab_' + tabid] = -1;
}
if(ajaxTabSelTabIds[name] != tabid)
{
var previousTab = document.getElementById(name + '_tab_' + ajaxTabSelTabIds[name]);
var currentTab = document.getElementById(name + '_tab_' + tabid);
var previousTabContent = document.getElementById(name + '_content_' + ajaxTabSelTabIds[name]);
var currentTabContent = document.getElementById(name + '_content_' + tabid);
var ajaxtabLoadingImage = document.getElementById(name + "_" + tabid + "_loadingimage");
if(ajaxtabLoadingImage && ajaxTabAjaxStatus[currentTab.id] == -1)
{
loading = document.getElementById(currentTab.id + "_onloading").value;
complete = document.getElementById(currentTab.id + "_oncomplete").value;
success = document.getElementById(currentTab.id + "_onsuccess").value;
failure = document.getElementById(currentTab.id + "_onfailure").value;
if(authenticityToken)
{
new Ajax.Updater(currentTabContent.id, url, {asynchronous:true, evalScripts:true, method:'post', onLoading:function(request){eval(loading)}, onComplete:function(request){eval(complete); if(request.status!=200){} }, onFailure:function(request){eval(failure); ajaxTabAjaxStatus[currentTab.id] = -1;}, onSuccess:function(request){eval(success); ajaxTabAjaxStatus[currentTab.id] = 0;}, parameters:'authenticity_token=' + encodeURIComponent(authenticityToken)});
}
else
{
new Ajax.Updater(currentTabContent.id, url, {asynchronous:true, evalScripts:true, method:'get', onLoading:function(request){eval(loading)}, onComplete:function(request){eval(complete); if(request.status!=200){} }, onFailure:function(request){eval(failure); ajaxTabAjaxStatus[currentTab.id] = -1;}, onSuccess:function(request){eval(success); ajaxTabAjaxStatus[currentTab.id] = 0;}});
}
}
if(previousTab)
{
previousTabOndeselect = document.getElementById(previousTab.id + "_ondeselect");
if(previousTabOndeselect)
{
eval(previousTabOndeselect.value);
}
previousTab.className = name + "_tab ajaxtab_unsel_tab";
previousTabContent.className = name + "_content ajaxtab_unsel_content";
}
if(currentTab)
{
currentTab.className = name + "_tab ajaxtab_sel_tab";
currentTabContent.className = name + "_content ajaxtab_sel_content";
currentTabOnselect = document.getElementById(currentTab.id + "_onselect");
if(currentTabOnselect)
{
eval(currentTabOnselect.value);
}
}
ajaxTabSelTabIds[name] = tabid;
}
}
/*
Author: Harish
Email: p.harish86@gmail.com
Blog: http://harishwords.wordpress.com
*/
|
app.layout.wide = (function(window, document, $, layout, undefined){
layout.query = 'screen and (min-width: 1300px)';
layout.setup = function(){
};
layout.match = function(){
app.is = 'wide';
};
layout.unmatch = function(){
app.was = 'wide';
};
layout.resize = function(){
};
return layout;
})(window, window.document, jQuery, {});
|
import React, { useEffect, useState } from "react";
import InfiniteScroll from "react-infinite-scroll-component";
import Spinner from "./Spinner";
import VideoPanel from "./VideoPanel";
// import InfiniteScroll from "react-infinite-scroll-component";
function Home(props) {
const { apiKey, tag, setProgress, pageSize } = props;
const [urls, setUrls] = useState([]);
const [searchTag, setsearchTag] = useState(tag);
const [result, setResult] = useState(tag);
const [loading, setloading] = useState(false);
const [offset, setoffset] = useState(0);
const [totalResult, settotalResult] = useState(0);
const updateGIFS = async () => {
setloading(true);
setProgress(30);
const endpoint = `https://api.giphy.com/v1/gifs/search?api_key=${apiKey}&q=${searchTag}&limit=${pageSize}&offset=${offset}&rating=g&lang=hi`;
const result = await fetch(endpoint);
setProgress(50);
const parsedData = await result.json();
setProgress(80);
setUrls(urls.concat(parsedData.data));
settotalResult(parsedData.pagination.total_count);
setloading(false);
setProgress(100);
setoffset(offset + pageSize);
};
const fetchGIF = async () => {
setloading(true);
setProgress(30);
const endpoint = `https://api.giphy.com/v1/gifs/search?api_key=${apiKey}&q=${searchTag}&limit=${pageSize}&offset=${offset}&rating=g&lang=hi`;
const result = await fetch(endpoint);
setProgress(50);
const parsedData = await result.json();
setProgress(80);
setUrls(parsedData.data);
settotalResult(parsedData.pagination.total_count);
setloading(false);
setProgress(100);
setoffset(offset + pageSize);
};
useEffect(() => {
updateGIFS();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const handleSearchSubmit = (e) => {
e.preventDefault();
const newResult = [];
setUrls(newResult);
setoffset(0);
console.log(urls);
fetchGIF();
};
const handleSearchInput = (event) => {
const tagValue = event.target.value;
const resultValue = event.target.value;
setResult(resultValue);
setsearchTag(tagValue);
};
return (
<>
<div className="container">
<div className="row mt-3">
<form onSubmit={handleSearchSubmit}>
<div className="input-group mb-3">
<input
className="form-control me-2"
type="search"
placeholder="Search your favourite GIF"
aria-label="Search"
onChange={handleSearchInput}
value={searchTag}
/>
<button className="btn btn-outline-success" type="submit">
Search
</button>
</div>
</form>
</div>
<h1 className="text-center"> Result for {result}</h1>
{loading && <Spinner />}
<InfiniteScroll
dataLength={urls.length}
next={updateGIFS}
hasMore={offset + pageSize < totalResult}
loader={Spinner}
>
<div className="container">
<div className="row">
{urls.map((url) => {
return (
<div className="col-md-4" key={url.id}>
<VideoPanel url={url.images.original.webp} />
</div>
);
})}
</div>
</div>
</InfiniteScroll>
</div>
</>
);
}
export default Home;
|
import React from 'react'
import renderer from 'react-test-renderer'
import { StyleRoot } from '@instacart/radium'
import TextFieldHint from '../TextFieldHint'
it('renders TextFieldHint correctly', () => {
const tree = renderer
.create(
<StyleRoot>
<div>
<TextFieldHint text="Text field hint text" show />
</div>
</StyleRoot>
)
.toJSON()
expect(tree).toMatchSnapshot()
})
it('renders TextFieldHint when show is false', () => {
const tree = renderer
.create(
<StyleRoot>
<div>
<TextFieldHint text="Text field hint text" show={false} />
</div>
</StyleRoot>
)
.toJSON()
expect(tree).toMatchSnapshot()
})
it('renders TextFieldHint when disabled', () => {
const tree = renderer
.create(
<StyleRoot>
<div>
<TextFieldHint text="Text field hint text" show disabled />
</div>
</StyleRoot>
)
.toJSON()
expect(tree).toMatchSnapshot()
})
|
import React, {Component} from 'react';
import EmergencyDetails from './EmergencyDetails';
import { Button, Modal, Header, Form, Dropdown,} from 'semantic-ui-react';
import fire from '../config/Fire';
import _ from 'lodash';
class QueueIncidents extends Component {
constructor(props){
super(props);
this.state = {
open: false,
incidentType: '',
incidentLocation: '',
isResponded: null,
incidentsList : [{
incidentType: '',
incidentLocation: '',
isResponded: ''
}]
}
let app = fire.database().ref('/incidents');
app.on('value', snapshot => {
this.getData(snapshot.val());
})
}
show = size => () => this.setState({ size, open: true })
close = () => this.setState({ open: false })
inputIncidentTypeHandler = (e) => {
this.setState({incidentType: e.target.value});
}
inputIncidentLocationHandler = (e) => {
this.setState({incidentLocation: e.target.value});
}
submitIncidentHandler = (e) => {
e.preventDefault();
let firebaseRef = fire.database().ref('/incidents');
firebaseRef.push({
incidentType: this.state.incidentType,
incidentLocation: this.state.incidentLocation,
responded: false
});
this.setState({
incidentType: '',
incidentLocation: '',
responded: null
});
}
getData = (values) => {
let incidentValues = values;
let incidentsList = _(incidentValues)
.keys()
.map(incidentKey => {
let cloned = _.clone(incidentValues[incidentKey]);
cloned.key = incidentKey;
return cloned;
})
.value();
this.setState({incidentsList: incidentsList});
}
render(){
const { open, size } = this.state
let incidentNodes = this.state.incidentsList.map((incidents, key) => {
return (
<div className='item' key={key}>
<EmergencyDetails
incidentType = {incidents.incidentType}
incidentLocation = {incidents.incidentLocation}
/>
</div>
);
});
return (
<div className="ui visible left vertical sidebar menu">
<div>
<Header>
<Button size="tiny"><Dropdown styles='width:0x;' text='Filter' icon='filter' floating labeled button className='icon'>
<Dropdown.Menu>
<Dropdown.Header icon='tags' content='Filter by incident status' />
<Dropdown.Divider />
<Dropdown.Item icon='attention' text='New' />
<Dropdown.Item icon='comment' text='Responding' />
<Dropdown.Item icon='conversation' text='Settled' />
</Dropdown.Menu>
</Dropdown></Button>
<Button primary onClick={this.show('tiny')}>
Add Incident
</Button>
</Header>
</div>
{incidentNodes}
<Modal size={size} open={open} onClose={this.close}>
<Modal.Header>New Emergency</Modal.Header>
<Modal.Content>
<Form>
<Form.Field>
<label>Type of Incident</label>
<input
name='incidentType'
onChange={this.inputIncidentTypeHandler}
/>
</Form.Field>
<Form.Field>
<label>Incident Location</label>
<input
name='incidentLocation'
onChange={this.inputIncidentLocationHandler}
/>
</Form.Field>
</Form>
</Modal.Content>
<Modal.Actions>
<Button basic color='green' onClick={this.submitIncidentHandler}>
Submit
</Button>
</Modal.Actions>
</Modal>
</div>
);
}
}
export default QueueIncidents;
|
export default class MainControllerComponent extends Engine.Component {
constructor(gameObject) {
super(gameObject);
}
static point;
static tickCounter = 0;
start() {
this.ticks = 0;
this.started = false;
Engine.Lives.start();
Engine.mapMaker.start();
Engine.Score.start();
this.wave1Check = false;
this.wave2Check = false;
this.wave3Check = false;
this.wave4Check = false;
this.wave5Check = false;
this.wave6Check = false;
this.waveNumber = 0;
}
update() {
MainControllerComponent.tickCounter++;
let point;
point = Engine.Input.getMousePosition();
point = Input.getMousePosition();
point.x += (Engine.SceneManager.screenWidth) / 2;
point.x /= 20;
point.y += Engine.SceneManager.screenHeight / 2;
point.y /= 20;
this.ticks++;
if(!this.started){
this.started = true;
this.dotCounterX = 0;
this.dotCounterY = 0;
let bubblesCount = 12;
for (let row = 0; row < bubblesCount; row++) {
for(let col = 0; col < bubblesCount; col++) {
let bubbles = Instantiate(
{
gameObject: {
name: "bubbles", components: [
{ name: "CircleGeometryComponent", args: [2] },
{ name: "DrawGeometryComponent", args: ['rgba(0, 0, 202, 0.41)', 'yellow', .2] },
]
}, drawLayer: "background"
}
)
bubbles.transform.position.x = -10 + this.dotCounterX
bubbles.transform.position.y = 0 + this.dotCounterY
this.dotCounterX += 7;
}
this.dotCounterX = -10 + (row * 2) + -2 + 7;
this.dotCounterY += 6;
}
}
this.waveText = Engine.SceneManager.currentScene.getGameObject("ScreenTextWave").getComponent("ScreenTextComponent")
if(Input.getKey(' ') & !this.wave1Check)
{
this.waveNumber = 1;
this.waveText.string = "Place your Towers!"
this.wave1Check = true;
Engine.waves.startWave1();
}
if(Input.getKey(' ') & this.wave1Check & Engine.waves.wave1Check & !this.wave2Check)
{
this.waveNumber = 2;
this.waveText.string = "Starts off slow :)"
this.wave2Check = true;
Engine.waves.startWave2();
}
if(Input.getKey(' ') & this.wave1Check & Engine.waves.wave1Check & this.wave2Check & Engine.waves.wave2Check & !this.wave3Check)
{
this.waveNumber = 3;
this.waveText.string = "Speeding up a little :)"
this.wave3Check = true;
Engine.waves.startWave3();
}
if(Input.getKey(' ') & this.wave1Check & Engine.waves.wave1Check & this.wave2Check & Engine.waves.wave2Check &
this.wave3Check & Engine.waves.wave3Check & !this.wave4Check)
{
this.waveNumber = 4;
this.waveText.string = "Keep placing Towers!!"
this.wave4Check = true;
Engine.waves.startWave4();
}
if(Input.getKey(' ') & this.wave1Check & Engine.waves.wave1Check & this.wave2Check & Engine.waves.wave2Check &
this.wave3Check & Engine.waves.wave3Check & this.wave4Check & Engine.waves.wave4Check & !this.wave5Check)
{
this.waveNumber = 5;
this.waveText.string = "Beware the next wave!"
this.wave5Check = true;
Engine.waves.startWave5();
}
if(Input.getKey(' ') & this.wave1Check & Engine.waves.wave1Check & this.wave2Check & Engine.waves.wave2Check &
this.wave3Check & Engine.waves.wave3Check & this.wave4Check & Engine.waves.wave4Check &
this.wave5Check & Engine.waves.wave5Check & !this.wave6Check)
{
this.waveNumber = 6;
this.waveText.string = "No chance? :)"
this.wave6Check = true;
Engine.waves.startWave6();
}
Engine.mapMaker.update(point);
Engine.SceneManager.currentScene.getGameObject("ScreenText").getComponent("ScreenTextComponent").
string = "" + Engine.Lives.getLives() + " / " + this.waveNumber + " / " + Engine.Score.getScore()
// if (this.ticks >= 1000) {
if (Input.getKey('Escape')){
Engine.SceneManager.changeScene("StartScene")
Engine.waves.stopWave1();
Engine.waves.stopWave2();
Engine.waves.stopWave3();
Engine.waves.stopWave4();
Engine.waves.stopWave5();
Engine.waves.stopWave6();
}
if(Engine.Lives.getLives() <= 0){
// if(this.ticks >= 10){
Engine.SceneManager.changeScene("GameOverScene")
Engine.waves.stopWave1();
Engine.waves.stopWave2();
Engine.waves.stopWave3();
Engine.waves.stopWave4();
Engine.waves.stopWave5();
Engine.waves.stopWave6();
}
}
}
|
import React, { useState, useContext } from "react";
import ReactModal from "react-modal";
import { Link } from "react-router-dom";
import {CopyToClipboard} from 'react-copy-to-clipboard';
import "./css.css";
import Context from 'components/Context/AppContext';
import deletePost from "components/services/deletePost";
export default function Options(props) {
const [open, setOpen] = useState(false);
const handleCloseModal = () => setOpen(false);
const handleOpenModal = () => setOpen(true);
const {profile} = useContext(Context);
const handleCopyTextOk = () => {
handleCloseModal();
alert('Enlace copiado en el portapapeles.');
}
const delete_post = async () => {
if(window.confirm('Seguro que desea eliminar esta publicación?')){
if(await deletePost(props.id, profile.user))
alert('Publicación eliminada con éxito.');
else alert('Hubo un error al eliminar la publicación');
handleCloseModal();
}
}
ReactModal.setAppElement("#root");
return (
<React.Fragment>
<div className="points" onClick={handleOpenModal}>
<div className="point"></div>
<div className="point"></div>
<div className="point"></div>
</div>
<ReactModal
isOpen={open}
onRequestClose={handleCloseModal}
className="Modal"
overlayClassName="Overlay"
>
<div className="modal">
<a
href={
"https://twitter.com/intent/tweet?text=https%3A%2F%2Fpupimarti.github.io%2Fpupigram%23%2Fposts%2F" +
props.id
}
target="_blank"
rel="noopener noreferrer"
className="action-modal"
>
Compartir
</a>
<CopyToClipboard text={"https://pupimarti.github.io/pupigram/#/posts/"+props.id}
onCopy={handleCopyTextOk}>
<div className="action-modal action-modal-bt">Copiar enlace</div>
</CopyToClipboard>
{props.user === profile.user &&
<div
className="action-modal action-modal-bt"
onClick={delete_post}
>
Eliminar publicación
</div>}
<Link
to={"/posts/" + props.id}
className="action-modal action-modal-bt"
>
Ir a la publicación
</Link>
<div
className="action-modal action-modal-bt"
onClick={handleCloseModal}
>
Cancelar
</div>
</div>
</ReactModal>
</React.Fragment>
);
}
|
'use strict';
var single_element = function(collection){
var even_collection = collection.filter(function(element, index) {
return index % 2;
});
var len = even_collection.length;
var result = [];
for(var i =0; i < len; i ++){
for(var j = 0; j < len; j ++){
if(even_collection[i] == even_collection[j] && j != i){
break;
}
if( j == len - 1 ){
result.push(even_collection[i]);
}
}
}
return result;
};
module.exports = single_element;
|
const selectors = {
body: document.querySelector("body"),
container: document.querySelector(".container"),
base: document.querySelector(".baseContainer"),
busp: document.querySelector(".buspContainer"),
cust: document.querySelector(".custContainer"),
store: document.querySelector(".storeContainer"),
baseCover: document.querySelector(".baseCover"),
buspCover: document.querySelector(".buspCover"),
};
let isDown = false;
selectors.body.addEventListener("mousemove", function(event) {
if (isDown === true) {
const midX = event.pageX - window.innerWidth / 2;
const midY = event.pageY - window.innerHeight / 2;
const distance = Math.sqrt( (Math.pow(Math.abs(midX),2)) + (Math.pow(Math.abs(midY),2)));
const opacity = distance / 400;
transform(midX, midY, distance);
opacityAdjustment(opacity);
}
});
selectors.container.addEventListener("mousedown", function() {
isDown = true;
});
selectors.body.addEventListener("mouseup", function() {
isDown = false;
});
selectors.body.addEventListener("mouseleave", function() {
isDown = false;
})
function transform(midX, midY, distance){
selectors.container.style.transform = "rotateX(" + (midY * .5) + "deg) rotateY(" + (midX * .5) + "deg)"
if (distance < 250) {
selectors.base.style.transform = "translateZ(" + (distance * -3) + "px)"
selectors.busp.style.transform = "translateZ(" + (distance * -1) + "px)"
selectors.cust.style.transform = "translateZ(" + (distance) + "px)"
selectors.store.style.transform = "translateZ(" + (distance * 3) + "px)"
} else {
selectors.base.style.transform = "translateZ(" + -750 + "px)"
selectors.busp.style.transform = "translateZ(" + -250 + "px)"
selectors.cust.style.transform = "translateZ(" + 250 + "px)"
selectors.store.style.transform = "translateZ(" + 750 + "px)"
}
};
function opacityAdjustment(opacity) {
if (opacity < .5) {
selectors.baseCover.style.opacity = 1 - opacity
selectors.buspCover.style.opacity = 1 - opacity
} else {
selectors.baseCover.style.opacity = .5
selectors.buspCover.style.opacity = .5
}
};
|
export const SelectedNode = {
add: '',
edit: '',
delete: '',
selectedNode: '',
categoryType: '',
selectedItem: '',
selectedNodeIndex: ''
}
|
import BusConstructor from '@/js/BusConstructor'
export default new BusConstructor()
|
$(document).ready(function() {
// load all images in 2 Arrays
//first array
var images = [];
for(var i = 0; i < 32; i++) {
if(i < 10) {
images.push('#0'+i);
} else {
images.push('#'+i);
}
}
//second array
var images2 = [];
for(var i = 31; i < 51; i++) {
images2.push('#'+i);
}
//debug
console.log(images + images2);
// Get Screensize
var viewportWidth = $(window).width();
var viewportHeight = $(window).height();
// init Scroll Magic
var ctrl = new ScrollMagic.Controller();
// images animation No.1
var obj = {curImg: 0};
// create tween
var tween1 = TweenMax.to(obj, 0.5,
{
curImg: images.length - 1, // stop @ image No. 31
roundProps: "curImg", // only integers so it can be used as an array index
repeat: 0, // no repeat
immediateRender: true, // load first image automatically
ease: Linear.easeNone, // show every image the same ammount of time
onUpdate: function () {
$("#boxImg").attr("xlink:href", images[obj.curImg])
}
}
);
var xValue1 = "-128";
var xValue2 = "-62";
var xValue3 = 0;
var xValue4 = "75";
if(viewportWidth >= 960) {
xValue1 = "-250";
xValue2 = "-125";
xValue3 = "5";
xValue4 = "0";
}
var tween2 = TweenMax.from('.ballons', 1.7, {
x: "-50%",
y: "0%",
// width: "125px",
ease: Sine.easeIn
// ease: Linear.easeOut
});
var tween21 = TweenMax.from('.facebook', .7, {
x: "-50%",
y: "50%",
ease: Sine.easeIn
// ease: Linear.easeOut
});
var tween22 = TweenMax.from('.instagram', 1.7, {
x: "-50%",
y: "50%",
ease: Sine.easeIn
// ease: Linear.easeOut
});
var tween23 = TweenMax.from('.youtube', .5, {
x: "-50%",
y: "50%",
ease: Sine.easeIn
// ease: Linear.easeOut
});
var tween24 = TweenMax.from('.soundcloud', 1.3, {
x: "-50%",
y: "50%",
ease: Sine.easeIn
// ease: Linear.easeOut
});
// var tween21 = TweenMax.fromTo('.facebook', 0.3, {
// // From
// // left: "-20px",
// x: 50,
// y: 50,
// // ease: Linear.easeOut
// },
// {
// //To
// x: xValue1,
// y: "50px",
// });
// var tween22 = TweenLite.to('.instagram', 0.3, {
// x: xValue2,
// y:"40px",
// ease: Linear.easeOut
// });
// var tween23 = TweenLite.to('.youtube', 0.3, {
// x: xValue3,
// y:"8px",
// ease: Linear.easeOut
// });
// var tween24 = TweenLite.to('.soundcloud', 0.3, {
// x: xValue4,
// y:"43px",
// ease: Linear.easeOut
// });
var showArrow = TweenLite.to('#arrow', 0.3, {
opacity: 1,
ease: Linear.easeOut
});
var hideArrow = TweenLite.to('#arrow', 0.3, {
opacity: 0,
ease: Linear.easeOut
});
var obj2 = {curImg2: 0};
var tween3 = TweenMax.to(obj2, 0.5,
{
curImg2: images2.length - 1, // STOP IMAGE 50!!!!
roundProps: "curImg2", // only integers so it can be used as an array index
repeat: 0, // no repeat
immediateRender: false, // load first image automatically
ease: Linear.easeNone, // show every image the same ammount of time
onUpdate: function () {
$("#boxImg").attr("xlink:href", images2[obj2.curImg2])
}
}
);
var bottomSize = "135px";
if(viewportWidth > 960) {
bottomSize = "40px";
}
var tween4 = TweenLite.to('.buttons', 0.3, {
bottom: bottomSize,
y: 0,
scale: 1,
ease: Linear.easeOut
});
// build scene
var scene = new ScrollMagic.Scene({triggerElement: "#one", duration: 3000, offset: 600})
.setTween(tween1)
.addIndicators({
name: 'Box Scene',
colorTrigger: 'black',
indent: 200
}) // add indicators (requires plugin)
.addTo(ctrl);
var scene2 = new ScrollMagic.Scene({triggerElement: "#two", duration: 1500, offset: 0})
.setTween(tween2)
// .setTween(ballonsTween)
.addIndicators({
name: 'Ballons Scene',
colorTrigger: 'black',
indent: 200
}) // add indicators (requires plugin)
.addTo(ctrl);
var scene21 = new ScrollMagic.Scene({triggerElement: "#two"})
.setClassToggle("#ballons", "fix")
.addTo(ctrl);
var scene22 = new ScrollMagic.Scene({triggerElement: "#two", duration: 1500, offset: 0})
.setTween(tween21)
.addTo(ctrl);
var scene23 = new ScrollMagic.Scene({triggerElement: "#two", duration: 1500, offset: 0})
.setTween(tween22)
.addTo(ctrl);
var scene24 = new ScrollMagic.Scene({triggerElement: "#two", duration: 1500, offset: 0})
.setTween(tween23)
.addTo(ctrl);
var scene25 = new ScrollMagic.Scene({triggerElement: "#two", duration: 1500, offset: 0})
.setTween(tween24)
.addTo(ctrl);
var scene3 = new ScrollMagic.Scene({triggerElement: "#four", duration: 1500, offset: 0})
.setTween(tween3)
.addIndicators({
name: 'Turn Box Scene',
colorTrigger: 'black',
indent: 200
}) // add indicators (requires plugin)
.addTo(ctrl);
var showArrowScene = new ScrollMagic.Scene({triggerElement: "#three", offset: 1000})
.setTween(showArrow)
.addTo(ctrl);
var scene4 = new ScrollMagic.Scene({triggerElement: "#four", duration: 1500, offset: 1500})
.setTween(tween4)
.addIndicators({
name: 'Button Scene',
colorTrigger: 'black',
indent: 200
}) // add indicators (requires plugin)
.addTo(ctrl);
var scene41 = new ScrollMagic.Scene({triggerElement: "#five", offset: 800})
// .setClassToggle("#three", "fix")
.setClassToggle("#buttons", "fix")
.addTo(ctrl);
var scene5 = new ScrollMagic.Scene({triggerElement: "#five", duration: 1500, offset: 1000})
.setClassToggle("#navigation", "fix")
.addIndicators({
name: 'Nav Scene',
colorTrigger: 'black',
indent: 200
}) // add indicators (requires plugin)
.addTo(ctrl);
var hideArrowScene = new ScrollMagic.Scene({triggerElement: "#five", offset: 0})
.setTween(hideArrow)
.addTo(ctrl);
//Scroll Detection
//Firefox
$(window).bind('DOMMouseScroll', function(e){
if(e.originalEvent.detail > 0) {
//scroll down
console.log('Down');
}else {
//scroll up
console.log('Up');
}
return true;
});
// IE, Opera, Safari
$(window).bind('mousewheel', function(e){
var lastScrollDirection = "";
if(e.originalEvent.wheelDelta < 0) {
//scroll down
if(lastScrollDirection == "" || lastScrollDirection == "up") {
if($(document).scrollTop() < scene3.scrollOffset()) {
speedPerPixel = (3 / scene3.scrollOffset()) * (scene3.scrollOffset() - $(document).scrollTop());
TweenLite.to(window, speedPerPixel, {scrollTo: {y:scene3.scrollOffset(), autoKill:false}});
console.log("Scroll Speed: " + speedPerPixel);
}
if($(document).scrollTop() >= scene3.scrollOffset()) {
speedPerPixel = (3 / (($(document).height() - viewportHeight) - scene3.scrollOffset())) * (((($(document).height() - viewportHeight) - scene3.scrollOffset()) - $(document).scrollTop()) * -1);
TweenLite.to(window, speedPerPixel, {scrollTo: {y:($(document).height() - viewportHeight), autoKill:false}});
console.log("Scroll Speed2: " + speedPerPixel);
console.log("Rechnung: " + ((($(document).height() - viewportHeight) - scene3.scrollOffset()) - $(document).scrollTop()));
}
console.log('Down1');
lastScrollDirection = "down";
}
}else {
//scroll up
if(lastScrollDirection == "" || lastScrollDirection == "down") {
if($(document).scrollTop() > scene3.scrollOffset()) {
TweenLite.to(window, 3, {scrollTo: {y:scene3.scrollOffset(), autoKill:false}});
}
if($(document).scrollTop() <= scene3.scrollOffset()) {
TweenLite.to(window, 3, {scrollTo: {y:0, autoKill:false}});
}
console.log('Up1');
lastScrollDirection = "up";
}
}
return true;
});
//mobile
$(window).on('touchstart', function(e) {
var swipe = e.originalEvent.touches,
start = swipe[0].pageY;
$(this).on('touchmove', function(e) {
var contact = e.originalEvent.touches,
end = contact[0].pageY,
distance = end-start;
if (distance < -20) {
// down;
if($(document).scrollTop() < scene3.scrollOffset()) {
TweenLite.to(window, 3, {scrollTo: {y:scene3.scrollOffset(), autoKill:false}, ease:SteppedEase.config(64)});
}
if($(document).scrollTop() >= scene3.scrollOffset()) {
TweenLite.to(window, 3, {scrollTo: {y:($(document).height() - viewportHeight), autoKill:false}, ease:SteppedEase.config(64)});
}
console.log('Down2');
}
if (distance > 20) {
// up
if($(document).scrollTop() > scene3.scrollOffset()) {
TweenLite.to(window, 3, {scrollTo: {y:scene3.scrollOffset(), autoKill:false}, ease:SteppedEase.config(64)});
}
if($(document).scrollTop() <= scene3.scrollOffset()) {
TweenLite.to(window, 3, {scrollTo: {y:0, autoKill:false}, ease:SteppedEase.config(64)});
}
console.log('Up2')
}
})
.one('touchend', function() {
$(this).off('touchmove touchend');
});
});
$('#arrow').click(
function() {
TweenLite.to(window, 3, {scrollTo: {y:$(document).height(), autoKill:false}, ease:SteppedEase.config(64)});
}
);
$(window).load(function() {
//Vorhang auf
$('body').addClass('loaded');
//Animated Scroll Scene 1
//if current scroll positon is smaller than the scrollOffset
if($(document).scrollTop() < scene3.scrollOffset()) {
TweenLite.to(window, 3, {scrollTo: {y:scene3.scrollOffset(), autoKill:false}, ease:SteppedEase.config(64), delay:1});
}
//debug
console.log('Current ScrollPosition: ' + $(document).scrollTop());
console.log('Scene3Position: ' + scene3.scrollOffset());
});
});
|
export const makeGrid = ({ rows, cols }) => {
const grid = [];
let plusOrMinusOrZero,
seed = Math.floor(Math.random() * cols);
for (let i = 0; i < rows; i++) {
let row = Array(cols).fill(1);
let random = Math.random();
if (random < 0.33) {
plusOrMinusOrZero = -1;
} else if (random > 0.33 && random < 0.66) {
plusOrMinusOrZero = 0;
} else if (random > 0.66 && random < 0.99) {
plusOrMinusOrZero = 1;
}
if (i === 0) {
row[seed] = 0;
grid.push(row);
} else {
seed += plusOrMinusOrZero;
if (seed > cols - 1) {
let backOneOrTwo = Math.random() > 0.55 ? -1 : -2;
seed += backOneOrTwo;
} else if (seed < 0) {
let nextOneOrTwo = Math.random() > 0.55 ? 1 : 2;
seed += nextOneOrTwo;
}
row[seed] = 0;
grid.push(row);
}
}
console.log(grid);
return grid;
};
|
import React, { Component } from 'react';
import logo from './logo.svg';
import './markdown.scss';
const marked = require("marked");
marked.setOptions({
breaks: true,
});
class MarkdownViewer extends Component {
constructor(props) {
super(props);
this.state = {
markdown: placeholder
}
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({
markdown: event.target.value
})
}
render() {
return (
<div className="MarkdownPreviewer">
<header className="Header">Editor</header>
<div className="Editor-div">
<textarea id="editor" value={this.state.markdown} onChange={this.handleChange}>
I am a text editor!
</textarea>
</div>
<header className="Header">Preview</header>
<div className="Preview-div">
<div id="preview" dangerouslySetInnerHTML = {{__html: marked(this.state.markdown)}} />
</div>
</div>
);
}
}
const placeholder =
`# This is a header.
## This is a sub-header.
This is some __bold__ text.
[This is a link to an awesome site.](https://stefanhk31.github.io/)
This is some code: \`function()\`
This is a code block:
\`\`\`python
str = "Hi, I'm Python!"
print str
\`\`\`
1. Here is a list.
2. It has multiple items.
> This is a block quote,
it continues on to the next line.
I made this with React. 
`
export default MarkdownViewer;
|
console.log('start');
setTimeout(() => {
console.log('setTimeout'); // 宏任务执行顺序比微任务靠后
}, 0);
Promise.resolve()
.then(()=>{
console.log('pp1'); // 微任务先执行
})
.then(()=>{
console.log('pp2');
})
.then(()=>{
console.log('pp3');
})
console.log('end');
|
import httpStatus from 'http-status';
import config from '../../config/env';
export default (err, req, res, next) => { // eslint-disable-line no-unused-vars
res.status(err.status).json({
message: err.isPublic ? err.message : httpStatus[err.status],
stack: config.appConfig.env === 'development' ? err.stack : {},
});
};
|
import { expect } from 'chai';
import { stub, match, assert, spy } from 'sinon';
import proxyquire from 'proxyquire';
export class Base {
constructor(args, jsonConfig, supportConfig, names) {
this.args = args;
this.config = jsonConfig;
this.support = supportConfig;
this.names = names;
this._super = {
install: stub().returns(Promise.resolve())
}
this.install = this._super.install;
}
get buildAssets() { return []; }
get generatedAssets() { return []; }
}
|
/*
POST /app/adduser -> add a new user in the system
GET /logout -> log the user out of the system
*/
const express = require('express');
const router = express.Router();
const passport = require ('passport');
const LocalStrategy = require ('passport-local').Strategy;
const User = require('./../server/models/user.js');
/*
POST /app/adduser -> add a new user in the system
*/
router.post('/app/adduser', (req, res) => {
var username = req.body.username;
var password = req.body.password;
// validation
req.checkBody('username', 'Username is required').notEmpty();
req.checkBody('password', 'Password is required').notEmpty();
// if there are errors, flash messages on the screen
var errors = req.validationErrors();
if(errors) {
res.status(400).redirect('systemsettings');
} else {
// if everything is OK, create a new user in the database
var newUser = new User({
username,
password
});
User.createUser(newUser, function(err, user) {
if (err) {
console.log(err);
return ;
}
});
req.flash('success_msg', 'User succesfully created');
res.status(200).redirect('/app/systemsettings');
}
});
/*
GET /app/logout -> function to logout from the system
*/
router.get('/app/logout', function(req, res) {
req.logout();
req.flash('success_msg', 'You are logged out');
res.status(200).redirect('/');
});
module.exports = router;
|
// @flow
import {StyleSheet, PixelRatio} from 'react-native';
import {SCENE_DEFAULT, THEME_COLOR} from '../../../constants/colors';
import {FONT_BOLD, DEFAULT_FONT_SIZE} from '../../../constants/text';
export const CONTAINER_BORDER_RADIUS = 5;
const styles = StyleSheet.create({
root: {
flex: 1,
},
tabBarContainer: {
justifyContent: 'center',
alignItems: 'center',
paddingVertical: 7,
},
tabBar: {
width: 250,
height: PixelRatio.roundToNearestPixel(35),
backgroundColor: 'white',
borderRadius: CONTAINER_BORDER_RADIUS,
},
tabTextActive: {
fontWeight: FONT_BOLD,
color: 'white',
fontSize: DEFAULT_FONT_SIZE,
},
tabTextDefault: {
fontWeight: FONT_BOLD,
color: THEME_COLOR,
fontSize: DEFAULT_FONT_SIZE,
},
searchContainer: {
backgroundColor: 'white',
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
},
listContainer: {
flex: 6,
backgroundColor: SCENE_DEFAULT,
},
searchTextInputContainer: {
flex: 1,
height: 40,
},
searchTextInput: {
fontSize: DEFAULT_FONT_SIZE,
},
});
export default styles;
|
import User from "../models/User";
import UserProfile from "../models/UserProfile";
import { sign } from "../helpers/jwt";
const createUserProfile = (user) => {
const userProfile = new UserProfile();
userProfile.user = user;
userProfile.save();
};
export default {
register(req, res) {
const user = new User();
user.email = req.body.email;
user.password = req.body.password;
user.name = req.body.name;
res.statusCode = 400;
if (req.body.email == null || req.body.email === ""
|| req.body.password == null || req.body.password === ""
|| req.body.name == null || req.body.name === "") {
res.json({ success: false, message: "Values missing." });
} else {
user.save((err) => {
if (err) {
res.json({ success: false, message: err.message });
} else {
const token = sign(user.email, user.id);
createUserProfile(user);
res.statusCode = 201;
res.json({ success: true, message: "User Successfully created.", token });
}
});
}
},
login(req, res) {
User.findOne({ email: req.body.email })
.exec((err, user) => {
res.statusCode = 401;
if (err) {
throw err;
} else if (!user) {
res.json({ success: false, message: "Failed to authenticate." });
} else if (user && req.body.password) {
const validPassword = user.comparePassword(req.body.password);
if (!validPassword) {
res.json({ success: false, message: "Password invalid." });
} else {
const token = sign(user.email, user.id);
res.statusCode = 200;
res.json({
success: true,
message: "Password valid.",
token,
user: user.getUserDetails(),
});
}
} else {
res.json({ success: false, message: "Fields missing." });
}
});
},
users(req, res) {
User.find({})
.exec((err, users) => {
res.statusCode = 401;
if (err) {
throw err;
} else {
res.json(users);
}
});
},
};
|
$(document).ready(function(){
$('#agree').change(function(){
var isChecked = $('#agree').is(':checked');
if (isChecked){
$('#continue').removeAttr('disabled');
} else {
$('#continue').attr('disabled', 'disabled');
}
});
});
|
/*
class Human {
constructor(name, lastName, age) {
if (isNaN(age) || typeof age !== "number") {
throw new TypeError("Age must be number");
}
if (age < 0) {
throw new RangeError("Age must be positive number");
}
this.name = name;
this.lastName = lastName;
this._age = age;
}
get age() {
return this._age;
}
set age(newAge) {
if (isNaN(newAge) || typeof newAge !== "number") {
throw new TypeError("Age must be number");
}
if (newAge < 0) {
throw new RangeError("Age must be positive number");
}
this._age = newAge;
}
}
const human1 = new Human("Test", "Testovich", 22);
class Car {
constructor(weight, Speed, maxSpeed, name) {
this.weight = weight;
this.Speed = Speed;
this.maxSpeed = maxSpeed;
this.name = name;
}
get weight() {
return this._weight;
}
set weight(newWeight) {
if (isNaN(newWeight) || typeof newWeight !== "number") {
throw new TypeError("Weight must be number");
}
if (newWeight < 0) {
throw new RangeError("Weight must be positive number");
}
this._weight = newWeight;
}
/////////////
get Speed() {
return this._Speed;
}
set Speed(newSpeed) {
if (isNaN(newSpeed) || typeof newSpeed !== "number") {
throw new TypeError("Speed must be number");
}
if (newSpeed < 0) {
throw new RangeError("Speed must be positive number");
}
this._Speed = newSpeed;
}
///////////////
get maxSpeed() {
return this._maxSpeed;
}
set maxSpeed(newMaxSpeed) {
if (isNaN(newMaxSpeed) || typeof newMaxSpeed !== "number") {
throw new TypeError("MaxSpeed must be number");
}
if (newMaxSpeed < 0) {
throw new RangeError("MaxSpeed must be positive number");
}
this._maxSpeed = newMaxSpeed;
}
get name() {
return this._name;
}
set name(newName) {
if (newName.trim() === "" || typeof newName !== "string") {
throw new TypeError("Invilid type Name");
}
return (this._name = newName.trim());
}
}
const cars = new Car(25, 150, 100, "lexus");
const cars2 = new Car(55, 330, 122, "mers");
const cars3 = new Car(11, 220, 33, " ff dsd ");*/
const thread = [];
class User {
constructor(name, lastName, age) {
this.name = name;
this.lastName = lastName;
this.age = age;
this.isBanned = false;
}
getFullName() {
return `${this.name} ${this.lastName}`;
}
createMessage(message) {
thread.push(message);
return message;
}
}
class Moderator extends User {
constructor(name,lastName,age,permissions){
super(name,lastName,age);
this.permissions = permissions;
}
deleteMessage(messageId) {
thread.pop();
}
betterDeleteMessage(messageId) {
thread = thread.filter((message, i) => {
return messageId !== i;
});
}
}
class Admin extends Moderator {
constructor(name, lastName, age, email,permissions) {
super(name,lastName,age,permissions);
this.email = email;
}
ban(user) {
user.isBanned = true;
}
}
const u1 = new User("Test", "tsts", 33);
const moder = new Moderator("oleg", "pavel", 22,{});
const admin = new Moderator("Feofam", "Semenovich", 25,
{canDeleteUsers:true,canDeleteMessage: true}, "semen456@gmail.com");
|
/**
* @format
* @flow
*/
import { NavigationContainer } from '@react-navigation/native';
import React from 'react';
import { connect } from 'react-redux';
import AuthStack from './AuthStack';
import MainStack from './MainStack';
import { navigationRef } from './RootNavigation';
import ModalLoading from '@components/ModalLoading';
function AppContainer({ userToken, isUserGuest }) {
return (
<NavigationContainer ref={navigationRef}>
{!userToken && !isUserGuest ? <AuthStack /> : <MainStack />}
<ModalLoading />
</NavigationContainer>
);
}
const mapStateToProps = (state, ownProps) => {
return {
userToken: state.auth.userToken,
isUserGuest: state.auth.isUserGuest,
};
};
export default connect(mapStateToProps)(AppContainer);
|
import Navbar from './components/Navbar';
import Home from './components/Home';
import { GalleryView as Gallery } from './components/GalleryView'
import Footer from './components/Footer'
export {
Navbar,
Home,
Gallery,
Footer
};
|
export default function OrderApprove() {
return <div>Conteúdo aprovação</div>;
}
|
{
"greetings": {
"cheers": "건배",
"hello": "안녕하세요.",
"bye": "안녕"
},
"menu": {
"file": {
"_root": "파일",
"new": "새로운",
"open": "열린",
"save": "저장",
"exit": "출구"
},
"edit": {
"_root": "편집",
"cut": "절단",
"copy": "부",
"paste": "풀",
"find": "발견",
"replace": "교체"
},
"format": {
"_root": "체재",
"bold": "대담한",
"italic": "이탤릭체",
"underline": "밑줄"
}
}
}
|
var advertStorrage = require("persistance/advertisements");
var spromise = require("spromise");
var ready = spromise.when(advertStorrage.ready);
var adName;
this.getName = function(){
return adName;
};
this.setName = function(newName){
adName = newName;
};
this.getID = function(){
return 1;
};
function advertisement() {
this.initialize();
var adName;
}
function initialize(options) {
options = options || {};
this.active = {};
this.ready = ready;
}
function insert_advertisement(name) {
return spromise(function(resolve){
var _msg = {
"advertisementName": name
};
advertStorrage.insert(_msg);
resolve();
});
}
function new_ad(data) {
insert_advertisement(data);
return;
}
function id() {
return this.getID();
}
function advertisementList() {
return spromise(function(resolve){
var query = {};
advertStorrage.find(query, function(err, advertStorrage) {
resolve(advertStorrage);
});
});
}
module.exports.initialize = initialize;
module.exports.new_ad = new_ad;
module.exports.id = this.getID;
module.exports.name = this.getName;
module.exports.adList = advertisementList;
|
import React from "react";
import { makeStyles, Paper } from "@material-ui/core/";
import { PhotoCamera } from "@material-ui/icons/";
import Navigation from "../components/Navigation";
import { grey, pink } from "@material-ui/core/colors";
import ImageUploader from "react-images-upload";
const useStyles = makeStyles(theme => ({
pageContainer: {
padding: theme.spacing(2, 2, 0),
background:
"linear-gradient(4deg, rgba(255,137,96,1) 0%, rgba(255,98,165,1) 100%);",
height: `calc(100vh)`
},
gridContainer: {
justifyContent: "center"
},
pageTitle: {
color: "#fff",
textAlign: "center"
},
paper: {
padding: theme.spacing(3),
maxWidth: "500px",
margin: `0 auto 24px`,
},
header: {
marginBottom: 0,
color: "#fff",
marginBottom: theme.spacing(2),
textAlign: "center",
}
}));
function Dashboard() {
const classes = useStyles();
return (
<>
<div className={classes.pageContainer}>
<h1 className={classes.header}>Dashboard</h1>
<Paper spacing={3} elevation={3} className={classes.paper}>
<h1>Mitch Budreski</h1>
<p>Has joined!</p>
</Paper>
<Paper spacing={3} elevation={3} className={classes.paper}>
<h1>Shimmy</h1>
<p>Sent you a message: "Hello there"</p>
</Paper>
</div>
</>
);
}
export default Dashboard;
|
export const SHOW_LIST = "SHOW_LIST";
export const EDIT_ELEMENT = "EDIT_ELEMENT";
export const SAVE_ENTITY_SUCCESS = "SAVE_ENTITY_SUCCESS";
export const DELETE_ENTITY_STARTED = "DELETE_ENTITY_STARTED";
export const DELETE_ENTITY_SUCCESS = "DELETE_ENTITY_SUCCESS";
export const DELETE_ENTITY_FAIL = "DELETE_ENTITY_FAIL";
export const CLONE_ENTITY_STARTED = "CLONE_ENTITY_STARTED";
export const CLONE_ENTITY_SUCCESS = "CLONE_ENTITY_SUCCESS";
export const CLONE_ENTITY_FAIL = "CLONE_ENTITY_FAIL";
export const ADD_CHILD_STARTED = "ADD_CHILD_STARTED";
export const ADD_CHILD_SUCCESS = "ADD_CHILD_SUCCESS";
export const ADD_CHILD_FAIL = "ADD_CHILD_FAIL";
const initialState =
{
showEditForm: false,
listForm: () => null,
editForm: () => null
};
const reducer = ( state = initialState, action ) =>
{
switch( action.type )
{
case SHOW_LIST:
return (
{
...state,
showEditForm: false,
listForm: action.payload.listForm
} );
case EDIT_ELEMENT:
return (
{
...state,
showEditForm: true,
editForm: action.payload.editForm
} );
case SAVE_ENTITY_SUCCESS:
if( action.payload.error === true )
return state;
else
return (
{
...state,
showEditForm: false
} );
default:
return state;
}
};
export default reducer;
|
"use strict";
let elems = document.querySelectorAll('.carousel');
let options = {
fullWidth: true,
indicators: true
};
let instances = M.Carousel.init(elems, options);
|
import React from 'react'
const under = () => {
return (
<div>
Under Construction
</div>
)
}
export default under
|
import React, { useEffect } from 'react';
import clsx from 'clsx';
import styles from './_register.module.scss';
import Button from 'components/UI/Button';
import { useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Link, useHistory } from 'react-router-dom';
import { Spin } from 'antd';
import * as yup from 'yup';
import Checkbox from 'components/UI/Checkbox';
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import { PHONE_REGEX } from 'utils/consts';
import { clearState, signup, userSelector } from 'store/slices/userSlice';
import { openNotification } from 'utils/notifications';
import { Select } from 'antd';
import PreloadSpinner from '../../components/UI/PreloadSpinner';
const { Option } = Select;
let schema = yup.object({
company_name: yup.string().required('Это обязательное поле'),
company_bin: yup.number().required('Это обязательное поле').typeError('Только цифры'),
bank_details: yup.number().required('Это обязательное поле').typeError('Только цифры'),
email: yup.string().required('Это обязательное поле').email('Введите email в корректном формате'),
phone_number: yup
.string()
.required('Это обязательное поле')
.min(12, 'Номер телефон должен быть больше 12-ти символов')
.matches(PHONE_REGEX, 'Введите корректный номер телефона в формате +996'),
password: yup.string().required('Введите пароль').min(6, 'Пароль должен содержать больше 6-ти символов'),
password_confirm: yup
.string()
.required('Введите подтверждение пароля')
.oneOf([yup.ref('password'), null], 'Пароли не совпадают'),
});
const CompanyRegister = () => {
const {
register,
handleSubmit,
formState: { errors },
} = useForm({ resolver: yupResolver(schema) });
const { isLoading, isSuccess, errorMessage, isError } = useSelector(userSelector);
const [isChecked, setChecked] = useState(false);
const [validate, setValidate] = useState(false);
const [validateBin, setValidateBin] = useState(false);
const [bank_choice, setBankChoice] = useState('kaspi');
const [DOMLoading, setDOMLoading] = useState(true);
const dispatch = useDispatch();
const history = useHistory();
const onSubmit = async (data) => {
if (!isChecked) {
setValidate(true);
return;
}
if (!bank_choice) {
return;
}
dispatch(signup({ ...data, bank_choice }));
};
const handleValidate = (value) => {
setChecked(value);
setValidate(!value);
};
const handleChange = (value) => {
setBankChoice(value);
};
useEffect(() => {
const handleDOMLoaded = () => {
console.log('worked');
setDOMLoading(false);
};
if (DOMLoading) {
window.addEventListener('load', handleDOMLoaded);
} else {
window.removeEventListener('load', handleDOMLoaded);
}
console.log('use effect');
return () => {
window.removeEventListener('load', handleDOMLoaded);
setDOMLoading(true);
};
}, []);
useEffect(() => {
if (isError) {
openNotification('error', errorMessage, 10);
console.log('from company register page');
dispatch(clearState());
}
if (isSuccess) {
dispatch(clearState());
openNotification('success', 'На вашу почту отправлено письмо с активацией аккаунта');
history.push('/');
}
}, [isSuccess, isError]);
return (
<div className={styles.register}>
{/* {DOMLoading && (
<PreloadSpinner/>
)} */}
<div className={styles.register_left_banner} />
<div className={styles.register_right_column}>
<form className={styles.register_form} onSubmit={handleSubmit(onSubmit)}>
<h1 className={styles.register_title}>Создать учетную запись</h1>
<div className={styles.register_subtitle}>
<Link to="/register">
<span> или создать личную учетную запись</span>
</Link>
</div>
<div className={styles.flex}>
<div className={styles.column}>
<div className={styles.input_item}>
<div className={styles.register_email_label}>Юридическое название организации</div>
<input
className={clsx({
[styles.input]: true,
[styles.error]: errors.company_name,
})}
type="text"
autoComplete="false"
{...register('company_name')}
/>
<p className={styles.validate_error}>{errors.company_name?.message}</p>
</div>
<div className={styles.input_item}>
<div className={styles.register_email_label}>Юридический электронный адрес организации</div>
<input
className={clsx({
[styles.input]: true,
[styles.error]: errors.email,
})}
type="text"
autoComplete="false"
{...register('email')}
/>
<p className={styles.validate_error}>{errors.email?.message}</p>
</div>
<div className={styles.input_item}>
<div className={styles.register_email_label}>БИН</div>
<input
className={clsx({
[styles.input]: true,
[styles.error]: errors.company_bin,
})}
type="text"
autoComplete="false"
{...register('company_bin')}
/>
<p className={styles.validate_error}>{errors.company_bin?.message}</p>
</div>
<div className={styles.input_item}>
<div className={styles.register_email_label}>Банковские реквизиты</div>
<input
className={clsx({
[styles.input]: true,
[styles.error]: errors.bank_details,
})}
type="text"
autoComplete="false"
{...register('bank_details')}
/>
<p className={styles.validate_error}>{errors.bank_details?.message}</p>
</div>
</div>
<div className={styles.column}>
<div className={styles.input_item}>
<div className={styles.register_email_label}>Юридический номер телефона организации</div>
<input
className={clsx({
[styles.input]: true,
[styles.error]: errors.phone_number,
})}
type="text"
{...register('phone_number')}
/>
<p className={styles.validate_error}>{errors.phone_number?.message}</p>
</div>
<div className={styles.input_item}>
<div className={styles.register_email_label}>Банк</div>
<div className="selector">
<Select style={{ width: '100%', height: '40px' }} value={bank_choice} onChange={handleChange}>
<Option value="kaspi">Каспи</Option>
</Select>
</div>
{validateBin || (!bank_choice && <p className={styles.validate_error}>Необходимо выбрать банк</p>)}
</div>
<div className={styles.input_item}>
<div className={styles.register_password_label}>
<span>Пароль</span>
</div>
<input
className={clsx({
[styles.input]: true,
[styles.error]: errors.password,
})}
placeholder="6+ симоволов и знаков"
type="password"
{...register('password')}
/>
<p className={styles.validate_error}>{errors.password?.message}</p>
</div>
<div className={styles.input_item}>
<div className={styles.register_password_label}>
<span>Потвердите пароль</span>
</div>
<input
className={clsx({
[styles.input]: true,
[styles.error]: errors.password_confirm,
})}
type="password"
{...register('password_confirm')}
/>
<p className={styles.validate_error}>{errors.password_confirm?.message}</p>
</div>
</div>
</div>
{/* <div className={styles.input_wrapper}>
</div> */}
<div className={styles.checkbox}>
<Checkbox onChange={handleValidate} value={isChecked} />
<div>
<span>Создание учетной записи означает, что вы согласны с нашими</span>
<span className={styles.text}>Условиями использования, Политикой конфиденциальности</span>
<span> и нашими настройками </span>
<span className={styles.text}>уведомлений</span> по умолчанию.
</div>
</div>
{validate ? (
<div className={styles.error}>Необходимо принять условия пользования перед регистрацией</div>
) : null}
<Button className={styles.register_btn}>
{isLoading ? (
<div className="spinner">
<Spin />
</div>
) : (
'Зарегистрироваться'
)}
</Button>
</form>
</div>
</div>
);
};
export default CompanyRegister;
|
define(['backbone','text!templates/about.html'], function(Backbone , AboutTemplate) {
var HomeView = Backbone.View.extend({
el : $('#main'),
initialize : function(){
this.render();
console.log('about section view');
},
render: function(){
var elem = this.el;
elem.html( AboutTemplate )
return this;
}
})
return HomeView;
});
|
(function() {
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "AIzaSyBhHpAx1zy0cVInPbCsh6H_wjJxAnvuEsM",
authDomain: "skywalker-consulting.firebaseapp.com",
databaseURL: "https://skywalker-consulting-default-rtdb.firebaseio.com",
projectId: "skywalker-consulting",
storageBucket: "skywalker-consulting.appspot.com",
messagingSenderId: "337383931316",
appId: "1:337383931316:web:712e404b0b3b03009c46e1"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
var db = firebase.firestore();
const docRef = db.doc("Subscribers/email-list");
const email = document.querySelector('#email');
const subscribe = document.querySelector('#subscribe');
const text = document.querySelector('#validator-text');
var pattern = /^[^ ]+@[^ ]+\.[a-z]{2,3}$/;
email.addEventListener('keydown', () => {
if (email.value.match(pattern)) {
subscribe.removeAttribute('disabled', false);
text.innerHTML = "Email is Valid. Please submit";
text.classList.add('valid');
text.classList.remove('invalid');
} else {
subscribe.setAttribute('disabled', true);
text.innerHTML = "Email is invalid, Please input a valid email address.";
text.classList.add('invalid');
text.classList.remove('valid');
}
if (email.value == "") {
text.removeAttribute('class');
text.innerHTML = '';
}
});
subscribe.addEventListener('click', () => {
const subscribersEmail = email.value;
docRef.update({ emails: firebase.firestore.FieldValue.arrayUnion(subscribersEmail) });
email.style.display ='none';
subscribe.style.display = 'none';
text.innerHTML = 'Thank You for Subscribing!';
});
var showInfo = document.querySelectorAll(".show-info");
var infoNodeList = document.querySelectorAll('.service');
const rollovers = infoNodeList[0];
const longTerm = infoNodeList[1];
const collegePlan = infoNodeList[2];
const lifeInsurance = infoNodeList[3];
const legacyPlan = infoNodeList[4];
const willsAndTrust = infoNodeList[5];
rollovers.addEventListener('click', ()=>{
const icon = rollovers.children[0].children[1];
if(rollovers.children[1].classList.contains('info-hide')){
rollovers.children[1].classList.remove('info-hide');
icon.style.transform = "rotate(180deg)";
}else{
rollovers.children[1].classList.add('info-hide');
icon.style.transform = "rotate(0deg)";
}
});
longTerm.addEventListener('click', ()=>{
const icon = longTerm.children[0].children[1];
if(longTerm.children[1].classList.contains('info-hide')){
longTerm.children[1].classList.remove('info-hide');
icon.style.transform = "rotate(180deg)";
}else{
longTerm.children[1].classList.add('info-hide');
icon.style.transform = "rotate(0deg)";
}
});
collegePlan.addEventListener('click', ()=>{
const icon = collegePlan.children[0].children[1];
if(collegePlan.children[1].classList.contains('info-hide')){
collegePlan.children[1].classList.remove('info-hide');
icon.style.transform = "rotate(180deg)";
}else{
collegePlan.children[1].classList.add('info-hide');
icon.style.transform = "rotate(0deg)";
}
});
lifeInsurance.addEventListener('click', ()=>{
const icon = lifeInsurance.children[0].children[1];
if(lifeInsurance.children[1].classList.contains('info-hide')){
lifeInsurance.children[1].classList.remove('info-hide');
icon.style.transform = "rotate(180deg)";
}else{
lifeInsurance.children[1].classList.add('info-hide');
icon.style.transform = "rotate(0deg)";
}
});
legacyPlan.addEventListener('click', ()=>{
const icon = legacyPlan.children[0].children[1];
if(legacyPlan.children[1].classList.contains('info-hide')){
legacyPlan.children[1].classList.remove('info-hide');
icon.style.transform = "rotate(180deg)";
}else{
legacyPlan.children[1].classList.add('info-hide');
icon.style.transform = "rotate(0deg)";
}
});
willsAndTrust.addEventListener('click', ()=>{
const icon = willsAndTrust.children[0].children[1];
if(willsAndTrust.children[1].classList.contains('info-hide')){
willsAndTrust.children[1].classList.remove('info-hide');
icon.style.transform = "rotate(180deg)";
}else{
willsAndTrust.children[1].classList.add('info-hide');
icon.style.transform = "rotate(0deg)";
}
});
const hamburger = document.getElementById('hamburger');
const close = document.getElementById('close');
const mobileNav = document.querySelector('.mobile-nav');
hamburger.addEventListener('click',()=>{
// hamburger.style.transform = "rotate(360deg)";
// hamburger.style.opacity = '0';
hamburger.classList.toggle('show');
// close.style.transform = "rotate(-360deg)";
// close.style.opacity = '1';
close.classList.toggle('show');
mobileNav.classList.toggle('mobile-nav-active');
});
close.addEventListener('click', ()=>{
close.classList.toggle('show');
hamburger.classList.toggle('show');
mobileNav.classList.toggle('mobile-nav-active');
});
const navLinks = document.querySelectorAll('a');
for(var navLink of navLinks){
navLink.addEventListener('click', ()=>{
close.classList.toggle('show');
hamburger.classList.toggle('show');
mobileNav.classList.toggle('mobile-nav-active');
});
}
// ADMIN JS
})();
|
console.log(module.parent.exports.test)
const exec = require('child_process').exec
const EventEmitter = require('events').EventEmitter
const is_windows = process.platform === 'win32'
const is_linux = process.platform === 'linux'
exports.listen = new EventEmitter
var listening
var default_connect
var speed = 500;
exports.listen.on('initial_status', function(data){
default_connect = data
})
//チェックしたいポート
check_port = "4000"
port = '":' + check_port + ' "'
//プロトコル
pro = 'UDP'
//サーバーが起動しているかをポートのlisten状態で判断し、結果をクライアントにプッシュする
// exports.listen_check = function (status) {
// console.log(status)
setInterval(() => {
//実行OSを基にnetstatとコマンドのオプションと検索コマンドの分岐
if (is_windows) {
args = ' -anp ' + pro + ' '
search_type = ' find '
}
if (is_linux) {
search_type = ' grep '
if (pro === 'TCP') args = ' -ant '
else args = ' -anu '
}
//指定されたポートがlistenされているかどうか判定
// var result = new Promise(function (resolve) {
exec('netstat' + args + '|' + search_type + port, (err, stdout) => {
if (!err) exports.listen.emit('listen', true)
else exports.listen.emit('listen', false)
})
// })
//(ポートのlisten確認後)前回の判定結果と今回の判定結果が違う場合はサーバーのステータスが変化したことをクライアントに知らせる
// result.then(function (data) {
// if (listening !== data || default_connect) {
// if (data) {
// exports.listen.emit('push', "Running!!", 'lightgreen')
// }
// else {
// exports.listen.emit('push', "Not Run!", 'red')
// }
// listening = data
// default_connect = false
// }
// })
}, speed)
// }
exports.Upper = function(str) {
if (!str || typeof str !== 'string') return str;
return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
};
|
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { Button, AppBar, Toolbar, Typography } from '@material-ui/core';
import { Link, useHistory } from 'react-router-dom';
import { logoutUser } from '../reducers/loginReducer';
import { notify } from '../reducers/notificationReducer';
const Navigation = () => {
const loginSelector = useSelector(({ login }) => login);
const history = useHistory();
const dispatch = useDispatch();
const handleLogout = () => {
window.localStorage.removeItem('loggedBlogappUser');
dispatch(logoutUser());
dispatch(
notify({ type: 'success', content: 'Successfully logged out' }, 5000)
);
history.push('/');
};
return (
<AppBar position="static">
<Toolbar>
<Button color="inherit" component={Link} to="/">
Blogs
</Button>
<Button color="inherit" component={Link} to="/users">
Users
</Button>
<Typography>
<em>{loginSelector.name} logged in</em>
</Typography>
<Button
variant="outlined"
color="inherit"
style={{ marginLeft: 5 }}
type="button"
onClick={handleLogout}
>
logout
</Button>
</Toolbar>
</AppBar>
);
};
export default Navigation;
|
var AppDispatcher = require('../dispatcher/app-dispatcher');
module.exports = {
createNewItem: function(comment) {
var action= {
eventName: 'NEW_ITEM',
newItem: comment
};
AppDispatcher.dispatch(action);
}
};
|
const ACTIONS = {
LOAD_MORE_EVENTS: Symbol('LOAD_MORE_EVENTS'),
LOAD_EVENTS: Symbol('LOAD_EVENTS')
}
export default ACTIONS;
|
// library
const express = require('express')
const crypto = require('crypto')
const jwt = require('jsonwebtoken')
const secretObj = require('../config/jwt')
// Model
const CompanyModel = require('../models/CompanyModel')
const VideoModel = require('../models/VideoModel')
const ChannelModel = require('../models/ChannelModel')
const ExposureModel = require('../models/ExposureModel')
// Routes
const companyRoutes = express.Router()
// 변수
// const admin_id = '5fa21b49bf786c138c6062ee'
// 함수
const hashpassword = (password) => {
return crypto.createHash('sha512').update(password).digest('hex')
}
// API
// 회원가입
companyRoutes.post('/signup', async (req, res) => {
try {
const companyEmail = req.body.company_email
const companyPwd = req.body.company_pwd
const companyNick = req.body.company_nickname
const companyIndustry = req.body.company_industry
const item = new CompanyModel({
company_email: companyEmail,
company_pwd: hashpassword(companyPwd),
company_nickname: companyNick,
company_industry: companyIndustry
})
await item.save()
res.status(200).send({
message: `${companyEmail} 회원가입이 완료되었습니다.`
})
} catch (err) {
res.status(500).send(err)
}
})
// 로그인
companyRoutes.post('/signin', async (req, res) => {
if (req.headers.token) {
res.status(403).json({ message: '이미 로그인 되어있습니다.' })
} else {
const companyEmail = req.body.company_email
const companyPwd = hashpassword(req.body.company_pwd)
await CompanyModel.findOne({ company_email: companyEmail })
.then((company) => {
if (company.company_pwd !== companyPwd) {
res.status(403).send({ message: '비밀번호가 다릅니다.' })
} else {
jwt.sign(
{ company_email: company.company_email },
secretObj.secret,
{ expiresIn: '1d' },
function (err, token) {
if (err) {
res.send(err)
} else {
res.json({
message: '로그인 성공, 토큰을 발급합니다.',
token: token,
status: 'login',
company_email: company.company_email,
company_id: company._id,
company_exception: company.company_exception,
company_video: company.company_video,
company_channel: company.company_channel,
company_contact: company.company_contact,
company_pwd: company.company_pwd,
company_nickname: company.company_nickname
})
}
}
)
}
})
.catch(() => {
res.status(403).send({
message: '존재하지 않는 아이디입니다.'
})
})
}
})
// 회원탈퇴
companyRoutes.delete('/', async (req, res) => {
if (req.headers.companyid) {
try {
const companyId = req.headers.companyid
const company = await CompanyModel.findOne({ _id: companyId })
if (company === null) {
res.status(403).send({ message: '존재하지 않는 회원입니다.' })
} else {
// video Cascade
// 1. exception_video 내에 있는 video에 있는 company_id 지워주기!
// 하나 이상일 때만 지워줘야 한다. (0개일 때는 지울필요 x)
if (company.company_exception.length > 0) {
for (let i = 0; i < company.company_exception.length; i++) {
const video = await VideoModel.findOne({ _id: company.company_exception[i] })
video.exception_company_id.remove(companyId)
await VideoModel.findOneAndUpdate(
{ _id: company.company_exception[i] },
{ exception_company_id: video.exception_company_id }
)
}
}
// 2.scrap_video 내에 있는 video에 있는 company_id 지워주기
if (company.company_video.length > 0) {
for (let j = 0; j < company.company_video.length; j++) {
const video_scrap = await VideoModel.findOne({ _id: company.company_video[j] })
video_scrap.scrap_company_id.remove(companyId)
await VideoModel.findOneAndUpdate(
{ _id: company.company_video[j] },
{ scrap_company_id: video_scrap.scrap_company_id }
)
}
}
// Channel Cascade
// 1.scrap_company_id
if (company.company_channel.length > 0) {
for (let k = 0; k < company.company_channel.length; k++) {
const channel_scrap = await ChannelModel.findOne({ _id: company.company_channel[k] })
channel_scrap.scrap_company_id.remove(companyId)
await ChannelModel.findOneAndUpdate(
{ _id: company.company_channel[k] },
{ scrap_company_id: channel_scrap.scrap_company_id }
)
}
}
// 2. contact_company_id
if (company.company_contact.length > 0) {
for (let l = 0; l < company.company_contact.length; l++) {
const channel_contact = await ChannelModel.findOne({ _id: company.company_contact[l] })
channel_contact.contact_company_id.remove(companyId)
await ChannelModel.findOneAndUpdate(
{ _id: company.company_contact[l] },
{ contact_company_id: channel_contact.contact_company_id }
)
}
}
// exposure
await ExposureModel.deleteMany({ company_id: companyId })
// 진짜 회원탈퇴
await CompanyModel.deleteOne({ _id: companyId })
res.status(200).send({ message: '회원이 탈퇴되었습니다.' })
}
} catch (err) {
res.status(500).send(err)
}
}
})
// 모든 회원조회
companyRoutes.get('/', async (req, res) => {
if (req.headers.token) {
try {
const companyAll = await CompanyModel.find()
res.status(200).send(companyAll)
} catch (err) {
res.status(500).send(err)
}
} else {
res.status(403).send({ message: '접근이 제한되었습니다.' })
}
})
// 스크랩 비디오 조회
companyRoutes.get('/video', async (req, res) => {
if (req.headers.token) {
try {
const company = await CompanyModel.findOne({
_id: req.headers.companyid
}).populate('company_video')
for (let i = 0; i < company.company_video.length; i++) {
const companyVideo = company.company_video[i]
for (let j = 0; j < companyVideo.video_record.length; j++) {
const companyId = companyVideo.video_record[j].company_id
const perCompany = await CompanyModel.findOne({ _id: companyId })
companyVideo.video_record[j].company_id = perCompany
}
}
res.status(200).send(company)
} catch (err) {
res.status(500).send(err)
}
} else {
res.status(403).send({ message: '로그인이 필요한 서비스입니다.' })
}
})
// 스크랩 채널 조회
companyRoutes.get('/channel', async (req, res) => {
if (req.headers.token) {
try {
const company = await CompanyModel.findOne({
_id: req.headers.companyid
}).populate('company_channel')
res.status(200).send(company)
} catch (err) {
res.status(500).send(err)
}
} else {
res.status(403).send({ message: '로그인이 필요한 서비스입니다.' })
}
})
// 닉네임 조회
companyRoutes.get('/nick', async (req, res) => {
if (req.headers.companyid) {
const company = await CompanyModel.findOne({
_id: req.headers.companyid
})
res.status(200).send(company.company_nickname)
} else {
res.status(403).send({ message: '로그인이 필요한 서비스입니다.' })
}
})
// 카테고리 조회
companyRoutes.get('/industry', async (req, res) => {
if (req.headers.companyid) {
const company = await CompanyModel.findOne({
_id: req.headers.companyid
})
res.status(200).send(company.company_industry)
} else {
res.status(403).send({ message: '로그인이 필요한 서비스입니다.' })
}
})
// 컨택 채널 조회
companyRoutes.get('/contact', async (req, res) => {
if (req.headers.token) {
try {
const company = await CompanyModel.findOne({
_id: req.headers.companyid
}).populate('company_contact')
res.status(200).send(company.company_contact)
} catch (err) {
res.status(500).send(err)
}
} else {
res.status(403).send({ message: '로그인이 필요한 서비스입니다.' })
}
})
// 제외 영상 조회
companyRoutes.get('/exception', async (req, res) => {
if (req.headers.token) {
try {
const company = await CompanyModel.findOne({ _id: req.headers.companyid }).populate('company_exception')
res.status(200).send(company.company_exception)
} catch (err) {
res.status(500).send(err)
}
} else {
res.status(403).send({ message: '회원만 조회할 수 있습니다.' })
}
})
// 회원조회
companyRoutes.get('/:company_id', async (req, res) => {
const companyId = req.params.company_id
if (companyId === req.headers.companyid) {
try {
const companyOne = await CompanyModel.findOne({ _id: companyId })
res.status(200).send(companyOne)
} catch (err) {
res.status(500).send(err)
}
} else {
res.status(403).send({ message: '접근이 제한되었습니다.' })
}
})
module.exports = companyRoutes
|
import React, { useContext } from 'react';
import styled from 'styled-components';
import { StyledHeading } from '../styles/multiStepStyles';
import JoinNamespaceForm from '../components/JoinNamespaceForm';
import { NamespaceControllerContext } from '../context/NamespaceControllerContext';
import * as Styles from '../styles/multiStepStyles';
const JoinNamespacePage = () => {
const { changePage } = useContext(NamespaceControllerContext);
return (
<>
<StyledHeading>Join to server</StyledHeading>
<JoinNamespaceForm />
<Styles.BackParagraph onClick={() => changePage(0)}>GO BACK</Styles.BackParagraph>
</>
);
};
export default JoinNamespacePage;
|
var express = require('express');
var router = express.Router();
var indexRoute = require('../routes/index.js')
router.route('/')
.get(indexRoute.get);
module.exports = router;
|
'use strict'
const PATH = require('path');
const Webpack = require('webpack');
const Validate = require('webpack-validator');
const Rx = require('rxjs/Rx');
const Boom = require('boom');
const Compiler = require('./compiler');
const Package = require('../package.json');
module.exports = function (bundle$, request, reply, options){
const internals = this.options.bundle_js.internals;
// Consolidate and/or validate configuration
bundle$ = bundle$
// merge user conf with bundle-specific conf.
.map(bundle => {
bundle.filename = PATH.format({
name : `~${bundle.name}`,
ext : this.path.ext
});
bundle.route = `${internals.route}/${bundle.filename}`;
bundle.conf = this.util
.object(options.engine)
.merge({
entry : bundle.path,
output : {
filename : bundle.filename,
chunkFilename : `[hash]-[name].js`,
}
});
if (!internals.FS.data[bundle.filename]) return bundle;
bundle.body = internals.FS.data[bundle.filename];
bundle.exists = true;
return bundle;
});
const rxCompile = source$ => source$
// Allow poking into resulting configuration
.mergeMap(bundle => Rx.Observable.create(observer => {
const name = `plugin:${internals.name}:engine`;
// To avoid letting the request hanging, check for listeners first
if (!this.events.listeners(name).length) {
observer.next(bundle);
observer.complete();
}
// Note: if the user doesn't use the callback, the request will hang.
try {
this.events.emit(name, bundle.conf, conf => {
if (this.util.is(conf).object()) bundle.conf = conf;
observer.next(bundle);
observer.complete();
});
} catch (err) {
observer.error(err);
}
}))
// If not in production, validate config.
.do(bundle => {
if (process.env.NODE_ENV === 'production') return;
const validate = Validate(bundle.conf, {quiet:true, returnValidation:true});
if (validate.error) throw validate.error;
})
// Compile via webpack
.mergeMap(bundle => Compiler
.call(this, internals.FS, bundle.conf)
.map(body => {
bundle.body = body;
return bundle;
})
);
// is the request a new file? compile it!
const result$ = bundle$
.switchMap(bundle => bundle.exists? bundle$ : rxCompile(bundle$))
result$.subscribe(
bundle => {
let response = reply(bundle.body).type('text/javascript');
if (!bundle.exists) response = response
.header('Last-Modified', (new Date()).toUTCString())
},
error => reply(Boom.wrap(error))
);
};
|
// Filename: models/Post.js
define([
'cat',
'underscore',
'backbone',
'backbone.associations'
], function(cat, _, Backbone) {
var Author = Backbone.AssociatedModel.extend({
defaults: {
count: 1,
title: "Catalyst",
url_title: "catalyst",
selected: false
}
});
var Essential = Backbone.AssociatedModel.extend({
defaults: {
count: 1,
title: "",
url_title: "",
selected: false
}
});
var Tag = Backbone.AssociatedModel.extend({
defaults: {
count: 1,
title: "",
url_title: "",
selected: false
}
});
var Media = Backbone.AssociatedModel.extend({
defaults: {
count: 1,
title: "",
url_title: "",
selected: false
}
});
var ViewTime = Backbone.AssociatedModel.extend({
defaults: {
count: 1,
title: "",
url_title: "",
selected: false
}
});
var Category = Backbone.AssociatedModel.extend({
defaults: {
count: 1,
title: "",
url_title: "",
selected: false
}
});
var TagsCollection = Backbone.Collection.extend({ model: Tag });
var AuthorsCollection = Backbone.Collection.extend({ model: Author });
var EssentialsCollection = Backbone.Collection.extend({ model: Essential });
var CategoriesCollection = Backbone.Collection.extend({ model: Category });
var MediaCollection = Backbone.Collection.extend({ model: Media });
var TimeCollection = Backbone.Collection.extend({ model: ViewTime });
return Backbone.AssociatedModel.extend({
relations: [
{
relatedModel: Tag,
type: Backbone.Many,
key: 'tags',
collectionType: TagsCollection
},
{
relatedModel: Author,
type: Backbone.Many,
key: 'authors',
collectionType: AuthorsCollection
},
{
relatedModel: Essential,
type: Backbone.Many,
key: 'essentials',
collectionType: EssentialsCollection
},
{
relatedModel: Category,
type: Backbone.Many,
key: 'categories',
collectionType: CategoriesCollection
},
{
relatedModel: Media,
type: Backbone.Many,
key: 'mediatypes',
collectionType: MediaCollection
},
{
relatedModel: ViewTime,
type: Backbone.Many,
key: 'viewtime',
collectionType: TimeCollection
}
],
defaults: {
keywords: "",
security: "",
categories: [],
tags: [],
authors: [],
essentials: [],
mediatypes: [],
viewtime: []
},
initialize: function() {
this.set({
keywords: "",
security: "",
});
},
parse: function(response) {
this.get('tags').set(response.data.tags);
this.get('authors').set(response.data.authors);
this.get('categories').set(response.data.categories);
this.get('essentials').set(response.data.essentials);
this.get('viewtime').set(response.data.viewtime);
this.get('mediatypes').set([{ id: 1, title: 'article' },{ id: 2, title: 'video' },{ id: 3, title: 'audio' },{ id: 4, title: 'download' },{ id: 5, title: 'podcast'},{id: 6, title: 'backstage'}]);
},
url: '/api/filters.json'
});
});
|
define([
'jquery'
], function($) {
var Helpers = {
loadPage: function(id, htmlF, maybeHash) {
if($('body > div.main').attr('id')) {
return Helpers.scrollTop()
.then(function() {
$('header nav a').removeClass('selected')
return Helpers.fade()
})
.then(function() {
htmlF(function(html, setup) {
$('body > div.main').attr('data-to', id).delay(250).promise().then(
function() {
$('body > div.main').attr('id', id).html(html).removeAttr('data-to')
$('header nav a[href="' + (maybeHash || document.location.hash) + '"]').addClass('selected')
if(setup) setup();
return html;
}
).then(function() {
return Helpers.fade();
});
});
})
} else {
htmlF(function(html, setup) {
$('body > div.main').attr('id', id).html(html);
$('header nav a[href="' + (maybeHash || document.location.hash) + '"]').addClass('selected')
if(setup) setup();
});
}
},
scrollTop: function() {
return $(document.body).animate({scrollTop: 0}, Math.min(250, $(document.body).scrollTop())).promise()
},
fade: function() {
var $el = $('body > div.main')
return Helpers.defer(function() {
return $el[$el.is('.fade') ? 'removeClass' : 'addClass']('fade').delay(250).promise()
})
},
defer: function(f) {
var p = $.Deferred()
setTimeout(function() {
f().then(function(x) { p.resolve(x) })
},0)
return p
}
};
return Helpers;
});
|
import React from 'react'
import Title from './Title'
import SubTitle from './SubTitle'
import SubTitleWithIcon from './SubTitleWithIcon'
import Description from './Description'
import { Row, Col } from 'react-bootstrap'
const MovieInfo = ({ movie }) =>
<div className="info">
<Row>
<Title title={movie.title} />
</Row>
<Row>
<Col xs={4} className="movieInfo">
<SubTitleWithIcon icon={'star'} title={movie.vote_average} />
</Col>
<Col xs={4}>
<SubTitleWithIcon icon={'heart'} title={movie.vote_count} />
</Col>
<Col xs={4}>
<SubTitle title={`Released: ${movie.release_date.substring(0, 4)}`} />
</Col>
</Row>
<Row>
<Description category={'Overview'} description={movie.overview} />
</Row>
</div>
export default MovieInfo
|
var parser = new X2JS();
function ProfesorList($) {
xhr('data/profesores.xml',function (data) {
var xml = parser.xml_str2json(data);
$.profesores = xml.profesores.profesor;
framux.render();
});
};
function ProfesorDetail($, params) {
xhr('data/profesor' + params[0] + '.xml',function(data) {
var xml = parser.xml_str2json(data);
$global.profesor = xml.profesor;
$.prof = $global.profesor;
framux.render();
});
};
|
var searchData=
[
['obj_5fsyntax',['obj_syntax',['../parsecommon_8h.html#aaf3587e2ef140d0c28a664dce0d701ca',1,'parsecommon.h']]],
['or_5fconn_5fstatus_5fevent_5ft',['or_conn_status_event_t',['../or_8h.html#a53c095ab81f2a8e2c459a95c35ab6ecc',1,'or.h']]],
['outbound_5faddr_5ft',['outbound_addr_t',['../or_8h.html#a483c58822bbaa88af698ab9ab7eb7262',1,'or.h']]]
];
|
import React from 'react';
import { Swiper, SwiperSlide } from "swiper/react";
import { Pagination } from "swiper";
import { portfolio_data } from '../../../data';
import Link from 'next/link';
const project_items = portfolio_data.filter(p => p.home_3);
const project_contents = {
subtitle: 'Projects',
title: 'Our complete',
highlight_text: 'project'
}
const { highlight_text, subtitle, title } = project_contents;
const ProjectArea = () => {
const [sliderLoop, setSliderLoop] = React.useState(false);
React.useEffect(() => setSliderLoop(true), [])
return (
<div className="tp-project-area pt-125 pb-120 grey-bg fix">
<div className="container-fluid">
<div className="row">
<div className="col-xl-12">
<div className="tp-project-section-box text-center pb-25">
<h5 className="tp-subtitle">{subtitle}</h5>
<h2 className="tp-title">{title}
<span className="tp-section-highlight">
{highlight_text}
<svg width="197" height="11" viewBox="0 0 197 11" fill="none" xmlns="http://www.w3.org/2000/svg">
<path className="wow" d="M0 0L197 11H0V0Z" fill="#FFDC60" />
</svg>
</span>
</h2>
</div>
</div>
</div>
<div className="tp-project-slider-section-three">
<Swiper
loop={sliderLoop}
slidesPerView={1}
spaceBetween={30}
modules={[Pagination]}
className="swiper-container project-slider-three-active"
pagination={{
el: ".project-slider-dots",
clickable: true,
}}
breakpoints={{
'1200': {
slidesPerView: 2,
},
'992': {
slidesPerView: 2,
},
'768': {
slidesPerView: 1,
},
'576': {
slidesPerView: 1,
},
'0': {
slidesPerView: 1,
},
}}
>
{project_items.map((item) => {
const { id, category, img, title } = item;
return <SwiperSlide key={id}>
<div className="tp-project-item-three text-center p-relative">
<div className="tp-project-item-three__img">
<img src={img} alt="" />
</div>
<div className="tp-project-item-three__bg">
<div className="tp-project-item-three__bg-info">
<h3 className="tp-project-title">
<Link href={`/portfolio-details/${id}`}>
<a>{title}</a>
</Link>
</h3>
<h5 className="tp-project-subtitle">{category}</h5>
</div>
</div>
</div>
</SwiperSlide>
})}
</Swiper>
<div className="project-slider-dots text-center"></div>
</div>
</div>
</div>
);
};
export default ProjectArea;
|
import * as React from 'react'
import {
Badge,
Box,
Flex,
Image,
LinkBox,
LinkOverlay,
Text,
} from '@chakra-ui/react'
import { MdStar } from 'react-icons/md'
import Link from 'next/link'
export default function ListingCard(props) {
const { listing } = props
console.log('listing:', listing)
return (
<LinkBox p='5' borderWidth='1px' rounded='md'>
<Image
borderRadius='md'
alt={listing.summary}
src={listing.images.picture_url}
w='100%'
h='40%'
/>
<Flex align='baseline' mt={2}>
{listing.host.host_is_superhost && (
<Badge colorScheme='pink' mr={2}>
Superhost
</Badge>
)}
<Text
textTransform='uppercase'
fontSize='sm'
fontWeight='bold'
color='pink.800'
>
{listing.host.host_identity_verified && 'Verified • '}
{listing.address.market}
Cape Town
</Text>
</Flex>
<Link href={`/listings/${listing._id}`} passHref>
<LinkOverlay>
<Text mt={2} fontSize='xl' fontWeight='semibold' lineHeight='short'>
{listing.name}
</Text>
</LinkOverlay>
</Link>
<Text mt={2}>${listing.price.$numberDecimal}/night</Text>
{listing.number_of_reviews > 0 && (
<Flex mt={2} align='center'>
<Box as={MdStar} color='orange.400' />
<Text ml={1} fontSize='sm'>
<b>
{(listing.review_scores.review_scores_rating / 20).toFixed(2)}
</b>{' '}
({listing.number_of_reviews})
</Text>
</Flex>
)}
</LinkBox>
)
}
|
import React from 'react';
import Cube from './Cube';
import Transactions from './Transactions';
import Computations from './Computations';
import RightArrow from './RightArrow';
import styles from '../styles/splash.scss';
const BlockchainDemo = () => {
return (
<div className={`${styles.container}`}>
<Computations />
<RightArrow num={1} />
<Transactions />
<RightArrow num={2} />
<Cube />
</div>
);
};
export default BlockchainDemo;
|
// put code here!
//Adding Functions
function yourMission() {
var prisoner = prompt("Hello prisoner. You're trapped in an 8ft by 8ft by 8ft box. Choose from the following items to free yourself: No.2 pencil (p), Chainsaw (c) or a Spoon (s).");
if (prisoner === "c"){
alert("You're a smart prisoner, you'll be free in no time!");
free();
}
else if (prisoner === "p"){
alert("What are we doing, writing our way out?")
pencil();
}
else {
alert("You've watched too much 'Shawshank Redemption'!")
}
}
//Free is the function that's invoked if the prisoner chooses the Chainsaw
function free(){
var sideOfBox = prompt("Which side of the box are you using the chainsaw on first? (l)Left, (r)Right, (f)Front, (b)Back, (c)Ceiling, (t)Floor");
if (sideOfBox === "f") {
alert("Wow, this works?")
}
else if (sideOfBox === "l") {
alert("To the front")
}
else {
alert("Seriously?")
}
}
//Pencil function is invoked if the prisoner selects the No.2 Pencil
function pencil() {
var lead = prompt("Now how exactly do you plan to escape with a No. 2 pencil? (0)Write, (1)Draw, (2)Scrape, (3)Poke, (4)Self mutilate");
switch (lead) {
case "0":
alert("Let's write to your captor, genuis!");
break;
case "1":
alert("Can you draw a door?");
break;
case "2":
alert("Maybe try scraping one of the corners.");
scrape(); //teddy bear
break;
case "3":
alert("What type of material is the box made of?");
break;
case "4":
alert("Are you sure you really want to harm yourself?");
break;
}
}
//Scrape function
function scrape() {
var numOfScrapes = prompt("How many scrapes would it take to set yourself free? If you pick a number closes to the correct answer, you're free to go!");
if (numOfScrapes < 10000) {
alert("We're sorry, you're stuck here!");
}
else {
alert("You're free to go!");
}
}
|
/*
* This file is part of the BenGorCookies library.
*
* (c) Beñat Espiña <benatespina@gmail.com>
* (c) Gorka Laucirica <gorka.lauzirika@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
'use strict';
import Default from './Default';
import Ie9 from './Ie9';
export {
Default,
Ie9
};
|
console.log(`/////////////////Creating and recalling propteries in objects//////////////////////`)
let closet ={
'Pants': 'jeans',
'Shirts': 'Printed Ts',
'Clean Today': true,
socks: 'crew',
underWear: 7,
watchBands: ['Blue', 'Green', 'Purple', 'Black']
};
let undiesCount = closet.underWear;
let watchWeek = closet.watchBands;
console.log(undiesCount, watchWeek);
console.log(closet['Clean Today']);
console.log(closet.underWear);
|
module.exports = {
name:'invite',
description:'Bot invite and support server link',
execute(options)
{
options.client.api.interactions(options.interaction.id,options.interaction.token).callback.post(
{
data:{
type:4,
data:{
flags:64,
content:'Here is the invite link of the bot and the support server',
components:[{
type:1,
components:[{
type:2,
style:5,
url:'https://discord.com/oauth2/authorize?client_id=854822210123202560&permissions=2150647808&scope=bot%20applications.commands',
label:'Invite Bot'
},
{
type:2,
style:5,
url:'https://discord.gg/G53qNs6m',
label:'Support Server'
}]
}]
}
}
})
}
}
|
var mongoose = require('mongoose'),
moment = require('moment');
var EventSchema = new mongoose.Schema({
title: { type: String, required: true },
owner: { type: String, required: true },
start: { type: String, required: true },
end: { type: String },
startTime: { type: String },
endTime: { type: String }
});
EventSchema.pre('save', concatDateTime);
module.exports = mongoose.model('Event', EventSchema);
function concatDateTime (next) {
var event = this;
var dateFormat = 'YYYY-MM-DDT';
var timeFormat = 'HH:mm';
event.start = formatDateTime(event.start, dateFormat);
event.start += formatDateTime(event.startTime, timeFormat);
next();
}
function formatDateTime (dateOrTime, format) {
return moment(dateOrTime).format(format);
}
|
import { nanoid } from 'nanoid';
// HEAD DATA
export const headData = {
title: 'Vayango Koné | Développeur web', // e.g: 'Name | Developer'
lang: 'fr', // e.g: en, es, fr, jp
description: 'Site portfolio de Vayango Koné, développeur web', // e.g: Welcome to my website
};
// HERO DATA
export const heroData = {
title: 'Bonjour, Je suis',
name: 'Vayango Koné',
subtitle: 'Développeur web',
cta: 'En savoir plus',
};
// ABOUT DATA
export const aboutData = {
img: 'profile.jpeg',
paragraphOne:
"Passionné de sciences et de nouvelles technologies, j'étudie l'informatique, notamment le développement web et mobile ",
paragraphTwo:
"J'ai le long de ma formation touché à beaucoup de technologies du web : php et symfony, javascript, react et angular, dart et flutter. Aujourd'hui je me suis spécialisé principalement dans l'écosystème React, dont vous pouvez voir quelques projets ci-dessous",
paragraphThree: 'Vous trouverez via ce lien un exemplaire de mon cv',
resume: 'https://www.resumemaker.online/es.php', // if no resume, the button will not show up
};
// PROJECTS DATA
export const projectsData = [
{
id: nanoid(),
img: 'luxuryCar.png',
title: 'luxuryCar',
info:
'Un site web responsive présentant différentes voitures de luxe. Il a été fait grâce au framework React js et create-react-app.',
info2: '',
url: 'https://vayango-kone.fr/luxuryCar/',
repo: 'https://github.com/jsswa/luxuryCar', // if no repo, the button will not show up
},
{
id: nanoid(),
img: 'webGallery.png',
title: 'webGallery',
info:
"Une application web responsive permettant d'afficher et de chercher différentes images via l'API web Flickr",
info2: '',
url: 'https://vayango-kone.fr/WebGallery/',
repo: 'https://github.com/jsswa/WebGallery', // if no repo, the button will not show up
},
{
id: nanoid(),
img: 'planningApp',
title: 'planningApp',
info:
"Une application faite avec le framework Angular démontrant l'utilisation du Drag and Drop (Glisser-Déposer) sur un planning",
info2: '',
url: 'https://vayango-kone.fr/planningApp/',
repo: 'https://github.com/jsswa/planningApp', // if no repo, the button will not show up
},
{
id: nanoid(),
img: 'expensesApp.png',
title: 'expensesApp',
info: 'Application React permettant de calculer ses dépenses quotidiennes',
info2: '',
url: 'https://vayango-kone.fr/expensesApp/',
repo: 'https://github.com/jsswa/expensesApp', // if no repo, the button will not show up
},
{
id: nanoid(),
img: 'marsGallery.png',
title: 'marsGallery',
info:
"Un site réalisé avec le framework Angular permettant d'afficher les images des missions d'explorations martiennes ",
info2: '',
url: 'https://vayango-kone.fr/marsGallery/',
repo: 'https://github.com/jsswa/marsGallery', // if no repo, the button will not show up
},
{
id: nanoid(),
img: 'registrationForm.png',
title: 'registrationForm',
info: "Un formulaire d'inscription javaScript",
info2: '',
url: 'https://vayango-kone.fr/RegistrationFormJS/',
repo: 'https://github.com/jsswa/RegistrationFormJS', // if no repo, the button will not show up
},
{
id: nanoid(),
img: 'netflixCloneApp.png',
title: 'netflixClone',
info:
"Une copie de l'interface du site web de streaming Netflix effectué en langage React et faisant ses requètes via l'api TMDb ",
info2: '',
url: 'https://vayango-kone.fr/netflixCloneApp/',
repo: 'https://github.com/jsswa/netflixCloneApp', // if no repo, the button will not show up
},
{
id: nanoid(),
img: 'covidTrackerApp.png',
title: 'CovidTracker',
info: "Une application démontrant des statistiques sur l'évolution du COVID 19",
info2: '',
url: 'https://vayango-kone.fr/covidTrackerApp/',
repo: 'https://github.com/jsswa/covidTrackerApp', // if no repo, the button will not show up
},
];
// CONTACT DATA
export const contactData = {
cta: "Souhaitez-vous plus de renseignement ? n'hésitez pas !",
btn: 'Contactez-moi',
email: 'vayango@hotmail.fr',
};
// FOOTER DATA
export const footerData = {
networks: [
{
id: nanoid(),
name: 'linkedin',
url: 'https://www.linkedin.com/in/vayango-kon%C3%A9/',
},
{
id: nanoid(),
name: 'github',
url: 'https://github.com/jsswa',
},
],
};
// Github start/fork buttons
export const githubButtons = {
isEnabled: false, // set to false to disable the GitHub stars/fork buttons
};
|
/**
* Created by yuanguozheng on 16/1/22.
*/
'use strict';
import React, {
Component,
View,
Text,
Image,
StyleSheet,
ScrollView,
RefreshControl
} from 'react-native';
// import Banner from './Banner';
const BANNER_IMGS = [
require('../images/banner/1.jpg'),
require('../images/banner/2.jpg'),
require('../images/banner/3.jpg'),
require('../images/banner/4.jpg')
];
export default class HomePage extends Component {
constructor(props) {
super(props);
// 实际的DataSources存放在state中
this.state = {
dataSource: null
}
}
render() {
return (
<View style={styles.page}>
</View>
)
}
}
const styles = StyleSheet.create({
page: {
flex: 1,
height: 130,
resizeMode: 'stretch'
},
});
|
var searchData=
[
['enemy',['Enemy',['../group___enemy.html',1,'']]],
['explosion',['Explosion',['../group___explosion.html',1,'']]]
];
|
import React from 'react';
import MessageForm from './MessageForm.jsx';
var Message = (props) => {
return (
<div className={"message message-" + props.position}>
<span>{props.text}</span>
</div>
)
}
var Messages = (props) => {
var messageElements = props.dialogsPage.messages.map((message) => {
let position;
if(message.id == props.id){
position = 'right'
}else{
position = 'left'
}
return (
<Message text={message.text} id={message.id} position={position}/>
)
});
return (
<div className="messages">
<div className="chat-zone">{messageElements}</div>
<MessageForm SendMessage={props.SendMessage} id={props.id} name={props.name}/>
</div>
)
}
export default Messages;
|
var request = require('request');
function getExistingRSVList(reqData,authToken){
return new Promise((resolve,reject)=>{
var options = {
'method': 'GET',
'url': `https://management.azure.com/subscriptions/${reqData.subscriptionId}/resourceGroups/${reqData.resourceGroupName}/providers/Microsoft.RecoveryServices/vaults?api-version=2016-06-01`,
'headers': {
'Authorization': authToken,
'Content-Type': 'application/json'
}
};
try{
request(options, function (error, response) {
if(!error && response.statusCode >= 200 && response.statusCode < 400){
resolve(JSON.parse(response.body));
}else if(!error && response.statusCode >= 400 ){
reject(JSON.parse(response.body))
}
else{
reject(error);
}
});
}catch(err){
console.log(err)
reject(err)
}
})
}
//get list of existing Vaults in VM backuo form
exports.existingVaultsList = async(req,res)=>{
try{
reqData = req.body
authToken = req.header('Authorization')
await getExistingRSVList(reqData,authToken).then((resData)=>{
res.send(resData)
}).catch((error)=>{
res.status(400).send('Something broke!')
})
}catch(err){
console.log(err)
res.status(404).send('Something broke. Please Try Again !!')
}
}
|
const Student = require("../models/students");
const { validationResult } = require("express-validator");
const getStudents = (req, res) => {
Student.find()
.then((students) => res.json(students))
.catch((err) => res.status(400).json("Error: " + err));
// res.json(res.pagination);
};
const addStudent = (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(404).json({ errors: errors.array() });
}
const { id, fname, lname, age, city, phone, email } = req.body;
const newStudent = new Student({ id, fname, lname, age, city, phone, email });
newStudent
.save()
.then(() => res.json("Student Added Successfully"))
.catch((err) => res.status(400).json("Error: " + err));
};
const updateStudent = (req, res) => {
Student.findById(req.params.id)
.then((student) => {
student.id = req.body.id;
student.fname = req.body.fname;
student.lname = req.body.lname;
student.age = req.body.age;
student.city = req.body.city;
student.phone = req.body.phone;
student.email = req.body.email;
student
.save()
.then(() => res.json("Student updated Successfully"))
.catch((err) => res.status(400).json("Error: " + err));
})
.catch((err) => res.status(400).json("Error: " + err));
};
const deleteStudent = (req, res) => {
console.log(req.params.id, "req.params.id");
Student.findByIdAndDelete(req.params.id)
.then(() => res.json("Student Deleted Successfully"))
.catch((err) => res.status(400).json("Error: " + err));
};
module.exports = { getStudents, addStudent, updateStudent, deleteStudent };
|
$(document).ready(function(){
$('#dashboard-link').on('click', function() {
open_dashboard()
});
$('#index-link').on('click', function() {
open_index()
});
$('#readability-link').on('click', function() {
open_readability()
});
$('#selenium-link').on('click', function() {
open_selenium()
});
$('#performance-link').on('click', function() {
open_performance()
});
})
const open_dashboard = function(){
alert("dashboard")
sections = $(".section")
sections.not( $("#dashboard-section") ).css({"display": "none"})
$("#dashboard-section").fadeIn()
fill_logs()
fill_readability()
}
const open_index = function(){
sections = $(".section")
sections.not( $("#index-section") ).css({"display": "none"})
$("#index-section").fadeIn()
}
const open_readability = function(){
sections = $(".section")
sections.not( $("#readability-section") ).css({"display": "none"})
$("#readability-section").fadeIn()
}
const open_selenium = function(){
sections = $(".section")
sections.not( $("#selenium-section") ).css({"display": "none"})
$("#selenium-section").fadeIn()
}
const open_performance = function(){
sections = $(".section")
sections.not( $("#performance-section") ).css({"display": "none"})
$("#performance-section").fadeIn()
}
|
// Generated by CoffeeScript 2.0.1
(function() {
module.exports.name = 'data.gov.sg';
module.exports.url = 'https://api.data.gov.sg/v1';
module.exports.imports = {
environment: [__dirname + '/environment'],
transport: [__dirname + '/transport']
};
module.exports.authCallbacks = {
'default': function(msg) {
return msg.addHeader('api-key', process.env.DATA_GOV_SG_KEY);
}
};
module.exports.registerExtensions = function(api) {
return {
defaultCall: function(endpoint, date, fullDay = false) {
var param;
if (date != null) {
date = date.toISOString();
}
param = fullDay ? 'data' : 'date_time';
return api.createCall({
endpoint: endpoint
}).describe(`getting ${endpoint} for ${date || 'now'}`).authorizeByDefault().setMethod('GET').addHeader(param, date);
}
};
};
}).call(this);
|
import './sass/main.scss';
import axios from "axios";
import debounce from "lodash.debounce";
import showCountry from "./template/showCountry";
import showCountries from "./template/showCountries";
import { error } from '../node_modules/@pnotify/core/dist/PNotify';
import '../node_modules/@pnotify/core/dist/PNotify.css';
import '../node_modules/@pnotify/core/dist/BrightTheme.css'
const refs = {
input: document.querySelector('.search'),
list: document.querySelector('.list'),
wrapper: document.querySelector('.wrapper'),
}
axios.defaults.baseURL = 'https://restcountries.eu/rest/v2/name/';
function onInput(e) {
let countryName = e.target.value;
axios.get(countryName).then(response => {
let names = response.data.map(e => e.name);
if (names.length === 1) {
clearList();
renderWrapper(response.data[0]);
return;
}
if (names.length >= 2 && names.length <= 10) {
clearWrapper();
renderList(names);
return;
}
clearList();
clearWrapper();
error({
text: 'Too many matches found. Please enter a more specific query!'
});
}).catch(error => console.log(error));
}
function clearList() {
if (refs.list.innerHTML !== '') {
refs.list.innerHTML = '';
}
}
function clearWrapper() {
if (refs.wrapper.innerHTML !== '') {
refs.wrapper.innerHTML = '';
}
}
function renderWrapper(country) {
refs.wrapper.innerHTML = showCountry(country);
}
function renderList(countries) {
refs.list.innerHTML = showCountries(countries);
}
refs.input.addEventListener('input', debounce(onInput, 500));
|
/*
An array is special if every even index contains an even number and every odd index contains an odd number. Create a function that returns true if an array is special, and false otherwise.
Examples
isSpecialArray([2, 7, 4, 9, 6, 1, 6, 3]) ➞ true
// Even indices: [2, 4, 6, 6]; Odd indices: [7, 9, 1, 3]
isSpecialArray([2, 7, 9, 1, 6, 1, 6, 3]) ➞ false
// Index 2 has an odd number 9.
isSpecialArray([2, 7, 8, 8, 6, 1, 6, 3]) ➞ false
// Index 3 has an even number 8.
*/
function isSpecialArray(arr)
{
for(let i=0;i<arr.length;i++)
{
if(i%2==0)
{
if(arr[i]%2!=0)
{
return false;
}
}
else
{
if(arr[i]%2==0)
{
return false;
}
}
}
return true;
}
console.log(isSpecialArray([2, 7, 4, 9, 6, 1, 6, 3]));
console.log(isSpecialArray([2, 7, 9, 1, 6, 1, 6, 3]));
|
import React from "react";
import { Flex, Heading, Text, Box } from "@chakra-ui/react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import {
faEllipsisV,
faSortDown,
faSortUp,
faChevronRight,
faChevronLeft,
} from "@fortawesome/free-solid-svg-icons";
import ExpenseCard from "./cards/ExpenseCard";
import BaseNewModal from "./modals/BaseNewModal";
import { sortByDate, sortByNumeric } from "../helpers/helper";
import NewButton from "./styled/NewButton";
import PropTypes from "prop-types";
import { CurrencyConsumer } from "../contexts/currencyContext";
const Expenses = ({ projectId, expenses, action }) => {
// ----- STATE -----
const [dateSorted, setDateSorted] = React.useState(null);
const [costSorted, setCostSorted] = React.useState(null);
const [sortedExpenses, setSortedExpenses] = React.useState(expenses);
const [paginatedExpenses, setPaginatedExpenses] = React.useState(expenses);
const [page, setPage] = React.useState(1);
// Repaginate when expenses updated or sorted
React.useEffect(() => {
let sorted = expenses;
// Sort by date
if (dateSorted) {
sorted =
dateSorted === "first"
? sortByDate(expenses, "last", "date")
: sortByDate(expenses, "first", "date");
}
// Sort by cost
if (costSorted) {
sorted =
costSorted === "first"
? sortByNumeric(expenses, "last", "cost")
: sortByNumeric(expenses, "first", "cost");
}
// Set sorted Expenses
setSortedExpenses(sorted);
// Paginate
setPaginatedExpenses(sorted?.slice(page * 6 - 6, page * 6 || []));
}, [expenses, dateSorted, costSorted]);
// ----- Pagination controls
const nextPage = () => {
const endSlice = (page + 1) * 6;
const startSlice = (page + 1) * 6 - 6;
setPaginatedExpenses(sortedExpenses.slice(startSlice, endSlice));
setPage(page + 1);
};
const previousPage = () => {
const endSlice = (page - 1) * 6;
const startSlice = (page - 1) * 6 - 6;
setPaginatedExpenses(sortedExpenses.slice(startSlice, endSlice));
setPage(page - 1);
};
// ----- Toggle sorted by due date -----
const sortDate = () => {
setDateSorted(dateSorted !== "first" ? "first" : "last");
setCostSorted(null);
};
// ----- Toggle sorted by hours -----
const sortCost = () => {
setCostSorted(costSorted === "first" ? "last" : "first");
setDateSorted(null);
};
return (
<Flex
flex="1"
direction="column"
minHeight="500px"
justify="space-between"
style={{ borderLeft: "1px solid rgba(0,0,0,.12)" }}
>
<Box>
{/* Heading */}
<Flex justify="space-between" align="center" p="10px 20px">
<Heading as="h3" fontWeight="300" fontSize="xl" color="gray.500">
Expenses
</Heading>
<BaseNewModal
type="Expense"
action={action}
buttonProps={{ primary: "#556885", hoverColor: "#728bb1" }}
buttonStyle={{ padding: "6px 10px", fontSize: "14px" }}
projectId={projectId}
/>
</Flex>
<Flex
align="center"
color="gray.600"
fontWeight="bold"
boxShadow="0 1px 1px 0 rgba(0, 0,0, .12)"
mt="5px"
p="5px 20px"
>
<Text fontSize="14px" casing="uppercase" flex="2">
Expense
</Text>
<Flex flex="1.25" justify="center">
<Text
fontSize="sm"
casing="uppercase"
textAlign="center"
cursor="pointer"
// Sort by date
onClick={sortDate}
data-cy="sort-expenses-date"
>
Date
</Text>
{/* Sorted icons */}
{dateSorted && dateSorted === "first" && (
<FontAwesomeIcon
icon={faSortDown}
style={{
marginLeft: "3px",
position: "relative",
top: "-4px",
}}
/>
)}
{dateSorted && dateSorted === "last" && (
<FontAwesomeIcon
icon={faSortUp}
style={{
marginLeft: "3px",
position: "relative",
top: "3px",
}}
/>
)}
</Flex>
<Flex justify="center" flex="1.25">
<Text
fontSize="sm"
casing="uppercase"
textAlign="center"
cursor="pointer"
// Sort by hours
onClick={sortCost}
data-cy="sort-expenses-cost"
>
Cost
</Text>
{/* Sorted icons */}
{costSorted && costSorted === "first" && (
<FontAwesomeIcon
icon={faSortDown}
style={{
marginLeft: "3px",
position: "relative",
top: "-4px",
}}
/>
)}
{costSorted && costSorted === "last" && (
<FontAwesomeIcon
icon={faSortUp}
style={{
marginLeft: "3px",
position: "relative",
top: "3px",
}}
/>
)}
</Flex>
{/* Keep spacing the same */}
<Box fontSize="sm" marginRight="20px" visibility="hidden">
Upload receipt
</Box>
<FontAwesomeIcon icon={faEllipsisV} color="transparent" />
</Flex>
{(!expenses || expenses?.length === 0) && (
<Text p="20px">No current expenses for this project</Text>
)}
{expenses?.length > 0 &&
paginatedExpenses?.map((expense) => (
<CurrencyConsumer key={expense.id}>
{() => (
<ExpenseCard
expense={expense}
updateExpensesForProject={action}
/>
)}
</CurrencyConsumer>
))}
</Box>
{/* Pagination */}
<Box>
<Flex m="10px" justify="space-between" align="center" width="60px">
{/* Previous */}
<NewButton
data-cy="expenses-prev"
onClick={previousPage}
style={{
marginRight: "10px",
padding: "5px 10px",
visibility: page !== 1 ? "visible" : "hidden",
}}
>
<FontAwesomeIcon icon={faChevronLeft} size="sm" color="white" />
</NewButton>
{/* Next */}
<NewButton
data-cy="expenses-next"
onClick={nextPage}
style={{
padding: "5px 10px",
visibility:
expenses?.length > page * 6 ||
(page === 1 && expenses?.length > 6)
? "visible"
: "hidden",
}}
>
<FontAwesomeIcon icon={faChevronRight} size="sm" color="white" />
</NewButton>
</Flex>
</Box>
</Flex>
);
};
Expenses.propTypes = {
projectId: PropTypes.number,
expenses: PropTypes.array,
action: PropTypes.func,
};
export default Expenses;
|
$(document).ready(function () {
"use strict";
var av_name = "ChomskyNormalFormFS";
var av = new JSAV(av_name,);
var Frames = PIFRAMES.init(av_name);
var arrow = String.fromCharCode(8594);
var grammar = "[[\"S\",\"→\",\"CBcd\"],\
[\"B\",\"→\",\"b\"],\
[\"C\",\"→\",\"Cc\"],\
[\"C\",\"→\",\"e\"]]";
var grammerArray = JSON.parse(grammar);
var grammerMatrix = new GrammarMatrix( av,grammerArray, {style: "table", left: 10, top: 75});
grammerMatrix.createRow(["", arrow, ""]);
grammerMatrix.createRow(["", arrow, ""]);
grammerMatrix.createRow(["", arrow, ""]);
grammerMatrix.createRow(["", arrow, ""]);
grammerMatrix.createRow(["", arrow, ""]);
grammerMatrix.productions.push(["", arrow, ""]);
grammerMatrix.productions.push(["", arrow, ""]);
grammerMatrix.productions.push(["", arrow, ""]);
grammerMatrix.productions.push(["", arrow, ""]);
grammerMatrix.productions.push(["", arrow, ""]);
for(var i = 4; i<8; i++)
grammerMatrix.hideRow(i);
grammerMatrix.hide();
// Frame 1
av.umsg("To summarize what we have done so far: We have found algorithms to remove from any CFG the useless productions, $\\lambda$ productions, and unit productions.");
av.displayInit();
// Frame 2
av.umsg(Frames.addQuestion("clean"));
av.step();
// Frame 3
av.umsg(Frames.addQuestion("order"));
av.step();
// Frame 4
av.umsg(Frames.addQuestion("next"));
av.step();
// Frame 5
av.umsg("Exactly, so we must follow the order<br/>1. Remove $\\lambda$-productions<br/>2. Remove unit productions<br/>3. Remove useless productions");
av.step();
// Frame 6
av.umsg("<b>Definition:</b> A CFG is in <b>Chomsky Normal Form (CNF)</b> if all productions are of the form<br/>$A \\rightarrow BC$ or $A \\rightarrow a$<br/>where $A, B, C \\in V$ and $a \\in T$<br/><br/>Why would you want to put a grammar in this form? Because it is easier to work with in proofs. We won't use this right away, but we will need this later in the semester.");
av.step();
// Frame 7
av.umsg("$\\textbf{Theorem:}$ Any CFG $G$ with $\\lambda$ not in L(G) has an equivalent grammar in CNF.");
av.step();
// Frame 8
av.umsg(Frames.addQuestion("ready"));
grammerMatrix.show();
av.step();
// Frame 9
av.umsg(Frames.addQuestion("removeterms"));
grammerMatrix.highlight(0);
av.step();
// Frame 10
av.umsg(Frames.addQuestion("Cc"));
grammerMatrix.unhighlight(0);
grammerMatrix.highlight(2);
grammerMatrix.showRow(4);
grammerMatrix.showRow(5);
grammerMatrix.modifyProduction(4,0,"$C_1$");
grammerMatrix.modifyProduction(4,2,"$c$");
grammerMatrix.modifyProduction(5,0,"$C_2$");
grammerMatrix.modifyProduction(5,2,"$d$");
//modify old production
grammerMatrix.modifyProduction(0,2,"$C\\ B\\ C_1\\ C_2$");
av.step();
// Frame 11
av.umsg(Frames.addQuestion("shortenS"));
grammerMatrix.unhighlight(2);
grammerMatrix.modifyProduction(6,0,"$C_3$");
grammerMatrix.modifyProduction(6,2,"$c$");
//modify old
grammerMatrix.modifyProduction(2,2,"$C\\ C_3$");
grammerMatrix.showRow(6);
//For new step:
grammerMatrix.highlight(0);
av.step();
// Frame 12
av.umsg(Frames.addQuestion("cisdone"));
grammerMatrix.unhighlight(0);
grammerMatrix.modifyProduction(0,2,"$C\\ D_1$");
grammerMatrix.showRow(7);
grammerMatrix.modifyProduction(7,0,"$D_1$");
grammerMatrix.modifyProduction(7,2,"$B\\ C_1\\ C_2$");
grammerMatrix.highlight(2);
av.step();
// Frame 13
av.umsg(Frames.addQuestion("D1"));
grammerMatrix.unhighlight(2);
grammerMatrix.highlight(7);
av.step();
// Frame 14
av.umsg(Frames.addQuestion("arewedone"));
grammerMatrix.unhighlight(7);
grammerMatrix.modifyProduction(8,0,"$D_2$");
grammerMatrix.modifyProduction(8,2,"$C_1\\ C_2$");
grammerMatrix.showRow(8);
//modify old
grammerMatrix.modifyProduction(7,2,"$B\\ D_2$");
av.step();
// Frame 15
av.umsg("The resulting grammar is in the CNF. This was quite easy once the grammar has had its $\\lambda$ productions, unit productions, and useless productions removed.");
av.step();
// Frame 16
av.umsg("Congratulations! Frameset completed.");
av.recorded();
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.