text
stringlengths 7
3.69M
|
|---|
// =============================================================================
// This file is the entry point for the server. Here are defined the start and
// stop functions, which configure the router, the database connection and
// the server itself.
// =============================================================================
var mongoose = require('mongoose');
var expressApp = require("./express-config");
var config = require("../config");
var UserModel = require("./models/user-model");
var server; // Keep a reference to the server instance
var port = process.env.PORT || config.port || 3000;
/*
* Connects to the database and starts the server. It takes a callback, that
* can be executed once everything is done.
*/
function start(cb) {
mongoose.connect(config.database.uri);
UserModel.remove({ is_admin: true }).then(function(data) {
return new UserModel({
first_name: 'root',
last_name: 'root',
email: config.admin.email,
password: config.admin.password,
is_admin: true
}).save();
}).then(function(data) {
console.log('Admin. credentials:');
console.log('- Email: ' + config.admin.email);
console.log('- Password: ' + config.admin.password);
}).catch(function(err) {
console.error(err);
});
server = expressApp.listen(port, function() {
console.log("Something beautiful is happening on port " + port);
if (cb) cb();
});
}
/*
* Disconnects from the database and stops the server. It takes a callback,
* that can be executed once everything is done.
*/
function close(cb) {
mongoose.connection.close(function() {
console.log('Terminated mongoose connection');
server.close(function() {
console.log('Shutting down the server');
if (cb) cb();
});
});
};
module.exports = {
start: start,
close: close,
}
|
import { connect } from 'react-redux';
import AudioPlayer from './audio_player';
const mapStateToProps = state => ({
});
const mapDispatchToProps = dispatch => ({
});
export default connect(mapStateToProps, mapDispatchToProps)(AudioPlayer);
|
//2.Write a function that finds all the prime numbers in a range
//It should return the prime numbers in an array
//It must throw an Error if any of the range params is not convertible to Number
//It must throw an Error if any of the range params is missing
"use strict";
function solve(from, to){
var primes = [],
isPrime = true,
maxDivider;
if(from === undefined || to === undefined){
throw new Error();
}
from = +from;
to = +to;
if(isNaN(from) || isNaN(to)){
throw new Error();
}
for (var i = from; i <= to; i++) {
if(i < 2){
i = 2;
}
maxDivider = Math.sqrt(i);
isPrime = true;
for (var j = 2; j <= maxDivider; j++) {
if(i % j === 0){
isPrime = false;
break;
}
}
if(isPrime){
primes.push(i);
}
}
return primes;
}
module.exports = solve;
|
import React from 'react'
import {connect} from 'react-redux'
import {fetchProduct} from '../store/product'
import EditProduct from './EditProduct'
import {ToastContainer, toast} from 'react-toastify'
import 'react-toastify/dist/ReactToastify.css'
import {addItem} from '../store/cart' //this thunk should add the item to the cart
// eslint-disable-next-line react/display-name
class Product extends React.Component {
constructor() {
super()
this.handleAddToLocalStorage = this.handleAddToLocalStorage.bind(this)
this.handleAddToCartButton = this.handleAddToCartButton.bind(this)
}
// handleEdit() {
// const productId = this.props.match.params.productId
// this.dispatch.updateProduct(productId)
// }
handleAddToLocalStorage() {
//if cart exists in local storage, add to it, if not, create the cart
toast.success('Added to cart!')
let product = this.props.product
let cart = JSON.parse(window.localStorage.getItem('cart'))
if (!cart)
window.localStorage.setItem(
'cart',
JSON.stringify([
{
productId: product.id,
name: product.name,
quantity: 1,
price: product.price
}
])
)
else if (
!cart.reduce((bool, item) => {
return item.productId === product.id || bool
}, false)
) {
cart.push({
productId: product.id,
name: product.name,
quantity: 1,
price: product.price
})
window.localStorage.setItem('cart', JSON.stringify(cart))
} else {
cart.forEach(item => {
if (item.productId === product.id) item.quantity++
})
window.localStorage.setItem('cart', JSON.stringify(cart))
}
}
handleAddToCart() {}
componentDidMount() {
const productId = this.props.match.params.productId
this.props.getProduct(productId)
}
handleAddToCartButton(productId) {
'invoking handleaddtocartButton'
toast.success('Added to cart!')
this.props.addItemToCart(productId)
}
render() {
const product = this.props.product
return !product.id ? (
<div className="container">
<h1>No Product Found</h1>
</div>
) : (
<div className="APcontainer">
<div className="container">
<div className="singleProduct">
<div className="SPLeft">
<img className="singleProductImg" src={product.imageUrl} />
</div>
<div className="SPRight">
<h2>{product.name}</h2>
<h2>Price: ${product.price}</h2>
<div>
<ToastContainer />
{this.props.isLoggedIn ? (
<button
className="addToCartButton"
type="submit"
onClick={() => this.handleAddToCartButton(product.id)}
>
Add To Cart
</button>
) : (
<button
className="addToCartButton"
type="button"
onClick={this.handleAddToLocalStorage}
>
Add To Cart
</button>
)}
</div>
</div>
</div>
</div>
{this.props.user.userType === 'ADMIN' ? (
<div>
<EditProduct product={product} />
</div>
) : (
<div />
)}
</div>
)
}
}
const mapProduct = state => {
return {
product: state.product,
isLoggedIn: !!state.user.id,
user: state.user
}
}
const mapDispatchToProps = dispatch => {
return {
getProduct: productId => dispatch(fetchProduct(productId)),
addItemToCart: productId => dispatch(addItem(productId))
}
}
export default connect(mapProduct, mapDispatchToProps)(Product)
|
var str = 'string!';
var num = 10;
var bool = true;
var decimal = 6;
var hex = 0xf00d;
var binary = 10;
var octal = 484;
var unknown = '1';
var numArray = [1, 2, 3];
var numArray1 = [1, 2, 4, 5];
//tuple type
var multType = [1, '2'];
var x;
x = ['hello', 10];
//enum
var Color;
(function (Color) {
Color[Color["Red"] = 2] = "Red";
Color[Color["Green"] = 3] = "Green";
Color[Color["Blue"] = 4] = "Blue";
})(Color || (Color = {}));
;
var c = Color.Green;
var d = Color[2];
console.log(d);
var myName = 'Roman';
var myAge = 25;
function getName() {
return myName;
}
var getAge = function () { return myAge; };
var voidFunc = function () { return console.log(); };
|
export default {
lang: 'sv',
mediaPlayer: {
oldBrowserVideo: 'Aktivera Javascript för att visa den här videon och/eller installera en webbläsare som stödjer HTML5 video',
oldBrowserAudio: 'Aktivera JavaScript för att lyssna på det här ljudet och/eller installera en webbläsare som stödjer HTML5 ljud',
pause: 'Pausa',
play: 'Spela',
settings: 'Inställningar',
toggleFullscreen: 'Växla fullskärm',
mute: 'Ljud av',
unmute: 'Ljud på',
speed: 'Uppspelningshastighet', // Playback rate
language: 'Språk',
playbackRate: 'Uppspelningstempo',
waitingVideo: 'Väntar på video',
waitingAudio: 'Väntar på ljud',
ratePoint5: '.5x',
rateNormal: 'Normal',
rate1Point5: '1.5x',
rate2: '2x',
trackLanguageOff: 'Av',
noLoadVideo: 'Kan inte ladda video',
noLoadAudio: 'Kan inte ladda ljud',
cannotPlayVideo: 'Kan inte spela video',
cannotPlayAudio: 'Kan inte spela ljud'
}
}
|
import React from 'react';
import classnames from 'classnames/bind';
import styles from './bar.scss';
const cx = classnames.bind(styles);
const Bar = (props) => {
const {
right,
left,
type,
onMouseDown,
width,
} = props;
const barLeftAndRightStyles = {
left: `${left}%`,
right: `${right}%`,
width: `${width}%`,
};
const handleMouseDown = () => {
onMouseDown(type);
};
const getClassnames = () => cx('range-input-bar', {
'range-input-bar--gradient-blue-red': (width <= 10 || width > 50) && width <= 60,
'range-input-bar--gradient-green-yellow': (width > 10 && width <= 20) || (width > 60 && width <= 70),
'range-input-bar--gradient-orange-red': (width > 20 && width <= 30) || (width > 70 && width <= 80),
'range-input-bar--gradient-purple-pink': (width > 30 && width <= 40) || (width > 80 && width <= 90),
'range-input-bar--gradient-yellow-blue': (width > 40 && width <= 50) || (width > 90 && width < 100),
});
return (
<div
type={type}
className={getClassnames()}
style={barLeftAndRightStyles}
onMouseDown={handleMouseDown}
/>
);
};
export default Bar;
|
const express = require('express');
const connectDB = require('./config/db');
const router = express.Router();
const bodyParser = require('body-parser');
const path = require('path');
//Load Routes:
const userRoutes = require('./routes/api/user');
const authRoutes = require('./routes/api/auth');
const profileRoutes = require('./routes/api/profile');
const postRoutes = require('./routes/api/post');
const app = express();
//Connect Database:
connectDB();
//Body Parser Middleware
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
//Define Routes:
router.use('/api/users', userRoutes);
router.use('/api/auth', authRoutes);
router.use('/api/profile', profileRoutes);
router.use('/api/posts', postRoutes);
app.use(router);
// Serve static assets in production
if(process.env.NODE_ENV === 'production') {
//Set Static folder
app.use(express.static('client/build'));
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
});
}
// Server Start Setting:
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server Started on port ${PORT}`));
|
class Vote {
value;
userId;
constructor(value, userId) {
this.value = value;
this.userId = userId;
}
update(value) {
this.value = value;
}
}
module.exports = Vote;
|
var tch = new tchPlanet(); //create technique
camera = new Camera(new vec3(0, 0, -1), vec3.unitZ(), vec3.unitY()); //create camera
let projectionMatrix = new mat4(); //create projection matrix
mat4.Perspective(projectionMatrix, canvas.width / canvas.height, 0.001, 50, 1); //setup projection matrix
//time_r
let t = 0.0;
let delta = 0.05;
setInterval(function() {
gl.clear(gl.DEPTH_BUFFER_BIT | gl.COLOR_BUFFER_BIT);
//update camera view matrix
camera.update();
//resulting matrix
let matrix = new mat4();
matrix.copy(camera.viewMatrix);
matrix.mul(projectionMatrix);
//draw sphere
tch.Use(matrix, new vec3(t - 5, 3, -1));
gl.bindBuffer(gl.ARRAY_BUFFER, sun.vertexBuffer);
tch.SetupAttributes();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, sun.indexBuffer);
gl.drawElements(gl.TRIANGLES, sun.elementCount, gl.UNSIGNED_SHORT, 0);
tch.DisableAttributes();
//update timer
t += delta;
}, 50);
|
import Api from "../../api"
const END_POINT = 'Dashboard/';
const dashboard = {
namespaced: true,
state () {
return {
Ventes: [],
Total: [],
Livraisons: [],
TopDestinations: [],
TopClients: [],
}
},
getters: {
getVentes: (state) => state.Ventes,
getTotal: (state) => state.Total,
getLivraisons: (state) => state.Livraisons,
getTopDestinations: (state) => state.TopDestinations,
getTopClients: (state) => state.TopClients,
},
mutations: {
setVentes: (state, payLoad) => state.Ventes = payLoad,
setTotal: (state, payLoad) => state.Total = payLoad,
setLivraisons: (state, payLoad) => state.Livraisons = payLoad,
setTopDestinations: (state, payLoad) => state.TopDestinations = payLoad,
setTopClients: (state, payLoad) => state.TopClients = payLoad,
},
actions: {
initVentes: ({commit}, year) => {
let tLocal = 0;
let tExport = 0;
return new Promise((resolve, reject) => {
Api.get(END_POINT + "Ventes/" + year)
.then((response) => {
response.data.forEach(el => {
tLocal += el.local || 0;
tExport += el.export || 0;
});
let total = [
{
type: 'Local',
montant: tLocal.toFixed(2)
},
{
type: 'Export',
montant: tExport.toFixed(2)
}
];
commit("setVentes", response.data);
commit("setTotal", total);
resolve(response.data);
})
.catch((error) => {
reject(error);
});
});
},
initLivraisons: ({commit}, date) => {
let nfData = {
facture: "Non Facturé",
count: 0
};
let fData = {
facture: "Facturé",
count: 0
};
return new Promise((resolve, reject) => {
Api.get(END_POINT + "Livraisons/" + date.start + "/" + date.end)
.then((response) => {
response.data.forEach(el => {
if (el.facture == "Non Facturé") {
nfData = el;
} else {
fData.count += el.count;
}
});
commit("setLivraisons", [fData, nfData]);
resolve(response.data);
})
.catch((error) => {
reject(error);
});
});
},
initTopDestinations: ({commit}, date) => {
return new Promise((resolve, reject) => {
Api.get(END_POINT + "TopDestinations/" + date.start + "/" + date.end)
.then((response) => {
const top = response.data.slice(0,20);
commit("setTopDestinations", top);
resolve(response.data);
})
.catch((error) => {
reject(error);
});
});
},
initTopClients: ({commit}, date) => {
return new Promise((resolve, reject) => {
Api.get(END_POINT + "TopClients/" + date.start + "/" + date.end)
.then((response) => {
const top = response.data.slice(0,10);
commit("setTopClients", top);
resolve(response.data);
})
.catch((error) => {
reject(error);
});
});
},
}
};
export default dashboard
|
document.addEventListener("DOMContentLoaded", function(){
var arriba = document.querySelector(".GoSup");
var abajo = document.querySelector(".GoDown");
var footer = document.querySelector(".Cs");
document.addEventListener("scroll", function(){
var cantidadScroll = window.scrollY * 2;
var tamanoVentana = document.body.scrollHeight - document.body.clientHeight;
arriba.innerHTML = cantidadScroll;
abajo.innerHTML = tamanoVentana;
/* if(document.body.scrollTop <= 100){
arriba.style.display = "none";
}else{
arriba.style.display = "flex";
}
if(cantidadScroll > (tamanoVentana - 100)){
abajo.style.display = "none"
}else{
abajo.style.display = "flex"
}*/
});
arriba.addEventListener("click", function(){
window.scrollTo(0,0);
});
abajo.addEventListener("click", function(){
var tamanoVentana = window.innerHeight / 2;
window.scrollTo(0, tamanoVentana);
});
});
|
'use strict';
var services = angular.module('wow.services.pvp', []);
services.factory('PvP', ['$http', function($http) {
function load(path) {
var request = $http({
method: 'GET',
url: path,
headers: {
'Access-Control-Allow-Origin': '*'
}
});
return request;
}
return {
list: function(bracket) {
return load('/api/pvp/' + bracket);
}
};
}]);
|
const env = require('dotenv');;
env.config();
const sec = process.env;
module.exports = sec;
|
import { faArrowsAltH, faArrowsAltV, faExpand, faSearchMinus, faSearchPlus } from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import React, { useState } from 'react';
import { useSelector } from 'react-redux';
export default function Acteur() {
const [isActiveOne, setIsActiveOne] = useState(true);
const [isActiveTwo, setIsActiveTwo] = useState(false);
const [isActiveThree, setIsActiveThree] = useState(false);
const [isActiveFour, setIsActiveFour] = useState(false);
const [isActiveFive, setIsActiveFive] = useState(false);
const [isActiveSix, setIsActiveSix] = useState(false);
const [isActiveSeven, setIsActiveSeven] = useState(false);
const isActivee = (n) => {
if(n === 1){
setIsActiveOne(true);
setIsActiveTwo(false);
setIsActiveThree(false);
setIsActiveFour(false);
setIsActiveFive(false);
setIsActiveSix(false);
setIsActiveSeven(false);
};
if(n === 2){
setIsActiveOne(false);
setIsActiveTwo(true);
setIsActiveThree(false);
setIsActiveFour(false);
setIsActiveFive(false);
setIsActiveSix(false);
setIsActiveSeven(false);
};
if(n === 3){
setIsActiveOne(false);
setIsActiveTwo(false);
setIsActiveThree(true);
setIsActiveFour(false);
setIsActiveFive(false);
setIsActiveSeven(false);
};
if(n === 4){
setIsActiveOne(false);
setIsActiveTwo(false);
setIsActiveThree(false);
setIsActiveFour(true);
setIsActiveFive(false);
setIsActiveSix(false);
setIsActiveSeven(false);
};
if(n === 5){
setIsActiveOne(false);
setIsActiveTwo(false);
setIsActiveThree(false);
setIsActiveFour(false);
setIsActiveFive(true);
setIsActiveSix(false);
setIsActiveSeven(false);
};
if(n === 6){
setIsActiveOne(false);
setIsActiveTwo(false);
setIsActiveThree(false);
setIsActiveFour(false);
setIsActiveFive(false);
setIsActiveSix(true);
setIsActiveSeven(false);
};
if(n === 7){
setIsActiveOne(false);
setIsActiveTwo(false);
setIsActiveThree(false);
setIsActiveFour(false);
setIsActiveFive(false);
setIsActiveSix(false);
setIsActiveSeven(true);
};
}
/* Get Actor */
const Acteur = useSelector(state => state.acteurs.acteur);
/*-----------*/
return (
<div>
<h5 className="po-h">Acteur.nom</h5>
<div>
<ul className="nav-po">
<li onClick={() => isActivee(1)} className={`nlpo ${isActiveOne ? 'nlpo-active' : ''}`}>Définition</li>
<li onClick={() => isActivee(2)} className={`nlpo ${isActiveTwo ? 'nlpo-active' : ''}`}>Diagramme</li>
<li onClick={() => isActivee(3)} className={`nlpo ${isActiveThree ? 'nlpo-active' : ''}`}>3</li>
<li onClick={() => isActivee(4)} className={`nlpo ${isActiveFour ? 'nlpo-active' : ''}`}>4</li>
<li onClick={() => isActivee(5)} className={`nlpo ${isActiveFive ? 'nlpo-active' : ''}`}>5</li>
<li onClick={() => isActivee(6)} className={`nlpo ${isActiveSix ? 'nlpo-active' : ''}`}>6</li>
<li onClick={() => isActivee(7)} className={`nlpo ${isActiveSeven ? 'nlpo-active' : ''}`}>7</li>
</ul>
</div>
<div className={` ${isActiveTwo ? '' : 'po-table-wrapper-b'}`}>
<div className="veBtnContainer" role="group">
<button type="button" className="btn btn-icon" onclick="ZoomIn(1)">
<FontAwesomeIcon icon={faSearchPlus}></FontAwesomeIcon>
</button>
<button type="button" className="btn btn-icon" onclick="ZoomOut(1)">
<FontAwesomeIcon icon={faSearchMinus}></FontAwesomeIcon>
</button>
<button type="button" className="btn btn-icon" onclick="OriginalSize(1);">
<FontAwesomeIcon icon={faExpand}></FontAwesomeIcon>
</button>
<button type="button" className="btn btn-icon" onclick="SizeToWidth(1);">
<FontAwesomeIcon icon={faArrowsAltV}></FontAwesomeIcon>
</button>
<button type="button" className="btn btn-icon" onclick="SizeToHeight(1);">
<FontAwesomeIcon icon={faArrowsAltH}></FontAwesomeIcon>
</button>
</div>
<div>
<img className="OGimg" src="assets/images/93bf9d395db42247_c_fa10fac95ff2442d.png" alt="../images/93bf9d395db42247_c_fa10fac95ff2442d.png" usemap="#FA10FAC95FF2442D" border="0" />
</div>
</div>
<div className={`po-table-wrapper ${isActiveOne ? 'po-table-wrapper' : 'po-table-wrapper-b'}`} >
<table className="po-table" >
<thead>
<tr>
<th>Type</th>
<th>Interne/Externe</th>
<th>Adresse electronique</th>
</tr>
</thead>
<tbody>
<tr>
<td>{Acteur.type}</td>
<td>{Acteur.profile}</td>
<td>{Acteur.email}</td>
</tr>
</tbody>
</table>
</div>
<div className={`po-table-wrapper ${isActiveOne ? 'po-table-wrapper' : 'po-table-wrapper-b'}`} >
<div>
<h5 style={{padding: '1%', textAlign: 'center', backgroundColor: '#324960', color: 'white'}}>Description</h5>
<p style={{padding: '2%'}}>{Acteur.description}</p>
</div>
</div>
</div>
)
}
|
import React, {Component, PropTypes} from 'react';
import {pushPath} from 'redux-simple-router';
import {connect} from 'react-redux';
import CustomTheme from '../theme';
import ThemeManager from 'material-ui/lib/styles/theme-manager';
import ThemeDecorator from 'material-ui/lib/styles/theme-decorator';
import AppBar from 'material-ui/lib/app-bar';
import IconButton from 'material-ui/lib/icon-button';
import IconMenu from 'material-ui/lib/menus/icon-menu';
import MoreVertIcon from 'material-ui/lib/svg-icons/navigation/more-vert';
import MenuItem from 'material-ui/lib/menus/menu-item';
@ThemeDecorator(ThemeManager.getMuiTheme(CustomTheme))
class App extends Component {
static propTypes = {
children: PropTypes.node.isRequired,
onPushPath: PropTypes.func.isRequired
}
redirectHandler(path) {
return () => {
this.props.onPushPath(path);
};
}
render() {
return (
<div>
<AppBar
title="Tarkan's Awesome Chat App"
iconElementRight={
<IconMenu
iconButtonElement={
<IconButton><MoreVertIcon /></IconButton>
}
targetOrigin={{horizontal: 'right', vertical: 'top'}}
anchorOrigin={{horizontal: 'right', vertical: 'top'}}
>
<MenuItem primaryText="My Account" onClick={this.redirectHandler('/account')} />
<MenuItem primaryText="Log out" onClick={this.redirectHandler('/logout')} />
</IconMenu>
}
/>
{this.props.children}
</div>
);
}
}
const bindActions = {
onPushPath: pushPath
};
export default connect(null, bindActions)(App);
|
/**
* Module dependencies.
*/
var express = require('express'),
// routes = require('./routes'),
http = require('http');
var app = express();
var server = app.listen(3030);
var io = require('socket.io').listen(server);
var SerialPort = require("serialport").SerialPort;
var serialPort;
var sock;
var alphabet = {
"0x4A 0x00 0x42 0xD9" : 'A'
}
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.static(__dirname + '/public'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
});
app.configure('development', function(){
app.use(express.errorHandler());
});
app.get('/', function(){
});
io.sockets.on('connection', function (socket) {
sock = socket;
// socket.emit('news', { hello: 'world' });
// socket.on('my other event', function (data) {
// console.log(data);
// });
sock.emit('serial', { data: "0x4A 0x00 0x42 0xD9", charecter: "A" })
});
serialPort = new SerialPort("/dev/tty-usbserial1", {
baudrate: 9600
});
serialPort.on("open", function () {
console.log('open');
serialPort.on('data', function(data) {
var charecter;
if(data in alpahbet) charecter = alphabet[data];
console.log('data received: ', data, charecter);
if (data == 'Ready') {
if (sock) sock.emit('ready');
} else {
if (sock) sock.emit('serial', { data: data, charecter: charecter });
}
});
// serialPort.write("ls\n", function(err, results) {
// console.log('err ' + err);
// console.log('results ' + results);
// });
});
console.log("Express server listening on port 3030");
|
import React from 'react';
import { Switch, Redirect } from 'react-router-dom';
import routes from '../routes';
import RouteWithLayout from '../RouteWithLayout';
const MainLayout = React.lazy(() => import('../layouts/Main'));
const MinimalLayout = React.lazy(() => import('../layouts/Minimal'));
const Login = React.lazy(() => import('./Login'));
const Register = React.lazy(() => import('./Register'));
const Page404 = React.lazy(() => import('./Page404'));
const Nav = () => {
return (
<Switch>
<Redirect
exact
from="/"
to="/landing"
/>
{routes.map((route, idx) => {
return(
<RouteWithLayout
key={idx}
path={route.path}
exact={route.exact}
component={route.component}
layout={route.layout}
/>)
})}
<Redirect to="/not-found" />
</Switch>
);
};
export default Nav;
|
let lazyLoadInstance = new LazyLoad();
document.addEventListener("DOMContentLoaded", () => {
if (document.getElementById('sliderBrands')) {
const sliderBrands = new Swiper('#sliderBrands', {
slidesPerView: 6,
navigation: {
nextEl: '.button-next',
prevEl: '.button-prev',
},
breakpoints: {
768: {
slidesPerView: 4,
},
991: {
slidesPerView: 4,
},
1200: {
slidesPerView: 6,
},
},
on: {
init: function (e) {
if (window.innerWidth < 575) {
e.destroy();
}
}
}
});
}
if (document.getElementById('certificateSlider')) {
const sliderBrands = new Swiper('#certificateSlider', {
slidesPerView: 6,
navigation: {
nextEl: '.button-next',
prevEl: '.button-prev',
},
spaceBetween: 30,
breakpoints: {
320: {
slidesPerView: 2,
spaceBetween: 10
},
576: {
slidesPerView: 3,
spaceBetween: 10
},
768: {
slidesPerView: 4,
spaceBetween: 20
},
991: {
slidesPerView: 4,
spaceBetween: 30
},
1200: {
slidesPerView: 6,
spaceBetween: 30
},
}
});
}
if (document.getElementById('viewedSlider')) {
const sliderBrands = new Swiper('#viewedSlider', {
slidesPerView: 4,
navigation: {
nextEl: '.button-next',
prevEl: '.button-prev',
},
spaceBetween: 30,
breakpoints: {
300: {
slidesPerView: 1,
spaceBetween: 25
},
576: {
slidesPerView: 2,
spaceBetween: 25
},
768: {
slidesPerView: 3,
spaceBetween: 25
},
991: {
slidesPerView: 3,
spaceBetween: 30
},
1200: {
slidesPerView: 4,
spaceBetween: 30
},
}
});
}
if (document.getElementById('sliderAction')) {
const sliderAction = new Swiper('#sliderAction', {
slidesPerView: 4,
navigation: {
nextEl: '#nextAction',
prevEl: '#prevAction',
},
preloadImages: false,
lazy: true,
spaceBetween: 30,
breakpoints: {
300: {
slidesPerView: 1,
spaceBetween: 25
},
576: {
slidesPerView: 2,
spaceBetween: 25
},
768: {
slidesPerView: 3,
spaceBetween: 25
},
991: {
slidesPerView: 3,
spaceBetween: 30
},
1200: {
slidesPerView: 4,
spaceBetween: 30
},
}
});
}
if (document.getElementById('sliderCat')) {
const sliderBrands = new Swiper('#sliderCat', {
navigation: {
nextEl: '#sliderCatNext',
prevEl: '#sliderCatPrev',
},
spaceBetween: 5,
pagination: {
el: '.swiper-pagination',
clickable: true,
},
loop: true,
/*autoHeight: true,*/
effect: 'fade',
fadeEffect: {
crossFade: true
},
preloadImages: false,
lazy: true,
});
}
if (window.innerWidth >= 1200) {
const navs = document.querySelectorAll('.complex__catalog-nav__list li');
navs.forEach(el => {
el.addEventListener('mouseover', () => {
let activeNav = document.querySelector('.complex__catalog-nav__list .active');
if (activeNav) {
activeNav.classList.remove("active");
}
el.classList.add('active');
let activeIdSubNav = el.dataset.hoverMenu;
let removeActiveNav = document.querySelector('.complex__catalog-nav__list__submenu.active');
if (removeActiveNav) {
removeActiveNav.classList.remove("active");
}
if (document.getElementById(activeIdSubNav)) {
document.getElementById(activeIdSubNav).classList.add("active");
}
});
});
if (document.getElementById("clients")) {
let clients = document.getElementById("clients");
let iPos = clients.offsetTop;
function partnersScroll() {
let scrollAmount = Math.max(window.pageYOffset, document.documentElement.scrollTop, document.body.scrollTop),
screenHeight = window.innerWidth,
windowWidth = window.innerHeight;
const clientsRow = document.querySelectorAll('.complex__clients__row');
clientsRow.forEach(el => {
if (scrollAmount + screenHeight > iPos - 10) {
let translateValue = .3 * (-scrollAmount + iPos - screenHeight);
el.style.transform = "translateX(" + translateValue + "px)";
}
});
}
window.addEventListener('scroll', function () {
partnersScroll();
});
}
function getScrollMenu() {
let el = document.getElementById('fixNav');
if (pageYOffset > 300) {
el.classList.add('active');
} else {
el.classList.remove("active");
}
}
getScrollMenu();
window.addEventListener('scroll', function () {
getScrollMenu();
});
const goTopBtn = document.getElementById('btnTop');
window.addEventListener('scroll', trackScroll);
function trackScroll() {
var scrolled = window.pageYOffset;
var coords = document.documentElement.clientHeight;
if (scrolled > coords) {
goTopBtn.classList.add('_show');
}
if (scrolled < coords) {
goTopBtn.classList.remove('_show');
}
}
trackScroll();
} else {
/*function getScrollMenuMob() {
let el = document.getElementById('fixNav');
if (pageYOffset > 200) {
el.classList.add('active_mob');
} else {
el.classList.remove("active_mob");
}
}
getScrollMenuMob();
window.addEventListener('scroll', function () {
getScrollMenuMob();
});*/
if (document.getElementById("clients")) {
const clientsSlider = new Swiper('#clientsSlider', {
slidesPerView: 6,
breakpoints: {
300: {
slidesPerView: 3,
},
576: {
slidesPerView: 4,
},
768: {
slidesPerView: 4,
},
991: {
slidesPerView: 5,
},
1200: {
slidesPerView: 6,
},
},
navigation: {
nextEl: '#clientsNext',
prevEl: '#clientsPrev',
},
});
}
if (document.getElementById('catalogModal')) {
let catalogModal = document.getElementById('catalogModal');
catalogModal.addEventListener('show.bs.modal', function (event) {
document.getElementById('fixNav').classList.add("active-menu");
});
catalogModal.addEventListener('hidden.bs.modal', function (event) {
document.getElementById('fixNav').classList.remove("active-menu");
});
}
const navsMob = document.querySelectorAll('.complex__catalog-nav__list__item');
navsMob.forEach(el => {
el.addEventListener('click', (event) => {
let liNav = el.parentNode;
let activeIdSubNav = liNav.dataset.hoverMenu;
if (liNav.classList.contains('is_active')) {
liNav.classList.remove('is_active');
document.getElementById('catalogNavNain').classList.remove('is_active');
document.getElementById(activeIdSubNav).classList.remove('is_active');
} else {
liNav.classList.add('is_active');
document.getElementById('catalogNavNain').classList.add('is_active');
document.getElementById(activeIdSubNav).classList.add('is_active');
}
//console.log(activeIdSubNav);
event.preventDefault(false);
});
});
if (document.getElementById('mobFilter')) {
document.getElementById('mobFilter').addEventListener('click', (event) => {
document.getElementById('filterBox').classList.add('is_active');
document.getElementById('filterBox').classList.add('is_active');
document.getElementById('top').classList.add('full-height');
event.preventDefault();
});
document.getElementById('mobFilterClose').addEventListener('click', (event) => {
document.getElementById('filterBox').classList.remove('is_active');
document.getElementById('filterBox').classList.remove('is_active');
document.getElementById('top').classList.remove('full-height');
event.preventDefault();
});
}
}
if (document.getElementById('moreTextBtn')) {
document.getElementById("moreTextBtn").addEventListener("click", (e) => {
document.getElementById("moreTextBtn").classList.add("d-none");
document.getElementById("moreText").style.display = "block";
e.preventDefault(false);
});
}
if (document.getElementsByClassName("js-more-props").length) {
const moreProps = document.querySelectorAll('.js-more-props');
moreProps.forEach(el => {
el.addEventListener('click', (event) => {
event.target.parentNode.parentNode.classList.add('show_all');
event.preventDefault(false);
});
});
}
if (document.getElementById('priceRange')) {
let priceRange = document.getElementById('priceRange');
noUiSlider.create(priceRange, {
start: [0, parseInt(priceRange.dataset.maxPrice)],
step: 1000,
connect: true,
format: wNumb({
decimals: 0,
thousand: ' ',
//suffix: ' ₽'
}),
range: {
'min': 0,
'max': parseInt(priceRange.dataset.maxPrice)
}
});
let priceMin = document.getElementById('priceMin'),
priceMax = document.getElementById('priceMax');
priceRange.noUiSlider.on('update', function (values, handle) {
//priceValue[handle].value = values[handle];
if (handle == 0) {
priceMin.value = values[handle];
} else {
priceMax.value = values[handle];
}
});
}
const phoneMask = document.querySelectorAll('.js-phone-mask');
phoneMask.forEach(el => {
IMask(el, {
mask: '+{7}(000)000-00-00',
});
});
if (document.getElementById('projectSlider')) {
const imageSliders = document.querySelectorAll('.complex__projects__item__slider');
let numberSlider = 1;
let projectThumbsSlider = [];
imageSliders.forEach(el => {
let projectThumbs = el.querySelector('.project-thumbs');
let selectSlider1 = '#' + projectThumbs.id;
let selectSlider2 = projectThumbs.dataset.sliderid;
projectThumbsSlider[numberSlider] = new Swiper(selectSlider1, {
loop: false,
spaceBetween: 30,
slidesPerView: 6,
freeMode: true,
watchSlidesProgress: true,
lazy: true,
breakpoints: {
300: {
spaceBetween: 10,
},
576: {
spaceBetween: 10,
},
1200: {
spaceBetween: 30,
},
},
});
//let projectImages = el.querySelector('.project-images');
//console.log(projectImages);
new Swiper(selectSlider2, {
loop: false,
spaceBetween: 10,
lazy: true,
pagination: {
el: '.swiper-pagination',
clickable: true,
},
thumbs: {
swiper: projectThumbsSlider[numberSlider],
},
});
numberSlider++;
});
let projectSlider = new Swiper('#projectSlider', {
effect: 'fade',
autoHeight: true,
fadeEffect: {
crossFade: true
},
navigation: {
nextEl: '#sl-next',
prevEl: '#sl-prev',
},
});
}
if (document.getElementById('objSliderTop') && screen.width < 769) {
const objSliderTop = new Swiper('#objSliderTop', {
slideClass: 'complex__obj-slider-top__item',
wrapperClass: 'complex__obj-slider-top__row',
navigation: {
nextEl: '#objSliderTop .button-next',
prevEl: '#objSliderTop .button-prev',
},
});
}
if (document.getElementById('projThumbSingle')) {
let projThumbSingle = new Swiper('#projThumbSingle', {
loop: false,
spaceBetween: 30,
slidesPerView: 6,
freeMode: true,
watchSlidesProgress: true,
lazy: true,
breakpoints: {
300: {
spaceBetween: 10,
},
576: {
spaceBetween: 10,
},
1200: {
spaceBetween: 30,
},
},
});
new Swiper('#projSingle', {
loop: false,
spaceBetween: 10,
lazy: true,
pagination: {
el: '.swiper-pagination',
clickable: true,
},
navigation: {
nextEl: '#projSingleNext',
prevEl: '#projSinglePrev',
},
thumbs: {
swiper: projThumbSingle,
},
});
}
if (document.getElementById('productBig')) {
let productMin = new Swiper('#productMin', {
loop: false,
spaceBetween: 30,
slidesPerView: 6,
/*freeMode: true,*/
watchSlidesProgress: true,
lazy: true,
breakpoints: {
576: {
spaceBetween: 10,
},
1200: {
spaceBetween: 30,
},
},
});
new Swiper('#productBig', {
loop: false,
spaceBetween: 10,
lazy: true,
pagination: {
el: '.swiper-pagination',
clickable: true,
},
thumbs: {
swiper: productMin,
},
});
}
if (document.getElementsByClassName("complex__slider-product").length) {
let swiperCatalog = new Swiper('.complex__slider-product', {
navigation: {
nextEl: '.button-next',
prevEl: '.button-prev',
},
slidesPerView: 4,
lazy: true,
observer: true,
observeParents: true,
spaceBetween: 30,
//loop: true,
//simulateTouch: false,
breakpoints: {
300: {
slidesPerView: 1,
spaceBetween: 0,
},
440: {
slidesPerView: 1,
spaceBetween: 0,
},
600: {
slidesPerView: 2,
},
991: {
slidesPerView: 3,
},
1280: {
slidesPerView: 4,
},
},
on: {
init: function () {
},
},
});
}
function setEqualHeight(elements) {
var mainDivs = document.getElementsByClassName(elements);
var maxHeight = 0;
for (var i = 0; i < mainDivs.length; ++i) {
if (maxHeight < mainDivs[i].clientHeight) {
maxHeight = mainDivs[i].clientHeight;
}
}
for (var i = 0; i < mainDivs.length; ++i) {
mainDivs[i].style.minHeight = maxHeight + "px";
}
}
function activeSlideCompare() {
let compareSlider = new Swiper('#compareSlider', {
navigation: {
nextEl: '#compareNext',
prevEl: '#comparePrev',
},
slidesPerView: 3,
spaceBetween: 30,
lazy: true,
//loop: true,
breakpoints: {
200: {
slidesPerView: 1,
spaceBetween: 0,
navigation: {
nextEl: '#compareSlider .button-next',
prevEl: '#compareSlider .button-prev',
},
},
768: {
slidesPerView: 2,
spaceBetween: 20,
navigation: {
nextEl: '#compareNext',
prevEl: '#comparePrev',
},
},
1280: {
slidesPerView: 3,
spaceBetween: 30,
navigation: {
nextEl: '#compareNext',
prevEl: '#comparePrev',
},
},
},
on: {
init: function () {
sinfroCompareRow();
},
resize: function () {
sinfroCompareRow();
}
},
});
}
function sinfroCompareRow() {
let rowCompare = [].slice.call(document.querySelectorAll('.js-compare-props li'))
rowCompare.forEach(function (e) {
setEqualHeight(e.dataset.sinhro);
});
}
if (document.getElementById('compareSlider')) {
activeSlideCompare();
let compareSlider2 = new Swiper('#compareSlider2', {
navigation: {
nextEl: '#compareSlider2 .button-next',
prevEl: '#compareSlider2 .button-prev',
},
slidesPerView: 1,
lazy: true,
on: {
init: function () {
},
}
});
compareSlider2.slideTo(1);
}
});
|
"use strict";
exports.__esModule = true;
var ws_1 = require("ws");
var sa = require('songle-api');
var sw = require('songle-widget');
var NUM_LEDS = parseInt(process.argv[2], 10) || 10;
//ws281
var ws281x = require('ws281x-native');
var pixelData = new Uint32Array(NUM_LEDS);
ws281x.init(NUM_LEDS);
//ws
var port = 8888;
var wss = new ws_1.Server({ port: port });
console.log("listening port: ", port);
wss.on('connection', function (ws) {
console.log('connection');
ws.on('message', function (msg) {
console.log('received: %s', msg);
ws.send('Hello from ws');
});
ws.on('close', function () {
console.log('close');
});
});
//songelsync
var settings = require('./settings');
var player = new sa.Player({
accessToken: settings.tokens.access
});
player.addPlugin(new sa.Plugin.Beat);
player.addPlugin(new sw.Plugin.Chord);
player.addPlugin(new sa.Plugin.SongleSync);
player.on("play", function (ev) { return console.log("play"); });
player.on("seek", function (ev) { return console.log("seek"); });
player.on("pause", function (ev) { return console.log("pause"); });
player.on("finish", function (ev) { return console.log("finish"); });
player.on("beatPlay", function (ev) {
console.log("beat:", ev.data.beat.position);
// beatflash(ev.data.beat.position);
});
player.on("chordPlay", function (ev) {
console.log("chordName:", ev.data.chord.name);
});
//util
function rgb2Int(r, g, b) {
return ((r & 0xff) << 16) + ((g & 0xff) << 8) + (b & 0xff);
}
function flash(r, g, b) {
pixelData.forEach(function (value) {
value = rgb2Int(r, g, b);
});
ws281x.remder(pixelData);
}
// function beatflash(beat: number) {
// if (beat == 1) {flash(255, 0, 0);
// } else if (beat == 2) {flash(0, 255, 0);
// } else if (beat == 3) {flash(0, 0, 255);
// } else if (beat == 4) {flash(255, 255, 255);
// } else {console.log("error dayon");
// }
// flash(0, 0, 0);
// }
|
//樹形図作成js
var myJSONObject = {};//モデルデータ一覧
var modelGene = [];//世代を記録する配列
var JYUKEI = [];
//樹形図の階層を探る
for (var ii = 0; ii < modelParentId.length; ii++) {
//var idss = modelIds[ii];
var idss = modelIds.indexOf(ii+1);
//console.log(ii+":"+idss);
var pID = modelParentId[idss];
var currentpID = pID;
var cou = 0;
var chi = [];
var ob = {"name":modelNames[idss], "ID":modelIds[idss], "children":chi, "paID":pID, "ipt":modelInitialPoints[idss], "apt":modelAdditionalPoints[idss], "cost":modelCosts[idss], "mpd":modelParentDifference[idss], "time":modelCreationTime[idss]};
JYUKEI.push(ob);
while (currentpID != 0) {
currentpID = ID(currentpID);
cou += 1;
}
modelGene.push(cou);
}
console.log(JYUKEI);
var mx = Math.max.apply(null, modelGene);
var my = array_count_values(modelGene);
//自分の子供データをインポート
for (var k = JYUKEI.length - 1; k >= 0; k--) {
var pn = JYUKEI[k].paID;//modelParentId[k];
if (pn > 0) {
var IDD = pn-1;//modelIds.indexOf(pn);
console.log(k+"::"+pn+"::"+IDD);
JYUKEI[IDD].children.push(JYUKEI[k]);
}
}
//樹形図の階層データをインポート
//ID:0が祖先
myJSONObject = JYUKEI[0];
//自分が何世代目かを調べる
function ID(_num) {
var nn = _num;
var cID;
if (nn == 0) {
cID = 0
} else {
var IDD = modelIds.indexOf(nn);
var cID = modelParentId[IDD]
}
return cID;
}
//キャンバスサイズ
//var width = mx * 200;//1280,
//var height = my * 150;//768;
var width = 1280;
var height =768;
var hc = height/2/100;
//drag用の設定(polymap)
var po = org.polymaps;
// Create the map object, add it to #map…
var map = po.map()
.container(d3.select("#map").append("svg:svg").node())
.center({lat:hc+2, lon:12})
.zoom(6)
.zoomRange([5, 7])
.add(po.interact());
// Add the compass control on top.
//map.add(po.compass()
// .pan("none"));
//d3初期設定
var cluster = d3.layout.tree()
.size([height, -width - 160]);
var diagonal = d3.svg.diagonal()
.projection(function (d) {
d = map.pointLocation({x:d.y, y:d.x});
var ll = -d.lon;// + 20;
var la = d.lat;// + 3;
return [ll * 50, la * 50];
//return [d.y, d.x];
});
var layer = d3.select("#map svg")
//.insert("svg:g", ".compass")
.insert("svg:g")
.attr("width", width)
.attr("height", height);
//樹形図描画
var nodes = cluster.nodes(myJSONObject);
//
var link = layer.selectAll("g")
//.insert("svg:g")
.data(cluster.links(nodes))
.enter().append("path")
.attr("class", "link")
.attr("d", diagonal)
.style("stroke-width", function (d) {
return Math.round(d.target.mpd * 5);
});
var node = layer.selectAll("g")
.data(nodes)
.enter().append("svg:g")
.attr("class", "node")
.attr("transform", transform);
node.append("svg:image")
.attr("xlink:href", function (d) {
var name = d.name;
var ch = d.paID;
var tm = d.time;
return "http://lmnarchitecture.com/thumbnail/" + name + "_" + ch + "_" + tm + "_s.png";
})
.attr("x", "-50px")
.attr("y", "-70px")
.attr("width", "100px")
.attr("height", "100px");
var xDis = 30;
var yDis = -40;
layer.selectAll("g")
.on("mouseover", function (d, i) {
d3.select(this)
.style('opacity', 0.8)
.style('fill', d3.rgb(0, 0, 255));
})
.on("mouseout", function (d, i) {
d3.select(this)
.style("fill", d3.rgb(0, 0, 0))
.style('opacity', 1);
})
.on("click", function (d, i) {
d3.select(this)
.style("fill", d3.rgb(255, 0, 0));
//link設定
gotoView(d.ID, d.paID);
});
node.append("text")
.attr("dx", -40)
.attr("dy", 7)
.attr("text-anchor", "left")
.style("font", "7px sans-serif")
.text(function (d) {
return "ID: ";
});
node.append("text")
.attr("dx", -40)
.attr("dy", 20)
.attr("text-anchor", "left")
.style("font", "15px sans-serif")
.text(function (d) {
return d.ID;
});
node.append("text")
.attr("dx", xDis)
.attr("dy", yDis - 10)
.attr("text-anchor", "left")
.style("font", "7px sans-serif")
.text(function (d) {
return "モデル名";
});
node.append("text")
.attr("dx", xDis)
.attr("dy", yDis)
.attr("text-anchor", "left")
.text(function (d) {
return d.name;
});
//
//node.append("text")
// .attr("dx", xDis)
// .attr("dy", yDis + 5)
// .attr("text-anchor", "left")
// .style("font","7px sans-serif")
// .text(function (d) {
// return "------------------";
// });
node.append("text")
.attr("dx", xDis)
.attr("dy", yDis + 15)
.attr("text-anchor", "left")
.text(function (d) {
return "親ID: " + d.paID;
});
node.append("text")
.attr("dx", xDis)
.attr("dy", yDis + 25)
.attr("text-anchor", "left")
.text(function (d) {
return "dif: " + Math.floor(d.mpd * 10000) / 100 + "%";
});
//node.append("text")
// .attr("dx", xDis)
// .attr("dy", yDis + 40)
// .attr("text-anchor", "left")
// .text(function (d) {
// return "i:" + d.ipt +"pts +"+"a:" + d.apt +"pts";
// });
node.append("text")
.attr("dx", xDis)
.attr("dy", yDis + 50)
.attr("text-anchor", "left")
.text(function (d) {
var sum = d.ipt + d.apt;
return sum + "pts";
});
node.append("text")
.attr("dx", xDis)
.attr("dy", yDis + 60)
.attr("text-anchor", "left")
.text(function (d) {
return d.cost + "万円";
});
map.on("move", function () {
layer.selectAll("g").attr("transform", transform);
layer.selectAll("g path").attr("d", diagonal);
});
//マウスドラッグ関数
function transform(d) {
var xxx, yyy;
var name;
if (d.x == undefined) {
xxx = d.source.x;
yyy = d.source.y;
} else {
xxx = d.x;
yyy = d.y;//console.log(d.x);
}
var x = xxx;
var y = yyy;
d = map.pointLocation({x:y, y:x});
var ll = -d.lon;
var la = d.lat;
return "translate(" + ll * 50 + "," + la * 50 + ")";
}
//オブジェクトのページへのリンク
function gotoView(modelId, modelParentId) {
var form = document.createElement("form");
document.body.appendChild(form);
var modelIdInput = document.createElement("input");
modelIdInput.setAttribute("type", "hidden");
modelIdInput.setAttribute("name", "modelId");
modelIdInput.setAttribute("value", modelId);
form.appendChild(modelIdInput);
var modelParentId = document.createElement("input");
modelParentId.setAttribute("type", "hidden");
modelParentId.setAttribute("name", "modelParentId");
modelParentId.setAttribute("value", modelParentId);
form.appendChild(modelIdInput);
form.setAttribute("action", "view.php");
form.setAttribute("method", "post");
form.submit();
}
//配列内の最も多い要素の数を調べる
function array_count_values(array) {
var tmp_arr = {},
key = '',
t = '';
var __getType = function (obj) {
// Objects are php associative arrays.
var t = typeof obj;
t = t.toLowerCase();
if (t === "object") {
t = "array";
}
return t;
};
var __countValue = function (value) {
switch (typeof(value)) {
case "number":
if (Math.floor(value) !== value) {
return;
}
// Fall-through
case "string":
if (value in this && this.hasOwnProperty(value)) {
++this[value];
} else {
this[value] = 1;
}
}
};
t = __getType(array);
if (t === 'array') {
for (key in array) {
if (array.hasOwnProperty(key)) {
__countValue.call(tmp_arr, array[key]);
}
}
}
//return tmp_arr;
var countArray = [];
for (var i in tmp_arr) {
countArray.push(tmp_arr[i]);
}
var maxCount = Math.max.apply(null, countArray);
return maxCount;
}
|
import React, {Component} from 'react';
import {StyleSheet, View, WebView} from 'react-native';
class WebViewScreen extends Component {
static navigationOptions = {
title: 'Đọc thêm',
headerBackTitle: 'Back',
};
constructor(props) {
super(props);
}
render() {
console.log(this.props);
return (
<View style={styles.container}>
<WebView
source={{uri: this.props.navigation.state.params}}
/>
</View>
)
}
}
export default WebViewScreen;
const styles = StyleSheet.create({
container: {
backgroundColor: '#FFF',
flex: 1
}
});
|
import React, { Component } from "react"
import PasswordRecoveryError from "./PasswordRecoveryError"
import InputAdornment from "@material-ui/core/InputAdornment"
import IconButton from "@material-ui/core/IconButton"
import Button from "@material-ui/core/Button"
import Typography from "@material-ui/core/Typography"
import CircularProgress from "@material-ui/core/CircularProgress"
import Fade from "@material-ui/core/Fade"
import zxcvbn from "zxcvbn"
import gql from "graphql-tag"
import logo from "./styles/assets/logo.svg"
import { Redirect, Link } from "react-router-dom"
import CenteredSpinner from "./components/CenteredSpinner"
import Visibility from "@material-ui/icons/Visibility"
import VisibilityOff from "@material-ui/icons/VisibilityOff"
import TextField from "@material-ui/core/TextField"
import MuiThemeProvider from "@material-ui/core/styles/MuiThemeProvider"
import createMuiTheme from "@material-ui/core/styles/createMuiTheme"
const theme = createMuiTheme({
palette: {
default: { main: "#fff" },
primary: { light: "#0083ff", main: "#0057cb" },
secondary: { main: "#ff4081" },
error: { main: "#f44336" },
},
overrides: {
MuiInput: {
root: {
color: "white",
},
},
MuiFormControlLabel: {
label: {
color: "white",
},
},
MuiFormLabel: {
root: {
color: "white",
opacity: 0.8,
"&$focused": {
color: "white",
opacity: 0.8,
},
},
},
MuiInputBase: { root: { color: "white" } },
},
})
export default class PasswordRecovery extends Component {
state = {
showPassword: false,
redirect: false,
showLoading: false,
passwordError: "",
}
async updatePassword() {
this.setState({ showLoading: true })
try {
let changePassword = await this.props.client.mutate({
mutation: gql`
mutation($newPassword: String!) {
changePassword(newPassword: $newPassword) {
token
user {
id
email
name
profileIconColor
}
}
}
`,
variables: {
newPassword: this.props.password,
},
})
if (typeof Storage !== "undefined") {
localStorage.setItem(
"userId",
changePassword.data.changePassword.user.id
)
localStorage.getItem("accountList")
? !JSON.parse(localStorage.getItem("accountList")).some(
account =>
account.id === changePassword.data.changePassword.user.id
) &&
localStorage.setItem(
"accountList",
JSON.stringify([
...JSON.parse(localStorage.getItem("accountList")),
{
token: changePassword.data.changePassword.token,
...changePassword.data.changePassword.user,
},
])
)
: localStorage.setItem(
"accountList",
JSON.stringify([
{
token: changePassword.data.changePassword.token,
...changePassword.data.changePassword.user,
},
])
)
}
this.forceUpdate()
this.setState({ redirect: true })
} catch (e) {
this.setState({ passwordError: "Unexpected error" })
}
this.setState({ showLoading: false })
}
updateDimensions() {
if (window.innerWidth < 400) {
!this.state.isMobile && this.setState({ isMobile: true })
} else {
this.state.isMobile && this.setState({ isMobile: false })
}
}
componentDidMount() {
this.updateDimensions()
window.addEventListener("resize", this.updateDimensions.bind(this))
}
componentWillUnmount() {
window.removeEventListener("resize", this.updateDimensions.bind(this))
}
render() {
document.body.style.backgroundColor = "#0057cb"
const {
userData: { error, loading, user },
} = this.props
let scoreText = ""
switch (this.state.passwordScore) {
case 0:
scoreText = "Very weak"
break
case 1:
scoreText = "Weak"
break
case 2:
scoreText = "Average"
break
case 3:
scoreText = "Strong"
break
case 4:
scoreText = "Very strong"
break
default:
scoreText = ""
break
}
if (!this.props.password) scoreText = ""
if (error) {
if (
error.message !==
"Network error: Response not successful: Received status code 401"
)
return "Unexpected error"
else {
return <PasswordRecoveryError error="Your recovery link is expired" />
}
}
if (loading) {
return (
<div
style={{
width: "100vw",
height: "100vh",
backgroundColor: "#0057cb",
display: "flex",
justifyContent: "center",
alignItems: "center",
}}
className="notSelectable defaultCursor"
>
<Fade
in={true}
style={{
transitionDelay: "800ms",
}}
unmountOnExit
>
<CircularProgress size={96} color="secondary" />
</Fade>
</div>
)
}
if (this.props.isTokenValid) {
return <PasswordRecoveryError error="Your recovery link isn't valid" />
}
if (this.state.redirect) {
return <Redirect push to="/" />
}
return (
<div
style={{
position: "absolute",
margin: "auto",
top: 0,
right: 0,
bottom: 0,
left: 0,
maxWidth: "332px",
maxHeight: "381px",
textAlign: "center",
padding: "0 32px",
backgroundColor: "#0057cb",
}}
className="notSelectable defaultCursor"
>
<img
src={logo}
alt="Igloo logo"
className="notSelectable nonDraggable"
draggable="false"
style={{
maxWidth: "192px",
marginBottom: "72px",
marginLeft: "auto",
marginRight: "auto",
}}
/>
<Typography
variant={this.state.isMobile ? "h5" : "h4"}
style={{ color: "white", marginBottom: "32px" }}
>
Recover your account
</Typography>
<MuiThemeProvider theme={theme}>
<TextField
variant="outlined"
id="recovery-new-password"
label="New password"
style={{
color: "white",
width: "100%",
marginBottom: "16px",
}}
value={this.props.password}
type={this.state.showPassword ? "text" : "password"}
onChange={event => {
this.setState({
passwordScore: zxcvbn(event.target.value, [
user.email,
user.email.split("@")[0],
user.name,
"igloo",
"igloo aurora",
"aurora",
]).score,
isPasswordEmpty: event.target.value === "",
})
this.props.updatePassword(event.target.value)
}}
onKeyPress={event => {
if (event.key === "Enter") {
this.updatePassword(this.props.password)
}
}}
helperText={
<font style={{ color: "white" }}>
{(this.state.isPasswordEmpty
? "This field is required"
: this.state.passwordError) || scoreText}
</font>
}
endAdornment={
this.props.password ? (
<InputAdornment position="end">
<IconButton
onClick={() =>
this.setState(oldState => ({
showPassword: !oldState.showPassword,
}))
}
tabIndex="-1"
style={{ color: "white" }}
>
{this.state.showPassword ? (
<VisibilityOff />
) : (
<Visibility />
)}
</IconButton>
</InputAdornment>
) : null
}
/>
</MuiThemeProvider>
<MuiThemeProvider
theme={createMuiTheme({
palette: {
primary: { main: "#fff" },
},
})}
>
<Button
variant="outlined"
color="primary"
disabled={!user || !(this.state.passwordScore >= 2)}
onClick={() => {
this.updatePassword(this.props.password)
}}
fullWidth
style={{ marginBottom: "8px" }}
>
Change password
{this.state.showLoading && <CenteredSpinner isInButton noDelay />}
</Button>
</MuiThemeProvider>
<Button
style={{ marginRight: "4px" }}
fullWidth
component={Link}
to="/"
>
Never mind
</Button>
</div>
)
}
}
|
import Vue from 'vue'
import Router from 'vue-router'
import routes from '../modules/routes'
Vue.use(Router)
const router = new Router({
mode: 'history',
routes: [
{
path: '/admin',
redirect: '/admin/index',
component: () => import('../modules/Root.vue'),
children: [
...routes,
]
},
{
path: '/admin/login',
component: () => import('../modules/Login.vue')
},
{
path: '*',
redirect: '/admin/404'
}
],
})
router.beforeEach((to, from, next) => {
next()
})
export default router
|
import Course from "./Course";
export default function CourseList({ online, offline }) {
return (
<>
<section className="section-courseoffline">
<div className="container">
<p className="top-des">
The readable content of a page when looking at its layout. The point
of using Lorem Ipsum is that it has a more-or-less normal
</p>
<div className="textbox">
<h2 className="main-title">Khoá Học online</h2>
</div>
<div className="list row">
{online?.map((e) => (
<Course key={e._id} {...e} />
))}
</div>
</div>
</section>
<section className="section-courseonline">
<div className="container">
<div className="textbox">
<h2 className="main-title">Khoá Học offline</h2>
</div>
<div className="list row">
{offline?.map((e) => (
<Course key={e._id} {...e} />
))}
</div>
</div>
</section>
</>
);
}
|
/* global readingTime, translate */
/* exported ReadingTime */
class ReadingTime {
constructor(element) {
const rawText = document.querySelector('main').innerText
const duration = readingTime(rawText).approximate
element.innerText = translate.reading_time.replace('%minutes%', duration)
}
}
|
import FieldContext from "./FieldContext";
import useForm from './UseForm'
import { useImperativeHandle } from 'react'
const Form = ({ children, form, onFinish, onFinishFailed }, ref) => {
// 兼容class
const [formInstance] = useForm(form)
useImperativeHandle(ref, () => formInstance)
formInstance.setCallBack({ onFinish, onFinishFailed })
return (
<FieldContext.Provider value={formInstance}>
<form
onSubmit={(e) => {
e.preventDefault();
formInstance.submit();
}}
>
{children}
</form>
</FieldContext.Provider>
);
};
export default Form;
|
function type(list){
let contbool=0;
let contnum=0;
let contobj=0;
let contstrn=0;
list.forEach(element => {
console.log(typeof element)
switch(typeof element){
case'boolean': contbool++;
break;
case 'number': contnum++;
break;
case 'object': contobj++;
break;
case 'string': contstrn++;
break;
}
});
console.log(`Resultados: Boolean: ${contbool} Number: ${contnum} Object: ${contobj} String ${contstrn}`)
}
|
'use strict';
module.exports = (sequelize, DataTypes) => {
const Products = sequelize.define('Products', {
brandId: DataTypes.INTEGER,
productName: DataTypes.TEXT,
productPrice: DataTypes.DECIMAL,
productDesc: DataTypes.TEXT,
productImgPath: DataTypes.TEXT,
createdBy: DataTypes.INTEGER,
modifiedBy: DataTypes.INTEGER,
createdDate: DataTypes.DATE,
modifiedDate: DataTypes.DATE
});
Products.associate = (models) => {
Products.belongsTo(models.ProductsToCategories, {
foreignKey: 'id',
onDelete: 'CASCADE',
});
};
return Products;
};
|
sap.ui.controller("com.raprins.archetype.controller.PageContainer", {
onInit: function(){
}
});
|
var React = require('react');
var ThumbnailList = require('./thumbnail-list.jsx');
var options = {
thumbnailData: [
{title : "Dumbo",
number : 118,
header : "Dumbo",
description : "React is a fantastic new library full of newts.",
imageUrl : "http://www.ourbreathingplanet.com/wp-content/uploads/2014/03/215.png"
},{
title : "Cirrina",
number : 118,
header : "Cirrinna",
description : "React is a fantastic new library full of newts.",
imageUrl : "http://data.cyclowiki.org/images/thumb/e/ed/Cirrina.jpg/300px-Cirrina.jpg"
},
{title : "North Pacific giant octopus",
number : 118,
header : "North Pacific giant octopust",
description : "React is a fantastic new library full of newts.",
imageUrl : "http://calphotos.berkeley.edu/imgs/512x768/0000_0000/0407/0381.jpeg"
}]
};
var element = React.createElement(ThumbnailList, options);
React.render(element, document.querySelector('.container'));
|
import styled from 'styled-components';
const CardContainer = styled.div`
.card {
background: url(${(prop) => prop.srcMobile});
background-size: cover;
height: 12rem;
position: relative;
cursor: pointer;
color: white;
}
.card::after {
content: '';
position: absolute;
top: 0;
left: 0;
height: 100%;
width: 100%;
background: rgba(255, 255, 255, 0);
z-index: 0;
transition: 0.5s ease;
}
.card:hover::after {
background: rgba(255, 255, 255, 0.75);
}
.card:hover {
color: black;
}
.card h3 {
position: absolute;
z-index: 1;
left: 2rem;
top: 5.2rem;
width: ${(prop) => prop.mobileWidth};
height: 4.8rem;
text-align: start;
font-size: ${(prop) => prop.theme.smallFont};
font-weight: 300;
line-height: 2.4rem;
text-transform: uppercase;
}
@media screen and (min-width: 550px) {
.card {
height: 25.6rem;
}
}
@media screen and (min-width: 950px) {
.card {
background: url(${(prop) => prop.srcDesktop});
background-size: cover;
height: 45rem;
}
.card h3 {
font-size: 3.2rem;
line-height: 3rem;
position: absolute;
left: 4rem;
top: 35.4rem;
width: ${(prop) => prop.desktopWidth};
}
}
`;
const Card = ({ item, className }) => {
const { img, text, mobileWidth, desktopWidth } = item;
const mobilLogo = require(`../assets/img/mobile/image-${img}.jpg`).default;
const desktopLogo = require(`../assets/img/desktop/image-${img}.jpg`)
.default;
return (
<CardContainer
className={className}
srcMobile={mobilLogo}
srcDesktop={desktopLogo}
desktopWidth={desktopWidth}
mobileWidth={mobileWidth}>
<div className="card">
<h3>{text}</h3>
</div>
</CardContainer>
);
};
export default Card;
|
import SaveWorkControl from 'hyrax/save_work/save_work_control'
export default class GppSaveWorkControl extends SaveWorkControl {
activate() {
super.activate();
this.initializeDatesCoveredCallbacks();
this.initializeRequiredReportField();
}
validateMetadata(e) {
let titleValid = this.titleValidator();
let descriptionValid = this.descriptionValidator();
let subjectValid = this.publicationSubjectValidator();
let datesCoveredValid = this.datesCoveredValidator();
if (this.requiredFields.areComplete && titleValid && descriptionValid && subjectValid && datesCoveredValid) {
this.requiredMetadata.check();
return true;
}
this.requiredMetadata.uncheck();
return false;
}
// Sets the files indicator to complete/incomplete
validateFiles() {
if (!this.uploads.hasFileRequirement) {
return true
}
if (!this.isNew || this.uploads.hasFiles) {
// Check for potential errors such as viruses
let errors = $('span:contains("Error")');
if (errors.length > 0) {
this.requiredFiles.uncheck();
return false;
}
this.requiredFiles.check();
return true
}
this.requiredFiles.uncheck();
return false
}
formChanged() {
this.requiredFields.reload();
this.initializeDatesCoveredCallbacks();
this.formStateChanged();
this.onAgencyChange();
this.getReportDueDateId()
}
titleValidator() {
let title = $('#nyc_government_publication_title');
if (title.val().length < 10 || title.val().length > 150) {
return false;
}
return true;
}
descriptionValidator() {
let description = $('#nyc_government_publication_description');
if (description.val().length < 100 || description.val().length > 300) {
return false;
}
return true;
}
publicationSubjectValidator() {
let selectedSubjects = $('#nyc_government_publication_subject option:selected');
let subjectError = $('#publication-subject-error');
if (selectedSubjects.length > 3) {
subjectError.show();
subjectError.focus();
return false;
}
subjectError.hide();
return true;
}
datesCoveredValidator() {
let fiscalYear = $('#nyc_government_publication_fiscal_year');
let calendarYear = $('#nyc_government_publication_calendar_year');
if (fiscalYear.val().length === 0 && calendarYear.val().length === 0) {
return false;
}
return true;
}
initializeDatesCoveredCallbacks() {
$('#nyc_government_publication_fiscal_year').change(() => this.formStateChanged());
$('#nyc_government_publication_calendar_year').change(() => this.formStateChanged());
}
initializeRequiredReportField() {
let requiredReportField = $('#nyc_government_publication_required_report_name');
if (requiredReportField.val() === '') {
requiredReportField.prop('disabled', true);
} else {
let selectedAgency = $('#nyc_government_publication_agency').val();
this.getAgencyRequiredReports(requiredReportField, selectedAgency, requiredReportField.val());
}
}
getAgencyRequiredReports(requiredReportField, selectedAgency, selectedRequiredReport) {
$.ajax({
url: '/required_reports/agency_required_reports',
type: 'GET',
data: {'agency': selectedAgency},
dataType: 'JSON',
success: function(data) {
let reportDueDate = $('#report_due_date_id');
requiredReportField.empty();
reportDueDate.val('');
if (selectedAgency !== '') {
// Add blank option
requiredReportField.append(new Option('', ''));
data['required_report_names'].forEach(function (report) {
let option = new Option(report['report_name'] + ' (' + report['base_due_date'] + ')', report['report_name']);
option.setAttribute('report_due_date_id', report['report_due_date_id']);
requiredReportField.append(option);
});
// Add Not Required option
requiredReportField.append(new Option('Not Required', 'Not Required'));
requiredReportField.prop('disabled', false);
if (selectedRequiredReport !== null) {
requiredReportField.val(selectedRequiredReport);
reportDueDate.val(requiredReportField.find('option:selected').attr('report_due_date_id'));
}
}
else {
requiredReportField.prop('disabled', true);
}
},
error: function(data) {}
});
}
onAgencyChange() {
let agency = $('#nyc_government_publication_agency');
let requiredReportField = $('#nyc_government_publication_required_report_name');
agency.change(() => {
this.getAgencyRequiredReports(requiredReportField, agency.val(), null);
});
}
getReportDueDateId() {
let requiredReportField = $('#nyc_government_publication_required_report_name');
requiredReportField.on('change', function() {
$('#report_due_date_id').val(requiredReportField.find('option:selected').attr('report_due_date_id'));
});
}
}
|
cwt = {};
cwt.Util = {};
cwt.Util.extend = function (destination, source) {
if (destination && source) {
for (var property in source) {
var value = source[property];
if (value !== undefined) {
destination[property] = value
}
}
var sourceIsEvt = typeof window.Event == "function" && source instanceof window.Event;
if (!sourceIsEvt && source.hasOwnProperty && source.hasOwnProperty("toString")) {
destination.toString = source.toString
}
}
return destination
};
cwt.Util.addScripts = function (jsfiles, charset, language, type, event, defer) {
var ajaxDode = function (oXML) {
var jstext = oXML.responseText;
cwt.Util.writeScript(jstext, this.charset, this.language, this.type, this.event, this.defer)
};
for (var i = 0; i < jsfiles.length; i++) {
var ajax = new cwt.Ajax();
var obj = {
charset: charset,
language: language,
type: type,
event: event,
defer: defer
};
ajax.connect(jsfiles[i], cwt.Ajax.METHOD_GET, "", false, cwt.Util.bind(ajaxDode, obj))
}
};
cwt.Util.addScripts2 = function (jsfiles) {
var allScriptTags = "";
for (var i = 0; i < jsfiles.length; i++) {
if (/MSIE/.test(navigator.userAgent) || /Safari/.test(navigator.userAgent)) {
var currentScriptTag = "<script src='" + jsfiles[i] + "'><\/script>";
allScriptTags += currentScriptTag
} else {
var s = document.createElement("script");
s.src = jsfiles[i];
var h = document.getElementsByTagName("head").length ? document.getElementsByTagName("head")[0] : document.body;
h.appendChild(s)
}
}
if (allScriptTags) {
document.write(allScriptTags)
}
};
cwt.Util.writeScript = function (jstext, charset, language, src, type, event, defer) {
var s = document.createElement("script");
if (charset) {
s.charset = charset
}
if (language) {
s.language = language
}
if (src) {
s.src = src
}
if (type) {
s.type = type
}
if (event) {
s.event = event
}
if (defer) {
s.defer = defer
}
if (jstext) {
s.text = jstext
}
var h = document.getElementsByTagName("head").length ? document.getElementsByTagName("head")[0] : document.body;
h.appendChild(s);
return s
};
cwt.Util.loadScript = function (url, callback) {
var script = document.createElement("script");
script.type = "text/javascript";
if (script.readyState) {
script.onreadystatechange = function () {
if (script.readyState == "loaded" || script.readyState == "complete") {
script.onreadystatechange = null;
if (typeof (callback) == "function") {
callback()
}
}
}
} else {
script.onload = function () {
if (typeof (callback) == "function") {
callback()
}
}
}
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script)
};
cwt.Util.writeCss = function (href, type) {
var link = document.createElement("link");
link.setAttribute("rel", "stylesheet");
if (type) {
link.setAttribute("type", type)
} else {
link.setAttribute("type", "text/css")
}
link.setAttribute("href", href);
document.getElementsByTagName("head")[0].appendChild(link);
return link
};
cwt.Util.getElement = function () {
var elements = [];
for (var i = 0; i < arguments.length; i++) {
var element = arguments[i];
if (typeof element == "string") {
element = document.getElementById(element)
}
if (arguments.length == 1) {
return element
}
elements.push(element)
}
return elements
};
cwt.Util.observeEvent = function (elementParam, name, observer, useCapture) {
var element = cwt.Util.getElement(elementParam);
useCapture = useCapture || false;
if (name == "keypress" && (navigator.appVersion.match(/Konqueror|Safari|KHTML/) || element.attachEvent)) {
name = "keydown"
}
if (element.addEventListener) {
element.addEventListener(name, observer, useCapture)
} else {
if (element.attachEvent) {
element.attachEvent("on" + name, observer)
}
}
};
cwt.Util.bind = function (func, object) {
var args = Array.prototype.slice.apply(arguments, [2]);
return function () {
var newArgs = args.concat(Array.prototype.slice.apply(arguments, [0]));
return func.apply(object, newArgs)
}
};
cwt.Util.bindAsEventListener = function (func, object) {
return function (event) {
return func.call(object, event || window.event)
}
};
cwt.Class = function () {
var Class = function () {
if (arguments && arguments[0] != cwt.Class.isPrototype) {
this.initialize.apply(this, arguments)
}
};
var extended = {};
var parent;
for (var i = 0; i < arguments.length; ++i) {
if (typeof arguments[i] == "function") {
parent = arguments[i].prototype
} else {
parent = arguments[i]
}
cwt.Util.extend(extended, parent)
}
Class.prototype = extended;
return Class
};
cwt.Class.isPrototype = function () { };
cwt.Class.create = function () {
return function () {
if (arguments && arguments[0] != cwt.Class.isPrototype) {
this.initialize.apply(this, arguments)
}
}
};
cwt.Class.inherit = function () {
var superClass = arguments[0];
var proto = new superClass(cwt.Class.isPrototype);
for (var i = 1; i < arguments.length; i++) {
if (typeof arguments[i] == "function") {
var mixin = arguments[i];
arguments[i] = new mixin(cwt.Class.isPrototype)
}
cwt.Util.extend(proto, arguments[i])
}
return proto
};
cwt.Hash = cwt.Class({
container: null,
initialize: function () {
this.container = {}
},
destroy: function () {
this.removeAll();
this.container = null
},
put: function (key, value) {
this.container[key] = value
},
remove: function (key) {
delete (this.container[key])
},
removeAll: function () {
var keySet = this.keySet();
for (var i = 0; i < keySet.length; i++) {
this.remove(keySet[i])
}
},
get: function (key) {
return this.container[key]
},
keySet: function () {
var keyset = [];
var count = 0;
for (var key in this.container) {
if (key == "extend") {
continue
}
keyset[count] = key;
count++
}
return keyset
},
size: function () {
var count = 0;
for (var key in this.container) {
if (key == "extend") {
continue
}
count++
}
return count
},
toString: function () {
var str = "";
for (var i = 0, keys = this.keySet(), len = keys.length; i < len; i++) {
str = str + keys[i] + "=" + this.container[keys[i]] + ";\n"
}
return str
}
});
cwt.Ajax = function () {
var xmlhttp,
bComplete = false;
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP")
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP")
} catch (e) {
try {
xmlhttp = new XMLHttpRequest()
} catch (e) {
xmlhttp = false
}
}
}
if (!xmlhttp) {
return null
}
this.xmlhttp = xmlhttp;
this.connect = function (sURL, sMethod, sVars, bAsync, fnDone) {
if (!xmlhttp) {
return false
}
bComplete = false;
sMethod = sMethod.toUpperCase();
try {
if (sMethod == "GET") {
xmlhttp.open(sMethod, sURL + "?" + sVars, bAsync);
sVars = ""
} else {
xmlhttp.open(sMethod, sURL, bAsync);
xmlhttp.setRequestHeader("Method", "POST " + sURL + " HTTP/1.1");
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
}
if (bAsync) {
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && !bComplete) {
bComplete = true;
if (fnDone) {
fnDone(xmlhttp)
}
}
}
}
xmlhttp.send(sVars);
if (!bAsync) {
fnDone(xmlhttp)
}
} catch (z) {
return false
}
return true
};
return this
};
cwt.Ajax.METHOD_GET = "GET";
cwt.Ajax.METHOD_POST = "POST";
cwt.Pixel = function (x, y) {
this.x = x;
this.y = y;
this.toString = function () {
return "x=" + this.x + ",y=" + this.y
};
this.clone = function () {
return new Pixel(this.x, this.y)
}
};
cwt.Pixel.CLASS_NAME = "cwt.Pixel";
cwt.Pixel.prototype.CLASS_NAME = "cwt.Pixel";
cwt.Size = function (w, h) {
this.w = w;
this.h = h;
this.toString = function () {
return "w=" + this.w + ",h=" + this.h
};
this.clone = function () {
return new Size(this.w, this.h)
}
};
cwt.Size.CLASS_NAME = "cwt.Size";
cwt.Size.prototype.CLASS_NAME = "cwt.Size";
cwt.LonLat = function (lon, lat) {
this.lon = lon;
this.lat = lat;
this.toString = function () {
return "lon=" + this.lon + ",lat=" + this.lat
};
this.clone = function () {
return new cwt.LonLat(this.lon, this.lat)
}
};
cwt.LonLat.CLASS_NAME = "cwt.LonLat";
cwt.LonLat.prototype.CLASS_NAME = "cwt.LonLat";
cwt.Bounds = function (left, bottom, right, top) {
this.left = left;
this.top = top;
this.right = right;
this.bottom = bottom;
this.contains = function (lonlat) {
return this.left <= lonlat.lon && this.right >= lonlat.lon && this.bottom <= lonlat.lat && this.top >= lonlat.lat
};
this.setString = function (strRect) {
var tmp_array = strRect.split(",");
if (tmp_array.length >= 4) {
this.left = parseFloat(tmp_array[0]);
this.bottom = parseFloat(tmp_array[1]);
this.right = parseFloat(tmp_array[2]);
this.top = parseFloat(tmp_array[3])
}
};
this.toString = function () {
return "left=" + this.left + ",bottom=" + this.bottom + ",right=" + this.right + ",top=" + this.top
};
this.clone = function () {
return new cwt.Bounds(this.left, this.bottom, this.right, this.top)
}
};
cwt.Bounds.CLASS_NAME = "cwt.Bounds";
cwt.Bounds.prototype.CLASS_NAME = "cwt.Bounds";
cwt.Style = function () {
this.fillColor = "#FF9510";
this.fillOpacity = 0.9;
this.hoverFillColor = "white";
this.hoverFillOpacity = 0.8;
this.strokeColor = "#000000";
this.strokeOpacity = 1;
this.strokeWidth = 2;
this.strokeStyle = "solid";
this.strokeLinecap = "round";
this.hoverStrokeColor = "red";
this.hoverStrokeOpacity = 1;
this.hoverStrokeWidth = 0.2;
this.pointRadius = 6;
this.hoverPointRadius = 1;
this.hoverPointUnit = "%";
this.pointerEvents = "visiblePainted"
};
cwt.Style.pointDefault = function () {
var style = new cwt.Style();
style.fillColor = "#FF9510";
style.fillOpacity = 0.9;
style.hoverFillColor = "white";
style.hoverFillOpacity = 0.8;
style.strokeColor = "#000000";
style.strokeOpacity = 1;
style.strokeWidth = 2;
style.strokeStyle = "solid";
style.strokeLinecap = "round";
style.hoverStrokeColor = "red";
style.hoverStrokeOpacity = 1;
style.hoverStrokeWidth = 0.2;
style.pointRadius = 6;
style.hoverPointRadius = 1;
style.hoverPointUnit = "%";
style.pointerEvents = "visiblePainted";
return style
};
cwt.Style.lineDefault = function () {
var style = new cwt.Style();
style.fillColor = "#0000FF";
style.fillOpacity = 0.4;
style.hoverFillColor = "white";
style.hoverFillOpacity = 0.8;
style.strokeColor = "#6600FF";
style.strokeOpacity = 0.6;
style.strokeWidth = 2;
style.strokeStyle = "solid";
style.strokeLinecap = "round";
style.hoverStrokeColor = "red";
style.hoverStrokeOpacity = 1;
style.hoverStrokeWidth = 0.2;
style.pointRadius = 6;
style.hoverPointRadius = 1;
style.hoverPointUnit = "%";
style.pointerEvents = "visiblePainted";
return style
};
cwt.Style.polygonDefault = function () {
var style = new cwt.Style();
style.fillColor = "#FFFFFF";
style.fillOpacity = 0.6;
style.hoverFillColor = "white";
style.hoverFillOpacity = 0.8;
style.strokeColor = "#333333";
style.strokeOpacity = 0.8;
style.strokeWidth = 1;
style.strokeStyle = "solid";
style.strokeLinecap = "round";
style.hoverStrokeColor = "red";
style.hoverStrokeOpacity = 1;
style.hoverStrokeWidth = 0.2;
style.pointRadius = 6;
style.hoverPointRadius = 1;
style.hoverPointUnit = "%";
style.pointerEvents = "visiblePainted";
return style
};
cwt.Polyline = function (id, points, hasArrow, style, pointStyle) {
this.id = id;
this.points = points;
this.hasArrow = hasArrow;
this.style = style ? style : cwt.Style.lineDefault();
this.pointStyle = pointStyle;
this.toString = function () {
return "id=" + this.id + ",points=(" + (this.points ? this.points.join(";") : "") + "),hasArrow=" + this.hasArrow + ",style=(" + this.style + ")pointStyle=(" + this.pointStyle + ")"
};
this.clone = function () {
var points = null;
if (this.points) {
var length = this.points.length;
points = new Array(length);
for (var i = 0; i < length; i++) {
points[i] = this.points[i].clone()
}
}
return new cwt.Polyline(this.id, points, this.hasArrow, this.style)
}
};
cwt.Polyline.CLASS_NAME = "cwt.Polyline";
cwt.Polyline.prototype.CLASS_NAME = "cwt.Polyline";
cwt.Rect = function (id, bounds, style) {
this.id = id;
this.bounds = bounds;
this.style = style ? style : cwt.Style.polygonDefault();
this.toString = function () {
return "id=" + this.id + ",bounds=(" + this.bounds + "),style=" + this.style
};
this.clone = function () {
return new cwt.Rect(this.id, this.bounds.clone(), this.style)
}
};
cwt.Rect.CLASS_NAME = "cwt.Rect";
cwt.Rect.prototype.CLASS_NAME = "cwt.Rect";
cwt.Circle = function (id, originLonlat, radius, style) {
this.id = id;
this.originLonlat = originLonlat;
this.radius = radius;
this.style = style ? style : cwt.Style.polygonDefault();
this.toString = function () {
return "id=" + this.id + ",originLonlat=(" + this.originLonlat + "),radius=" + this.radius + "style=" + this.style
};
this.clone = function () {
return new cwt.Circle(this.id, this.originLonlat ? this.originLonlat.clone() : null, this.radius, this.style)
}
};
cwt.Circle.CLASS_NAME = "cwt.Circle";
cwt.Circle.prototype.CLASS_NAME = "cwt.Circle";
cwt.Polygon = function (id, points, style) {
this.id = id;
this.points = points;
this.style = style ? style : cwt.Style.polygonDefault();
this.addPoint = function (point) {
if (points == null || points == undefined) {
points = []
}
if (point != null && point != undefined) {
points.add(point)
}
};
this.toString = function () {
return "id=" + this.id + ",points=(" + (this.points ? this.points.join(";") : "") + ",style=" + this.style
};
this.clone = function () {
var points = null;
if (this.points) {
var length = this.points.length;
points = new Array(length);
for (var i = 0; i < length; i++) {
points[i] = this.points[i].clone()
}
}
return new cwt.Polygon(this.id, points, this.style)
}
};
cwt.Polygon.CLASS_NAME = "cwt.Polygon";
cwt.Polygon.prototype.CLASS_NAME = "cwt.Polygon";
cwt.Icon = function (url, size, offset, angle) {
this.url = url;
this.size = size;
this.offset = offset;
this.angle = angle;
this.toString = function () {
return "url=" + this.url + ",size=(" + this.size + "),offset=(" + this.offset + "),angle=" + this.angle
};
this.clone = function () {
return new cwt.Icon(this.url, this.size ? this.size.clone() : null, this.offset ? this.offset.clone() : null, this.angle)
}
};
cwt.Icon.CLASS_NAME = "cwt.Icon";
cwt.Icon.prototype.CLASS_NAME = "cwt.Icon";
cwt.Popup = function (size, offset, content, bgColor, opacity, borderColor, borderWidth, closeBox, title,event) {
this.size = size;
this.offset = offset;
this.content = content;
this.closeBox = closeBox;
this.bgColor = bgColor;
this.title = title;
this.opacity = opacity;
this.borderColor = borderColor;
this.borderWidth = borderWidth;
this.event = event;
this.toString = function () {
return "size=(" + this.size + "),offset=(" + this.offset + "),content=" + this.content + ",closeBox=" + this.closeBox + ",bgColor=" + this.bgColor + ",opacity=" + this.opacity + ",borderColor=" + this.borderColor + ",borderWidth=" + this.borderWidth + ",title=" + this.title
};
this.clone = function () {
return new cwt.Popup(this.size ? this.size.clone() : null, this.offset ? this.offset.clone() : null, this.content, this.bgColor, this.opacity, this.borderColor, this.borderWidth, this.closeBox,this.title,this.event)
}
};
cwt.Popup.CLASS_NAME = "cwt.Popup";
cwt.Popup.prototype.CLASS_NAME = "cwt.Popup";
cwt.Caption = function (content) {
this.content = content;
this.setOptions = function(opts){
this.options = opts;
};
};
cwt.Caption.CLASS_NAME = "cwt.Caption";
cwt.Caption.prototype.CLASS_NAME = "cwt.Caption";
cwt.POI = function (id, lonlat, icon, caption, popup) {
this.id = id;
this.lonlat = lonlat;
this.icon = icon;
this.caption = caption;
this.popup = popup;
this.toString = function () {
return "id=" + this.id + ",lonlat=(" + this.lonlat + "),icon=(" + this.icon + "),caption=(" + this.caption + "),popup=(" + this.popup + ")"
};
this.clone = function () {
return new cwt.POI(this.id, this.lonlat ? this.lonlat.clone() : null, this.icon ? this.icon.clone() : null, this.caption ? this.caption.clone() : null, this.popup ? this.popup.clone() : null)
}
};
cwt.POI.CLASS_NAME = "cwt.POI";
cwt.POI.prototype.CLASS_NAME = "cwt.POI";
cwt.GPSData = function (id, lonlat, utc, heading, iconUrl, captionText, popupText) {
this.id = id;
this.lonlat = lonlat;
this.utc = utc;
this.heading = heading;
this.iconUrl = iconUrl;
this.captionText = captionText;
this.popupText = popupText
};
cwt.GPSData.CLASS_NAME = "cwt.GPSData";
cwt.GPSData.prototype.CLASS_NAME = "cwt.GPSData";
cwt.RegionOverlay = function () {
this.zdcRegionOverlay = new ZdcRegionOverlay();
this.addRegion = function (key, minzoom, maxzoom, color, highlight, opcation) {
this.zdcRegionOverlay.addRegion(key, minzoom, maxzoom, color, highlight, opcation)
};
this.isFull = function () {
return this.zdcRegionOverlay.isFull()
};
this.removeRegion = function (key) {
this.zdcRegionOverlay.removeRegion(key)
}
};
cwt.RegionOverlay.CLASS_NAME = "cwt.RegionOverlay";
cwt.RegionOverlay.prototype.CLASS_NAME = "cwt.RegionOverlay";
cwt.Panorama = function (id, position) {
this.id = id;
this.position = position;
this.zoom = 0;
this.heading = 0;
this.pitch = 0;
this.setId = function (id) {
this.id = id
};
this.getId = function () {
return this.id
};
this.setPosition = function (position) {
this.position = position
};
this.getPosition = function () {
return this.position
};
this.setZoom = function (zoom) {
this.zoom = zoom
};
this.getZoom = function () {
return this.zoom
};
this.setHeading = function (heading) {
this.heading = heading
};
this.getHeading = function () {
return this.heading
};
this.setPitch = function (pitch) {
this.pitch = pitch
};
this.getPitch = function () {
return this.pitch
}
};
cwt.Panorama.CLASS_NAME = "cwt.Panorama";
cwt.Panorama.prototype.CLASS_NAME = "cwt.Panorama";
cwt.PanoramaData = function (id, position, description) {
this.id = id;
this.position = position;
this.description = description;
this.toString = function () {
return "Id=" + this.id + ",经纬度(" + this.position + "),位置描述=" + this.description
}
};
cwt.PanoramaData.CLASS_NAME = "cwt.PanoramaData";
cwt.PanoramaData.prototype.CLASS_NAME = "cwt.PanoramaData";
function getValue(value, defaultValue) {
if (value == null || value == undefined || new String(value) == "") {
return defaultValue
} else {
return new String(value).replace(/,/g, ".")
}
}
cwt.Event = cwt.Class({
object: null,
eventType: null,
pixel: null,
lonlat: null,
points: null,
bounds: null,
radius: null,
initialize: function (options) {
cwt.Util.extend(this, options)
},
destroy: function () {
this.object = null;
this.eventType = null;
this.pixel = null;
this.lonlat = null;
this.points = null;
this.bounds = null;
this.radius = null
}
});
|
looker.plugins.visualizations.add({
create: function(element, config) {
// Insert a <style> tag with some styles we'll use later.
var css = element.innerHTML = `
<style>
.hello-world-vis {
// Vertical centering
height: 100%;
display: flex;
flex-direction: column;
justify-content: center;
text-align: center;
}
</style>
`;
// Create a container element to let us center the text.
var container = element.appendChild(document.createElement("div"));
container.className = "embed-folder-vis";
// Create an element to contain the text.
this._textElement = container.appendChild(document.createElement("div"));
},
updateAsync: function(data, element, config, queryResponse, details, done) {
// Grab the first cell of the data.
var firstRow = data[0];
var firstCell = firstRow[queryResponse.fields.dimensions[0].name];
// Insert the data into the page.
this._textElement.innerHTML = LookerCharts.Utils.htmlForCell(firstCell);
// Always call done to indicate a visualization has finished rendering.
done()
}
})
|
module.exports = function(sequelize, DataTypes) {
var Student = sequelize.define("Student", {
student_name: {
type: DataTypes.STRING,
allowNull: false,
}
});
Student.associate = function(models) {
Student.hasMany(models.Post, {
onDelete: "cascade"
});
Student.belongsTo(models.Parent, {
foreignKey: {
allowNull: false
}
});
Student.belongsTo(models.Teacher, {
foreignKey: {
allowNull: false
}
});
};
return Student;
};
|
import React from 'react';
import Link from 'next/link';
import Facebook from './svg/facebook';
import Instagram from './svg/instagram';
import Youtube from './svg/youtube';
import Twitter from './svg/twitter';
import Pinterest from './svg/pinterest';
import Telegram from './svg/telegram';
export default function Socials() {
return (
<div className="d-flex align-self-start col-lg-4 col-md-4 justify-content-end">
<div className="footer__socials socials">
<span className="socials__title">אנחנו ברשתות החברתיות: </span>
<div className="socials__links">
<Link href="//www.facebook.com/BoomaIsrael/">
<a
className="socials__link socials__link--facebook"
target="_blank"
>
<Facebook />
</a>
</Link>
<Link href="//www.youtube.com/channel/UCTfySO-UYpD7tvMGDYuR1bA">
<a className="socials__link socials__link--youtube" target="_blank">
<Youtube />
</a>
</Link>
</div>
</div>
</div>
);
}
|
function mostrar(valor) {
/*
document: hace referencia a la pagina web cargada en el navegador
getElementById(): obtiene el elemento html asociado al id que le pasemos por parametro
style: accede a la propiedad style de la etiqueta html obtenida y modifica cualquier propiedad
perteneciente a este atributo, style es refernte al css de esa etiqueta
*/
if (valor == 1) { document.getElementById("crear").style.display = ""; }
else { document.getElementById("crear").style.display = "none"; }
if (valor == 2) {
mostrarContactos();
document.getElementById("mostrar").style.display = "";
} else { document.getElementById("mostrar").style.display = "none"; }
if (valor == 3) { document.getElementById("editar").style.display = ""; }
else { document.getElementById("editar").style.display = "none"; }
if (valor == 4) { document.getElementById("eliminar").style.display = ""; }
else { document.getElementById("eliminar").style.display = "none"; }
}
// async: funcion que puede contener await adentro de ella
async function crear(){
// value: Retorna el valor asociado a la etiqueta
let nombre = document.getElementById("nombre-crear").value
let descripcion = document.getElementById("descripcion-crear").value
let numero = document.getElementById("numero-crear").value
/*
await: es un operador que "espera" por una Promise.
Promise: es un valor que puede tardar un cierto tiempo en computarse.
fetch: forma nativa de JavaScript de poder realizar peticiones http, esta puede tener
varios parametros asociados
-> method: tipo de metodo de la peticion http, si se omite por defecto es get
-> headers: estos son regularmente asociados con el tiepo de body que se esta enviando
-> body: cuerpo de la peticion
JSON.stringify: convierte el objeto JSON en una notación de texto para su transmision en
la web
*/
let peticion = await fetch("http://localhost:3000/agregarContacto", {
method: "post",
headers: {"Content-Type": 'application/json'},
body: JSON.stringify({
nombre: nombre,
descripcion: descripcion,
numero: numero
})
})
let respuesta = await peticion.json()
alert(respuesta.mensaje)
document.getElementById("nombre-crear").value = ""
document.getElementById("descripcion-crear").value = ""
document.getElementById("numero-crear").value = ""
}
async function mostrarContactos() {
let cuerpo = document.getElementById("tbody")
//innerHTML: modifica el contenido que se encuentra como hijo de la etiqueta especificada
cuerpo.innerHTML = "";
let peticion = await fetch("http://localhost:3000/obtenerContactos")
let respuesta = await peticion.json()
for (let i = 0; i < respuesta.length; i++){
// createElement(): crea una etiqueta del tipo que es pasado por parametro
let tr = document.createElement("tr")
let th = document.createElement("th")
th.scope = "row" // scope: especifica que esa etiqueta es la cabecera, en este caso de la fila
th.innerHTML = i + 1
tr.appendChild(th) //appendChild(): agrega un nuevo hijo a la etiqueta especificada
let td = document.createElement("td")
td.innerHTML = respuesta[i].nombre
tr.appendChild(td)
td = document.createElement("td")
td.innerHTML = respuesta[i].descripcion
tr.appendChild(td)
td = document.createElement("td")
td.innerHTML = respuesta[i].numero
tr.appendChild(td)
cuerpo.appendChild(tr);
}
}
async function eliminar() {
let nombre = document.getElementById("nombre-eliminar").value
let peticion = await fetch("http://localhost:3000/eliminarContacto/" + nombre, {
method: "delete"
})
let respuesta = await peticion.json()
alert(respuesta.mensaje)
document.getElementById("nombre-eliminar").value = ""
}
async function editar() {
let nombre = document.getElementById("nombre-editar").value
let numero = document.getElementById("numero-editar").value
let peticion = await fetch("http://localhost:3000/actualizarContacto/" + nombre, {
method: "put",
headers: {"Content-Type": 'application/json'},
body: JSON.stringify({
numero: numero
})
})
let respuesta = await peticion.json()
alert(respuesta.mensaje)
document.getElementById("nombre-editar").value = ""
document.getElementById("numero-editar").value = ""
}
|
var ____user____viewer____8h__8js_8js =
[
[ "__user__viewer__8h_8js", "____user____viewer____8h__8js_8js.html#accdf528004ec5193bc075cfaeae92f4f", null ]
];
|
const assert = require('assert')
function foo () {}
foo.prototype = {p: 'a'}
const inst = new foo()
assert.equal(inst.p, 'a')
|
/*!
* SAP UI development toolkit for HTML5 (SAPUI5/OpenUI5)
* (c) Copyright 2009-2014 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
jQuery.sap.declare("sap.ui.commons.FileUploaderParameter");jQuery.sap.require("sap.ui.commons.library");jQuery.sap.require("sap.ui.unified.FileUploaderParameter");sap.ui.unified.FileUploaderParameter.extend("sap.ui.commons.FileUploaderParameter",{metadata:{deprecated:true,library:"sap.ui.commons"}});
/*!
* SAP UI development toolkit for HTML5 (SAPUI5)
*
* (c) Copyright 2009-2014 SAP SE. All rights reserved
*/
jQuery.sap.declare("sap.ui.commons.FileUploaderParameter");(function(){try{sap.ui.getCore().loadLibrary("sap.ui.unified")}catch(e){alert("The element 'sap.ui.commons.FileUploaderParameter' needs library 'sap.ui.unified'.");throw(e)}})();
|
document.addEventListener('DOMContentLoaded', function() {
//Global Variables
var questionStrings = ['Aterielle',
'Niereninsuffizien',
'Leberfunktion',
'Age',
'Schlaganfall',
'Blutungsereignis',
'INR-Blutungsereignis',
'beeinflussen',
'Alkohol-Abusus'];
var arrayOfHashQuestions=[];
for (var i=0; i<questionStrings.length; i++){
var hash= {
"yes": document.querySelector('#'+questionStrings[i]+'-Yes'),
"no": document.querySelector('#'+questionStrings[i]+'-No')
};
arrayOfHashQuestions.push(hash);
}
var $outputValue = document.querySelector('#Final-Score');
var $outputText = document.querySelector('#Final-Score-Text');
//Reset button
document.getElementById('btnReset').addEventListener('click', function(event) {
//Stop form input submission
event.preventDefault();
//Reset radio buttons and outputs
for (var x=0; x<arrayOfHashQuestions.length; x++){
arrayOfHashQuestions[x]['yes'].checked=false;
arrayOfHashQuestions[x]['no'].checked=false;
}
$outputValue.value = '';
$outputText.innerHTML = "";
});
//Calculate button
document.getElementById('btnCalc').addEventListener('click', function(event) {
//Stop form input submission
event.preventDefault();
//Reset all ouput values before calculating
$outputValue.value = '';
$outputText.innerHTML = "";
//Add up all the "checked" yes radio values and create a "totalScore"
var totalScore= new Number(0);
//Description for tiasymptoms below
var tiaSymptoms="";
for (var x=0; x<arrayOfHashQuestions.length; x++){
if (arrayOfHashQuestions[x]['yes'].checked==true){
totalScore += new Number(arrayOfHashQuestions[x]['yes'].value);
}
//Check to see if any radio button sets have not been selected
else if(arrayOfHashQuestions[x]['no'].checked==false){
alert(arrayOfHashQuestions[x]['no'].id+' or '+arrayOfHashQuestions[x]['yes'].id+' has not been checked. One of them must be checked');
return;
}
}
//Output calculated value
$outputValue.value = totalScore;
//Print associated output Text
$outputText.innerHTML = "Ein Score von > 3 zeigt ein erhoehtes Risiko an fuer:<br>-Hirnblutung<br>-Blutung mit Notwendigkeit eines stationaeren Aufenthaltes<br>-Hb-Abfall > 2g/l<br>-Transfusionbeduerftigkeit<br><br>Diese Patienten beduerfen einer genauen Ueberwachung und einer INR-Kontrolle mindestens alle 2 Wochen! Eine regelmaessige Neubewertung der Situation sollte ebenfalls vorgenommen werden";
});
});
|
function set_ajax(){
var a = new FormData(); // using additional FormData object
var b = []; // using an array
for(var i = 0; i < document.forms.length; i++){
var form = document.forms[i];
var data = new FormData(form);
var formValues = data.entries()
while (!(ent = formValues.next()).done) {
// Note the change here
//console.log(`${ent.value[0]}[]`, ent.value[1])
}
// Ajax Here
}
var send_data = new FormData(form); //create a FormData object
var firstform = jQuery(document.forms['form_name1']).serializeArray();
for (var i=0; i<firstform.length; i++)
{
send_data.append(firstform[i].name, firstform[i].value);
}
var agreement = $("#iAgree").prop('checked'); /*return true or false*/
if (agreement==false) {
alertify.alert('Error Message!', 'Anda harus mencentang checkbox "<em>Saya telah membaca dan saya setuju dengan Kebijakan Privasi & Syarat Ketentuan</em>"');
return false;
}else{
$.ajax
({
type: "POST",
url: BASEURL + "ajax/register_check",
data: send_data,
processData: false,
contentType: false,
beforeSend: function() {
},
success: function(html_data)
{
/*alert(html_data);*/
objdata = JSON.parse(html_data);
if (objdata.error == '1')
{
alertify.alert('Error Message!',objdata.message);
return false;
}else{
show_modal();
}
}
});
}
}
function show_modal()
{
var fullname = $('#fullname').val();
var email = $('#email').val();
var telp = $('#telp').val();
var password = $('#password').val();
var confirm_password = $('#confirm_password').val();
var nomor_rekening = $('#nomor_rekening').val();
var nama_bank = $('#nama_bank option:selected').val();
var jumlah_pinjam = $('#jumlah_pinjam').val();
var product = $('#product option:selected').text();
$('#m_fullname').text(fullname);
$('#m_email').text(email);
$('#m_telp').text(telp);
$('#m_password').text(password);
$('#m_confirm_password').text(confirm_password);
$('#m_nomor_rekening').text(nomor_rekening);
$('#m_nama_bank').text(nama_bank);
$('#m_jumlah_pinjam').text(jumlah_pinjam);
$('#m_product').text(product);
$('#modal_confirm').modal('show');
}
$('#btn-back').click(function(e){
e.preventDefault();
$('#modal_confirm').modal('hide');
});
$('#btn-submit').click(function(e){
e.preventDefault();
$('#modal_confirm').modal('hide');
exec_submit();
});
function exec_submit()
{
var a = new FormData(); // using additional FormData object
var b = []; // using an array
for(var i = 0; i < document.forms.length; i++){
var form = document.forms[i];
var data = new FormData(form);
var formValues = data.entries()
while (!(ent = formValues.next()).done) {
// Note the change here
//console.log(`${ent.value[0]}[]`, ent.value[1])
}
// Ajax Here
}
var send_data = new FormData(form); //create a FormData object
var firstform = jQuery(document.forms['form_name1']).serializeArray();
for (var i=0; i<firstform.length; i++)
{
send_data.append(firstform[i].name, firstform[i].value);
}
$.ajax
({
type: "POST",
url: BASEURL + "submit-register-pinjaman-mikro",
data: send_data,
processData: false,
contentType: false,
beforeSend: function() {
countDown();
$('#modal_loading').modal('show');
$('.next').prop('disabled', true);
$('.previous').prop('disabled', true);
},
success: function(html_data)
{
objdata = JSON.parse(html_data);
if (objdata.error == '1')
{
$('#modal_loading').modal('hide');
$('.next').prop('disabled', false);
$('.previous').prop('disabled', false);
alertify.alert('Error Message!',objdata.message);
return false;
}else{
//prompt('link ', objdata.activation_url);
if(objdata.activation_url != null){
window.location.replace(objdata.activation_url);
}
else{
window.location.replace(BASEURL + 'message/registrasi_success');
}
}
//alert(html_data);
},
error: function (request, status, error) {
alert(request.responseText);
}
});
}
var sec = 60;
var myTimer = document.getElementById('myTimer');
var myBtn = document.getElementById('myBtn');
function countDown() {
if (sec < 10) {
myTimer.innerHTML = "0" + sec;
} else {
myTimer.innerHTML = sec;
}
if (sec <= 0) {
$("#myBtn").removeAttr("disabled");
$("#myBtn").removeClass().addClass("btnEnable btn btn-primary");
$("#myTimer").fadeTo(2500, 0);
return;
}
sec -= 1;
window.setTimeout(countDown, 1000);
}
function resend_email()
{
var emailu = encodeURIComponent($('#email').val());
alertify.confirm('Konfirmasi', 'Kirim ulang Email Aktivasi?', function(){
window.location.replace(BASEURL + 'resend-email-aktivasi?email='+emailu);
}, function(){ });
}
history.pushState(null, null, location.href);
window.onpopstate = function () {
history.go(1);
};
|
export const MINE_MENU = [
{
iconUrl:`${process.env.PUBLIC_URL}/image/mine_icon1.png`,
text:'我的打卡',
link:'/MyClickIn'
},
{
iconUrl:`${process.env.PUBLIC_URL}/image/mine_icon2.png`,
text:'我的成就',
link:'/MyAchievement'
},
{
iconUrl:`${process.env.PUBLIC_URL}/image/mine_icon3.png`,
text:'我的奖品',
link:'/MyAward'
}
]
|
import React from "react";
import styles from "./css/mobnavbar.module.css";
import { Link } from "react-router-dom";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faBars } from "@fortawesome/free-solid-svg-icons";
import { withRouter } from "react-router-dom";
function MobNavBar({ history }) {
return (
<div className={styles.navbar}>
<input type="checkbox" id="check" className={styles.check} />
<label htmlFor="check" className={styles.checkbtn}>
<FontAwesomeIcon icon={faBars} />
</label>
<ul className={styles.ul}>
<li className={`${styles.li} ${styles.download}`}>
<a
href="http://covid19.interieur.gov.ma/assets/files/attestation_confinement_ar.pdf"
target="blank"
>
تحميل الاستمارة{" "}
</a>
</li>
<li className={styles.li}>
<Link
onClick={() => {
history.push("/home");
}}
to="/home"
className={styles.link}
>
الرئيسية
</Link>
</li>
<li className={styles.li}>
<Link
onClick={() => {
history.push("/protection");
}}
to="/protection"
className={styles.link}
>
طرق الوقاية
</Link>
</li>
<li className={styles.li}>
<Link
onClick={() => {
history.push("/questions");
}}
to="/questions"
className={styles.link}
>
الاسئلة الشائعة
</Link>
</li>
<li className={styles.li}>
<Link
onClick={() => {
history.push("/sources");
}}
to="/sources"
className={styles.link}
>
مصادر مهمة
</Link>
</li>
<li className={styles.li}>
<Link
onClick={() => {
history.push("/map");
}}
to="/map"
className={styles.link}
>
خريطة الاصابات
</Link>
</li>
</ul>
</div>
);
}
export default withRouter(MobNavBar);
|
import * as types from './mutation-types'
export default {
//设置token
[types.SET_TOKEN](state,token){
localStorage.token = token;
state.userInfo.token = token;
},
//登录
[types.LOGIN](state,data){
localStorage.avatar = data.member_list_headpic;
localStorage.username = data.member_list_username;
state.userInfo.avatar = data.member_list_headpic;
state.userInfo.username = data.member_list_username;
},
//退出
[types.LOGOUT](state){
localStorage.removeItem('avatar');
localStorage.removeItem('username');
localStorage.removeItem('token');
state.userInfo.avatar=null;
state.userInfo.username=null;
state.userInfo.token=null;
}
}
|
import React from 'react';
import {
Image,
StyleSheet,
Text,
TouchableHighlight,
View
} from 'react-native';
const styles = StyleSheet.create({
container: {
alignItems: 'center',
backgroundColor: '#F5FCFF',
borderBottomWidth: 1,
borderBottomColor: '#dfdfdf',
flexDirection: 'row',
justifyContent: 'space-between',
height: 150
},
image: {
alignItems: 'center',
justifyContent: 'center',
height: 100,
width: 100
},
imageContainer: {
flex: 1,
flexBasis: 50,
alignItems: 'center'
},
labelContainer: {
alignItems: 'center',
flex: 1,
flexBasis: 50,
paddingRight: 35
}
});
export default function MenuItem({ imageSource, onPress, title }) {
return (
<TouchableHighlight onPress={onPress}>
<View style={styles.container}>
<View style={styles.imageContainer}>
<Image style={styles.image} source={imageSource} />
</View>
<View style={styles.labelContainer}>
<Text>{title}</Text>
</View>
</View>
</TouchableHighlight>
);
}
|
$(function(){
$(".question").on('click', function(){
var answer = $(this).next();
$('.block .answer:visible').not(answer).slideUp();
$(this).next().slideToggle();
});
});
|
import actionTypes from '../../constants/action-types';
import actions from './shows';
describe('Shows Actions', () => {
it('should create an action to set Shows List.', () => {
const payload = [{
thumbnail_url: 'http://url',
title: 'Best Show',
media_type: 'AUDIO_ONLY',
user_rating: 3,
episode_count: 10,
date_added: 1522349605827,
author: 'Silent Jay'
}];
const expectedAction = {
type: actionTypes.shows.SET_SHOWS,
payload
};
expect(actions.setShows(payload)).toEqual(expectedAction);
});
it('should create an action to add a Show in the List.', () => {
const payload = {
thumbnail_url: 'http://url',
title: 'Best Show',
media_type: 'AUDIO_ONLY',
user_rating: 3,
episode_count: 10,
date_added: 1522349605827,
author: 'Silent Jay'
};
const expectedAction = {
type: actionTypes.shows.ADD_SHOW,
payload
};
expect(actions.addShow(payload)).toEqual(expectedAction);
});
it('should create an action to set sortBy', () => {
const payload = 'title';
const expectedAction = {
type: actionTypes.shows.SET_SHOWS_SORT,
payload
};
expect(actions.setSortBy(payload)).toEqual(expectedAction);
});
it('should create an action to set view', () => {
const payload = 'grid';
const expectedAction = {
type: actionTypes.shows.SET_VIEW,
payload
};
expect(actions.setView(payload)).toEqual(expectedAction);
});
});
|
$(document).ready(function () {
$('#btnResetFilter').click(function () {
ResetTable();
});
$(".confirm").click(function (evt) {
// Capture link
var href = $(evt.target).parent().attr('href');
if (href == undefined) {
href = $(evt.target).parent().parent().attr('href');
}
evt.preventDefault();
$(this).fastConfirm({
position: 'left',
questionText: "Are you sure you want to delete this fish?",
onProceed: function (trigger) {
window.location = href;
}
});
});
});
function GenusFilterSelected(data){
//get all rows
if (data.value > 0) {
var rows = $('.tableRow');
rows.each(function (index) {
if ($(this).attr('id') != 'TableRow_' + data.value) {
$(this).fadeOut('slow');
}
});
}
}
function ResetTable() {
var combobox = $("#GenusBox").data("tComboBox");
combobox.value(0);
$('.tableRow').each(function (index) {
$(this).fadeIn('slow');
});
}
|
document.getElementById("year").focus();
var allbttn = document.getElementById("allbttn");
allbttn.addEventListener("click", bttnClicked);
var year = document.getElementById("year");
var month = document.getElementById("month");
var day = document.getElementById("day");
day.addEventListener("keydown", (e) => {
if (e.key === "Enter") {
bttnClicked();
}
});
day.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode >= 48 && event.keyCode <= 57) {
bttnClicked();
}
});
month.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode >= 48 && event.keyCode <= 57) {
bttnClicked();
}
});
year.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode >= 48 && event.keyCode <= 57) {
bttnClicked();
}
});
function bttnClicked() {
// Return today's date and time
var currentTime = new Date();
// returns the month (from 0 to 11)
var currentMonth = currentTime.getMonth() + 1;
// returns the day of the month (from 1 to 31)
var currentDay = currentTime.getDate();
// returns the year (four digits)
var currentYear = currentTime.getFullYear();
year = parseInt(document.getElementById("year").value); // gets value of year
month = parseInt(document.getElementById("month").value); // gets value of month
day = parseInt(document.getElementById("day").value); // gets value of day
var yearsAlive = currentYear - year;
var monthsAlive = currentMonth - month;
var daysAlive = currentDay - day;
var yearToDays = (yearsAlive * 365) + (monthsAlive * 30.417) + (daysAlive);
var daysToSec = Math.round(yearToDays * 86400);
document.getElementById("print").style.display = "inline";
document.getElementById("bold").style.display = "inline";
document.getElementById("error").style.display = "none";
if (year > currentYear) {
document.getElementById("error").style.display = "inline";
document.getElementById("error").innerHTML = "Invalid year!";
document.getElementById("print").style.display = "none";
document.getElementById("bold").style.display = "none";
}
if (month >= 13) {
document.getElementById("error").style.display = "inline";
document.getElementById("error").innerHTML = "Invalid month!";
document.getElementById("print").style.display = "none";
document.getElementById("bold").style.display = "none";
}
if (day >= 32) {
document.getElementById("error").style.display = "inline";
document.getElementById("error").innerHTML = "Invalid day!";
document.getElementById("print").style.display = "none";
document.getElementById("bold").style.display = "none";
}
document.getElementById("print").innerHTML = " " + daysToSec;
}
|
// import { Image } from "@chakra-ui/image";
// import { Box, Heading, Text } from "@chakra-ui/layout";
// import Page from "components/layout/Page";
// import { BLOG_URL, CONTENT_API_KEY } from "global/envs";
// export default function blog_post({ post }) {
// return (
// <Page
// description={post.excerpt}
// image={post?.feature_image ? post.feature_image : ""}
// title={post.title}
// date={post.updated_at}
// >
// <Box my={8}>
// <Heading as="h1" size="2xl" width="90%" textAlign="center" mx="auto">
// {post.title}
// </Heading>
// {post.custom_excerpt && (
// <Text width="90%" textAlign="center" mx="auto" my={2}>
// {post.custom_excerpt}
// </Text>
// )}
// {post?.feature_image && (
// <Image src={post.feature_image} alt={post.title} px="4rem" />
// )}
// </Box>
// <Box
// dangerouslySetInnerHTML={{ __html: post.html }}
// css={{
// "h2, h3, h4": {
// fontWeight: 700,
// marginTop: "56px",
// width: "90%",
// marginLeft: "auto",
// marginRight: "auto",
// },
// a: {
// textDecoration: "underline",
// color: "#FF1A75",
// },
// p: {
// marginTop: "15px",
// width: "90%",
// marginLeft: "auto",
// marginRight: "auto",
// },
// figure: {
// marginTop: "22px",
// },
// figcaption: {
// textAlign: "center",
// paddingTop: "15px",
// marginLeft: "auto",
// marginRight: "auto",
// },
// img: {
// // width: "80%",
// // marginLeft: "auto",
// // marginRight: "auto",
// paddingLeft: "4rem",
// paddingRight: "4rem",
// },
// "ul, ol": {
// marginTop: "14px",
// width: "90%",
// marginLeft: "auto",
// marginRight: "auto",
// paddingLeft: "30px",
// paddingRight: "30px",
// },
// pre: {
// backgroundColor: "black",
// color: "white",
// borderRadius: "6px",
// padding: "1rem",
// // width: "50%",
// width: "90%",
// overflow: "auto",
// marginLeft: "auto",
// marginRight: "auto",
// },
// }}
// ></Box>
// </Page>
// );
// }
// export const getStaticProps = async context => {
// const contentApiKey = CONTENT_API_KEY;
// const blogUrl = BLOG_URL;
// const res = await fetch(
// `${blogUrl}/ghost/api/v3/content/posts/slug/${context.params.slug}/?key=${contentApiKey}&limit=all`
// );
// const data = await res.json();
// const post = data.posts[0];
// return {
// props: {
// post,
// },
// };
// };
// export const getStaticPaths = async () => {
// const contentApiKey = CONTENT_API_KEY;
// const blogUrl = BLOG_URL;
// try {
// const res = await fetch(
// `${blogUrl}/ghost/api/v3/content/posts/?key=${contentApiKey}&limit=all`
// );
// const posts = await res.json();
// const slugs = posts.posts.map(post => post.slug);
// const paths = slugs.map(slug => ({ params: { slug: slug } }));
// return {
// paths,
// fallback: false,
// };
// } catch (err) {
// return { paths: [], fallback: false };
// }
// };
|
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, ltsvlogger = require('../index.js')
, http = require('http')
, fs = require('fs')
, path = require('path');
// select tokens
var ltsv = [];
ltsv.push("time");
ltsv.push("host");
ltsv.push("X-Forwarded-For");
ltsv.push("user");
ltsv.push("ident");
ltsv.push("req");
ltsv.push("method");
ltsv.push("uri");
ltsv.push("protocol");
ltsv.push("status");
ltsv.push("size");
ltsv.push("reqsize");
ltsv.push("referer");
ltsv.push("ua");
ltsv.push("vhost");
ltsv.push("reqtime");
ltsv.push("X-Cache");
ltsv.push("X-Runtime");
ltsv.push("hoge"); //will be ignored
var out = fs.createWriteStream("./example/log/access.log",{flags: 'a+'});
var app = express();
app.configure(function(){
app.set('port', process.env.PORT || 3001);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(ltsvlogger({format:ltsv,stream:out}));
// app.use(ltsvlogger()); //use default format
// app.use(ltsvlogger("default")); //use default format
// app.use(ltsvlogger("tiny")); //use tiny format
// app.use(ltsvlogger("short")); //use short format
// app.use(ltsvlogger({format:"short"})); //use short format
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
app.configure('development', function(){
app.use(express.errorHandler());
});
app.get('/', routes.index);
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
|
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'asdf0813',
database : 'o2'
});
connection.connect();
// connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
// if (error) throw error;
// console.log('The solution is: ', results[0].solution);
// });
/*
var sql = 'INSERT INTO TOPIC (title, description, author) VALUES (?,?,?)'
var params = ['Supervisor', 'Watcher', 'jwon'];
connection.query(sql, params, function (error, results, fields){
if(error){
console.log(error);
}else{
console.log(results.insertId);
//console.log(fields);
}
});
*/
/* var sql = 'UPDATE TOPIC SET title=?, description=? WHERE id = ?'
var params = ['functional program', 'learn function program', 4];
connection.query(sql, params, function (error, results, fields){
if(error){
console.log(error);
}else{
console.log(results);
//console.log(fields);
}
}); */
var sql = 'DELETE FROM TOPIC WHERE id = ?'
var params = [5];
connection.query(sql, params, function (error, results, fields){
if(error){
console.log(error);
}else{
console.log(results);
}
});
connection.end();
|
'use strict';
/**
* egg-http-parameter default config
* @member Config#httpParameter
* @property {String} SOME_KEY - some description
*/
exports.httpParameter = {
errorStatus: 400,
errorMessage: 'Validation Failed',
errorCode: 'invalid_param',
};
|
import Link from 'next/link';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import {
faInstagram as IG,
faFacebook as FB,
faTwitter as TW,
faLinkedin as LI
} from '@fortawesome/free-brands-svg-icons'
import { Typography } from '@material-ui/core';
const td = new Date();
export default () => (
<footer>
<div className="logo-wrapper">
<a>
<img src="/static/images/Logo.png"></img>
</a>
</div>
<div className="copyright">
<Typography variant="subtitle2">
{`Copyright © 2009-${td.getFullYear()} Practical Dental Solutions LLC. All Rights Reserved.`}
</Typography>
<Typography variant="subtitle2">
YAPI™ is a property of Practical Dental Solutions LLC
</Typography>
<Typography variant="subtitle2">
True Paperless™ is a property of Practical Dental Solutions LLC
</Typography>
<Typography variant="subtitle2">
InstaReview™ is a property of Practical Dental Solutions LLC
</Typography>
<Typography variant="subtitle2">
PhoneAssistant™ is a property of Practical Dental Solutions LLC
</Typography>
<Typography variant="subtitle2">
UbiquitousHuddle™ is a property of Practical Dental Solutions LLC
</Typography>
<Typography variant="subtitle2">
Bring Your Own Number™ (BYON) is a property of Practical Dental Solutions LLC
</Typography>
</div>
<div className="footer-links">
<div className="footer-link-col">
<Typography variant="h6">Our Products</Typography>
<ul>
<li>
<Link href='/productPages/truePaperless'>
<a>True Paperless</a>
</Link>
</li>
<li>
<Link href='/practiceDash'>
<a>Practice Dashboard</a>
</Link>
</li>
<li>
<Link href='/intraOffice'>
<a>Intra-Office Communication</a>
</Link>
</li>
<li>
<Link href='/patientEngagement'>
<a>Patient Engagement</a>
</Link>
</li>
<li>
<Link href='/instaReview'>
<a>InstaReview</a>
</Link>
</li>
<li>
<Link href='/phoneAssistant'>
<a>Phone Assistant</a>
</Link>
</li>
</ul>
</div>
<div className="footer-link-col">
<Typography variant="h6">Company</Typography>
<ul>
<li>
<Link href='/about'>
<a>About Us</a>
</Link>
</li>
<li>
<Link href='/contact'>
<a>Contact Us</a>
</Link>
</li>
<li>
<Link href='/customerStories'>
<a>Customer Stories</a>
</Link>
</li>
</ul>
</div>
<div className="footer-link-col">
<Typography variant="h6">Resources</Typography>
<ul>
<li>
<Link href='/blog'>
<a>Blog</a>
</Link>
</li>
<li>
<Link href='/integrations'>
<a>PMS Integrations</a>
</Link>
</li>
<li>
<Link href='/demo'>
<a>Schedule a Demo</a>
</Link>
</li>
<li>
<Link href='/webinar'>
<a>Join a Webinar</a>
</Link>
</li>
<li>
<Link href='https://help.yapicentral.com'>
<a>Knowledge Base</a>
</Link>
</li>
<li>
<Link href='/behindTheSmiles'>
<a>Behind the Smiles</a>
</Link>
</li>
</ul>
</div>
</div>
<div className="footer-foot">
<img src="https://yapiapp.com/wp-content/uploads/2017/07/applestore-logo.jpg"></img>
<div className="social-links">
<Typography variant="h6">Let's Be Social!</Typography>
<div className="social-icons">
<div className="social-icon fb-icon">
<Link href="/facebook">
<FontAwesomeIcon icon={FB} />
</Link>
</div>
<div className="social-icon tw-icon">
<Link href="/twitter">
<FontAwesomeIcon icon={TW} />
</Link>
</div>
<div className="social-icon li-icon">
<Link href="/linkedIn">
<FontAwesomeIcon icon={LI} />
</Link>
</div>
<div className="social-icon ig-icon">
<Link href="/instagram">
<FontAwesomeIcon icon={IG} />
</Link>
</div>
</div>
</div>
</div>
<style jsx>{`
footer{
margin: -8px;
padding: calc(15px * 4) 20px;
background: rgba(246, 246, 246, 1);
display: grid;
grid-template-columns: 1fr 2fr;
grid-template-rows: 60px 1fr auto;
grid-gap: 10px 20px;
color: #9e9e9e;
}
.logo-wrapper{
width: 100%;
height: 100%;
grid-column: 1 / 3;
grid-row: 1 / 2;
}
.logo-wrapper img{
height: 95%;
width: auto;
}
.copyright{
display: flex;
flex-direction: column;
justify-content:flex-start;
align-self: center;
align-items:flex-start;
}
.copyright p{
font-style: italic;
font-size: 13px;
margin: 0 0 5px;
}
.footer-links {
display: grid;
grid-template-columns: repeat(3, 1fr)
}
.footer-link-col h2 {
margin-top: 0;
color: rgba(109, 109, 109, 1);
}
.footer-link-col ul {
padding: 0;
}
.footer-link-col ul li{
list-style-type: none;
padding: 2px 0
}
a {
text-decoration: none;
color: blue;
font-family: "Arial";
color: #9e9e9e;
font-size: 15px;
}
a:hover {
opacity: 0.6;
}
.footer-foot {
grid-column: 2 / 3;
display: flex;
justify-content: space-between;
align-items: flex-end;
width: 80%;
}
.social-links h3 {
font-size: 1.5em;
margin: 0;
color: rgba(109, 109, 109, 1);
}
.social-icons {
display: flex;
justify-content:space-between;
align-items:flex-end;
}
.social-icon {
width: 24px;
height: 24px;
line-height: 24px !important;
border-radius: 50%;
color: white;
display: flex;
justify-content: center;
align-items: center;
}
.social-icon:hover{
cursor: pointer;
}
.fb-icon{
background: #3b5998;
}
.li-icon{
background: #03a9ff;
}
.tw-icon{
background: #9bcef5;
}
.ig-icon{
background: #9bcef5;
}
`}</style>
</footer>
)
|
const Models = require('./models/model');
module.exports = {
DoesUserExist: function (mongoclient, url, usrcred){
return new Promise( (resolve, reject) => {
synchronousSearch( resolve, reject, mongoclient, url, usrcred, searchForUser);
});
},
RegisterUser: function (mongoclient, url, usrcred){
return new Promise( (resolve, reject) => {
synchronousSearch( resolve, reject, mongoclient, url, usrcred, registerUser);
});
},
UserTagLists: function (mongoclient, url, vm){
return new Promise( (resolve, reject) => {
synchronousSearch( resolve, reject, mongoclient, url, vm, usertaglists);
});
},
RetrieveUserTagList: function (mongoclient, url, vm){
return new Promise( (resolve, reject) => {
synchronousSearch( resolve, reject, mongoclient, url, vm, retrievetaglist);
});
},
AddNewUserTagList: function (mongoclient, url, vm){
return new Promise( (resolve, reject) => {
synchronousSearch( resolve, reject, mongoclient, url, vm, newusertaglist);
});
},
RemoveUserTagList: function (mongoclient, url, vm){
return new Promise( (resolve, reject) => {
synchronousSearch( resolve, reject, mongoclient, url, vm, removeusertaglist);
});
},
AddMarkerToList: function (mongoclient, url, vm){
return new Promise( (resolve, reject) => {
synchronousSearch( resolve, reject, mongoclient, url, vm, addmarkertolist);
});
},
RemoveMarkerFromList: function (mongoclient, url, vm){
return new Promise( (resolve, reject) => {
synchronousSearch( resolve, reject, mongoclient, url, vm, removemarkerfromlist);
});
},
searchHistoryForMap: function (mongoclient, url, vm){
var queryobject = new Models.SearchFormModel(vm);
console.log(queryobject);
return new Promise( (resolve, reject) => {
synchronousSearch( resolve, reject, mongoclient, url, queryobject, searchHistory);
});
},
logSearchTermAndResults: function(mongoclient, url, results){
return new Promise( (resolve, reject) => {
synchronousSearch( resolve, reject, mongoclient, url, results, logSearchResults);
});
},
searchInMarkerList: function(mongoclient, url, searchkey){
return new Promise( (resolve, reject) => {
synchronousSearch(resolve, reject, mongoclient, url, searchkey, searchMarker);
});
},
searchCountyList: function(mongoclient, url, searchkey){
return new Promise( (resolve, reject) => {
synchronousSearch(resolve, reject, mongoclient, url, searchkey, searchCounty);
});
},
searchCategoryList: function(mongoclient, url, searchkey){
return new Promise( (resolve, reject) => {
synchronousSearch(resolve, reject, mongoclient, url, searchkey, searchCategory);
});
},
searchLocationDescriptionList: function(mongoclient, url, searchkey){
return new Promise( (resolve, reject) => {
synchronousSearch(resolve, reject, mongoclient, url, searchkey, searchLocationDescription);
});
}
}
// function to syncrhonize select2 searching by wrapping promise-then template
// on connect
// removes code that is repeated throughout above
function synchronousSearch(resolve, reject, mc, url, key, function_name){
mc.connect(url)
.then( (client) => {
if ( key != null){
function_name(resolve, reject, client, key);
}
}).catch( (err) =>{console.log(err)});
}
function registerUser (resolve, reject, client, key){
var db = client.db('PHF');
db.collection('users').insert(new Models.RegisterUserModel(key))
.then( (list) => {
resolve('1');
}, (err)=>{
resolve('0');
});
}
function searchForUser(resolve, reject, client, key){
var db = client.db('PHF');
db.collection('users').find({Username:key.Username, Password:key.Password})
.toArray( (err, list) => {
(list.length > 0 ) ? resolve('1'):resolve('0');
});
}
function usertaglists(resolve, reject, client, vm){
var db = client.db('PHF');
db.collection('usertags').find({ user:vm.usrname})
.toArray( (err, list) => {
var results = {};
results.items = [];
if (list.length > 0){
list[0].lists.forEach( (el, i) => {
results.items.push(new Models.Select2ModelFromUserTagLists(el.name));
});
}
client.close();
resolve(results);
});
}
function retrievetaglist(resolve, reject, client, vm){
var db = client.db('PHF');
db.collection('usertags').find({ user:vm.usrname, 'lists.name': vm.listname})
.toArray( (err, list) => {
var results = {};
results.items = [];
if (list.length > 0){
list[0].lists.forEach( (el, i) => {
if (el.name == vm.listname){
results.ListName = el.name;
el.markers.forEach( (m, i) => {
results.items.push(new Models.ModelFromUserTagList(m));
});
}
});
}
client.close();
resolve(results);
});
}
function newusertaglist(resolve, reject, client, key){
var db = client.db('PHF');
db.collection('usertags').update({user: key.User}, {'$push': { lists: { name:key.NameOfList, markers: []} }}, {upsert:true} )
.then( (result) =>{
resolve('1');
},
(err) => {
resolve(err);
});
}
function removeusertaglist(resolve, reject, client, key){
var db = client.db('PHF');
db.collection('usertags').update({user: key.User}, {'$pull': { lists: { name:key.NameOfList}}} )
.then( (result) =>{
resolve('1');
},
(err) => {
resolve('0');
});
}
function addmarkertolist(resolve, reject, client, key){
var db = client.db('PHF');
db.collection('usertags').update({user: key.User, 'lists.name': key.ListName}, {'$push': { 'lists.$.markers': { ListName:key.ListName, Title:key.Title, Description:key.Description } }} )
.then( (result) =>{
resolve('1');
});
}
function removemarkerfromlist(resolve, reject, client, key){
var db = client.db('PHF');
db.collection('usertags').update({user: key.User, 'lists.name': key.NameOfList}, {'$pull': { 'lists.$.markers': { ListName: key.NameOfList, Title:key.ItemTitle } } } )
.then( (result) =>{
resolve('1');
},
(err) => {
resolve('0');
});
}
function searchHistory(resolve, reject, client, searchkey){
var results = new Models.SearchHistoryResultsModel(new Models.Log(searchkey));
var searchModel = new Models.SearchHistoryModel(searchkey);
// queries for records with sub string searchkey
// duplicates are then removed by searching the index
var db = client.db('PHF');
db.collection('markers').find(searchModel) // searchkey must be a queryobject
.toArray( (err, list) => {
if (list != null){
list.forEach( (el, i) => {
var i2 = list.findIndex(e => e.Historical_Marker_Id === el.Historical_Marker_Id);
if (i === i2){
results.items.push(el);
results.log.searchResults.push(el.Historical_Marker_Id);
}
});
client.close();
resolve(results);
}
client.close();
});
}
function logSearchResults(resolve, reject, client, results){
var db = client.db('PHF');
db.collection('searchlogs').insert(results.log, { w: 1 }).then( (err, doc) =>{
client.close();
resolve(results.items);
}, (err) =>{
console.log(err);
});
}
function searchMarker(resolve, reject, client, searchkey){
var results = {};
results.items = [];
// queries for records with sub string searchkey
// duplicates are then removed by searching the index
var db = client.db('PHF');
db.collection('markers').find( {Name_of_the_Marker: {$regex: new RegExp(searchkey)}})
.toArray( (err, list) => {
if (list != null){
list.forEach( (el, i) => {
var i2 = list.findIndex(e => e.Historical_Marker_Id === el.Historical_Marker_Id);
if (i === i2){
results.items.push({ id: el.Historical_Marker_Id, text: el.Name_of_the_Marker+'-'+el.Dedicated_Year });
}
});
client.close();
resolve(results);
}
client.close();
});
}
function searchCounty(resolve, reject, client, searchkey){
var results = {};
results.items = [];
// queries for records with sub string searchkey
// duplicates are then removed by searching the index
var db = client.db('PHF');
db.collection('markers').find( {County: {$regex: new RegExp(searchkey)}})
.toArray( (err, list) => {
if (list != null){
list = list.filter( (el, i) => {
var i2 = list.findIndex(e => e.County === el.County);
if (i === i2){
results.items.push({ id: el.County, text: el.County });
}
});
client.close();
resolve(results);
}
client.close();
});
}
function searchCategory(resolve, reject, client, searchkey){
var results = {};
results.items = [];
// queries for records with sub string searchkey
// duplicates are then removed by searching the index
var db = client.db('PHF');
db.collection('markers').find( {Category: {$regex: new RegExp(searchkey)}})
.toArray( (err, list) => {
if (list != null){
list = list.filter( (el, i) => {
var i2 = list.findIndex(e => e.Category === el.Category);
if (i === i2) {
results.items.push({ id: el.Category, text: el.Category });
}
});
client.close();
resolve(results);
}
client.close();
});
}
function searchLocationDescription(resolve, reject, client, searchkey){
var results = {};
results.items = [];
// queries for records with sub string searchkey
// duplicates are then removed by searching the index
var db = client.db('PHF');
db.collection('markers').find( {Location_Description: {$regex: new RegExp(searchkey)}})
.toArray( (err, list) => {
if (list != null){
list = list.filter( (el, i) => {
var i2 = list.findIndex(e => e.Location_Description === el.Location_Description);
if (i === i2) {
results.items.push({ id: el.Location_Description, text: el.Location_Description });
}
});
client.close();
resolve(results);
}
client.close();
});
}
|
import React from 'react'
import './TopPodcast.css';
function TopPodcast() {
return (
<div className="podcast">
</div>
)
}
export default TopPodcast
|
function ShowClicked() {
alert('Clicked!');
}
function ChangeColor1() {
var div1 = document.getElementById('div1');
var txt1 = document.getElementById('txt1');
div1.style.backgroundColor = txt1.value;
}
function ChangeColor2() {
$('#div2').css('background-color', $('#txt2').val());
}
function Fade3() {
var d3 = $('#div3');
if (d3.css('display') == 'none') {
d3.fadeIn(2000);
} else {
d3.fadeOut(2000);
}
}
|
import React from 'react';
import AlumnosProvider from './Context/AlumnosContext';
import {NavigationContainer} from '@react-navigation/native';
import BottomTabNavigator1 from './Navigations/BottomTabNavigator1';
export default function App() {
return (
<AlumnosProvider>
<NavigationContainer>
<BottomTabNavigator1/>
</NavigationContainer>
</AlumnosProvider>
);
}
|
export { Humidity } from './Humidity';
|
(function() {
"use strict";
kintone.events.on([
'app.record.index.show'
], function(event){
RelatedRecordsFieldManager.prototype.getFieldProperties().then(function(){
var relatedRecordsField = new RelatedRecordsFieldManager('販売情報');
event.records.forEach(function(record, index){
relatedRecordsField.getRecords(record).then(function(records){
if(records.length){
kintone.app.getFieldElements('製番')[index].style.background = '#f00';
}
});
});
});
});
var RelatedRecordsFieldManager = (function(fieldCode){
function RelatedRecordsFieldManager(fieldCode) {
this.fieldCode = fieldCode;
this.targetAppId = kintone.app.getRelatedRecordsTargetAppId(fieldCode);
this.property = this.fieldProperties[fieldCode].referenceTable;
}
RelatedRecordsFieldManager.prototype = {
selfAppId: kintone.app.getId(),
records: [],
limit: 1,
//limit: 500,
offset: 0,
getFieldProperties: function(){
return kintone.api(kintone.api.url('/k/v1/app/form/fields', true), 'GET', {
app: RelatedRecordsFieldManager.prototype.selfAppId,
}).then(function(response){
RelatedRecordsFieldManager.prototype.fieldProperties = response.properties;
});
},
query: function(record){
return (
this.property.condition.relatedField +
'="' +
record[this.property.condition.field].value +
(this.property.filterCond ? '" and ' : '"') +
this.property.filterCond
);
},
getRecords: function(record){
var _this = this;
return kintone.api(kintone.api.url('/k/v1/records', true), 'GET', {
app: this.targetAppId,
query:
this.query(record) +
' order by ' + this.property.sort +
' limit ' + this.limit +
' offset ' + this.offset
}).then(function(response){
return response.records;
/*_this.records = _this.records.concat(response.records);
_this.offset += response.records.length;
if(response.records.length === _this.limit){
return _this.getRecords(record);
}else{
return _this.records;
}*/
});
}
}
return RelatedRecordsFieldManager;
})();
})();
|
import './style'
import Close from '@kuba/close'
import Container from './container'
import Form from './form'
import h, { Fragment } from '@kuba/h'
import Overlayer from './overlayer'
function component (search) {
return (
<>
<Container opened={search.opened}>
<Form />
<Close onClick={() => search.close()} />
</Container>
<Overlayer opened={search.opened} onClick={() => search.close()} />
</>
)
}
export default component
|
document.addEventListener("DOMContentLoaded", function(event){
const formularioContactos = document.querySelector('#contacto');
const notificaciones = document.querySelector('#notificacion');
evento();
function evento() {
formularioContactos.addEventListener('submit', leerFormulario);
}
function leerFormulario(e) {
e.preventDefault();
const nombre = document.querySelector('#nombre').value;
if(nombre === ''){
mostrarNotificacion('Todos los Campos son Obligatorios', 'error');
}else{
const infoContacto = new FormData();
infoContacto.append('nombre', nombre);
insertarBD(infoContacto);
}
}
function insertarBD(datos){
const xhr = new XMLHttpRequest();
xhr.open('POST', 'includes/funciones/model.php', true);
xhr.onload = function(){
if(this.status === 200){
const respuesta =JSON.parse( xhr.responseText);
console.log(respuesta);
mostrarNotificacion('Registro exitoso', 'correcto');
}
}
xhr.send(datos);
}
function mostrarNotificacion(mensaje, clase){
const notificacion = document.createElement('div');
notificacion.classList.add(clase, 'notificacion', 'sombra');
notificacion.textContent = mensaje;
notificaciones.insertBefore(notificacion, document.querySelector('#notificacion legend'));
setTimeout(() => {
notificacion.classList.add('visible');
setTimeout(() =>{
notificacion.classList.remove('visible');
setTimeout(() => {
notificacion.remove();
}, 500);
}, 3000);
}, 100);
}
});
|
(function(btn){
btn.addEventListener('click', function () {
if(JACKYS.OpenMenu) {
JACKYS.body.classList.remove('menu-show');
window.scrollTo(0,JACKYS.windowScrollOld);
JACKYS.OpenMenu = false;
}
else {
JACKYS.OpenMenu = true;
// записываем значение скролла страницы
JACKYS.windowScrollOld = window.pageYOffset;
window.scrollTo(0,0);
JACKYS.body.classList.add('menu-show');
}
});
})(document.querySelector('.menu__btn-toggle'));
Array.prototype.forEach.call(document.querySelectorAll('.menu__item--parent .menu__link'), function(parentLink){
parentLink.addEventListener('click', function(e){
e.preventDefault();
});
});
|
P.views.workouts.edit.Set = P.views.Item.extend({
templateId: 'workouts.edit.set',
className: 'set',
events: {
'click .js-set-remove': 'del',
'drop': 'onDrop'
},
initialize: function() {
this.listenTo(this.model, 'change:index', this.reindex);
},
serializeData: function() {
var context = this.model.toJSON();
context.set_num = this.index();
return context;
},
del: function() {
this.model.destroy();
},
/**
* Return the index value of the set. Starts at 1.
*/
index: function() {
return parseInt(this.model.get('index'), 10) + 1;
},
/**
* Callback after sorting stops, but triggered by the collection.
* See P.views.workouts.edit.SetCollection for more details.
*/
onDrop: function(event, position) {
this.save();
this.$el.trigger('sort-set', [this.model, position - 1]);
},
/**
* Update the set number on display.
*/
reindex: function() {
this.$('.index').html(this.index());
},
/**
* Update the set with the current input values.
*/
save: function() {
var model = this.model;
this.$('.set-input').each(function() {
model.set(this.dataset.attr, this.value);
});
}
});
|
var express = require('express');
var passport = require('passport');
var Account = require('../models/account');
var mongoose = require('mongoose');
var router = express.Router();
var uid = require('uuid/v1');
router.get('/', function (req, res) {
if (!req.user) return res.redirect(301, '/login');
res.render('home', {user: req.user});
});
router.get('/changepassword', function (req, res) {
if (!req.user) return res.redirect(301, '/login');
res.render('changepassword', {user: req.user});
});
router.get('/register', function(req, res) {
res.render('register', { });
});
router.post('/changepassword', function(req, res) {
if (!req.user) return res.redirect(301, '/login');
var user = req.user;
user.setPassword(req.body.newPassword, function (err, model, passwordErr) {
if(!err){
user.save(function(err){
if (err) { next(err) }
else {
res.redirect(301, '/home');
}
})
}
});
});
router.post('/register', function(req, res) {
try {
var authToken = uid();
Account.register(new Account({ username : req.body.username, role: req.body.role, authToken: authToken }), req.body.password, function(err, account) {
if (err) {
return res.render('register', { account : account });
}
passport.authenticate('local')(req, res, function () {
res.render('registerSuccess', { authToken: authToken });
});
});
}catch (err){
console.log(err);
}
});
router.get('/login', function(req, res) {
res.render('login', { user : req.user });
});
router.get('/logout', function(req, res) {
req.logout();
res.redirect('/');
});
router.get('/ping', function(req, res){
res.status(200).send("pong!");
});
module.exports = router;
|
$(function() {
var $el = $('#headquote');
$el.data('quotes', {
quotes: [
{quote: 'A memory is what is left when something happens and does not completely unhappen', source: 'Edward de Bono'},
{quote: 'Cherish all your happy moments: they fine a fine cushion for old age', source: 'Tarkington Booth'},
{quote: 'Every goodbye is the birth of a memory', source: 'Dutch Proverb'},
{quote: 'How we remember, what we remember, and why we remember form the most personal map of our individuality', source: 'Christina Baldwin'},
{quote: 'I have more memories than if I were a thousand years old', source: 'Charles Baudelaire'},
{quote: 'I wear the key of memory, and can open every door in the house of my life', source: 'Amelia E. Barr'},
{quote: 'In memory everything seems to happen to music', source: 'Tennessee Williams'},
{quote: 'Memories of our lives, of our works and our deeds will continue in others', source: 'Rosa Parks'},
{quote: 'Memory\'s the very skin of life', source: 'Elizabeth Hardwick'},
{quote: 'Memory is a man\'s real possession . In nothing else is he rich, in nothing else is he poor', source: 'Alexander Smith'},
{quote: 'Memory is the diary that we all carry about with us', source: 'Oscar Wilde'},
{quote: 'They may forget what you said, but they will never forget how you made them feel', source: 'Carl W. Buechner'},
{quote: 'We all have our time machines. Some take us back, they are called memories. Some take us forward, they are called dreams', source: 'Jeremy Irons'},
{quote: 'We do not know the true value of our moments unitl they have undergone the test of memory', source: 'Georges Duhamel'},
{quote: 'We do not remember days;<br>we remember moments', source: 'Cesare Pavese'}
],
selected: 0
});
showQuote();
setInterval(showQuote, 5000);
function showQuote() {
var $el = $('#headquote');
var obj = $el.data('quotes');
var selected = obj.selected;
var quote = obj.quotes[selected];
var quotesLen = obj.quotes.length;
var $oldQuote = $('p', $el);
var newQuote = document.createElement('p');
$(newQuote).html(quote.quote + ' <span>- ' + quote.source + '</span>');
$(newQuote).hide();
$el.get(0).appendChild(newQuote);
$oldQuote.ClearTypeFadeOut(2000, function () {
$(newQuote).ClearTypeFadeIn(2000, function () {
$oldQuote.remove();
});
});
obj.selected = (selected + 1) % quotesLen;
}
});
|
var fs = require('fs')
var p1 = new Promise(function (resolve, reject) {
fs.readFile('./a.txt', function (err, data) {
if (err) {
reject(err)
}
else {
resolve(data.toString())
}
})
})
var p2 = new Promise(function (resolve, reject) {
fs.readFile('./b.txt', function (err, data) {
if (err) {
reject(err)
}
else {
resolve(data.toString())
}
})
})
var p3 = new Promise(function (resolve, reject) {
fs.readFile('./c.txt', function (err, data) {
if (err) {
reject(err)
}
else {
resolve(data.toString())
}
})
})
p1.
then(function (data) {
console.log(data)
//當p1讀取成功的時候
// 當前函數中return的結果就可以在後面的then function接收到
// 當return 123後面就接收到123
// 可以return一個promise物件
// 當Return一個promise物件的時候,後面的then中的finction會變成p2
return p2
}, function (err) {
console.log("讀取文件失敗", err)
})
.then(function(data){
console.log(data)
return p3
})
.then(function(data){
console.log(data)
})
|
import React, {Component} from 'react';
import './Settings.css';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faTools } from '@fortawesome/free-solid-svg-icons'
import Bacon from 'baconjs'
const settingsClickedBus = new Bacon.Bus()
const settingsClicked = settingsClickedBus.toProperty(false)
const entitySettingsBus = new Bacon.Bus()
const getEntitySettings = () => JSON.parse(window.localStorage['entitySettings'] || '{}')
const entitySettings = entitySettingsBus.toProperty(getEntitySettings())
class SettingsButton extends Component {
render() {
return <label className='settings-switch'>
<input type='checkbox' onClick={e => settingsClickedBus.push(e.target.checked)}/>
<span className='settings-button'>
<FontAwesomeIcon icon={faTools} style={{width: '100%', height: '100%'}} />
</span>
</label>
}
}
const setEntitySettings = (id, settings) => {
window.localStorage.setItem('entitySettings', JSON.stringify({...getEntitySettings(), [id]: settings}))
entitySettingsBus.push(getEntitySettings())
}
const settingsForEntity = id => getEntitySettings()[id] || {}
const getSetting = (id, name, defaultValue = undefined) => settingsForEntity(id)[name] || defaultValue
const getName = id => getSetting(id, 'name')
const isEnabled = id => getSetting(id, 'enabled', false)
const setSettingForEntity = (id, name, value) => {
setEntitySettings(id, {...settingsForEntity(id), [name]: value})
}
const setEnabled = (id, enabled) => setSettingForEntity(id, 'enabled', enabled)
const setName = (id, name) => setSettingForEntity(id, 'name', name)
class SettingsItem extends Component {
constructor(props) {
super()
this.state = {enabled: isEnabled(props.id), name: getName(props.id)}
}
render() {
return <li>
<label className='settings-switch'>
<input type='checkbox' checked={this.state.enabled} onChange={e => {this.setState({enabled: e.target.checked}); setEnabled(this.props.id, e.target.checked)}} />
<span className='settings-item'>
<span className='settings-item-id'>{this.props.id}</span>
<input placeholder={this.props.placeholder} className='settings-item-name' onChange={e => {this.setState({name: e.target.value}); setName(this.props.id, e.target.value)}} value={this.state.name} />
</span>
</label>
</li>
}
}
const renderItem = ({entity_id, title, attributes: {friendly_name}}) => <SettingsItem {...{id: entity_id, name: title, placeholder: friendly_name}} />
class SettingsPanel extends Component {
render() {
return <ul className='no-style-list'>
<li>
<h2>Sensors</h2>
<ul className='no-style-list'>
{this.props.sensors.map(renderItem)}
</ul>
</li>
<li>
<h2>Scenes</h2>
<ul className='no-style-list'>
{this.props.scenes.map(renderItem)}
</ul>
</li>
<li>
<h2>Switches</h2>
<ul className='no-style-list'>
{this.props.switches.map(renderItem)}
</ul>
</li>
</ul>
}
}
export {
SettingsButton,
SettingsPanel,
settingsClicked,
entitySettings
}
|
var contratoNuevoView = Backbone.View.extend({
el: '#Principal',
events: {
// Evento para detectar cuando alguien escribe una letra
// en el input de cliente.
"keyup #FormContratoNuevoCliente": "buscarCliente",
// Seleccionar el cliente que necesitemos despues de
// hacer la busqueda.
"click .autocomplete__item": "seleccionarCliente",
// Seleccionar categoria.
"change #FormContratoNuevoTipo": "seleccionarTipoContrato",
// Para crear nuevo cliente.
"click #CrearNuevoCliente": "crearNuevoCliente",
// Desbloquear el porcentaje de rebaja
"click #botonDesbloquear": "desbloquearPorcentaje",
"click #FormContratoNuevoGuardar": "guardarContrato",
},
// Template para mostrar todo el forumalario
// de crear un nuevo contrato.
template: _.template( $('#tplContratoNuevoFormulario').html() ),
// Temaple para crear nuevo cliente.
templateNuevoCliente: _.template( $('#tplNuevoCliente').html() ),
// Inicializamos llamando a la funcion render
// para mostrar todo el contenido del template.
initialize: function() {
this.render();
},
// La funcion nos permite agregar dentro del la propiedad el
// el template que hemos creado.
render: function() {
this.$el.html( this.template() );
},
// Se activa cuando alguien teclea dentro del input.
buscarCliente: function() {
// Recojemos el valor que se escribe en el input.
var input = $('#FormContratoNuevoCliente').val();
// Si se escribio algo
if (input.length != 0) {
// Traemos todos los que coinciden con la busqueda.
var clientes_encontrados = app.clientes.busquedaCompleta(input);
// Si hay clientes encontrados.
if (clientes_encontrados.length != 0) {
// Limpiamos todos los datos de alguna busqueda anterior.
app.clientes_busqueda.reset();
// Agregamos todos los datos encontrados en la busqueda.
app.clientes_busqueda.add(clientes_encontrados);
// Creamos una vista para mostrar los clientes encontrados.
var clientes_autocompletados = new clientesAutoCompletadoView(
{collection: app.clientes_busqueda}
);
// Mostramos los clientes dentro del DOM
$('#ClientesAutoCompletado').html(clientes_autocompletados.$el);
}
// Si no hay clientes encontrados.
else {
$('#ClientesAutoCompletado').html("");
}
}
// Si no se ha escrito nada
else {
$('#ClientesAutoCompletado').html("");
}
},
seleccionarCliente: function(e) {
// Recogemos el id(pk) del cliente.
pk = e.currentTarget.dataset.pk;
// Encontramos el cliente con el siguiente id(pk).
var cliente = app.clientes.get(pk);
// Creamos una vista para mostrarlo en la parte lateral.
var cliente_lateral = new clienteLateralView({model:cliente});
$('#Lateral').html(cliente_lateral.$el);
// Estamos utiliando jeditable para editar en la parte lateral.
$('.lateralNombre').editable('/ajax/editar-nombre/');
$('.lateralApellido').editable('/ajax/editar-apellido/');
$('.lateralEmail').editable('/ajax/editar-email/');
$('.lateralDireccion').editable('/ajax/editar-direccion/');
$('.lateralNacimiento').editable('/ajax/editar-nacimiento/');
// Agregamos dentro del input el cliente seleccionado(Nombres y apellidos).
$('#FormContratoNuevoCliente').val(cliente.get('nombres') + ' ' + cliente.get('apellidos'));
$('#FormContratoNuevoCliente').data('pk', pk);
// Limpiamos la lista de clientes autocompletados
$('#ClientesAutoCompletado').html("");
},
seleccionarTipoContrato: function(e) {
// Recogemos el id del tipo de contrato.
tipo_contrato_id = e.currentTarget.value
// Actualizamos las categorias que tienen ese tipo de contrato.
app.categorias = categorias_original.filter(function(categoria) {
return categoria.tipo_contrato == tipo_contrato_id;
});
// Llamamos para agregar un articulo.
new articuloNuevoView();
},
// Funcion para crear nuevo cliente.
crearNuevoCliente: function() {
var vista_crear_cliente = new crearNuevoCliente();
$('#Lateral').html( vista_crear_cliente.$el );
},
// Desbloquear input
desbloquearPorcentaje: function() {
var vista_enviar_porcentaje = new enviarPorcentajeView({model:app.modelos.contrato});
$('#Lateral').html( vista_enviar_porcentaje.$el );
},
guardarContrato: function() {
// Recolección de datos de contrato en formularios
if ($('#FormContratoNuevoCliente').val() == false) {
$('#FormContratoNuevoCliente').addClass('formulario__error');
} else {
var cliente = $('#FormContratoNuevoCliente').data('pk');
}
if ($('#FormContratoNuevoPlazo').val() == false) {
$('#FormContratoNuevoPlazo').addClass('formulario__error');
} else {
var plazo = $('#FormContratoNuevoPlazo').val();
}
if ($('#FormContratoNuevoPorcentaje').val() == false) {
$('#FormContratoNuevoPorcentaje').addClass('formulario__error');
} else {
var porcentaje_retroventa = $('#FormContratoNuevoPorcentaje').val();
}
if ($('#FormContratoNuevoTipo').val() == false) {
$('#FormContratoNuevoTipo').addClass('formulario__error');
} else {
var tipo_contrato = $('#FormContratoNuevoTipo').val();
}
app.modelos.contrato.set({
cliente: cliente,
plazo: plazo,
porcentaje_retroventa: porcentaje_retroventa,
tipo_contrato: tipo_contrato,
}, {validate: true});
if (!app.modelos.contrato.isValid()) {
alert("El modelo no es valido");
} else {
var articulos_json = app.colecciones.articulos.toJSON();
$.ajax({
url: "/ajax/contrato-nuevo/",
data: {
cliente: app.modelos.contrato.get('cliente'),
plazo: app.modelos.contrato.get('plazo'),
tipo_contrato: app.modelos.contrato.get('tipo_contrato'),
porcentaje_retroventa: app.modelos.contrato.get('porcentaje_retroventa'),
valor: app.modelos.contrato.get('valor'),
peso: app.modelos.contrato.get('peso'),
empleado: app.modelos.contrato.get('empleado'),
codigo: app.modelos.contrato.get('codigo'),
articulos: JSON.stringify(articulos_json)
},
type: 'POST',
success: function(data) {
alert("El contrato se guardo.")
}
});
}
},
});
// Vista para crear nuevo Cliente.
var crearNuevoCliente = Backbone.View.extend({
initialize: function() {
this.render();
},
className: 'form__cliente_nuevo',
events: {
"click #clienteGuardar": "guardarCliente",
},
template: _.template( $('#tplNuevoCliente').html() ),
// Se recogen todos los clientes encontrados y se les pasa al template.
render: function() {
this.$el.html(this.template());
return this;
},
guardarCliente: function() {
var nombre = $('#clienteNombre').val();
var apellido = $('#clienteApellido').val();
var cedula = $('#clienteCedula').val();
var email = $('#clienteEmail').val();
var direccion = $('#clienteDireccion').val();
var nacimiento = $('#clienteNacimiento').val();
var dt = new Date(nacimiento);
console.log(dt);
nacimiento_dia = dt.getUTCDate();
nacimiento_mes = dt.getUTCMonth() + 1;
nacimiento_year = dt.getUTCFullYear();
$.ajax({
url: '/ajax/guardar-cliente/',
data: {
nombre:nombre,
apellido:apellido,
cedula:cedula,
email:email,
direccion:direccion,
nacimiento_dia:nacimiento_dia,
nacimiento_mes:nacimiento_mes,
nacimiento_year:nacimiento_year,
},
type: "POST",
success: function(data) {
cliente = new clienteClass(data);
app.clientes.add(cliente);
console.log(cliente.toJSON());
console.log(app.clientes.toJSON());
$('#FormContratoNuevoCliente').val(cliente.get('nombres') + ' ' + cliente.get('apellidos'));
$('#FormContratoNuevoCliente').data('pk', cliente.get('pk'));
var cliente_lateral = new clienteLateralView({model:cliente});
$('#Lateral').html(cliente_lateral.$el);
}
});
}
});
// Vista para mostrar los clientes encontrados.
var clientesAutoCompletadoView = Backbone.View.extend({
initialize: function() {
this.render();
},
tagName: 'ul',
className: 'autocomplete__items',
template: _.template( $('#tplClientesAutoCompletado').html() ),
// Se recogen todos los clientes encontrados y se les pasa al template.
render: function() {
this.$el.html(this.template({
clientes: this.collection.toJSON()
}));
return this;
}
});
// Mostrar cliente seleccionado al costado
var clienteLateralView = Backbone.View.extend({
initialize: function() {
this.render();
},
template: _.template( $('#tplClienteLateral').html() ),
render: function() {
this.$el.html( this.template(this.model.toJSON() ));
return this;
}
});
// Mostrar cliente seleccionado al costado
var enviarPorcentajeView = Backbone.View.extend({
initialize: function() {
console.log(this.model.toJSON());
this.render();
},
events: {
"click #firebtn": "enviarPorcentaje",
},
template: _.template( $('#tplEnviarPorcentaje').html() ),
render: function() {
this.$el.html( this.template());
return this;
},
enviarPorcentaje: function() {
var input = $('#fire').val();
var cliente = $('#FormContratoNuevoCliente').data('pk');
var valor = this.model.get('valor');
var envio;
$.ajax({
data: {cliente: cliente},
url: "/ajax/buscar-cliente/",
type: "POST",
success: function(data) {
envio = datos.push({
cliente_nombre: data.nombre,
cliente_cedula: data.cedula,
pedido: input,
valor: valor,
porcentaje: input,
cambio: false,
});
console.log(envio);
// console.log(envio.value());
// $('#fire').val('');
// datos.on('child_added', function(snapshot) {
// console.log(envio);
// $('#FormContratoNuevoPorcentaje').val(envio.porcentaje);
// });
// console.log(envio.val().porcentaje);
// console.log(envio.val());
var ref = new Firebase("https://intense-torch-2716.firebaseio.com/"+envio.key());
ref.on("value", function(snapshot){
console.log(snapshot.val());
$('#FormContratoNuevoPorcentaje').val(snapshot.val().porcentaje);
});
ref.on("child_changed", function(snapshot) {
var changedPost = snapshot.val();
console.log("The updated post title is " + changedPost.title);
$('#FormContratoNuevoPorcentaje').val(snapshot.val().porcentaje);
});
}
});
}
});
|
// pages/home/diseaseInfo/diseaseInfo.js
Page({
/**
* 页面的初始数据
*/
data: {
isOK: false
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
var that=this
wx.request({
url: 'http://127.0.0.1:8080/wxjoba/disease/getDiseaseById',
data: {
"id": options.id
},
header: {
'Content-Type': 'application/json'
},
success: function (res) {
that.setData({
disease:res.data,
isOK: true
})
}
})
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})
|
import Vue from 'vue'
import Router from '@/router.js'
const user = {
namespaced: true,
state: {
// general information about user, such as login, allowed upload size, number of giles uploaded etc
generalInfo: null,
// an array of objects assigned to user
assignedObjects: [],
// offset of assigned objects - is passed to the API for the purpose of lazy loading
assignedObjectsOffset: 0,
// total number of assigned objects
assignedObjectsCount: 0,
// an array of the objects visited by user, sorted by the date of visit DESC
lastVisitedObjects: [],
// offset of last visited objects
lastVisitedObjectsOffset: 0,
// total number of last visited objects
lastVisitedObjectsCount: 0,
// limit of objects to be loaded per request
objectListLimit: 50
},
mutations: {
// sets general info of the user fetched from API
setGeneralInfo (state, data) {
state.generalInfo = data
},
// when lazy loading assigned objecs - concats current object list with the list received from API
concatAssignedObjects (state, list) {
state.assignedObjects = state.assignedObjects.concat(list)
},
// when loading objects first time after component created - replaces current assigned objects list with the list received from API
replaceAssignedObjects (state, list) {
state.assignedObjects = list
},
// when lazy loading last visited objecs - concats current object list with the list received from API
concatLastVisitedObjects (state, list) {
state.lastVisitedObjects = state.lastVisitedObjects.concat(list)
},
// when loading objects first time after component created - replaces current last visited objects list with the list received from API
replaceLastVisitedObjects (state, list) {
state.lastVisitedObjects = list
},
// empties user info after logout
emptyGeneralInfo (state) {
state.generalInfo = null
}
},
actions: {
// fetches user info from API
getGeneralInfo ({ commit }) {
Vue.http.get('/j_index').then(response => {
if (response.body.user) {
commit('setGeneralInfo', response.body.user)
}
})
},
/* fetches objects, which are assigned to user
@param shouldReplace - if set to true, replaces current objects list, otherwise - contacts */
getAssignedObjects ({ state, commit }, shouldReplace) {
Vue.http.post('/j_archive', { limit: state.objectListLimit, offset: state.assignedObjectsOffset }).then(response => {
if (shouldReplace) {
commit('replaceAssignedObjects', response.body.object_list)
} else {
commit('concatAssignedObjects', response.body.object_list)
}
})
},
/* fetches last visited objects
@param shouldReplace - if set to true, replaces current objects list, otherwise - contacts */
getLastVisitedObjects ({ state, commit }, shouldReplace) {
Vue.http.post('/j_home', { limit: state.objectListLimit, offset: state.lastVisitedObjectsOffset }).then(response => {
if (shouldReplace) {
commit('replaceLastVisitedObjects', response.body.object_list)
} else {
commit('concatLastVisitedObjects', response.body.object_list)
}
})
},
// performs logout and clears user data
logout ({ commit }) {
Vue.http.post('/signout').then(response => {
commit('emptyGeneralInfo')
Router.push('/')
})
}
}
}
export default user
|
import React from 'react';
import {noop} from "../noop";
import PropTypes from 'prop-types';
import './styles.css';
export const Input = (
{
placeholder,
label,
type,
value,
onChange,
onBlur,
disabled,
name
}
) => {
return (
<label className="input">
{label && (
<span className="input__label">{label}</span>
)}
<input
name={name}
type={type}
className="input__field"
value={value}
onBlur={onBlur}
placeholder={placeholder}
disabled={disabled}
onChange={onChange}/>
</label>
);
};
Input.defaultProps = {
placeholder: '',
label: '',
value: '',
type: 'text',
onChange: noop,
onBlur: noop,
disabled: false,
name: '',
mix: ''
};
Input.propTypes = {
label: PropTypes.node,
type: PropTypes.string,
placeholder: PropTypes.string,
value: PropTypes.string,
onChange: PropTypes.func,
onBlur: PropTypes.func,
mix: PropTypes.string,
name: PropTypes.string,
disabled: PropTypes.bool
};
|
'use strict';
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const ImageminPlugin = require('imagemin-webpack-plugin').default;
const path = require('path');
const distDir = path.resolve(__dirname, 'docs');
module.exports = {
// Entry point : first executed file
// This may be an array. It will result in many output files.
entry: './src/main.ts',
// What files webpack will manage
resolve: {
extensions: ['.js', '.ts', '.tsx']
},
// Make errors mor clear
devtool: 'inline-source-map',
// Configure output folder and file
output: {
path: distDir,
filename: 'main_bundle.js'
},
module: {
rules: [
{
test: /\.tsx?$/,
loader: 'ts-loader'
}
]
},
devServer: {
contentBase: ['./docs', './src']
},
plugins: [
new CopyWebpackPlugin([
{
from: './src/assets',
to: 'assets'
},
{
from: './src/db.json',
to: 'db.json'
}
]),
new ImageminPlugin({
disable: process.env.NODE_ENV !== 'production',
test: /\.(jpe?g|png|gif|svg)$/i ,
optipng: {
optimizationLevel: 9
}
}),
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
template: 'src/index.html'
})
]
};
|
var module = angular.module('ucms.app.datalist.addedit');
module.controller('dataListTypeAddEditCtrl', function ($scope, $xhttp, $modal, $uibModal) {
$scope.objectType = 'DataList';
$scope.type = {
Id: 'new',
Name: '',
Description: '',
Fields: []
};
$scope.submit = function() {
var id = Utils.getParameterByName("id");
if (id) {
/* update */
$xhttp.post(WEBAPI_ENDPOINT + '/api/datalisttype/update', $scope.type).then(function () {
$scope.alertSvc.addSuccess('Update DataList Type successfully');
window.setTimeout(function () {
location.href = '/datalist';
}, 1000);
});
} else {
/* create new */
$xhttp.post(WEBAPI_ENDPOINT + '/api/datalisttype/create', $scope.type).then(function () {
$scope.alertSvc.addSuccess('Create DataList Type successfully');
window.setTimeout(function() {
location.href = '/datalist';
}, 1000);
});
}
}
$scope.cancel = function() {
location.href = '/datalist';
}
$scope.createField = function() {
var modal = $uibModal.open({
templateUrl: 'dataListTypefieldModal.html',
controller: 'datalistfieldModalCtrl',
resolve: {
dataListType: function () { return $scope.type; },
field: function(){return undefined;}
}
});
modal.result.then(function(field) {
$scope.type.Fields.push(field);
});
}
$scope.edit = function(field) {
var modal = $uibModal.open({
templateUrl: 'dataListTypefieldModal.html',
controller: 'datalistfieldModalCtrl',
resolve: {
dataListType: function () { return $scope.type; },
field: function(){return field;}
}
});
modal.result.then(function (newField) {
field = _.cloneDeep(newField);
});
}
$scope.delete = function(field) {
$modal.showConfirm('Are you sure you want to delete this field?').then(function() {
_.remove($scope.type.Fields, field);
});
}
$scope.init = function () {
// check permission
$scope.getPermissions().then(function () {
// check permission and redirect if not authorize
if ($scope.hasPermission('None', $scope.objectType)) {
window.location = PAGE_403;
}
});
var id = Utils.getParameterByName("id");
if (id) {
$xhttp.get(WEBAPI_ENDPOINT + '/api/datalisttype/getbyid?id=' + id)
.then(function(response) {
$scope.type = response.data;
});
}
}
});
module.controller('datalistfieldModalCtrl', function ($scope, $xhttp, $uibModalInstance, dataListType, field) {
$scope.namePattern = /^[a-zA-Z]{1,50}/;
$scope.field = {};
$scope.init = function () {
if (field && field != null) {
$scope.field = _.clone(field);
}
$scope.field.DataListTypeId = dataListType.Id;
}
$scope.init();
$scope.ok = function () {
$uibModalInstance.close($scope.field);
}
$scope.cancel = function() {
$uibModalInstance.dismiss('cancel');
}
});
|
/**
* Created by Liuchenling on 1/21/15.
*/
var express = require('express');
path = require('path'),
bodyParser = require('body-parser'),
router = require('./routers'),
settings = require('./config.json'),
pluginManager = require('./common/pluginManager'),
_ = require('lodash'),
app = express();
var __root = settings.root;
/* engine */
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
/* midddlewares */
app.use(__root, bodyParser.urlencoded());
/*
cache the static directory path, use black to split if have more.
*/
app.set('static', 'public');
_.each(app.get('static').split(' '), function(staticPath){
app.use(__root, express.static(path.join(__dirname, staticPath)));
});
/* route */
app.use(__root, router.logger);
app.use(__root, router.cache);
app.use(__root, router.api);
/* plugin */
app.use(__root, pluginManager);
///* error handler */
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
app.use(function(err, req, res, next){
res.json({
status: err.status || 404,
info: err.info || "plugin and method not match"
});
});
module.exports = app;
|
// 名刺: 91 x 55 mm
// canvas: 455 x 275 px
var canvas, context;
var MW = 455;
var MH = 275;
var selected_design_name;
var json_cached;
var isDrawing = false;
var isAndroid = false;
// http://ninoha.com/?p=60
/*
文字列を指定幅ごとに区切る
context : 描画コンテキスト
text : 変換元の文字列
width : 1行の最大幅
戻り値 : 1行毎に分割した文字列の配列
*/
function multilineText(context, text, width) {
var len = text.length;
var strArray = [];
var tmp = "";
var i = 0;
if( len < 1 ){
//textの文字数が0だったら終わり
return strArray;
}
for( i = 0; i < len; i++ ){
var c = text.charAt(i); //textから1文字抽出
if( c == "\n" ){
/* 改行コードの場合はそれまでの文字列を配列にセット */
strArray.push( tmp );
tmp = "";
continue;
}
/* contextの現在のフォントスタイルで描画したときの長さを取得 */
if (context.measureText( tmp + c ).width <= width){
/* 指定幅を超えるまでは文字列を繋げていく */
tmp += c;
}else{
/* 超えたら、それまでの文字列を配列にセット */
strArray.push( tmp );
tmp = c;
}
}
/* 繋げたままの分があれば回収 */
if( tmp.length > 0 )
strArray.push( tmp );
return strArray;
}
function fillMultilineText(context, text, width, x, y, line_height, max_line) {
var ary = multilineText(context, text, width);
var n = ary.length;
if (n > max_line) {
n = max_line;
}
for (var i = 0; i < n; ++i) {
context.fillText(ary[i], x, y + line_height * i);
}
}
function fillMultilineTextBottom(context, text, width, x, y, line_height, max_line) {
var ary = multilineText(context, text, width);
var n = ary.length;
if (n > max_line) {
n = max_line;
}
var pad = max_line - n;
for (var i = 0; i < n; ++i) {
context.fillText(ary[i], x, y + line_height * (i + pad) );
}
}
function excute_draw(json) {
if (isDrawing) {
return;
}
isDrawing = true;
draw_functions[selected_design_name].call(this, json);
isDrawing = false;
}
function apply_screen_name() {
var screen_name = $("#screen_name").val();
if (screen_name == "") {
return;
}
// Now Loading
var loading = {};
loading.background_image_url = "background_images/design_a.png";
loading.screen_name = "Now_Loading"
loading.profile_image_local_url = "images/loading.png";
loading.name = "Now Loading...";
loading.description = "Now Loading...";
// excute_draw(loading);
$.get(
"twitter.json",
{},
function(data) {
if (data == "(´・ω・`)") {
$("#alert_screen_name").css('display', 'block');
return;
}
var json = json_cached = data;
$("#alert_screen_name").css('display', 'none');
excute_draw(json);
});
}
function init_design_select() {
$("ol.carousel-indicators li").first().addClass('active');
$("div.carousel-inner div.item").first().addClass('active');
select_design(selected_design_name = 'design_a');
}
function post_image() {
if (isDrawing) {
return false;
}
var type = 'image/png';
$('#image_data').val( canvas.toDataURL(type) );
$('#screen_name_hidden').val( $("#screen_name").val() );
return true;
}
function save_image() {
if (isDrawing || isAndroid) {
return false;
}
var type = 'image/png';
window.open( canvas.toDataURL(type) );
}
function delete_image(id) {
document.location.href = "delete.rb?id=" + id;
}
function select_design(name) {
$('a#design_a_' + selected_design_name).first().removeClass('active');
selected_design_name = name;
$('a#design_a_' + selected_design_name).first().addClass('active');
if (json_cached != null) {
excute_draw(json_cached);
} else {
apply_screen_name();
}
}
function submitCheck(e) {
if (!e) var e = window.event;
// Enter キー で Twitter ID を確定する。
if(e.keyCode == 13){
apply_screen_name();
return false;
}
}
$(function() {
canvas = document.getElementById("canvas");
context = canvas.getContext("2d");
init_design_select();
apply_screen_name();
var agent = navigator.userAgent;
if(agent.search(/Android/) != -1){
isAndroid = true;
}
});
|
import {range} from 'lodash'
import React from 'react'
import {Link} from 'react-router-dom'
import {compose, withState, lifecycle, withHandlers} from 'recompose'
import {withStyles} from '@material-ui/core/styles'
import Button from '@material-ui/core/Button'
// local libs
import {
plainProvedGet as g,
immutableProvedGet as ig,
PropTypes,
setPropTypes,
compareCurrentBreakpoint as ccb,
breakpointSM as sm,
breakpoints,
} from 'src/App/helpers'
import {immutableI18nButtonsModel} from 'src/App/models'
import WrappedButton from 'src/generic/WrappedButton'
import {muiStyles} from 'src/generic/Pagination/assets/muiStyles'
import {ButtonsListWrapper, ButtonsList} from 'src/generic/Pagination/assets'
const
Pagination = ({
classes, cb, pageNumber, pagesCount, linkBuilder,
setButtonRef, setWrapperRef, i18nButtons,
}) => {
const
// pagination
buttonsElements = range(1, pagesCount + 1).map(n =>
<Link
key={n}
to={linkBuilder({pagination: n})}
className={g(classes, 'paginationLink')}
>
<Button
buttonRef={ccb(cb, sm) === -1 && n === pageNumber
? g(setButtonRef, []) : null}
classes={{
root: g(classes, 'paginationButtonRoot'),
}}
variant={n === pageNumber ? 'contained' : 'outlined'}
color="primary"
>
{n}
</Button>
</Link>
)
return <ButtonsListWrapper>
{ccb(cb, sm) === -1 && pageNumber !== 1
? <WrappedButton
link={linkBuilder({pagination: pageNumber - 1})}
text={ig(i18nButtons, 'prev')}
/>
: null}
<ButtonsList ref={ccb(cb, sm) === -1 ? g(setWrapperRef, []) : null}>
{buttonsElements}
</ButtonsList>
{ccb(cb, sm) === -1 && pageNumber !== pagesCount
? <WrappedButton
link={linkBuilder({pagination: pageNumber + 1})}
text={ig(i18nButtons, 'next')}
marginRight0={true}
/>
: null}
</ButtonsListWrapper>
}
export default compose(
withState('buttonRef', 'setButtonRef', null),
withState('wrapperRef', 'setWrapperRef', null),
withHandlers({
scrollToCurrentPageButton: props => () => {
const
buttonOffset = g(props, 'buttonRef', 'offsetLeft'),
wrapperOffset = g(props, 'wrapperRef', 'offsetLeft')
g(props, 'wrapperRef').scrollTo(buttonOffset - wrapperOffset, 0)
}
}),
lifecycle({
componentDidUpdate(prevProps) {
if (ccb(g(this.props, 'cb'), sm) === -1 && g(this.props, 'buttonRef') !== null)
this.props.scrollToCurrentPageButton()
},
}),
withStyles(muiStyles),
setPropTypes(process.env.NODE_ENV === 'production' ? null : {
classes: PropTypes.shape({
paginationButtonRoot: PropTypes.string,
paginationLink: PropTypes.string,
}),
cb: PropTypes.oneOf(breakpoints),
pageNumber: PropTypes.number,
pagesCount: PropTypes.number,
buttonRef: PropTypes.nullable(PropTypes.object),
wrapperRef: PropTypes.nullable(PropTypes.object),
i18nButtons: immutableI18nButtonsModel,
linkBuilder: PropTypes.func,
setButtonRef: PropTypes.func,
setWrapperRef: PropTypes.func,
}),
)(Pagination)
|
/**
* @fileoverview A visual containing a model in JSON format
* @author Tony Parisi
*/
goog.provide('SB.JsonModel');
goog.require('SB.Model');
goog.require('SB.Shaders');
/**
* @constructor
* @extends {SB.Model}
*/
SB.JsonModel = function(param)
{
SB.Model.call(this, param);
}
goog.inherits(SB.JsonModel, SB.Model);
SB.JsonModel.prototype.handleLoaded = function(data)
{
var material = new THREE.MeshFaceMaterial(); // data.materials ? data.materials[0] : null;
this.object = new THREE.Mesh(data, material);
this.addToScene();
}
SB.JsonModel.prototype.initialize = function(param)
{
param = param || {};
var material = param.material || new THREE.MeshBasicMaterial();
var geometry = param.geometry || new THREE.Geometry();
this.object = new THREE.Mesh(geometry, material);
this.addToScene();
}
|
const consulclient = require('../index')({host: 'localhost'})
const serviceName = 'test-service'
const keyName = 'test/key'
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
consulclient.registerService(serviceName, 'localhost', getRandomInt(9001, 9100))
setInterval(() => {
consulclient.setKey(keyName, `${getRandomInt(1, 100000)}`)
.then(console.log, console.err)
}, 10000)
|
/*
Nessa aula usamos os childrens de um componente
utilizando o props.children
*/
import React from 'react';
import { Text } from 'react-native';
import Style from '../../styles/default';
export default ({ nome, sobrenome }) => {
return (
<>
<Text style={Style.text20}>{nome} {sobrenome}</Text>
</>
)
}
|
import React, { Component } from 'react';
import ContactForm from '../components/ContactForm';
import '../style/contact.css';
class Contact extends Component {
render() {
const { contact, contact_invitation } = this.props.content;
return (
<div className="contactSection">
<h3>{contact}</h3>
<div className="socialmedia">
<a href="https://github.com/AnnaOrysiak"><i className="fab fa-github"></i></a>
<a href="https://www.linkedin.com/in/anna-orysiak-b1796a137/"><i className="fab fa-linkedin-in"></i></a>
<a href="https://www.facebook.com/anna.walkiewicz.77"><i className="fab fa-facebook"></i></a>
</div>
<h4 className="contactHeader">{contact_invitation}</h4>
<ContactForm id="mainContactForm" className="contactForm" name="contactForm" method="post" action="" content={this.props.content} language={this.props.language} />
</div>
);
}
}
export default Contact;
|
const readline = require('readline');
const fs = require('fs');
const google = require('googleapis');
const googleAuth = require('google-auth-library');
const glob = require('glob');
let fileNames = glob.sync('./client_secret*.json');
let googleCredentials = fs.readFileSync(fileNames[0], 'utf8');
let credentials = (JSON.parse(googleCredentials)).installed;
let auth = new googleAuth();
let oauth2Client = new auth.OAuth2(
credentials.client_id,
credentials.client_secret,
credentials.redirect_uris[0]
);
let scopes = [
'https://www.googleapis.com/auth/drive'
];
let url = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: scopes,
});
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
console.log(`Follow this link: ${url}`);
rl.question('Enter code here: ', (code) => {
getKEys(code);
rl.close();
});
function getKEys(code) {
oauth2Client.getToken(code, function (err, tokens) {
if (!err) {
fs.writeFile('key.txt', `export const GOOGLE_CLIENT_ID = '${credentials.client_id}';\r\n` +
`export const GOOGLE_CLIENT_SECRET = '${credentials.client_secret}';\r\n` +
`export const GOOGLE_REDIRECT_URL = '${credentials.redirect_uris[0]}';\r\n`+
`export const GOOGLE_REFRESH_TOKEN = '${tokens.refresh_token}';\r\n`+
`export const GOOGLE_FOLDER_ID = 'DIRECTORY ID';`);
console.log('Tokens were created');
} else {
console.log(err);
}
});
}
|
import React from 'react';
import {View,Text, StyleSheet,Image,Button,TouchableOpacity} from 'react-native';
const ProductItem =({image,title,price,onSelect,onAddToCart,children})=>{
return <TouchableOpacity onPress={onSelect}><View style={styles.product}>
<Image source={{uri:image}} style={styles.image}/>
<Text style={styles.title}>{title}</Text>
<Text style={styles.price}>${price.toFixed(2)}</Text>
<View style={styles.actions}>
{children}
</View>
</View>
</TouchableOpacity>
}
const styles=StyleSheet.create({
product:{
shadowColor:'#000',
shadowOpacity:0.26,
shadowOffset:{width:0,height:2},
shadowRadius:8,
elevation:5,
borderRadius:10,
backgroundColor:'#fff',
height:300,
margin:20
},
image:{
height:'60%',
width:'100%'
},
title:{
fontSize:18,
marginVertical:4,
textAlign:'center',
fontFamily:"open-sans-bold"
},
price:{
fontSize:14,
textAlign:'center',
color:'#888',
fontFamily:"open-sans"
},
actions:{
flexDirection:'row',
marginTop:5,
justifyContent:'space-around',
alignItems:'center'
}
});
export default ProductItem;
|
var Pusher = require('pusher');
var pusher = new Pusher({
appId: '398003',
key: '4600601226fca311289b',
secret: 'a2d5f722685e10c17c87',
cluster: 'us2',
encrypted: true
});
module.exports = pusher;
|
import {
GET_DICIPLINE_REQUEST,
GET_DICIPLINE_SUCCESS,
GET_DICIPLINE_FAILURE,
} from '../constants/dicipline.constants';
import api from '../services/api';
//GET DICIPLINE
export const getDicipline = () => (dispatch) => {
dispatch({ type: GET_DICIPLINE_REQUEST });
api.get('/subjects')
.then((res) => {
const { data } = res;
// Formatando data para ficar compativel com o select tree do ant
const formatData = data.map((dicipline, a) => ({
title: dicipline.name_dicipline,
value: `0-${a}`,
id: dicipline.id_dicipline,
children: dicipline.length !== 0 && dicipline.subject_niv_1.map((subject01, b) => {
{
return ({
title: subject01.name_subject,
value: `0-${a}-${b}`,
id: subject01.id_subject_niv_1,
children: subject01.length !== 0 && subject01.subject_niv_2.map((subject02, c) => {
{
return ({
title: subject02.name_subject,
value: `0-${a}-${b}-${c}`,
id: subject02.id_subject_niv_2,
children: subject02.length !== 0 && subject02.subject_niv_3.map((subject03, d) => {
{
return ({
title: subject03.name_subject,
value: `0-${a}-${b}-${c}-${d}`,
id: subject03.id_subject_niv_3,
// children: subject03.length !== 0 && subject03.subject_niv_4.map((subject04, e) => {
// {
// return ({
// title: subject04.name_subject,
// value: `0-${a}-${b}-${c}-${d}-${e}`,
// key: `0-${a}-${b}-${c}-${d}-${e}`,
// children: subject04.length !== 0 && subject04.subject_niv_5.map((subject05, f) => {
// {
// return ({
// title: subject05.name_subject,
// value: `0-${a}-${b}-${c}-${d}-${e}-${f}`,
// key: `0-${a}-${b}-${c}-${d}-${e}-${f}`,
// children: subject05.length !== 0 && subject05.subject_niv_6.map((subject06, g) => {
// {
// return ({
// title: subject06.name_subject,
// value: `0-${a}-${b}-${c}-${d}-${e}-${f}-${g}`,
// key: `0-${a}-${b}-${c}-${d}-${e}-${f}-${g}`,
// children: subject06.length !== 0 && subject06.subject_niv_7.map((subject07, h) => {
// {
// return ({
// title: subject07.name_subject,
// value: `0-${a}-${b}-${c}-${d}-${e}-${f}-${g}`,
// key: `0-${a}-${b}-${c}-${d}-${e}-${f}-${g}`,
// })
// }
// })
// })
// }
// })
// })
// }
// })
// })
// }
// })
})
}
})
})
}
})
})
}
})
}));
dispatch({ type: GET_DICIPLINE_SUCCESS, formatData });
})
.catch((error) => {
const { response: err } = error;
const message = err && err.data ? err.data.message : 'Erro desconhecido';
dispatch({ type: GET_DICIPLINE_FAILURE, message });
});
};
|
import Vue from 'vue'
import VueRouter from 'vue-router'
import MainNavbar from '@/layout/MainNavbar.vue';
import MainFooter from '@/layout/MainFooter.vue';
import Login from '@/pages/Login.vue';
import Landing from '@/pages/Landing.vue';
import Index from '@/pages/Index.vue';
Vue.use(VueRouter)
const routes = [
{
path: '/',
name: 'index',
components: { default: Index, header: MainNavbar, footer: MainFooter },
props: {
header: { colorOnScroll: 400 },
footer: { backgroundColor: 'black' }
}
},
{
path: '/login',
name: 'login',
components: { default: Login, header: MainNavbar },
props: {
header: { colorOnScroll: 400 }
}
},
{
path: '/landing',
name: 'landing',
components: { default: Landing, header: MainNavbar, footer: MainFooter },
props: {
header: { colorOnScroll: 400 },
footer: { backgroundColor: 'black' }
}
}
]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
export default router
|
module.exports = function (sequelize, DataTypes, Model) {
class Publisher extends Model {}
Publisher.init({
name: {
type: DataTypes.STRING,
allowNull: false
},
phoneNumber: {
type: DataTypes.STRING(15),
allowNull: false
},
address: {
type: DataTypes.TEXT,
allowNull: true
}
}, { sequelize, modelName: 'Publisher' } );
Publisher.paginate = async function(query = {}, page = 1, perpage = 10) {
query.offset = ((page-1) * perpage);
query.limit = perpage;
const data = await this.findAll(query);
const total = await this.count();
const totalPage = Math.ceil(total / perpage);
return {
data: data,
pagination: {
perpage: perpage,
current_page: page,
max_page: totalPage,
total_shown: data.length,
total: total
}
}
}
return Publisher;
}
|
/// <reference types="cypress" />
describe('Dynamic Perspective', () => {
beforeEach(() => {
//escape page error "Uncaught ReferenceError: slidesPerPage is not define"
cy.on('uncaught:exception', (err, runnable) => {
// returning false here prevents Cypress from
// failing the test
return false;
});
cy.visit('https://template1.booost.bg/feello/index');
});
it('active readers should be visible', () => {
cy.get('[data-cy=reader-count]').should('be.visible');
});
it('should hide active readers bar on iphone 6 layout', () => {
cy.viewport('iphone-6');
cy.get('[data-cy=reader-count]').should('be.hidden');
});
it('should change logo link width on different viewport orientation', () => {
cy.viewport('iphone-6');
cy.get('a > img').invoke('outerWidth').should('not.be.above', 100);
cy.viewport('iphone-6', 'landscape');
cy.get('a > img').invoke('outerWidth').should('not.be.above', 120);
});
it('should show hamburger menu on lower resolution', () => {
cy.get('.manu-btn').should('be.hidden');
cy.viewport(990, 768);
cy.get('.manu-btn').should('be.visible');
});
it('should open sidebar menu on hamburger click', () => {
cy.viewport(990, 768);
cy.get('.manu-btn').click().wait(1000);
cy.get('.manu-list').should('be.visible');
});
it('should close sidebar menu on X button click', () => {
cy.viewport(990, 768);
cy.get('.manu-btn').click();
cy.get('.manu-list').should('be.visible');
cy.get('.close-btn').click().wait(1000).should('be.hidden');
});
});
|
var searchData=
[
['skok',['skok',['../classokienka_1_1_rysy.html#a8e986ff3f4e4045d3186ff5cc7c6fa7e',1,'okienka::Rysy']]],
['skok2',['skok2',['../classokienka_1_1_rysy.html#a90f734cdd1d6f6d6c04c00eca0c3e721',1,'okienka::Rysy']]]
];
|
var objBean = require('NodeBean')
var typeBean = require('TypeBean')
cc.Class({
extends: cc.Component,
properties: {
_bgMusicPlay: {
default: null
},
overDialog: {
type: cc.Node,
default: null
},
winLable: {
default: null,
type: cc.Label
},
leftTime: 60, //剩余时间的秒数
myLeft: 80,
opponentLeft: 80,
leftTimeCompnent: {
type: cc.Label,
default: null
}, //剩余时间的秒数
myLeftCompnent: {
type: cc.Label,
default: null
},
opponentLeftCompnent: {
type: cc.Label,
default: null
},
myuuid: 0,
time: 0,
ws: {
default: null,
type: WebSocket
},
rowCount: 8,
columCount: 10,
xiaocuMusic: {
default: null,
url: cc.AudioClip
},
bgm: {
default: null,
url: cc.AudioClip
},
selectedBgm: {
default: null,
url: cc.AudioClip
},
desAnim: {
default: null,
type: cc.Prefab
},
bgNode: { //背景节点预制体
default: null,
type: cc.Prefab
},
bgNodes: [], //背景节点数组
gameObjs: { //预制体
default: [],
type: [cc.Prefab]
},
gameNodes: {
default: [],
type: objBean
}, //游戏节点
linecanvas: {
default: null,
type: cc.Node
},
nodeContaint: {
default: null,
type: cc.Node,
},
// 匹配界面
pipeiView: {
default: null,
type: cc.Node
},
pipeiMyName: {
default: null,
type: cc.Label
},
pipeiOpName: {
default: null,
type: cc.Label
},
pipeiMyCover: {
default: null,
type: cc.Sprite
},
pipeiOpCover: {
default: null,
type: cc.Sprite
},
pipeiTimeLable: {
default: null,
type: cc.Label
},
pipeiTimer: null,
pipeiTime: 0,
rootIds: ''
},
popGame() {
cc.director.popScene();
},
restartGame() {
if (this.nodeContaint) {
// let removeAction = cc.removeSelf(false);
this.nodeContaint.removeAllChildren();
}
this.overDialog.active = false;
// if (this.currentBgm) {
// cc.audioEngine.stop(this.currentBgm);
// // cc.audioEngine.play(that.bgm, true, 1);
// }
this.startGame();
},
// //生成背景节点列表
// createBGNodes() {
// let that = this;
// let width = that.nodeContaint.width;
// let height = that.nodeContaint.height;
// for (let i = 0; i < that.columCount + 2; ++i) {
// let rowNode = [];
// if (i > 0 && i < (that.columCount + 1)) { //第一行和最后一行为空
// for (let j = 0; j < that.rowCount + 2; ++j) {
// if (j > 0 && j < (that.columCount + 1)) { //第一列和最后一列置空
// let newNodeObj = new objBean();
// let newNode = cc.instantiate(this.bgNode);
// let x = -71 * (that.rowCount / 2) + 71 * (j - 1) + 35.5 + width / 2;
// let y = -71 * (that.columCount / 2) + 71 * (i - 1) + 35.5 + height / 2;
// newNode.setPosition(x, y);
// // gameNewNode.setPosition(x, y);
// newNodeObj.pointX = x;
// newNodeObj.pointY = y;
// newNodeObj.pointIndexX = j;
// newNodeObj.pointIndexY = i;
// newNodeObj.pointBgNode = newNode;
// rowNode.push(newNodeObj);
// that.nodeContaint.addChild(newNode);
// } else {
// let newNodeObj = new objBean();
// //console.log("节点 = " + newNodeObj.pointX);
// let x = -71 * (that.rowCount / 2) + 71 * (j - 1) + 35.5 + width / 2;
// let y = -71 * (that.columCount / 2) + 71 * (i - 1) + 35.5 + height / 2;
// newNodeObj.pointX = x;
// newNodeObj.pointY = y;
// newNodeObj.pointIndexX = j;
// newNodeObj.pointIndexY = i;
// rowNode.push(newNodeObj);
// }
// }
// } else {
// for (let j = 0; j < that.rowCount + 2; ++j) {
// let newNodeObj = new objBean();
// //console.log("节点 = " + newNodeObj.pointX);
// let x = -71 * (that.rowCount / 2) + 71 * (j - 1) + 35.5 + width / 2;
// let y = -71 * (that.columCount / 2) + 71 * (i - 1) + 35.5 + height / 2;
// newNodeObj.pointX = x;
// newNodeObj.pointY = y;
// newNodeObj.pointIndexX = j;
// newNodeObj.pointIndexY = i;
// rowNode.push(newNodeObj);
// }
// }
// this.gameNodes.push(rowNode);
// }
// },
isOver() {
for (let i = 1; i < this.columCount + 1; ++i) {
for (let j = 1; j < this.rowCount + 1; ++j) {
if (this.gameNodes[i][j].pointValue >= 0) {
console.log("还没结束");
return false;
}
}
}
console.log("已经结束了");
this.overDialog.active = true;
return true;
},
shuffle(a) {
var len = a.length;
for (var i = 0; i < len - 1; i++) {
var index = parseInt(Math.random() * (len - i));
var temp = a[index];
a[index] = a[len - i - 1];
a[len - i - 1] = temp;
}
return a;
},
//生成可消除的节点列表并打乱顺序后放到地图中
createGameNodes() {
let that = this;
let gameObjs = []; //生成的游戏节点对象
let typeCount = 0; //可消除类型种类
let nodeTotalCount = that.rowCount * that.columCount; //总节点数
if (this.gameObjs) {
typeCount = that.gameObjs.length;
}
if (typeCount > 0) {
let subTypeCount = parseInt(nodeTotalCount / typeCount); //每种生成的个数,如果这个个数是偶数则直接用,如果这个个数是奇数个,则减一然后最后一种球补全
if (subTypeCount % 2 === 1) { //奇数个需要减一变成偶数个
subTypeCount -= 1;
}
for (let i = 0; i < typeCount - 1; ++i) { //前面N-1种偶数个
for (let j = 0; j < subTypeCount; ++j) {
// let gameNewNode = cc.instantiate(that.gameObjs[i]);
let bean = new typeBean();
bean.type = i;
bean.node = cc.instantiate(that.gameObjs[i]);
gameObjs.push(bean);
}
}
let remainCount = nodeTotalCount - gameObjs.length;
for (let j = 0; j < remainCount; ++j) { //最后一种补全剩下的
// let gameNewNode = cc.instantiate(that.gameObjs[typeCount - 1]);
let bean = new typeBean();
bean.type = typeCount - 1;
bean.node = cc.instantiate(that.gameObjs[typeCount - 1]);
gameObjs.push(bean);
// gameObjs.push(gameNewNode);
}
}
gameObjs = that.shuffle(gameObjs);
console.log("创建节点完成,节点个数" + gameObjs.length);
return gameObjs;
// let index = 0;
// for (let i = 1; i < that.columCount + 1; ++i) {
// for (let j = 1; j < that.rowCount + 1; ++j) {
// let nodeObj = gameObjs[index];
// nodeObj.setPosition(that.gameNodes[i][j].pointX, that.gameNodes[i][j].pointY);
// that.gameNodes[i][j].pointNode = nodeObj;
// that.gameNodes[i][j].pointValue = nodeType;
// that.nodeContaint.addChild(nodeObj);
// index += 1;
// }
// }
// for (let i = 0; i < this.columCount; ++i) {
// for (let j = 0; j < this.rowCount; ++j) {
// if (objCount)
// }
// }
},
startWebSocket() {
let that = this;
let data = new Date();
that.time = data.getTime();
console.log("开始连接配对");
// cc.loader.load(remoteUrl, function (err, texture) {
// // Use texture to create sprite frame
// });
cc.loader.load('http://p003bt12y.bkt.clouddn.com/mycover.jpg', function (err, texture) {
// console.log("error = " + err);
// that.pipeiMyName.getComponent(cc.Label).string = JSON.stringify(err);
var frame = new cc.SpriteFrame(texture);
that.pipeiMyCover.spriteFrame = frame;
});
that.pipeiTimer = setInterval(() => {
that.pipeiTime += 1;
// console.log("时间 = " + that.pipeiTime);
if (that.pipeiTime < 60) {
if (that.pipeiTime < 10) {
that.pipeiTimeLable.getComponent(cc.Label).string = "00:0" + that.pipeiTime;
} else {
that.pipeiTimeLable.getComponent(cc.Label).string = "00:" + that.pipeiTime;
}
} else {
if (that.pipeiTime % 60 < 10) {
that.pipeiTimeLable.getComponent(cc.Label).string = "0" + parseInt(that.pipeiTime / 60) + ":0" + that.pipeiTime % 60;
} else {
that.pipeiTimeLable.getComponent(cc.Label).string = "0" + parseInt(that.pipeiTime / 60) + ":" + that.pipeiTime % 60;
}
}
}, 1000);
this.ws = new WebSocket("ws://172.16.10.44:8888/webSocket");
this.ws.onopen = function (event) {
console.log("websocke连接成功");
let jsonString = JSON.stringify(
{
mType: 1,
bType: 1,
uid: that.myuuid + '',
data: {
openId: that.myuuid + '',
name: '雷帮文',
avatarUrl: 'https://img2.woyaogexing.com/2018/05/31/ecf76710fc9d8201!400x400_big.jpg',
gender: 1,
city: '杭州'
}
});
console.log("发送的json数据 = " + jsonString);
that.ws.send(jsonString);
};
this.ws.onmessage = function (event) {
console.log("response text msg: " + event.data);
console.log("接收数据成功");
if (event.data) {
let jsonData = JSON.parse(event.data);
if (jsonData.bType === 1) {
if (that.ws && that.ws.readyState === WebSocket.OPEN) {
let jsonString = JSON.stringify(
{
mType: 1,
bType: 2,
uid: that.myuuid + '',
data: {
openId: that.myuuid + '',
subject: '连连看1区'
}
});
console.log("发送的json数据 = " + jsonString);
that.ws.send(jsonString);
}
} else if (jsonData.bType === 2) {
that.rootIds = jsonData.data.roomId;
}
}
// that.ws.onclose();
// let dataObj = JSON.parse(event.data);
};
this.ws.onerror = function (event) {
console.log("websocke连接错误");
};
this.ws.onclose = function (event) {
console.log("websocke连接关闭");
};
// setTimeout(function () {
// if (this.ws.readyState === WebSocket.OPEN) {
// this.ws.send("Hello WebSocket, I'm a text message.");
// }
// else {
// console.log("WebSocket instance wasn't ready...");
// }
// }, 3);
},
startGame() {
let that = this;
if (that.gameNodes && that.gameNodes.length > 0) {
that.gameNodes = [];
}
let gameNodeObjs = that.createGameNodes();
let canvasComponey = that.linecanvas.getComponent(cc.Graphics);
let width = that.nodeContaint.width;
let height = that.nodeContaint.height;
let nodeType = 0;
let clickedNode = new objBean();
let playAnim = null;
let desAnim1 = null;
let desAnim2 = null;
let currentSocr = 1;
// that._bgMusicPlay = cc.audioEngine.play(that.bgm, true, 1);
let index = 0;
for (let i = 0; i < that.columCount + 2; ++i) {
let rowNode = [];
if (i > 0 && i < (that.columCount + 1)) { //第一行和最后一行为空
for (let j = 0; j < that.rowCount + 2; ++j) {
if (j > 0 && j < (that.rowCount + 1)) { //第一列和最后一列置空
let newNodeObj = new objBean();
let newNode = cc.instantiate(this.bgNode);
nodeType = parseInt(Math.random() * (4 + 1), 10);
let gameNewNode = gameNodeObjs[index].node;
let x = -71 * (that.rowCount / 2) + 71 * (j - 1) + 35.5 + width / 2;
let y = -71 * (that.columCount / 2) + 71 * (i - 1) + 35.5 + height / 2;
newNode.setPosition(x, y);
gameNewNode.setPosition(x, y);
newNodeObj.pointX = x;
newNodeObj.pointY = y;
newNodeObj.pointIndexX = j;
newNodeObj.pointIndexY = i;
this.nodeContaint.addChild(newNode);
this.nodeContaint.addChild(gameNewNode);
newNodeObj.pointBgNode = newNode;
newNodeObj.pointNode = gameNewNode;
newNodeObj.pointValue = gameNodeObjs[index].type;
gameNewNode.on(cc.Node.EventType.TOUCH_START, function (event) {
if (clickedNode.pointValue !== -1
&& clickedNode !== newNodeObj
&& clickedNode.pointValue === newNodeObj.pointValue) {
let node_1_x = clickedNode.pointNode.getPosition().x;
let node_1_y = clickedNode.pointNode.getPosition().y;
let node_2_x = newNodeObj.pointNode.getPosition().x;
let node_2_y = newNodeObj.pointNode.getPosition().y;
//console.log("gameNewNode.getTag() = " + newNodeObj.pointValue + ", clickedNode.getTag() = " + clickedNode.pointValue);
let points = that.matchBolck(that.gameNodes, newNodeObj, clickedNode);
if (points === null) {
points = that.matchBolckOne(that.gameNodes, newNodeObj, clickedNode);
if (points === null) {
points = that.matchBolckTwo(that.gameNodes, newNodeObj, clickedNode);
if (points !== null) {
//console.log('2折相连节点数 = ' + points.length)
}
} else {
//console.log('1折相连节点数 = ' + points.length)
}
} else {
//console.log('0折相连节点数 = ' + points.length)
}
if (points && points !== null && points.length > 0) {
if (that.ws && that.ws.readyState === WebSocket.OPEN) {
let jsonString = JSON.stringify(
{
mType: 1,
bType: 5,
data: {
openId: that.myuuid + '',
currentCompleted: currentSocr++,
currentScore: currentSocr++,
isOver: 0,
roomId: that.rootIds
}
});
console.log("发送的json数据 = " + jsonString);
that.ws.send(jsonString);
}
// if (that.ws && that.ws.readyState === WebSocket.OPEN) {
// that.ws.send(JSON.stringify(
// {
// time: that.time,
// myScor: 500,
// opponentScor: 700
// }));
// } else {
// console.log("webSocket没有连接");
// }
// that.ws.send({ myScor: 500, opponentScor: 700 });
cc.audioEngine.play(that.xiaocuMusic, false, 1);
clickedNode.pointValue = -1;
newNodeObj.pointValue = -1;
clickedNode.pointNode.destroy();
newNodeObj.pointNode.destroy();
let desclickedNode = cc.instantiate(that.desAnim);
let desnewNode = cc.instantiate(that.desAnim);
desclickedNode.setPosition(node_1_x, node_1_y);
desnewNode.setPosition(node_2_x, node_2_y);
that.nodeContaint.addChild(desclickedNode);
that.nodeContaint.addChild(desnewNode);
playAnim = null;
for (let k = 0; k < points.length; ++k) {
if (k === 0) {
canvasComponey.moveTo(points[k].pointX, points[k].pointY);
} else {
canvasComponey.lineTo(points[k].pointX, points[k].pointY);
}
//console.log('x = ' + points[k].pointX + ' + y = ' + points[k].pointY);
}
canvasComponey.stroke();
setTimeout(() => {
canvasComponey.clear();
}, 500);
that.isOver();
} else {
//console.log('不符合条件,重新选取' + clickedNode.pointValue);
cc.audioEngine.play(that.selectedBgm, false, 1);
if (playAnim !== null) {
playAnim.stop();
}
playAnim = newNodeObj.pointNode.getComponent(cc.Animation);
playAnim.play('click');
clickedNode = newNodeObj;
}
// //console.log(node_1_x + " + " + node_1_y + " + " + node_2_x + " + " + node_2_y)
} else {
if (playAnim !== null) {
playAnim.stop();
}
cc.audioEngine.play(that.selectedBgm, false, 1);
playAnim = newNodeObj.pointNode.getComponent(cc.Animation);
playAnim.play('click');
clickedNode = newNodeObj;
}
}, newNodeObj);
rowNode.push(newNodeObj);
index += 1;
} else {
let newNodeObj = new objBean();
//console.log("节点 = " + newNodeObj.pointX);
let x = -71 * (that.rowCount / 2) + 71 * (j - 1) + 35.5 + width / 2;
let y = -71 * (that.columCount / 2) + 71 * (i - 1) + 35.5 + height / 2;
newNodeObj.pointX = x;
newNodeObj.pointY = y;
newNodeObj.pointIndexX = j;
newNodeObj.pointIndexY = i;
rowNode.push(newNodeObj);
}
}
} else {
for (let j = 0; j < that.rowCount + 2; ++j) {
let newNodeObj = new objBean();
//console.log("节点 = " + newNodeObj.pointX);
let x = -71 * (that.rowCount / 2) + 71 * (j - 1) + 35.5 + width / 2;
let y = -71 * (that.columCount / 2) + 71 * (i - 1) + 35.5 + height / 2;
newNodeObj.pointX = x;
newNodeObj.pointY = y;
newNodeObj.pointIndexX = j;
newNodeObj.pointIndexY = i;
rowNode.push(newNodeObj);
}
}
this.gameNodes.push(rowNode);
}
},
onLoad() {
cc.audioEngine.play(this.bgm, true, 1);
this.myuuid = parseInt(Math.random() * 1000000);
this.startGame();
this.startWebSocket();
},
// start() {
// },
// 0折相连
matchBolck(datas, startPoint, endPoint) {
if (startPoint.pointIndexX != endPoint.pointIndexX && startPoint.pointIndexY != endPoint.pointIndexY) {
return null;
}
let min, max;
if (startPoint.pointIndexX == endPoint.pointIndexX) {
min = startPoint.pointIndexY < endPoint.pointIndexY ? startPoint.pointIndexY : endPoint.pointIndexY;
max = startPoint.pointIndexY > endPoint.pointIndexY ? startPoint.pointIndexY : endPoint.pointIndexY;
for (min++; min < max; min++) {
if (!(datas[min][startPoint.pointIndexX].isEmpty())) {
return null;
}
}
} else {// 如果两点的y坐标相等,则在竖直方向上扫描
min = startPoint.pointIndexX < endPoint.pointIndexX ? startPoint.pointIndexX : endPoint.pointIndexX;
max = startPoint.pointIndexX > endPoint.pointIndexX ? startPoint.pointIndexX : endPoint.pointIndexX;
for (min++; min < max; min++) {
if (!(datas[startPoint.pointIndexY][min].isEmpty())) {
return null;
}
}
}
return [startPoint, endPoint];
},
//1折相连
matchBolckOne(datas, startPoint, endPoint) {
// if (startPoint.pointIndexX == endPoint.pointIndexX || startPoint.pointIndexY == endPoint.pointIndexY) {
// return null;
// }
let linePoint = []; //链接点
let pt = new objBean(startPoint.pointIndexX, endPoint.pointIndexY, startPoint.pointX, endPoint.pointY);
let stMatch = false;
let tdMatch = false;
if (datas[pt.pointIndexY][pt.pointIndexX].isEmpty()) {
stMatch = this.matchBolck(datas, startPoint, pt);
tdMatch = (stMatch !== null) ?
this.matchBolck(datas, pt, endPoint) : stMatch;
if (stMatch !== null && tdMatch !== null) {
linePoint.push(startPoint);
linePoint.push(pt);
linePoint.push(endPoint);
return linePoint;
}
}
pt = new objBean(endPoint.pointIndexX, startPoint.pointIndexY, endPoint.pointX, startPoint.pointY);
if (datas[pt.pointIndexY][pt.pointIndexX].isEmpty()) {
stMatch = this.matchBolck(datas, startPoint, pt);
tdMatch = (stMatch !== null) ?
this.matchBolck(datas, pt, endPoint) : stMatch;
if (stMatch !== null && tdMatch !== null) {
linePoint.push(startPoint);
linePoint.push(pt);
linePoint.push(endPoint);
return linePoint;
}
}
return null;
},
matchBolckTwo(datas, startPoint, endPoint) {
if (datas && datas !== null && datas.length > 0) {
let pointList = []; //链接点
let stMatch = null;
let etMatch = null;
for (let i = startPoint.pointIndexX + 1; i < this.rowCount + 2; ++i) {
if (datas[startPoint.pointIndexY][i].pointValue === -1) {
stMatch = this.matchBolckOne(datas, datas[startPoint.pointIndexY][i], endPoint);
if (stMatch !== null && stMatch.length > 0) {
pointList.push(startPoint);
pointList = pointList.concat(stMatch);
return pointList;
}
} else {
break;
}
}
for (let i = startPoint.pointIndexX - 1; i >= 0; --i) {
if (datas[startPoint.pointIndexY][i].pointValue === -1) {
stMatch = this.matchBolckOne(datas, datas[startPoint.pointIndexY][i], endPoint);
if (stMatch !== null && stMatch.length > 0) {
pointList.push(startPoint);
pointList = pointList.concat(stMatch);
return pointList;
}
} else {
break;
}
}
for (let i = startPoint.pointIndexY + 1; i < this.columCount + 2; ++i) {
if (datas[i][startPoint.pointIndexX].pointValue === -1) {
stMatch = this.matchBolckOne(datas, datas[i][startPoint.pointIndexX], endPoint);
if (stMatch !== null && stMatch.length > 0) {
pointList.push(startPoint);
pointList = pointList.concat(stMatch);
return pointList;
}
} else {
break;
}
}
for (let i = startPoint.pointIndexY - 1; i >= 0; --i) {
if (datas[i][startPoint.pointIndexX].pointValue === -1) {
stMatch = this.matchBolckOne(datas, datas[i][startPoint.pointIndexX], endPoint);
if (stMatch !== null && stMatch.length > 0) {
pointList.push(startPoint);
pointList = pointList.concat(stMatch);
return pointList;
}
} else {
break;
}
}
} else {
return null;
}
}
});
|
import React from 'react';
import { useDrop } from 'react-dnd';
import Card from '../Card/index.jsx'
import './index.less'
const ChooseList = ({
dimensionList,
targetList,
dimensionBorderIsHeight,
targetBorderIsHeight,
deleteChooseList
}) => {
const [dimensionCollectProps, dimensionDroper] = useDrop({
accept: 'dimensionBox',
collect: (minoter) => {
return {
isOver: minoter.isOver()
}
}
})
const [targetCollectProps, targetDroper] = useDrop({
accept: 'targetbox',
collect: (minoter) => {
return {
isOver: minoter.isOver()
}
}
})
return <div className='ChooseListContainer'>
<div className='dimension'>
<div>已选择维度:</div>
<div
ref={ dimensionDroper }
className='listItem'
style={{border:dimensionBorderIsHeight?'1px solid red':'1px solid black'}}
>
{dimensionList.map(v => <Card
key={v.key}
className='ChooseListItem'
cardData={v}
deleteChooseList={deleteChooseList}
type='dimension'
/>)}
</div>
</div>
<div className='target'>
<div>已选择指标:</div>
<div
ref={ targetDroper }
className='listItem'
style={{border:targetBorderIsHeight?'1px solid red':'1px solid black'}}
>
{targetList.map(v => <Card
key={v.key}
className='ChooseListItem'
cardData={v}
deleteChooseList={deleteChooseList}
type='target'
/>)}
</div>
</div>
</div>
}
export default ChooseList
|
const imagesArray = [
{
id:1,
image :"/banner1.jpg"
},
{
id:2,
image:"/banner2.jpg"
},
{
id:3,
image:"/banner3.jpg"
},
{
id:4,
image:"/banner4.jpg"
},
{
id:5,
image:"/banner5.jpg"
}
]
export default imagesArray
|
// Came with Theme
function cardPressed() {
this.TagList.add('card-hover');
}
function cardReleased() {
this.TagList.remove('card-hover');
}
// Responsive Map Lists
function responsiveRow () {
if ((document.getElementById("responsive").children.length % 3) !== 0) {
$("#responsive").css("padding", "0 25vw");
}
}
$( document ).ready(function() {
responsiveRow();
});
// For popups on page scroll
const callback = (entries, observer) => {
entries.forEach(entry => {
const anchor = document.querySelector('#' + entry.target.id);
if (entry.isIntersecting) {
anchor.classList.add('activeAnchor');
console.log($('h1.activeAnchor').attr('id'));
} else {
anchor.classList.remove('activeAnchor');
}
});
};
const options = {
threshold: 0.5
};
const observer = new IntersectionObserver(callback, options);
const container = $("article.post.dropcase");
const targetElements = document.querySelectorAll('h1');
targetElements.forEach(element => {
observer.observe(element);
});
|
define([], function () {
return {
"PropertyPaneDescription": "Configure the leaderboard.",
"ConnectivityGroupName": "Connectivity",
"ApiUrlFieldLabel": "API-Url",
"ValidateApiUrlNotNull": "The API-Url must not be empty.",
"ValidateApiUrlValidUrl": "The API-Url must be a valid URL.",
"UITitle": "Quiz",
"UIDescription": "Fill out the quiz.",
"UIPrimary": "Finish",
"UISecondary": "Quiz will be closed.",
"UITableUser": "Username",
"UITablePoints": "Points",
"UITableRank": "Rank",
"UITableBadge": "Badge"
}
});
|
function Product(){
var x = window.prompt("Enter first number : ")
var y = window.prompt("Enter second number : ")
var z = x*y;
alert("Result : "+z)
}
Product();
|
exports.seed = function (knex) {
return knex("ships")
.truncate()
.then(function () {
return knex("ships").insert([
{
ship_id: "1",
chassis_id: "1",
name: "Aurora ES"
},
{
ship_id: "3",
chassis_id: "1",
name: "Aurora LX"
},
{
ship_id: "4",
chassis_id: "1",
name: "Aurora MR"
},
{
ship_id: "5",
chassis_id: "1",
name: "Aurora CL"
},
{
ship_id: "6",
chassis_id: "1",
name: "Aurora LN"
},
{
ship_id: "7",
chassis_id: "2",
name: "300i"
},
{
ship_id: "8",
chassis_id: "2",
name: "315p"
},
{
ship_id: "9",
chassis_id: "2",
name: "325a"
},
{
ship_id: "10",
chassis_id: "2",
name: "350r"
},
{
ship_id: "11",
chassis_id: "3",
name: "F7C Hornet"
},
{
ship_id: "122",
chassis_id: "3",
name: "F7C Hornet Wildfire"
},
{
ship_id: "13",
chassis_id: "3",
name: "F7C-S Hornet Ghost"
},
{
ship_id: "14",
chassis_id: "3",
name: "F7C-R Hornet Tracker"
},
{
ship_id: "15",
chassis_id: "3",
name: "F7C-M Super Hornet"
},
{
ship_id: "37",
chassis_id: "3",
name: "F7A Hornet"
},
{
ship_id: "177",
chassis_id: "3",
name: "F7C-M Super Hornet Heartseeker"
},
{
ship_id: "47",
chassis_id: "4",
name: "Constellation Aquila"
},
{
ship_id: "45",
chassis_id: "4",
name: "Constellation Andromeda"
},
{
ship_id: "46",
chassis_id: "4",
name: "Constellation Taurus"
},
{
ship_id: "49",
chassis_id: "4",
name: "Constellation Phoenix"
},
{
ship_id: "156",
chassis_id: "4",
name: "Constellation Phoenix Emerald"
},
{
ship_id: "16",
chassis_id: "5",
name: "Freelancer"
},
{
ship_id: "31",
chassis_id: "5",
name: "Freelancer DUR"
},
{
ship_id: "32",
chassis_id: "5",
name: "Freelancer MAX"
},
{
ship_id: "33",
chassis_id: "5",
name: "Freelancer MIS"
},
{
ship_id: "56",
chassis_id: "6",
name: "Cutlass Black"
},
{
ship_id: "57",
chassis_id: "6",
name: "Cutlass Red"
},
{
ship_id: "58",
chassis_id: "6",
name: "Cutlass Blue"
},
{
ship_id: "193",
chassis_id: "6",
name: "Cutlass Black Best In Show Edition"
},
{
ship_id: "100",
chassis_id: "7",
name: "Avenger Stalker"
},
{
ship_id: "124",
chassis_id: "7",
name: "Avenger Titan Renegade"
},
{
ship_id: "101",
chassis_id: "7",
name: "Avenger Warlock"
},
{
ship_id: "102",
chassis_id: "7",
name: "Avenger Titan"
},
{
ship_id: "64",
chassis_id: "8",
name: "Gladiator"
},
{
ship_id: "22",
chassis_id: "9",
name: "M50"
},
{
ship_id: "88",
chassis_id: "10",
name: "Starfarer"
},
{
ship_id: "89",
chassis_id: "10",
name: "Starfarer Gemini"
},
{
ship_id: "24",
chassis_id: "11",
name: "Caterpillar"
},
{
ship_id: "125",
chassis_id: "11",
name: "Caterpillar Pirate Edition"
},
{
ship_id: "194",
chassis_id: "11",
name: "Caterpillar Best In Show Edition"
},
{
ship_id: "72",
chassis_id: "12",
name: "Retaliator Bomber"
},
{
ship_id: "99",
chassis_id: "12",
name: "Retaliator Base"
},
{
ship_id: "26",
chassis_id: "13",
name: "Scythe"
},
{
ship_id: "27",
chassis_id: "14",
name: "Idris-M"
},
{
ship_id: "28",
chassis_id: "14",
name: "Idris-P"
},
{
ship_id: "92",
chassis_id: "15",
name: "P-52 Merlin"
},
{
ship_id: "65",
chassis_id: "16",
name: "Mustang Alpha"
},
{
ship_id: "66",
chassis_id: "16",
name: "Mustang Beta"
},
{
ship_id: "67",
chassis_id: "16",
name: "Mustang Gamma"
},
{
ship_id: "69",
chassis_id: "16",
name: "Mustang Delta"
},
{
ship_id: "70",
chassis_id: "16",
name: "Mustang Omega"
},
{
ship_id: "172",
chassis_id: "16",
name: "Mustang Alpha Vindicator"
},
{
ship_id: "59",
chassis_id: "17",
name: "Redeemer"
},
{
ship_id: "60",
chassis_id: "18",
name: "Gladius"
},
{
ship_id: "121",
chassis_id: "18",
name: "Gladius Valiant"
},
{
ship_id: "188",
chassis_id: "18",
name: "Pirate Gladius"
},
{
ship_id: "35",
chassis_id: "19",
name: "Khartu-Al"
},
{
ship_id: "36",
chassis_id: "20",
name: "Merchantman"
},
{
ship_id: "55",
chassis_id: "21",
name: "890 Jump"
},
{
ship_id: "62",
chassis_id: "22",
name: "Carrack"
},
{
ship_id: "204",
chassis_id: "22",
name: "Carrack w/C8X"
},
{
ship_id: "205",
chassis_id: "22",
name: "Carrack Expedition w/C8X"
},
{
ship_id: "206",
chassis_id: "22",
name: "Carrack Expedition"
},
{
ship_id: "61",
chassis_id: "23",
name: "Herald"
},
{
ship_id: "41",
chassis_id: "24",
name: "Hull C"
},
{
ship_id: "84",
chassis_id: "24",
name: "Hull A"
},
{
ship_id: "85",
chassis_id: "24",
name: "Hull B"
},
{
ship_id: "86",
chassis_id: "24",
name: "Hull D"
},
{
ship_id: "87",
chassis_id: "24",
name: "Hull E"
},
{
ship_id: "71",
chassis_id: "25",
name: "Orion"
},
{
ship_id: "51",
chassis_id: "26",
name: "Reclaimer"
},
{
ship_id: "196",
chassis_id: "26",
name: "Reclaimer Best In Show Edition"
},
{
ship_id: "63",
chassis_id: "28",
name: "Javelin"
},
{
ship_id: "75",
chassis_id: "30",
name: "Vanguard Warden"
},
{
ship_id: "95",
chassis_id: "30",
name: "Vanguard Harbinger"
},
{
ship_id: "96",
chassis_id: "30",
name: "Vanguard Sentinel"
},
{
ship_id: "127",
chassis_id: "30",
name: "Vanguard Hoplite"
},
{
ship_id: "90",
chassis_id: "31",
name: "Reliant Kore"
},
{
ship_id: "105",
chassis_id: "31",
name: "Reliant Mako"
},
{
ship_id: "106",
chassis_id: "31",
name: "Reliant Sen"
},
{
ship_id: "107",
chassis_id: "31",
name: "Reliant Tana"
},
{
ship_id: "91",
chassis_id: "32",
name: "Genesis Starliner"
},
{
ship_id: "93",
chassis_id: "33",
name: "Glaive"
},
{
ship_id: "97",
chassis_id: "34",
name: "Endeavor"
},
{
ship_id: "98",
chassis_id: "35",
name: "Sabre"
},
{
ship_id: "120",
chassis_id: "35",
name: "Sabre Comet"
},
{
ship_id: "148",
chassis_id: "35",
name: "Sabre Raven"
},
{
ship_id: "103",
chassis_id: "37",
name: "Crucible"
},
{
ship_id: "104",
chassis_id: "38",
name: "P72 Archimedes"
},
{
ship_id: "207",
chassis_id: "38",
name: "P72 Archimedes Emerald"
},
{
ship_id: "108",
chassis_id: "39",
name: "Blade"
},
{
ship_id: "109",
chassis_id: "40",
name: "Prospector"
},
{
ship_id: "110",
chassis_id: "41",
name: "Buccaneer"
},
{
ship_id: "111",
chassis_id: "42",
name: "Dragonfly Yellowjacket"
},
{
ship_id: "112",
chassis_id: "42",
name: "Dragonfly Black"
},
{
ship_id: "113",
chassis_id: "43",
name: "MPUV Personnel"
},
{
ship_id: "114",
chassis_id: "43",
name: "MPUV Cargo"
},
{
ship_id: "115",
chassis_id: "44",
name: "Terrapin"
},
{
ship_id: "116",
chassis_id: "45",
name: "Polaris"
},
{
ship_id: "117",
chassis_id: "46",
name: "Prowler"
},
{
ship_id: "123",
chassis_id: "47",
name: "85X"
},
{
ship_id: "126",
chassis_id: "48",
name: "Razor"
},
{
ship_id: "157",
chassis_id: "48",
name: "Razor EX"
},
{
ship_id: "158",
chassis_id: "48",
name: "Razor LX"
},
{
ship_id: "128",
chassis_id: "49",
name: "Hurricane"
},
{
ship_id: "129",
chassis_id: "50",
name: "Banu Defender"
},
{
ship_id: "130",
chassis_id: "51",
name: "Eclipse"
},
{
ship_id: "131",
chassis_id: "52",
name: "Nox"
},
{
ship_id: "132",
chassis_id: "52",
name: "Nox Kue"
},
{
ship_id: "134",
chassis_id: "53",
name: "Cyclone"
},
{
ship_id: "135",
chassis_id: "53",
name: "Cyclone-TR"
},
{
ship_id: "136",
chassis_id: "53",
name: "Cyclone-RC"
},
{
ship_id: "137",
chassis_id: "53",
name: "Cyclone-RN"
},
{
ship_id: "138",
chassis_id: "53",
name: "Cyclone-AA"
},
{
ship_id: "139",
chassis_id: "54",
name: "Ursa Rover"
},
{
ship_id: "179",
chassis_id: "54",
name: "Ursa Rover Fortuna"
},
{
ship_id: "140",
chassis_id: "55",
name: "600i Touring"
},
{
ship_id: "141",
chassis_id: "55",
name: "600i Explorer"
},
{
ship_id: "143",
chassis_id: "56",
name: "X1 Base"
},
{
ship_id: "145",
chassis_id: "56",
name: "X1 Velocity"
},
{
ship_id: "147",
chassis_id: "56",
name: "X1 Force"
},
{
ship_id: "149",
chassis_id: "57",
name: "Pioneer"
},
{
ship_id: "150",
chassis_id: "58",
name: "Hawk"
},
{
ship_id: "151",
chassis_id: "59",
name: "Hammerhead"
},
{
ship_id: "195",
chassis_id: "59",
name: "Hammerhead Best In Show Edition"
},
{
ship_id: "154",
chassis_id: "61",
name: "Nova"
},
{
ship_id: "155",
chassis_id: "62",
name: "Vulcan"
},
{
ship_id: "159",
chassis_id: "63",
name: "100i"
},
{
ship_id: "160",
chassis_id: "63",
name: "125a"
},
{
ship_id: "161",
chassis_id: "63",
name: "135c"
},
{
ship_id: "162",
chassis_id: "64",
name: "C2 Hercules"
},
{
ship_id: "163",
chassis_id: "64",
name: "M2 Hercules"
},
{
ship_id: "164",
chassis_id: "64",
name: "A2 Hercules"
},
{
ship_id: "165",
chassis_id: "65",
name: "Vulture"
},
{
ship_id: "166",
chassis_id: "66",
name: "Apollo Triage"
},
{
ship_id: "167",
chassis_id: "66",
name: "Apollo Medivac"
},
{
ship_id: "168",
chassis_id: "67",
name: "Mercury Star Runner"
},
{
ship_id: "169",
chassis_id: "68",
name: "Valkyrie"
},
{
ship_id: "171",
chassis_id: "68",
name: "Valkyrie Liberator Edition"
},
{
ship_id: "170",
chassis_id: "69",
name: "Kraken"
},
{
ship_id: "175",
chassis_id: "69",
name: "Kraken Privateer"
},
{
ship_id: "173",
chassis_id: "70",
name: "Arrow"
},
{
ship_id: "174",
chassis_id: "71",
name: "San'tok.yāi"
},
{
ship_id: "176",
chassis_id: "72",
name: "SRV"
},
{
ship_id: "178",
chassis_id: "73",
name: "Corsair"
},
{
ship_id: "180",
chassis_id: "74",
name: "Ranger RC"
},
{
ship_id: "181",
chassis_id: "74",
name: "Ranger TR"
},
{
ship_id: "182",
chassis_id: "74",
name: "Ranger CV"
},
{
ship_id: "183",
chassis_id: "75",
name: "Anvil Ballista "
},
{
ship_id: "184",
chassis_id: "75",
name: "Anvil Ballista Snowblind"
},
{
ship_id: "185",
chassis_id: "75",
name: "Anvil Ballista Dunestalker"
},
{
ship_id: "186",
chassis_id: "76",
name: "Nautilus "
},
{
ship_id: "187",
chassis_id: "76",
name: "Nautilus Solstice Edition"
},
{
ship_id: "189",
chassis_id: "77",
name: "Mantis"
},
{
ship_id: "191",
chassis_id: "78",
name: "C8 Pisces"
},
{
ship_id: "192",
chassis_id: "78",
name: "C8X Pisces Expedition "
},
{
ship_id: "198",
chassis_id: "79",
name: "Crusader Ares Inferno "
},
{
ship_id: "200",
chassis_id: "79",
name: "Crusader Ares Ion"
},
{
ship_id: "201",
chassis_id: "80",
name: "Argo Mole"
},
{
ship_id: "202",
chassis_id: "80",
name: "Argo Mole Carbon Edition"
},
{
ship_id: "203",
chassis_id: "80",
name: "Argo Mole Talus Edition"
},
{
ship_id: "208",
chassis_id: "81",
name: "Origin G12"
},
{
ship_id: "209",
chassis_id: "81",
name: "Origin G12r"
},
{
ship_id: "210",
chassis_id: "81",
name: "Origin G12a"
},
{
ship_id: "211",
chassis_id: "82",
name: "Esperia Talon"
},
{
ship_id: "212",
chassis_id: "82",
name: "Esperia Talon Shrike"
},
{
ship_id: "214",
chassis_id: "83",
name: "ROC"
}
]);
});
};
|
export type SingleFileContainerProps =
{
data: {},
file: string,
size: number,
progress: number,
removeButton: () => React.Node
};
export type FileUploadProps =
{
files?: Array<{}>,
actionURL: string,
autoupload?: boolean,
defaultFileProps: {},
filenameField: string,
positionField?: string,
orderProp?: number, //( props: {} ) => number,
componentContainer: ( props: { childs: Array<{}> } ) => React.Node,
singleFileContainer: ( SingleFileContainerData ) => React.Node,
addButton: React.Node,
removeButton: React.Node,
onChange: ( {} ) => void
};
type SingleFileState =
{
id: number,
file: File | null,
isUploaded: boolean,
isError: boolean,
data: {}
};
type State =
{
files: Array<SingleFileState>
// value: string,
// items: Array<ItemObject>
};
|
import React from "react";
import {Card, DatePicker} from "antd";
const {RangePicker} = DatePicker;
function onChange(value, dateString) {
console.log('Selected Time: ', value);
console.log('Formatted Selected Time: ', dateString);
}
function onOk(value) {
console.log('onOk: ', value);
}
const ChooseTime = () => {
return (
<Card className="gx-card" title="Choose Time">
<DatePicker className="gx-mb-3 gx-w-100"
showTime
format="YYYY-MM-DD HH:mm:ss"
placeholder="Select Time"
onChange={onChange}
onOk={onOk}
/>
<RangePicker className="gx-w-100"
showTime={{format: 'HH:mm'}}
format="YYYY-MM-DD HH:mm"
placeholder={['Start Time', 'End Time']}
onChange={onChange}
onOk={onOk}
/>
</Card>
);
};
export default ChooseTime;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.