text stringlengths 7 3.69M |
|---|
export * from './T1'
export { T1 as default } from './T1';
|
import React, { useEffect, memo } from 'react';
import { func } from 'prop-types';
import { useTranslation } from 'react-i18next';
import useModalView from '../hooks/useModalView';
import Popup from './Popup';
import ReportForm from './ReportForm';
const propTypes = {
onSubmit: func.isRequired,
};
const ReportPopup = ({ onSubmit, ...popupProps }) => {
const { t } = useTranslation();
const createModalView = useModalView('/reports/new');
useEffect(createModalView, []);
return (
<Popup {...popupProps} title={t('How is the beach here?')}>
<ReportForm onSubmit={onSubmit} />
</Popup>
);
};
export default memo(ReportPopup);
ReportPopup.propTypes = propTypes;
|
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const dxfparsing = require('dxf-parsing');
const dxf = dxfparsing.Parser;
const authenticate = require('../authenticate');
const cors = require('./cors');
const PropertyVat = require('../models/propertyVat');
const dxfFileReader = require('../modelLibs/dxfFileReader');
const coordProjection = require('../modelLibs/coordProjection');
const loadJsonFile = require('load-json-file');
const propertyVatRouter = express.Router();
propertyVatRouter.use(bodyParser.json());
propertyVatRouter.options('*', cors.corsWithOptions, (req, res) => { res.sendStatus(200); });
/**
* POSTING A NEW GEOJSON FEATURES FOR PROPERTY VAT AND
* TAX PAYMENT TO THE MONGODB SERVER
*/
propertyVatRouter.post('/properties', cors.corsWithOptions, authenticate.verifyUser, (req, res, next) => {
// let projType = req.query.projType;
let filepath = req.query.path;
loadJsonFile(filepath).then(json => {
// data = coordProjection.projGeoJsonRequestBody(json, projType)
// console.log(data.data.features[0].geometry.coordinates[0]);
PropertyVat.create(json)
.then((features) => {
// console.log('Features Created ', features);
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json(features);
}, (err) => next(err))
.catch((err) => next(err));
});
});
/**
* API TO GET A SPECIFIC LAYER DOCUMENT FORM THE DATABASE
*/
propertyVatRouter.route('/vatdata')
.options(cors.corsWithOptions, (req, res) => { res.sendStatus(200); })
.get(cors.cors, (req, res, next) => {
// var layerName = req.query.layer;
var ppty_use = req.query._id;
PropertyVat.findById(ppty_use)
// .populate('comments.author')
.then((lay) => {
if (lay != null) {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json(lay);
} else {
err = new Error('Layer ' + ppty_use + ' not found');
err.status = 404;
return next(err);
}
}, (err) => next(err))
.catch((err) => next(err));
})
module.exports = propertyVatRouter;
// User.find({})
// .then((users) => {
// res.statusCode = 200;
// res.setHeader('Content-Type', 'application/json');
// res.json(users);
// }, (err) => next(err))
// .catch((err) => next(err)); |
'use strict'
const files = require('serve-static')
const path = require('path')
const app = require('../../index')({
disableResponseEvent: true
})
app.use(require('http-cache-middleware')())
const serve = files(path.join(__dirname, 'src'), {
lastModified: false,
setHeaders: (res, path) => {
res.setHeader('cache-control', 'public, no-cache, max-age=604800')
}
})
app.use(serve)
app.start(3000)
|
var $form = $('#questionForm');
var $result = $('#question-result');
var $cnt = $('#answer-cnt-prompt');
var $answer = $('input[type=text][name=answer]');
var $submit = $('input[type=submit][name=answer]');
var $skip = $('input[type=button][name=skip]');
var $back = $('#back-btn');
var $submitPrompt = $('#submit-prompt');
var showMsg = function (text, auto_close) {
$result.children('.content').html('<p>' + text + '</p>');
$result.addClass('active');
if (typeof auto_close == 'undefined' || auto_close) {
setTimeout("closeMsg()", 3000);
}
};
var closeMsg = function () {
$result.removeClass('active')
};
$result.click(closeMsg);
$skip.click(function () {
$.ajax({
url: window.location.href,
data: "_method=DELETE",
type: "POST",
beforeSend: function () {
if (skipped < 2) {
if (!confirm('纭璺宠繃璇ラ锛�'))
return false;
} else if (skipped == 2) {
if (!confirm('纭璺宠繃璇ラ锛熷鏋滃啀娆¤烦杩囧繀绛旈锛屾瘮璧涘皢澶辫触骞舵棤娉曡繘鍏ラ€夌瓟棰樼幆鑺傦紝璇锋厧閲嶈€冭檻銆�'))
return false;
}
$submit.attr('disabled', 'disabled');
$skip.attr('disabled', 'disabled');
$back.attr('disabled', 'disabled');
return true;
},
success: function (data) {
if (data == 2) {
if (skipped < 2)
showMsg("鎴愬姛璺宠繃锛�");
setTimeout("window.location.href = '/user'", 1500);
} else {
showMsg("鍑洪敊浜嗭紝鍏朵腑蹇呮湁韫婅贩...");
$submit.removeAttr('disabled');
$skip.removeAttr('disabled');
$back.removeAttr('disabled');
}
},
error: function (xhr, errorText, errorType) {
showMsg("鍑洪敊鍟︼細" + errorType + "<br>璇疯仈绯绘姝ヤ负璧㈣礋璐d汉锛�", false);
$submit.removeAttr('disabled');
$skip.removeAttr('disabled');
$back.removeAttr('disabled');
}
});
return false;
});
$form.submit(function () {
// The return value can be seen in App\TeamQuestion constants
$.ajax({
url: window.location.href,
data: $form.serialize(),
type: "POST",
beforeSend: function () {
if (!$answer.val()) {
showMsg('nothing');
return false
} else if (answer_type == 'number' && !$.isNumeric($answer.val())) {
showMsg('not a number');
return false
}
if (!confirm('纭鎻愪氦绛旀锛�'))
return false;
$submit.attr('disabled', 'disabled');
$skip.attr('disabled', 'disabled');
$back.attr('disabled', 'disabled');
$submitPrompt.html('姝e湪鎻愪氦绛旀锛岃鑰愬績绛夊緟...');
$('body').animate({scrollTop: 0});
return true;
},
success: function (data) {
console.log(data);
showMsg([
"绛旈敊鍟oQ<br>娌℃湁鏈轰細浜� 危( 掳 鈻� 掳|||)锔�<br><br>椤甸潰鍗冲皢璺宠浆...",
"涓嶆暍鐩镐俊锛岀珶鐒剁瓟瀵逛簡鈯櫹夆姍.<br><br>椤甸潰鍗冲皢璺宠浆...",
"ERROR!缃戠珯鍑洪敊浜嗭紒<br>璇峰姟蹇呰仈绯绘姝ヤ负璧㈣礋璐d汉锛侊紒锛�<br>锛堥敊璇唬鐮侊細0x00008d锛�",
"ERROR!缃戠珯鍑洪敊浜嗭紒<br>璇疯仈绯绘姝ヤ负璧㈣礋璐d汉<br>锛堥敊璇唬鐮侊細0x00009e锛�",
"绛旈敊鍟oQ<br>杩樻湁 1 娆℃満浼毼燺螤"
][data[0]], data[0] > 3);
if (data[0] < 2) {
if(data[1])//data[1]鏄嚜宸卞凡缁忔槸鍚﹂€氳繃
{
var msg = '璇ュ皬闃熷繀绛旈宸插畬鎴愭爣鍑嗭紝鎮ㄥ彲浠ョ户缁瓟棰橈紝鐜板畬鎴愭爣鍑嗙殑灏忕粍鏈�'+data[2]+'涓�';
alert(msg);
}
setTimeout("window.location.href = '/user'", 1500)
} else if (data[0] > 3) {
$cnt.text('鍓╀綑鏈轰細: ' + (5 - data[0]));
$submit.removeAttr('disabled');
$skip.removeAttr('disabled');
$back.removeAttr('disabled');
$submitPrompt.html(' ');
}
},
error: function (xhr, errorText, errorType) {
showMsg("鍑洪敊鍟︼細" + errorType + "<br>璇疯仈绯绘姝ヤ负璧㈣礋璐d汉锛�", false);
$submit.removeAttr('disabled');
$skip.removeAttr('disabled');
$back.removeAttr('disabled');
$submitPrompt.html(' ');
}
});
return false;
});
$back.click(function () {
$submit.attr('disabled', 'disabled');
$skip.attr('disabled', 'disabled');
$back.attr('disabled', 'disabled');
window.location.href = '/user';
}); |
import React, { Component } from 'react';
import './App.css';
import Roster from './components/roster';
import Options from './components/options';
import PokedexService from './services/pokedex';
class App extends Component {
constructor() {
super();
this.state = {
options: {
maxEvolutionsOnly: true
},
roster: []
};
this.pokedex = new PokedexService();
this.getNewRoster = this.getNewRoster.bind(this);
this.changeOptions = this.changeOptions.bind(this);
this.getNewRoster();
}
getNewRoster() {
this.setState({
roster: []
});
this.pokedex.getRoster(this.state.options)
.then(roster => {
this.setState({roster});
});
}
changeOptions(name, value) {
this.setState(prevState => ({
options: Object.assign(prevState.options, {[name]: value})
}));
}
render() {
return (
<div className="App">
<header className="App-header">
<h1 className="App-title">Pokémon Random Team Generator</h1>
</header>
<Roster pokemon={this.state.roster}></Roster>
<button onClick={this.getNewRoster}>Reroll</button>
<Options initialState={this.state.options} onChange={this.changeOptions}></Options>
</div>
);
}
}
export default App;
|
$(document).ready(function () {
"use strict";
var av_name = "TransformGrammarsFS";
var av = new JSAV(av_name,);
var Frames = PIFRAMES.init(av_name);
// Frame 1
av.umsg("Now we start our exploration of useful transformations for CFGs.");
av.displayInit();
// Frame 2
av.umsg(Frames.addQuestion("membership"));
av.step();
// Frame 3
av.umsg(Frames.addQuestion("power"));
av.step();
// Frame 4
av.umsg(Frames.addQuestion("lambda"));
av.step();
// Frame 5
av.umsg(Frames.addQuestion("subst"));
av.step();
// Frame 6
av.umsg(Frames.addQuestion("replace"));
av.step();
// Frame 7
av.umsg(Frames.addQuestion("whatP"));
av.step();
// Frame 8
av.umsg(Frames.addQuestion("notyet"));
av.step();
// Frame 9
av.umsg(Frames.addQuestion("replaceB"));
av.step();
// Frame 10
av.umsg(Frames.addQuestion("useless"));
av.step();
// Frame 11
av.umsg(Frames.addQuestion("leftrec"));
av.step();
// Frame 12
av.umsg("<b>Parsing</b> is the process of solving the membership problem for a given string. In practice, it has the effect of finding a suitable derivation tree for the string. There are many different algorithms for parsing. A top-down parser starts with the start symbol of the grammar and replaces it through a series of productions to derive the string. In general, a good strategy is to find the leftmost terminal as soon as possible. But a left-recursive grammar requires that we first derive the rest of the string.");
av.step();
// Frame 13
av.umsg(Frames.addQuestion("leftterm"));
av.step();
// Frame 14
av.umsg(Frames.addQuestion("second"));
av.step();
// Frame 15
av.umsg(Frames.addQuestion("problem"));
av.step();
// Frame 16
av.umsg("We now show how to eliminate left recursion so that we can derive a sentential form with the leftmost terminal before deriving any other terminals.");
av.step();
// Frame 17
av.umsg(Frames.addQuestion("whichleft"));
av.step();
// Frame 18
av.umsg(Frames.addQuestion("nonleft"));
av.step();
// Frame 19
av.umsg(Frames.addQuestion("finish"));
av.step();
// Frame 20
av.umsg(Frames.addQuestion("transform"));
av.step();
// Frame 21
av.umsg(Frames.addQuestion("leftT"));
av.step();
// Frame 22
av.umsg(Frames.addQuestion("nonleftT"));
av.step();
// Frame 23
av.umsg(Frames.addQuestion("endT"));
av.step();
// Frame 24
av.umsg(Frames.addQuestion("newT"));
av.step();
// Frame 25
av.umsg(Frames.addQuestion("lastvar"));
av.step();
// Frame 26
av.umsg(Frames.addQuestion("better"));
av.step();
// Frame 27
av.umsg(Frames.addQuestion("samepower"));
av.step();
// Frame 28
av.umsg("Congratulations! Frameset completed.");
av.recorded();
});
|
import { SNComponent, http, snu, router } from "@socialNetwork";
class TabsComponent extends SNComponent {
constructor(config) {
super(config);
this.data = {
ip: ''
}
}
afterInit() {
let comp = document.querySelector('.nav-pills');
let url = router.getUrl().split('/')[1];
comp.querySelectorAll('.nav-link').forEach(el => {
el.classList.remove('active');
if (el.innerText.toLowerCase() === url)
el.classList.add('active');
})
}
events() {
return {
'click .nav': 'onTabClick',
}
}
onTabClick({ target }) {
if (!target.classList.contains('nav-link')) return;
if (target.classList.contains('active')) return;
router.navigate(`#tabs/${target.innerText.toLowerCase()}`);
}
}
export const tabsComponent = new TabsComponent({
selector: 'app-tabs',
template: `
<ul class="nav nav-pills">
<li class="nav-item padding-nav-item">
<a class="nav-link btn btn-bd-download active" >Users</a>
</li>
<li class="nav-item padding-nav-item">
<a class="nav-link btn btn-bd-download " >Friends</a>
</li>
</ul>
`,
styles: `
.btn-bd-download{
border: 0px solid transparent;
padding: .375rem .75rem;
font-size: 1rem;
line-height: 1.5;
font-weight: 500;
color: #ffffff;
}
.nav-pills .nav-link.active{
color: #6f42c0;
background-color: #ffffff;
}
.padding-nav-item{
padding-right:20px;
}
`
}) |
import React from 'react';
import Next from './Next';
export const Section4Parcours = () => (
<section id="section4" className="section sectionParcours rel">
<div className="chevron abs haut1 larg1" onClick={Next}>
<i className="chevronBas fas fa-chevron-down"></i>
</div>
<div className="bord larg1 haut1 coul0 car6 inv3 abs"></div>
<h2 className="titre bord larg2 haut1 coul1">
Parcours</h2>
<div className="tout flex-v">
<div className="bord sstitre haut1 larg2 coul2 rel raj"><h3 className="experiences abs ">Experiences</h3></div>
<div className="haut flex-h">
<div className="bord sstitre larg1 coul2 rel inv4"><h3 className="experiences abs ">Experiences</h3></div>
<div className="haut-droite flex-v">
<div className="flex-h">
<p className="date">2018‑2019</p>
<p className="info">Conseillère en accessibilité (PFI)
chez Plain-Pied à Namur
</p>
</div>
<div className="flex-h">
<p className="date">2015‑2020</p>
<p className="info">Chef de chœur à la paroisse St Lambert
à Lasne
</p>
</div>
<div className="flex-h">
<p className="date">2010‑2018</p>
<p className="info">Assistante chef de groupe pour la FSE
à La Hulpe (scoutisme)
</p>
</div>
<div className="flex-h">
<p className="date">2008‑2015</p>
<p className="info">Catéchiste pour le secteur de Lasne
</p>
</div>
</div>
</div>
<div className="bas flex-h">
<div className="bas-gauche flex-v">
<div className="flex-h">
<div className="bord sstitre haut1 coul3 rel larg2 raj"><h3 className="formations abs">Formations</h3></div>
</div>
<div className="flex-h">
<p className="info">Webmaster - Front End Developer
chez Interface3 à Bruxelles
</p>
<p className="date">2020‑2021</p>
</div>
<div className="flex-h">
<p className=" info">Certificat d’Aptitude Pédagogique
au Centre de formation pour les secteurs infirmier
et de santé de l‘ACN à Bruxelles
</p>
<p className="date">2006‑2008</p>
</div>
<div className="flex-h">
<p className="info"> Etudes et obtention du titre d’Architecte
à l’institut Supérieur d’Architecture Saint-Luc à Bruxelles
</p>
<p className="date">1991‑1996</p>
</div>
<div className="flex-h">
<p className="info"> Etudes secondaires à la Frankfurt International School
et obtention du Bac International (équivalent CESS)
</p>
<p className="date">1985‑1989</p>
</div>
</div>
<div className="bord sstitre larg1 coul3 rel inv4"><h3 className="formations abs">Formations</h3></div>
<div className="larg1 haut1 inv4"></div>
</div>
</div>
<div className="bord larg1 haut1 coul0 car2 inv3 abs"></div>
</section>
); |
const ServerErrors = require('../../helpers/ServerErrors');
const { YouBike } = require('../../schemas/YouBike');
async function model(args) {
try {
const result = await searchSiteByBikes(args.num);
return Promise.resolve(result);
} catch (err) {
return Promise.reject(err);
}
}
// 根據可借車位數搜尋站場
async function searchSiteByBikes(num) {
try {
const result = await YouBike.findAll({ where: { available_num: num }, raw: true });
return Promise.resolve(result);
} catch (err) {
return Promise.reject(new ServerErrors.MySQLError(err.stack));
}
}
module.exports = model;
|
var start = performance.now();
var clickMade = 0;
function radius() {
var shape = Math.random();
if (shape > 0.5) {
return "50%";
} else {
return "0%";
}
}
function randomColours() {
var allowed = "ABCDEF0123456789", S = "#";
while(S.length < 7){
S += allowed.charAt(Math.floor((Math.random()*16)+1));
}
return S;
}
function yAxis() {
var y = Math.random();
y = (y * 301);
y = Math.floor(y);
y = y + "px";
return(y);
}
function xAxis() {
var x = Math.random();
x = (x * 1000);
x = Math.floor(x);
x = x + "px";
return(x);
}
function delay() {
setTimeout(function(){
var b = Math.random();
b = ((b * 500) + 15);
b = b + "px";
document.getElementById("shape").style.display = "block";
document.getElementById("shape").style.borderRadius = radius();
document.getElementById("shape").style.background = randomColours();
document.getElementById("shape").style.width = b;
document.getElementById("shape").style.height = b;
document.getElementById("shape").style.top = yAxis();
document.getElementById("shape").style.left = xAxis();
start = performance.now(); }, Math.floor(Math.random() * 2000)+100); //timer for the delay.
}
var averageTime = 0;
var bestTimeLog = [];
document.getElementById("shape").onclick = function() {
document.getElementById("shape").style.display = "none";
clickMade +=1;
var finish = performance.now();
var time = (finish - start)/1000;
document.getElementById("yourTime").innerHTML = "Your Time: " + (time).toFixed(4) + "s."; //Add toFixed(4) here as caused issues when tried to add earlier.
bestTimeLog.push(time);
var z = 0;
for (j = 0; j < bestTimeLog.length; j++) {
z += bestTimeLog[j];
}
averageTime = z/bestTimeLog.length;
if (clickMade < 10) {
document.getElementById("average").innerHTML = "Rolling average: " + (averageTime).toFixed(4) + "s";
document.getElementById("best").innerHTML = "Personal Best: " + (bestTimeLog.sort()[0]).toFixed(4) + "s";
delay();
} else {
document.getElementById("congratulations").style.display = "block";
document.getElementById("yourTime").style.display = "none";
document.getElementById("best").style.marginTop = "10px";
document.getElementById("average").style.marginTop = "10px";
document.getElementById("total").innerHTML = "Total time spent: " + (z).toFixed(4) + "s";
document.getElementById("one").style.display = "none";
document.getElementById("two").style.display = "none";
}
};
|
module.exports = {
url:
"mongodb+srv://development:XYem3mEh4nbDTUq@cluster0-fgeyn.mongodb.net/small-chat?retryWrites=true&w=majority",
};
|
const express = require("express");
const app = express();
const port = 3100;
const cors = require("cors");
var corsOptions = {
origin: "http://localhost:3000",
};
app.use(cors(corsOptions));
const fakeResponse = [
{
id: "c9a5c012-6295-48d5-a103-68ca76ff047b",
name: "Intelligent Concrete Computer",
description:
"Omnis veritatis in aliquam aspernatur nulla. Officia quidem qui. Maxime veniam nulla sint qui dolorem qui saepe neque placeat. Magni culpa aut eos molestiae nihil molestias. Quidem consectetur quia quo blanditiis perspiciatis facere dolorem.",
price: "752.00",
brand: "Gusikowski - Ebert",
stock: 44903,
photo: "http://lorempixel.com/640/480/technics",
categories: ["Services"],
},
{
id: "b98fba89-fd2e-493d-81f8-65ce6142bdcc",
name: "Intelligent Fresh Keyboard",
description:
"Et omnis voluptas. Eveniet est nostrum beatae aut dolores qui illo quis. Eveniet libero sint consectetur dolor doloremque cumque quos iste.",
price: "520.00",
brand: "McCullough, Parisian and Waters",
stock: 55349,
photo: "http://lorempixel.com/640/480/sports",
categories: ["Office"],
},
{
id: "bde2ab21-8880-4552-8f3a-e575b0513a1d",
name: "Ergonomic Rubber Chips",
description:
"Esse eum sapiente. Impedit accusantium officiis similique sit veritatis. Quo nam quia sapiente non quas qui.",
price: "149.00",
brand: "Murphy Inc",
stock: 7793,
photo: "http://lorempixel.com/640/480/technics",
categories: ["Tech", "Office"],
},
{
id: "a8946d49-2ed5-4e8d-87ce-8e9900dfdc22",
name: "Gorgeous Steel Chips",
description:
"Eos rem assumenda. Minima aperiam pariatur deleniti mollitia sed. Maiores saepe magnam. Et voluptates omnis corrupti. Eos possimus reiciendis repudiandae ea voluptatum. Omnis corporis similique.",
price: "268.00",
brand: "Fadel, Lemke and Weber",
stock: 98720,
photo: "http://lorempixel.com/640/480/business",
categories: ["Office"],
},
{
id: "747a3b2c-8125-4dca-9c37-9e4b41b8a77a",
name: "Refined Frozen Table",
description:
"Nulla occaecati qui laboriosam reprehenderit veritatis ea eaque. Blanditiis consequuntur enim mollitia reprehenderit est sunt corrupti quibusdam error. Provident minus non labore et alias aut quos rerum.",
price: "526.00",
brand: "Carter and Sons",
stock: 28915,
photo: "http://lorempixel.com/640/480/food",
categories: ["Office"],
},
{
id: "e89d3936-12b7-4deb-a4ff-3c5bb17854ab",
name: "Intelligent Frozen Car",
description:
"Commodi dolorem earum delectus aut enim est. Ut dolor possimus. Ut iste ut sed ut necessitatibus. Magni voluptatem ab accusamus.",
price: "818.00",
brand: "Collins, Johnson and Wolf",
stock: 99626,
photo: "http://lorempixel.com/640/480/technics",
categories: ["Tech", "Office"],
},
{
id: "bda696f5-af7b-4fd0-a93d-cdc3f1df5512",
name: "Rustic Cotton Towels",
description:
"Facilis voluptate eum perferendis voluptatem sequi quo. Saepe amet omnis expedita debitis. Nisi blanditiis nobis qui inventore asperiores distinctio quod tempore. Ut quas eos sit. Sed soluta est explicabo. Architecto at at voluptatem ea sit.",
price: "162.00",
brand: "Reinger - Daniel",
stock: 76502,
photo: "http://lorempixel.com/640/480/food",
categories: ["Tech", "Services"],
},
{
id: "bd75c0df-ae5c-46ca-bf8f-32c021ca7271",
name: "Handmade Soft Bike",
description:
"Veritatis rerum deleniti similique veritatis ab iste repellat. Architecto autem facilis. Est eaque ea minima est architecto. Adipisci et inventore aperiam aliquid ea voluptates. Sunt occaecati doloremque dolorem voluptas eius consequuntur qui laudantium qui.",
price: "56.00",
brand: "Von, Baumbach and Schmidt",
stock: 39600,
photo: "http://lorempixel.com/640/480/technics",
categories: ["Tech", "Office"],
},
{
id: "657dfba9-fc8a-4a5c-8de6-ecf7668e6a95",
name: "Ergonomic Frozen Keyboard",
description:
"Qui recusandae quo at adipisci quo corrupti modi. Cupiditate ipsam laborum nulla possimus quia esse. Quos et magni labore. Ex quibusdam ratione nihil rerum delectus doloribus facilis quis. A aut provident ipsum delectus ad. Nemo esse alias ipsum quidem esse modi blanditiis enim ratione.",
price: "388.00",
brand: "Feil - Friesen",
stock: 55329,
photo: "http://lorempixel.com/640/480/nightlife",
categories: ["Tech", "Services"],
},
{
id: "50dce8f1-4d11-47dc-9715-ec9d52c36f23",
name: "Awesome Wooden Sausages",
description:
"Necessitatibus tempore molestias atque rerum illo minus omnis modi. Dolor et id facilis at veritatis nisi consequatur voluptate eaque. Ipsum itaque voluptatem dignissimos et culpa quia modi ut nisi. Et quidem corrupti eum assumenda. Quam placeat nihil consequatur.",
price: "430.00",
brand: "Reichel - Jerde",
stock: 37040,
photo: "http://lorempixel.com/640/480/cats",
categories: ["Services"],
},
{
id: "7a15536c-49de-4208-a6db-9e1136c270ee",
name: "Tasty Concrete Chips",
description:
"Voluptate expedita amet nostrum porro ad magnam quae itaque. Aut exercitationem ut voluptates. Sed aut architecto enim illo quidem veniam esse voluptatibus nihil. Omnis temporibus et consequuntur est nisi odio impedit harum quo.",
price: "687.00",
brand: "Wilkinson - Kunze",
stock: 66017,
photo: "http://lorempixel.com/640/480/sports",
categories: ["Tech", "Services"],
},
{
id: "f0275d26-a0b6-43a8-b4d4-17cf23b110e2",
name: "Unbranded Metal Hat",
description:
"Perferendis perspiciatis nam fuga dolorem earum enim. Labore nemo delectus laboriosam aut molestiae quia repellendus esse est. Dolor ducimus similique facilis odit possimus. Laborum vitae placeat.",
price: "373.00",
brand: "Kertzmann - Hayes",
stock: 53247,
photo: "http://lorempixel.com/640/480/food",
categories: ["Services"],
},
{
id: "969639c1-371d-48c3-904c-e74b469cca12",
name: "Licensed Wooden Mouse",
description:
"Et est dicta non recusandae aperiam aliquam blanditiis. Nulla corporis id recusandae repellendus sed sit accusantium. Dolore odio provident aliquid neque omnis et ab ipsum. Et et dolores ipsum.",
price: "14.00",
brand: "Barton - Christiansen",
stock: 16282,
photo: "http://lorempixel.com/640/480/transport",
categories: ["Office"],
},
{
id: "4f6f94b5-0dbf-4dda-ab31-0f60e4c8d876",
name: "Practical Steel Bacon",
description:
"Quia corrupti odio expedita velit autem sed ut. Nemo aperiam voluptatem sed explicabo. Quisquam ratione dolor error mollitia rerum voluptates quis earum non. Dignissimos ipsum facilis reprehenderit ipsum placeat quam velit accusamus autem. Tenetur mollitia sint dolor rerum aliquid.",
price: "48.00",
brand: "Rodriguez, Stokes and Morar",
stock: 49835,
photo: "http://lorempixel.com/640/480/food",
categories: ["Office"],
},
{
id: "99587bf4-1a15-4cd5-9b1b-fe50fbc8ad2e",
name: "Unbranded Fresh Sausages",
description:
"Voluptatem ad neque ipsum repellendus accusamus quae autem ut. Maiores esse blanditiis sint eius asperiores qui eaque. Qui omnis repudiandae. Ratione saepe id ratione aut dolore ea dicta. Modi labore perspiciatis illum.",
price: "306.00",
brand: "Streich - Howell",
stock: 76777,
photo: "http://lorempixel.com/640/480/sports",
categories: ["Office"],
},
{
id: "9f0b7c2f-5ab6-4983-868e-d238320a6fc9",
name: "Tasty Frozen Pants",
description:
"Omnis et dolore fugit aliquam laboriosam voluptatibus adipisci sed itaque. Et non quibusdam consequatur laudantium eum ut expedita. Distinctio facere qui odio repudiandae ipsam vel numquam tempore sed. Officia nihil sit eligendi blanditiis.",
price: "398.00",
brand: "Collier, Labadie and Turner",
stock: 79261,
photo: "http://lorempixel.com/640/480/food",
categories: ["Tech", "Services"],
},
{
id: "4a93853b-10df-4c07-b7a3-e7f4b91bf7dc",
name: "Sleek Concrete Bike",
description:
"Recusandae distinctio id rerum. Eius aspernatur maxime est. Architecto officia eum repudiandae tempore laudantium libero perferendis. Et expedita eum dolor impedit enim ut. Laudantium harum numquam voluptatem cum. Eaque ut possimus dolor pariatur ipsa iure.",
price: "255.00",
brand: "Grady - Emmerich",
stock: 76804,
photo: "http://lorempixel.com/640/480/nightlife",
categories: ["Tech", "Services"],
},
{
id: "955920b4-274d-4eb6-b453-53d94bd91556",
name: "Awesome Fresh Mouse",
description:
"Voluptatem non quia. Voluptate laboriosam molestias corrupti labore laudantium. Impedit voluptate reprehenderit. Enim cumque et ea consequatur esse. Cum deleniti atque ipsa eaque iusto ipsa quis ullam. Dolores nobis exercitationem provident enim aliquam explicabo voluptas quia unde.",
price: "973.00",
brand: "Friesen, Terry and Anderson",
stock: 86778,
photo: "http://lorempixel.com/640/480/transport",
categories: ["Tech", "Office"],
},
{
id: "b7032ed8-134f-4338-aca4-91004ae4ed70",
name: "Refined Steel Computer",
description:
"Ut temporibus quo provident. Quia quo nihil optio soluta est quas commodi id fugit. Ut dicta sapiente velit.",
price: "885.00",
brand: "Green, Von and McCullough",
stock: 95531,
photo: "http://lorempixel.com/640/480/technics",
categories: ["Services"],
},
{
id: "8aee374f-ee6d-4d09-8c81-614cbd4c6c30",
name: "Tasty Frozen Shirt",
description:
"Consequatur consequatur non maxime. Quasi vel vitae. Sed sit tempore rerum rerum quia assumenda sapiente.",
price: "170.00",
brand: "DuBuque Inc",
stock: 40536,
photo: "http://lorempixel.com/640/480/cats",
categories: ["Services"],
},
{
id: "5d63bf93-b835-475e-9bbc-493b0c261380",
name: "Ergonomic Concrete Shoes",
description:
"Ipsa commodi voluptas. Et in necessitatibus delectus voluptatibus at error atque. Nesciunt temporibus amet nostrum.",
price: "57.00",
brand: "Lemke - Gaylord",
stock: 31149,
photo: "http://lorempixel.com/640/480/people",
categories: ["Services"],
},
{
id: "205eaa75-b7af-4f6a-9f33-041269c37602",
name: "Small Steel Chips",
description:
"Provident omnis illo doloribus qui voluptatem. In quasi ipsam doloremque perspiciatis qui explicabo nobis doloribus. Explicabo error cupiditate ducimus dolore et omnis dignissimos et dolores.",
price: "344.00",
brand: "Harvey, Kunde and Cummerata",
stock: 36214,
photo: "http://lorempixel.com/640/480/technics",
categories: ["Tech", "Services"],
},
{
id: "cda9e3f8-5943-41f6-90a2-92c8768c9e49",
name: "Handcrafted Wooden Mouse",
description:
"Omnis labore velit. Velit dolores nobis laboriosam. Incidunt ex ducimus placeat. Mollitia alias mollitia eligendi saepe alias perspiciatis. Earum sunt occaecati hic quae quia corporis autem qui.",
price: "709.00",
brand: "Lehner, Metz and Mayert",
stock: 88511,
photo: "http://lorempixel.com/640/480/nature",
categories: ["Office"],
},
{
id: "c6dc8fa6-756d-4221-8508-9af30060423a",
name: "Practical Frozen Towels",
description:
"Dicta corrupti temporibus architecto nihil cumque nostrum. Error voluptas in. Fugiat accusantium enim ut omnis et asperiores beatae. Praesentium id non debitis ut facilis temporibus. Suscipit magni culpa rem.",
price: "180.00",
brand: "Koelpin - Toy",
stock: 60247,
photo: "http://lorempixel.com/640/480/people",
categories: ["Tech", "Services"],
},
{
id: "8274b8fa-7537-407e-9dea-f0e8786cd280",
name: "Generic Frozen Gloves",
description:
"Et omnis quidem velit. Maiores dolore enim vel. Maiores perferendis veritatis. Est quia veniam qui et deleniti molestiae pariatur. Molestias modi adipisci architecto quidem eaque deleniti rerum dolorum voluptatem. Dolor voluptatem voluptas porro iste et.",
price: "83.00",
brand: "Eichmann - Haley",
stock: 3713,
photo: "http://lorempixel.com/640/480/transport",
categories: ["Office"],
},
{
id: "595c5d7b-593e-44bc-93f9-f24f61a10941",
name: "Ergonomic Frozen Cheese",
description:
"Rem consequatur voluptate distinctio ratione earum ut et. Illo quasi quo quas voluptatibus illo fugiat itaque accusamus. Quas aspernatur eligendi sequi voluptate molestiae perspiciatis. Sit repellendus repellendus. Dolore dolor eum quo ipsa ea natus aut animi quae. Et dolorum quia architecto distinctio.",
price: "350.00",
brand: "Cartwright - Wunsch",
stock: 42604,
photo: "http://lorempixel.com/640/480/transport",
categories: ["Tech", "Services"],
},
{
id: "99e3f066-c183-4ef2-bd05-30326de51ae2",
name: "Licensed Concrete Table",
description:
"Blanditiis sapiente quisquam quia voluptatem quod dolores in vero. Aliquid nostrum dolor. Ut velit sed reiciendis possimus. Sit adipisci qui ut blanditiis et qui eos fuga praesentium. Eligendi aut nisi incidunt.",
price: "389.00",
brand: "Yundt LLC",
stock: 97102,
photo: "http://lorempixel.com/640/480/fashion",
categories: ["Tech", "Services"],
},
{
id: "40fc1686-877b-4639-9a81-5fd93f946989",
name: "Gorgeous Plastic Chicken",
description:
"Doloribus beatae fugit ad repudiandae omnis aut. Eos distinctio laboriosam. Eum praesentium dolores et veritatis rem et aut veniam unde.",
price: "909.00",
brand: "Tremblay LLC",
stock: 46592,
photo: "http://lorempixel.com/640/480/city",
categories: ["Services"],
},
{
id: "447836e1-aa9b-4006-b289-8b3ad0d5c83a",
name: "Unbranded Cotton Cheese",
description:
"Commodi officiis autem enim recusandae aut. Praesentium nobis beatae aut officia impedit. Hic reiciendis ad quas. Iste doloremque eum quam modi ratione nihil aperiam et atque.",
price: "816.00",
brand: "Crist - Hirthe",
stock: 72349,
photo: "http://lorempixel.com/640/480/nature",
categories: ["Tech", "Services"],
},
{
id: "ba5ee136-3094-4585-957d-0190f2d132e0",
name: "Refined Soft Bike",
description:
"Blanditiis unde sit. Non omnis quas vero quaerat quia qui cum voluptas. Beatae ut hic. Consequuntur dolore est dolor neque dolor dolorem est qui consequatur. Culpa aspernatur soluta ducimus beatae eum odio. Et ullam illo doloremque nostrum pariatur.",
price: "676.00",
brand: "Konopelski and Sons",
stock: 11562,
photo: "http://lorempixel.com/640/480/people",
categories: ["Office"],
},
{
id: "593fa6a7-e87f-455f-be72-8d4f9a863224",
name: "Licensed Plastic Chips",
description:
"Sit quo deserunt et voluptas ut accusantium perspiciatis sit et. Error soluta qui dolorem possimus atque similique voluptates sed. Quia quo excepturi velit quis aut. Similique consequatur dolores nihil reprehenderit quia. Dolorem totam dolore magnam explicabo numquam. Non nulla quo dolorem ullam et.",
price: "456.00",
brand: "Feil - Dibbert",
stock: 84958,
photo: "http://lorempixel.com/640/480/transport",
categories: ["Tech", "Services"],
},
{
id: "fa948e8d-8006-4111-a34d-47422a7f9184",
name: "Licensed Concrete Ball",
description:
"Aperiam nihil quae repellat repellat est sunt sit perspiciatis odit. Sit facilis illum architecto. Quis dolor sint.",
price: "402.00",
brand: "Walker, Spencer and Johns",
stock: 4361,
photo: "http://lorempixel.com/640/480/cats",
categories: ["Services"],
},
{
id: "acd9dddc-eb28-4e9e-9ae8-ca999c5b5bd5",
name: "Handmade Cotton Tuna",
description:
"Consequuntur perferendis voluptatem sed in repellendus est qui quis quia. Totam quam vitae maiores quidem nesciunt excepturi vitae laborum. Veritatis ut aut eius incidunt dolor provident quia quis est. Ut sit velit aut voluptas aperiam fugiat.",
price: "501.00",
brand: "Purdy - Leffler",
stock: 12576,
photo: "http://lorempixel.com/640/480/transport",
categories: ["Services"],
},
{
id: "a19a51b7-287b-4199-8398-f309511d62b1",
name: "Rustic Fresh Salad",
description:
"Facere reiciendis modi nihil voluptas nesciunt et est magni. Quia autem aut nulla necessitatibus architecto corrupti cupiditate voluptatem. Enim voluptas est.",
price: "412.00",
brand: "Larson, Welch and Feeney",
stock: 98851,
photo: "http://lorempixel.com/640/480/fashion",
categories: ["Tech", "Services"],
},
{
id: "cd7ba5e2-c38b-42e8-9c24-99bc4f6fadd9",
name: "Handmade Cotton Mouse",
description:
"Sunt quas nam suscipit rem. Eos asperiores architecto architecto. Commodi doloremque ipsam saepe omnis ut cum veritatis et perferendis. Perspiciatis ratione nulla id omnis. Accusamus illo doloribus consequatur.",
price: "573.00",
brand: "Hayes - Christiansen",
stock: 29631,
photo: "http://lorempixel.com/640/480/abstract",
categories: ["Tech", "Services"],
},
];
app.get("/", (req, res) => {
res.send(fakeResponse);
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});
|
import React from 'react';
import {Text, StyleSheet, View} from 'react-native';
const ComponentScreen = () =>
{
const name = 'Pedro'
return(
<View>
<Text style={styles.textStyle}>Getting started wit components</Text>
<Text style={styles.subHeaderStyle}>My name is {name}</Text>
</View>
);
}
const styles = StyleSheet.create({
textStyle: {
fontSize: 40
},
subHeaderStyle: {
}
});
export default ComponentScreen; |
export { default } from "./ListAdmin" |
// @flow
import React from 'react';
import styles from './Footer.scss';
import applyClasses from './../../utils/applyClasses';
const footerIconClassNames = applyClasses({
footerIcon: true,
'fa fa-heart-o': true
});
const Footer = () => (
<footer className={styles.footer}>
<p>Gabriel García Seco</p>
<p>
Made with <i className={footerIconClassNames} />, Madrid 2018
</p>
</footer>
);
export default Footer;
|
angular.module('focus.models.companyuser', [
'ngResource'
])
.factory('companyUserModel', [
'$resource',
function($resource) {
return $resource('/api/companyuser/:id', { id : '@Id' }, {});
}
]); |
import React from 'react';
import Tabs from '@material-ui/core/Tabs';
import Tab from '@material-ui/core/Tab';
import Paper from '@material-ui/core/Paper';
class SimpleTabs extends React.Component {
state = {
value: 0,
};
handleChange = (event, value) => {
this.setState({value});
this.props.onChange(value);
};
render() {
return (
<Paper square>
<Tabs
value={this.state.value}
indicatorColor="primary"
style={{color: "#1a73ba", fontSize:'12px', fontFamily: 'sans-serif'}}
onChange={this.handleChange}
>
<Tab label="Trainings"/>
<Tab label="Participants"/>
<Tab label="Trainers"/>
</Tabs>
</Paper>
);
}
}
export default SimpleTabs;
|
/*
* Copyright (c) 2012 Mike Chambers. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, $, brackets, btoa, atob */
define(function (require, exports, module) {
'use strict';
// Brackets modules
var EditorManager = brackets.getModule("editor/EditorManager");
var CommandManager = brackets.getModule("command/CommandManager");
var Menus = brackets.getModule("command/Menus");
var StringUtils = brackets.getModule("utils/StringUtils");
var CONVERT_UPPERCASE = "convert_uppercase";
var CONVERT_LOWERCASE = "convert_lowercase";
var CONVERT_HTML_ENCODE = "convert_html_encode";
var CONVERT_HTML_DECODE = "convert_html_decode";
var CONVERT_DOUBLE_SINGLE = "convert_double_to_single";
var CONVERT_SINGLE_DOUBLE = "convert_single_to_double";
var CONVERT_TOGGLE_QUOTES = "convert_toggle_quotes";
var CONVERT_ENCODE_URI = "convert_encode_uri_component";
var CONVERT_DECODE_URI = "convert_decode_uri_component";
var CONVERT_STRIP_TRAILING_WHITESPACE = "convert_strip_trailing_whitespace";
var CONVERT_TABS_TO_SPACES = "convert_tabs_to_spaces";
var CONVERT_SPACES_TO_TABS = "convert_spaces_to_tabs";
var _getActiveSelection = function () {
return EditorManager.getFocusedEditor().getSelectedText();
};
var _replaceActiveSelection = function (text) {
EditorManager.getFocusedEditor()._codeMirror.replaceSelection(text);
};
var _convertTabsToSpaces = function () {
var s = _getActiveSelection();
console.log("convertTabsToSpaces");
var spaceCount = EditorManager.getFocusedEditor()._codeMirror.getOption("tabSize");
var chars = s.split("");
var len = chars.length;
var spaces;
var out = [];
var char;
var i;
for (i = 0; i < len; i++) {
char = chars[i];
if (char === "\t") {
spaces = 4 - (out.length % spaceCount);
//console.log(spaces);
var k;
for (k = 0; k < spaces; k++) {
out.push(" ");
}
} else {
out.push(char);
}
}
_replaceActiveSelection(out.join(""));
};
var _convertSpacesToTabs = function () {
var s = _getActiveSelection();
_replaceActiveSelection(s.replace(/ {4}/g, "\t"));
};
var _convertSelectionToUpperCase = function () {
var s = _getActiveSelection();
_replaceActiveSelection(s.toUpperCase());
};
var _convertSelectionToLowerCase = function () {
var s = _getActiveSelection();
_replaceActiveSelection(s.toLowerCase());
};
var _encodeHTMLEntities = function () {
var s = _getActiveSelection();
var escaped = $("<div />").text(s).html();
escaped = escaped.replace(/"/g, """).replace(/'/g, "'");
_replaceActiveSelection(escaped);
};
var _decodeHTMLEntities = function () {
var s = _getActiveSelection();
var escaped = $("<div />").html(s).text();
_replaceActiveSelection(escaped);
};
var _convertToEncodeURIComponent = function () {
var s = _getActiveSelection();
_replaceActiveSelection(encodeURIComponent(s));
};
var _convertToDecodeURIComponent = function () {
var s = _getActiveSelection();
_replaceActiveSelection(decodeURIComponent(s));
};
var _doubleQuoteReg = /\"/g;
var _convertToSingleQuotes = function () {
var s = _getActiveSelection();
var out = s.replace(_doubleQuoteReg, "'");
_replaceActiveSelection(out);
};
var _singleQuoteReg = /\'/g;
var _convertToDoubleQuotes = function () {
var s = _getActiveSelection();
var out = s.replace(_singleQuoteReg, "\"");
_replaceActiveSelection(out);
};
var _toggleQuotes = function () {
var s = _getActiveSelection();
var chars = s.split('');
var len = chars.length;
var i;
var char;
for (i = 0; i < len; i++) {
char = chars[i];
if (char === "\"") {
chars[i] = "'";
} else if (char === "'") {
chars[i] = "\"";
}
}
_replaceActiveSelection(chars.join(""));
};
var _base64Encode = function () {
var s = _getActiveSelection();
try {
var encoded = btoa(s);
_replaceActiveSelection(encoded);
} catch (e) {
console.log("StringConvert : Base64 Encoding failed.");
}
};
var _base64Decode = function () {
var s = _getActiveSelection();
try {
var decoded = atob(s);
_replaceActiveSelection(decoded);
} catch (e) {
console.log("StringConvert : Base64 Decoding failed.");
}
};
var _trimRightReg = /\s+$/;
var _cleanTrailingWhitespace = function () {
var s = _getActiveSelection();
var lines = s.split("\n");
var len = lines.length;
var i;
for (i = 0; i < len; i++) {
lines[i] = lines[i].replace(_trimRightReg, "");
}
var output = lines.join("\n");
_replaceActiveSelection(output);
};
var buildMenu = function (m) {
m.addMenuDivider();
m.addMenuItem(CONVERT_UPPERCASE);
m.addMenuItem(CONVERT_LOWERCASE);
m.addMenuDivider();
m.addMenuItem(CONVERT_HTML_ENCODE);
m.addMenuItem(CONVERT_HTML_DECODE);
m.addMenuDivider();
m.addMenuItem(CONVERT_DOUBLE_SINGLE);
m.addMenuItem(CONVERT_SINGLE_DOUBLE);
m.addMenuItem(CONVERT_TOGGLE_QUOTES);
m.addMenuDivider();
m.addMenuItem(CONVERT_ENCODE_URI);
m.addMenuItem(CONVERT_DECODE_URI);
m.addMenuDivider();
m.addMenuItem(CONVERT_STRIP_TRAILING_WHITESPACE);
m.addMenuDivider();
m.addMenuItem(CONVERT_TABS_TO_SPACES);
m.addMenuItem(CONVERT_SPACES_TO_TABS);
};
CommandManager.register("To Upper Case + [Ctrl + Alt + U]", CONVERT_UPPERCASE, _convertSelectionToUpperCase);
CommandManager.register("To Lower Case + [Ctrl + Alt + Shift + L]", CONVERT_LOWERCASE, _convertSelectionToLowerCase);
CommandManager.register("HTML Entity Encode", CONVERT_HTML_ENCODE, _encodeHTMLEntities);
CommandManager.register("HTML Entity Decode", CONVERT_HTML_DECODE, _decodeHTMLEntities);
CommandManager.register("Double to Single Quotes", CONVERT_DOUBLE_SINGLE, _convertToSingleQuotes);
CommandManager.register("Single to Double Quotes", CONVERT_SINGLE_DOUBLE, _convertToDoubleQuotes);
CommandManager.register("Toggle Quotes", CONVERT_TOGGLE_QUOTES, _toggleQuotes);
CommandManager.register("Encode URI Component", CONVERT_ENCODE_URI, _convertToEncodeURIComponent);
CommandManager.register("Decode URI Component", CONVERT_DECODE_URI, _convertToDecodeURIComponent);
CommandManager.register("Strip Trailing Whitespace", CONVERT_STRIP_TRAILING_WHITESPACE, _cleanTrailingWhitespace);
CommandManager.register("Convert Tabs to Spaces", CONVERT_TABS_TO_SPACES, _convertTabsToSpaces);
CommandManager.register("Convert Spaces to Tabs", CONVERT_SPACES_TO_TABS, _convertSpacesToTabs);
var menu = Menus.getMenu(Menus.AppMenuBar.EDIT_MENU);
buildMenu(menu);
var contextMenu = Menus.getContextMenu(Menus.ContextMenuIds.EDITOR_MENU);
buildMenu(contextMenu);
var _KeyPress = function (e) {
var evtobj = window.event ? event : e
if (evtobj.ctrlKey && evtobj.altKey && evtobj.keyCode == 85) _convertSelectionToUpperCase();
if (evtobj.ctrlKey && evtobj.shiftKey && evtobj.keyCode == 76) _convertSelectionToLowerCase();
}
document.onkeydown = _KeyPress;
});
|
const Recommendation = () => {
const currentMonth = new Date().getMonth();
const isSpring = currentMonth >= 2 && currentMonth <= 5
return (isSpring ? (<div>It's spring, repot! 🌱 </div>) : null)
}
export default Recommendation; |
import firebase from 'react-native-firebase';
import { Actions } from 'react-native-router-flux';
export const SET_USER_IN_STATE = 'SET_USER_IN_STATE';
export const USER_AUTH_ERROR = 'USER_AUTH_ERROR';
export const USER_LOGOUT = 'USER_LOGOUT';
// AUTHENTICATION
export function registerUser(email, password) {
return (dispatch, getState) => {
const cred = firebase.auth.EmailAuthProvider.credential(email, password);
const userState = getState().user;
firebase.auth().currentUser.linkAndRetrieveDataWithCredential(cred)
.then(user => {
const dbUserRef = firebase.database().ref('users').child(firebase.auth().currentUser.uid);
const userInState = {
lastUpdate: Date.now(),
favourites: userState.favourites || []
};
dispatch(setUserInState(userInState));
dbUserRef.set(userInState)
.then(() => Actions.popTo('landingPage'))
.catch(error => Actions.WarningPopup({ error }));
})
.catch(error => Actions.WarningPopup({ error }));
};
}
export function loginUser(email, password) {
return dispatch => {
firebase.auth().signInAndRetrieveDataWithEmailAndPassword(email, password)
.then(async user => {
try {
const dbUserRef = firebase.database().ref('users').child(user.user.uid);
const value = await dbUserRef.once('value').then(x => x.val());
// Firebase doesn't support empty arrays so check if the user
// has any favourites or else assign empty array
value.favourites = value.favourites || [];
dispatch(setUserInState(value));
Actions.popTo('landingPage');
} catch (error) {
Actions.WarningPopup({ error });
}
})
.catch(error => {
Actions.WarningPopup({ error });
});
};
}
export function logoutUser() {
return dispatch => {
Actions.popTo('landingPage');
firebase.auth().signOut()
.then(() => {
dispatch(userLogout());
})
.catch(() => undefined);
};
}
export function signInAnonymously() {
return dispatch => {
firebase.auth().signInAnonymouslyAndRetrieveData()
.then(() => {
const userInState = {
favourites: []
};
dispatch(setUserInState(userInState));
})
.catch(error => undefined);
};
}
export function setUserInState(user) {
return {
type: SET_USER_IN_STATE,
user
};
}
export function userLogout() {
return {
type: USER_LOGOUT
};
}
// END AUTHENTICATION
// BUS RELATED
export const ADD_FAVOURITES_TO_STATE = 'ADD_FAVOURITES_TO_STATE';
export const REMOVE_LINE_SUCCESS = 'REMOVE_LINE_SUCCESS';
export function addLineToFavourites(bus) {
return async (dispatch, getState) => {
const { user } = getState();
const favArray = user.favourites || [];
const busFromDB = await firebase.database().ref('buses').child(bus).once('value')
.then(val => val.val());
busFromDB.id = bus;
favArray.push(busFromDB);
user.favourites = favArray;
user.lastUpdate = Date.now();
if (!firebase.auth().currentUser.isAnonymous) {
const userInDb = firebase.database().ref('users').child(firebase.auth().currentUser.uid);
userInDb.child('favourites').set(favArray);
userInDb.child('lastUpdate').set(user.lastUpdate);
}
dispatch(addFavouritesToState(user));
Actions.MessageBox({ message: 'Линията беше добавена в любими!' });
};
}
export function addFavouritesToState(user) {
return {
type: ADD_FAVOURITES_TO_STATE,
user
};
}
export function removeLineFromFavourites(bus) {
return async (dispatch, getState) => {
const { user } = getState();
const dbUserRef = firebase.database().ref('users').child(firebase.auth().currentUser.uid);
let favArray = user.favourites || [];
if (favArray.some(busID => busID.id === bus)) {
favArray = favArray.filter(busID => busID.id !== bus);
}
user.favourites = favArray;
user.lastUpdate = Date.now();
if( !firebase.auth().currentUser.isAnonymous ) {
dbUserRef.child('favourites').set(favArray);
dbUserRef.child('lastUpdate').set(user.lastUpdate);
}
dispatch(removeLineFromState(user));
Actions.MessageBox({ message: 'Линията беше премахната от любими!' });
};
}
export function removeLineFromState(user) {
return {
type: REMOVE_LINE_SUCCESS,
user
};
}
// LINE VOTE
export const VOTE_SUCCESS = 'VOTE_SUCCESS';
const defualtVoteDB = {
totalVotes: 0,
rate: 0,
userIDs: []
};
export function voteLine(busId, rating, comment) {
return async dispatch => {
const dbVoteRef = firebase.database().ref('votes');
let voteRef = await dbVoteRef.child(busId).once('value').then(x => x.val());
if (voteRef === null) {
voteRef = defualtVoteDB;
voteRef.busId = busId;
}
if (voteRef.userIDs.some(x => x.userID === firebase.auth().currentUser.uid)) {
Actions.MessageBox({ message: 'Вече сте оценили тази линия' });
return;
}
// proccess the vote
voteRef.totalVotes += 1;
voteRef.rate = (voteRef.rate + rating) / voteRef.totalVotes;
// create single vote unit
const vote = {
userID: firebase.auth().currentUser.uid,
rate: rating,
comment
};
// add updated vote
voteRef.userIDs.push(vote);
Actions.MessageBox({ message: 'Гласувахте успешно!' });
Actions.pop();
dbVoteRef.child(busId).set(voteRef)
.catch(() => undefined);
dispatch(voteSuccess());
};
}
export function voteSuccess() {
return {
type: VOTE_SUCCESS
};
}
|
module.exports = class Delivery {
constructor(order, adress) {
this.order = order
this.adress = adress
}
}
|
require('dotenv').config()
const AppError = require('../../../../../shared/errors/AppError')
const usersRepository = require('../../repositories/UsersRepository')
const domain = process.env.DOMAIN
class AuthenticateUserService {
constructor() {}
async execute(user, password) {
const foundUser = await usersRepository.searchByUser(user)
if (!foundUser) {
throw new AppError(404, `User or password incorrect!`);
};
const sAMAccountName = foundUser.sAMAccountName.concat(`${domain}`)
const auth = await usersRepository.authenticateUser(sAMAccountName, password);
if (!auth) {
throw new AppError(404, `User or password incorrect!`)
}
return auth
}
}
module.exports = new AuthenticateUserService;
|
import React, { useState, useEffect } from "react";
import { Line } from "react-chartjs-2";
import { connect } from "react-redux";
import styled from "styled-components";
import { getAverages } from "../utils/getAverages";
import { getDataFromDateRange } from "../actions/bwActions";
import { formatDateForInput } from "../utils/formatDateForInput";
import "./TestGraph.css";
const ChartContainer = styled.div`
height: 80%;
`;
const DateInputContainer = styled.div`
display: flex;
justify-content: space-between;
align-items: center;
margin: 1rem auto 0;
max-width: 325px;
`;
const DateLabel = styled.label`
margin-bottom: 0;
`;
const DateInput = styled.input`
border: solid 1px lightgray;
border-radius: 8px;
@media (max-width: 375px) {
width: ;
}
`;
const TestGraph = ({
graphDatesArray,
getDataFromDateRange, // need to destructure for useEffect dependency array
}) => {
const [dateLabels, setDateLabels] = useState([]);
const [amountOfSleepArray, setAmountOfSleepArray] = useState([]);
const [moodAndRestObj, setMoodAndRestObj] = useState({
sleepHours: amountOfSleepArray,
mood: [],
restfulness: [],
});
const [startingDate, setStartingDate] = useState(() => {
const today = new Date();
const sevenDaysAgo = new Date(today.setDate(today.getDate() - 6));
return sevenDaysAgo;
});
const [stringStartingDate, setStringStartingDate] = useState(
formatDateForInput(startingDate)
);
const chartProps = {
data: {
labels: [...dateLabels],
datasets: [
{
data: amountOfSleepArray,
label: "This Week",
moodAndRest: moodAndRestObj,
borderColor: "#3e95cd",
fill: false,
lineTension: 0,
radius: 10,
hoverRadius: 15,
pointHoverBackgroundColor: "yellow",
datalabels: {
textStrokeColor: "black",
textStrokeWidth: 1,
color: "black",
font: {
size: 16,
},
},
},
],
},
options: {
animation: {
duration: 0,
},
responsive: true,
maintainAspectRatio: true,
legend: {
onClick: e => e.stopPropagation(),
display: false,
},
scales: {
yAxes: [
{
ticks: {
suggestedMax: 12,
beginAtZero: true,
},
},
],
xAxes: [
{
ticks: {
min: 9,
},
},
],
},
plugins: {
// Change options for ALL labels of THIS CHART
},
title: {
display: false,
},
tooltips: {
titleFontSize: 10,
bodyFontSize: 16,
bodySpacing: 10,
bodyAlign: "center",
caretPadding: 6,
mode: "nearest",
callbacks: {
// Use the footer callback to display the sum of the items showing in the tooltip
formatter: function(value) {
return `line1\nline2\n${value}`;
// eq. return ['line1', 'line2', value]
},
label: function(tooltipItem, data) {
const thisDataset =
data.datasets[Number(tooltipItem.datasetIndex)];
const WeekLabel = `Hours slept: ${
thisDataset.data[Number(tooltipItem.index)]
}`;
return WeekLabel;
},
afterLabel: function(tooltipItem, data) {
const thisDataset =
data.datasets[Number(tooltipItem.datasetIndex)];
const rest =
thisDataset.moodAndRest.restfulness[
Number(tooltipItem.index)
];
const mood =
thisDataset.moodAndRest.mood[
Number(tooltipItem.index)
];
const stringo = `Tiredness: ${rest} | Mood: ${mood}`;
return stringo;
},
},
footerFontStyle: "normal",
},
},
};
const chartReference = React.createRef();
const handleDateChange = e => {
const newTime = e.target.value;
const timeZoneAdjusted = `${newTime}T00:00-0800`;
setStartingDate(new Date(timeZoneAdjusted));
setStringStartingDate(e.target.value);
};
useEffect(() => {
const getDates = startDate => {
getDataFromDateRange(startDate);
};
getDates(formatDateForInput(startingDate));
}, [startingDate, getDataFromDateRange]);
useEffect(() => {
const sleepArray = graphDatesArray.map(day => day.totalTimeInBed);
setAmountOfSleepArray(sleepArray);
const graphDateLabels = graphDatesArray.map(day => day.date);
setDateLabels(graphDateLabels);
}, [graphDatesArray]);
useEffect(() => {
const moodAndRest = {
sleepHours: amountOfSleepArray,
mood: [],
restfulness: [],
};
moodAndRest.mood = getAverages(graphDatesArray).averageMood;
moodAndRest.restfulness = getAverages(graphDatesArray).averageTiredness;
setMoodAndRestObj(moodAndRest);
}, [graphDatesArray, amountOfSleepArray]);
return (
<>
<ChartContainer className="chartCanvas">
<DateInputContainer>
<DateLabel htmlFor="graphDate">Graph start date:</DateLabel>
<DateInput
id="graphDate"
type="date"
name="startingDate"
value={stringStartingDate}
onChange={e => handleDateChange(e)}
/>
</DateInputContainer>
<div className="actualChart">
<Line
ref={chartReference}
data={chartProps.data}
options={chartProps.options}
/>
</div>
</ChartContainer>
</>
);
};
const mapStateToProps = state => {
return {
user: state.user,
graphDatesArray: state.graphDatesArray,
};
};
export default connect(mapStateToProps, { getDataFromDateRange })(TestGraph);
|
'use strict';
angular.module('controller.order.items', [])
.controller('itemsOrderCtrl', ['$scope', '$state', '$ionicModal', 'itemsFactory',
function ($scope, $state, $ionicModal, itemsFactory) {
$scope.orderitems ={};
// Load the add / change dialog from the given template URL
$ionicModal.fromTemplateUrl('templates/modal/item-order.html', function(modal) {
$scope.addDialog = modal;
}, {
scope: $scope,
animation: 'slide-in-up'
});
$scope.showAddChangeDialog = function(action) {
$scope.action = action;
$scope.addDialog.show();
};
$scope.leaveAddChangeDialog = function() {
// Remove dialog
$scope.addDialog.remove();
// Reload modal template to have cleared form
$ionicModal.fromTemplateUrl('templates/modal/item-order.html', function(modal) {
$scope.addDialog = modal;
}, {
scope: $scope,
animation: 'slide-in-up'
});
};
$scope.insert = function(e) {
$scope.showAddChangeDialog('add');
};
// Get list from storage
$scope.list = itemsFactory.getList();
// Used to cache the empty form for Edit Dialog
$scope.saveEmpty = function(form) {
$scope.form = angular.copy(form);
}
$scope.addItem = function(form) {
var newItem = {};
// Add values from form to object
newItem.item = form.item.$modelValue;
newItem.description = form.description.$modelValue;
// Save new list in scope and factory
$scope.list.push(newItem);
itemsFactory.setList($scope.list);
// Close dialog
$scope.leaveAddChangeDialog();
};
$scope.removeItem = function(item) {
// Search & Destroy item from list
$scope.list.splice($scope.list.indexOf(item), 1);
// Save list in factory
itemsFactory.setList($scope.list);
}
$scope.showEditItem = function(item) {
// Remember edit item to change it later
$scope.tmpEditItem = item;
// Preset form values
$scope.item = item.item;
$scope.description = item.description;
// Open dialog
$scope.showAddChangeDialog('change');
};
$scope.editItem = function(form) {
var item = {};
item.item = form.item.$modelValue;
item.description = form.description.$modelValue;
var editIndex = itemsFactory.getList().indexOf($scope.tmpEditItem);
$scope.list[editIndex] = item;
itemsFactory.setList($scope.list);
$scope.leaveAddChangeDialog();
}
$scope.orderitems.PlacName = itemsFactory.getPlace();
$scope.loadNext = function (state) {
var newPlace = $scope.orderitems.PlacName;
itemsFactory.setPlace(newPlace);
return $state.transitionTo(state);
};
}]); |
const mini = {
// 滚动时触发
onScroll(e) {
// console.log(e.detail.scrollTop);
let scrollTop = e.detail.scrollTop;
if (scrollTop > 200 && !this.data.showBackTop) {
this.setData({
showBackTop: true
});
} else if (scrollTop < 200 && this.data.showBackTop) {
this.setData({
showBackTop: false,
viewId: '',
});
}
},
onBackTop() { // 返回到顶部
this.setData({
viewId: 'scrollTop',
});
},
}
module.exports = mini;
|
import React from 'react';
import './App.css';
import { Header, Container, Table, } from 'semantic-ui-react';
import Cards from "./Cards";
import CardForm from "./CardForm";
class App extends React.Component {
state = {
cards: [
{ id: 1, cardFront: "State", cardBack: "Always an 'object'", showBack: false, },
{ id: 2, cardFront: "Prop", cardBack: "An HTML element passed down from a parent", showBack: false, },
{ id: 3, cardFront: "React", cardBack: "Library for Javascript", showBack: false, },
{ id: 4, cardFront: "Javascript", cardBack: "The language you have been writing in, obviously", showBack: false, },
{ id: 5, cardFront: "Rails", cardBack: "You learned this one already, homie!", showBack: false, },
{ id: 6, cardFront: "Ruby", cardBack: "You learned this one already, homie!", showBack: false, },
], showFront: true,
};
toggleCard = (id) => {
this.setState({
cards: this.state.cards.map( card => {
if (card.id === id){
return { ...card, showBack: !card.showBack}
}
return card
})})
};
removeCard = (id) => {
const cards = this.state.cards.filter( card => {
if (card.id !== id)
return card
});
this.setState({ cards: [...cards], });
};
getId = () => {
return Math.floor((1 + Math.random()) * 10000);
};
addCard = (cardData) => {
let card = { id: this.getId(), ...cardData, };
this.setState({ cards: [card, ...this.state.cards], });
};
render () {
return (
<Container style={{ paddingTop: "25px" }}>
<Header as="h1" textAlign='center'>
Flash Cards
</Header>
<CardForm add={this.addCard} />
<br/>
<Container textAlign='center'>
<Cards cards={this.state.cards} remove={this.removeContact} toggleCard={this.toggleCard} removeCard={this.removeCard} />
</Container>
<br/>
</Container>
);
}
};
export default App;
|
The MIT License (MIT)
Copyright (c) 2014 Ali Gajani (http://www.aligajani.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
$(window).load(function () {
//Infinite Scroll Ajax
$(document).ready(function ($) {
//to get the max page, I suggest to output the result via an API call
var api = "http://localhost:8000" + "/api/v1/collection";
$.getJSON(api, function (json) {
var max_page = json.collection['last_page'];
var count = 2;
var total = max_page;
//when user reaches bottom of the page, make an ajax request
$(window).scroll(function () {
if ($(window).scrollTop() == $(document).height() - $(window).height()) {
if (count > total) {
return false;
} else {
loadFeed(count);
}
count++;
}
});
});
//the ajax request comes here with the page number
function loadFeed(pageNumber) {
//display the ajax loader while things load
$('a#inifiniteLoader').show('fast');
//get the current url
var curURL = window.location.href;
//the actual ajax request happens here
$.ajax({
//these query strings must look familiar by now
url: curURL + "?page=%",
//perform a GET request with the data
type: 'GET',
data: {page: pageNumber},
//when there is an output
success: function (html) {
$('a#inifiniteLoader').hide('1000');
//you need to manipulate the DOM by filtering via class
var items = $(html).find(".ajax_scroll").html();
//don't render if there are no items
render(items);
}
});
return false;
}
//once items are loaded, now render them in HTML
function render(item_html) {
var el = jQuery(item_html);
//this makes the masonry animation happen
$('.ajax_scroll').append(el).masonry('appended', el, true);
}
});
}); |
// 需求: 你要封装一个方法, 我给你一个要读取文件的路径, 你这个方法能帮我读取文件, 并把内容返回给我
const fs = require('fs')
const path = require('path')
function getFileBypath(fpath, succCb, errCb){
// 异步读文件的方法
fs.readFile(fpath, 'utf-8', (err, dataStr)=>{
// 如果报错 后续代码就不用执行了
if(err) return errCb(err)
succCb(dataStr)
})
}
// getFileBypath(path.join(__dirname, './1.txt'), (err, dataStr)=>{
// if (err) return console.log(err)
// console.log(dataStr)
// })
// getFileBypath(path.join(__dirname, './1.txt'), function(data){
// console.log(data)
// }, function(err){
// console.log(err)
// })
// 需求 先读取文件1 再读取文件2 最后读取文件3
getFileBypath(path.join(__dirname, './1.txt'),function(data){
console.log(data)
getFileBypath(path.join(__dirname, './2.txt'),function(data){
console.log(data)
getFileBypath(path.join(__dirname, './3.txt'),function(data){
console.log(data)
})
})
})
// 这种代码叫回调地狱
// 使用 es6的Promise 来解决 回调地狱的问题
// Promise就是单纯的解决回调地狱的问题 并不能帮我们减少代码量
// 使用then这样
|
(function() {
'use strict';
angular
.module('app.products')
.service('ProductService', ProductService);
ProductService.$inject = ['$q', '$http', 'AuthService'];
function ProductService($q, $http, AuthService) {
////////////////
this.get = function () {
var deferred = $q.defer();
$http.get('http://dash-api.elasticbeanstalk.com/products/', AuthService.getHttpOptions())
.success(function (data) {
deferred.resolve(data);
})
.error(function (error, status) {
Error.msg(error, status, "Nao foi possivel carregar produtos");
});
return deferred.promise;
}
}
})(); |
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const mysql = require('mysql')
require('dotenv').config()
const port = process.env.CHIRPER_PORT
const connection = mysql.createConnection({
host : process.env.CHIRPER_DB_HOST,
user : process.env.CHIRPER_DB_USER,
password : process.env.CHIRPER_DB_PASS,
database : process.env.CHIRPER_DB_NAME
})
app.use(express.static('public'))
app.use(bodyParser.urlencoded({ extended: true }))
app.set('view engine', 'ejs')
app.get('/', (_, response) => {
connection.query('SELECT * FROM chirps;', (error, results) => {
if (error) throw error
response.render('index', { 'chirps' : results })
})
})
app.post('/', (request, response) => {
const content = request.body.content
connection.query(`INSERT INTO chirps SET ?;`, { 'content': content }, (error) => {
if (error) throw error
response.writeHead(302, {
'Location': '/'
});
response.end();
})
})
app.listen(port, () => console.log(`The Chirper server is listening on port ${port}.`)) |
//Constructor
function Chronometer() {
this.intervalId = 0
this.currentTime = 0
}
var minDec = document.getElementById("minDec");
var minUni = document.getElementById("minUni");
var secDec = document.getElementById("secDec");
var secUni = document.getElementById("secUni");
var milDec = document.getElementById("milDec");
var milUni = document.getElementById("milUni");
var centesimas = 0;
var segundos = 0;
var minutos = 0;
Chronometer.prototype.startClick = function () {
this.intervalId = setInterval(() => {
this.setMilliseconds()
this.setSeconds()
this.setMinutes()
}, 10)
};
Chronometer.prototype.setMinutes = function () {
if ((centesimas == 0) && (segundos == 0)) {
minutos++;
if (minutos >= 10) {
var splitM = this.twoDigitsNumber(minutos)
minDec.innerHTML = splitM[0]
minUni.innerHTML = splitM[1]
} else {
minUni.innerHTML = minutos;
}
}
if (minutos == 59) {
minutos = -1;
}
return this.currentTime = minutos
};
Chronometer.prototype.setSeconds = function () {
if (centesimas == 0) {
segundos++;
if (segundos >= 10) {
var splitS = this.twoDigitsNumber(segundos)
secDec.innerHTML = splitS[0]
secUni.innerHTML = splitS[1]
} else {
secDec.innerHTML = "0"
secUni.innerHTML = segundos;
}
}
if (segundos == 59) {
segundos = -1;
}
return this.currentTime = segundos
};
Chronometer.prototype.twoDigitsNumber = function (number) {
var newNumberArray = '' + number < 10 ? "0" + number : "" + number
return newNumberArray
};
Chronometer.prototype.setTime = function () {
};
Chronometer.prototype.setMilliseconds = function () {
if (centesimas < 99) {
centesimas++;
if (centesimas >= 10) {
milDec.style.display = "none"
}
milUni.innerHTML = centesimas;
}
if (centesimas == 99) {
centesimas = -1;
}
return this.currentTime = centesimas
};
Chronometer.prototype.stopClick = function () {
clearInterval(this.intervalId)
};
Chronometer.prototype.resetClick = function () {
milDec.removeAttribute("style");
clearInterval(this.intervalId);
centesimas = 0;
segundos = 0;
minutos = 0;
secDec.innerHTML = "0"
secUni.innerHTML = "0"
milDec.innerHTML = "0"
milUni.innerHTML = "0"
minDec.innerHTML = "0"
minUni.innerHTML = "0"
const ul_list = document.getElementById("splits");
const childs = Array.from(ul_list.childNodes).reverse();
childs.forEach(item => {
ul_list.removeChild(item);
});
};
Chronometer.prototype.splitClick = function (a, b, c, d, e, f) {
var splitOne = `${e}${f}:${c}${d}:${a}${b}`.split(":")
var resultIndexTree = splitOne[2].substring(1, 3).length
if (resultIndexTree == 1) {
resultIndexTree = '0' + splitOne[2].substring(1, 3)
} else {
resultIndexTree = splitOne[2].substring(1, 3)
}
var newString = splitOne[0] + ":" + splitOne[1] + ":" + resultIndexTree;
var node = document.createElement("li");
var mySplit = document.createTextNode(newString);
node.appendChild(mySplit);
document.getElementById("splits").appendChild(node);
};
|
var EnemyGroup = new Class({
"initialize": function(cols, rows, distance, stage) {
this.create(cols, rows, distance);
this.totalEnemys = cols*rows;
this.goto = 'right';
this.stageWidth = 674;
this.enemyWidth = 34;
this.setPosition(cols, rows, distance);
this.speed = 1000 / stage;
/*var that = this;
setTimeout(function()
{
this.move.call(that);
}, 50);*/
this.move();
},
"position": function() {
var rect = this.object.getCoordinates("stage");
return {
"x": rect.left,
"y": rect.top
};
},
"create": function(cols, rows, distance) {
this.object = new Element("div", {
"class": "group"
});
this.object.inject("stage");
for(top=0; rows > top; top++) {
for(left=0; cols > left; left++) {
var enemy = new GameEnemy({
"styles": {
"left": left * distance,
"top": top * distance
},
"id": "enemy-" + left + "-" + top,
"class": "enemy"
}, this.object);
}
}
},
"remove": function()
{
this.totalEnemys--;
},
"checkTotalEnemys" : function()
{
if(this.totalEnemys <= 0) this.destroy();
},
"destroy": function()
{
this.object.destroy();
},
"setPosition": function(cols, rows, distance)
{
var dif = distance - this.enemyWidth;
this.objWidth = cols * distance - dif;
this.objHeight = rows * distance - dif;
this.top = 0;
this.left = this.stageWidth/2 - this.objWidth / 2;
this.object.setStyles(
{
"width": this.objWidth,
"height": this.objHeight,
"left": this.left
});
},
"move": function()
{
this.checkTotalEnemys();
if(this.goto == "right")
{
this.top += 2;
this.left += 10;
}
else
{
this.top += 2;
this.left -= 10;
}
if(this.left <= 0)
{
this.left = 0;
this.goto = "right";
}
if(this.left >= this.stageWidth - this.objWidth - this.enemyWidth)
{
this.left = this.stageWidth - this.objWidth - this.enemyWidth;
this.goto = "left";
}
this.object.setStyles({
"top": this.top,
"left": this.left
});
setTimeout(this.move.bind(this), this.speed);
}
}); |
import React from 'react';
import { mount } from 'enzyme';
import { injectIntl } from '../../lib/index.es.js';
const intlConfig = {
locale: 'en',
formats: {
date: {
leave: {
year: 'numeric',
month: '2-digit',
day: '2-digit',
},
},
},
};
describe('format date', () => {
it('formats date properly', () => {
const Component = ({ intl }) => (
<span>
{intl.formatDate('1990-08-01', {
format: 'leave',
})}
</span>
);
const EnhancedComponent = injectIntl(Component);
const wrapper = mount(<EnhancedComponent intl={intlConfig} />);
expect(wrapper.text()).toEqual('08/01/1990');
});
});
|
/* 🤖 this file was generated by svg-to-ts*/
export const EOSIconsAdmin = {
name: 'admin',
data: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M12 1L3 5v6c0 5.55 3.84 10.74 9 12 5.16-1.26 9-6.45 9-12V5zm0 3.9a3 3 0 11-3 3 3 3 0 013-3zm0 7.9c2 0 6 1.09 6 3.08a7.2 7.2 0 01-12 0c0-1.99 4-3.08 6-3.08z"/></svg>`
};
|
/**
* 服务+现场点单-席位查看
*/
import React, { Component, PureComponent } from "react";
import {
StyleSheet,
Dimensions,
View,
Text,
Image,
ScrollView,
TouchableOpacity,
} from "react-native";
import { connect } from "rn-dva"
import moment from 'moment'
import CommonStyles from '../../../common/Styles'
import Header from '../../../components/Header'
import Content from "../../../components/ContentItem";
const { width, height } = Dimensions.get("window")
const service = require('../../../images/shopOrder/service.png')
function getwidth(val) {
return width * val / 375
}
export default class SeatsNameView extends Component {
renderImages = () => {
let data = this.props.navigation.state.params.images
if (data.length > 9) {
data = data.slice(0, 9)
}
return data.map((item, index) => {
return (
<View key={index} style={[styles.itemImage, { marginTop: 10 }]}>
<Image source={{ uri: item }} style={styles.itemImage} />
</View>
)
})
}
render() {
const { navigation } = this.props
return (
<View style={styles.container}>
<Header
navigation={navigation}
goBack={true}
title='席位名'
/>
<View style={styles.mainView}>
<ScrollView>
{
this.renderImages()
}
</ScrollView>
</View>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
...CommonStyles.containerWithoutPadding,
alignItems: 'center',
backgroundColor: CommonStyles.globalBgColor,
},
mainView: {
width: width,
flex: 1,
paddingHorizontal: 10,
backgroundColor: '#fff'
},
itemImage: {
width: getwidth(355),
height: 178
}
})
|
document.getElementById("carDetailBox").style.width = (document.body.clientWidth - 10) + 'px';
mui.init({
swipeBack:false
});
mui.ready(function(){
$('.rightSpan').width($('#carDetailBox ul').width()-50);
var carData = JSON.parse(localStorage.getItem('car_detail_data'));
// var carData = {VehicleNum:'A123Q5',GPSTime:'2017-06-14 13:12:00',Speed:'0.00',Mileage:'123.0',OilNum:'0.0',DirectStr:'正北',StatusDes:'ACC关',CarStatusStr:'在线停车',HoldName:'烽火台',offsetLon:'109.014802',offsetLat:'29.123131'}
var point = new BMap.Point(carData.offsetLon, carData.offsetLat);
var carDetailMap = new BMap.Map('carDetailMap',{
minZoom: 5,
maxZoom: 25,
});
carDetailMap.centerAndZoom(point,15);
var playIcon = directionToImg(carData);
var Marker = new BMap.Marker(point,{icon:new BMap.Icon(playIcon.img,new BMap.Size(28,28))});
carDetailMap.addOverlay(Marker);
getRightLocation(carData.offsetLat,carData.offsetLon,'Adress');
$('#VehicleNum').html(carData.VehicleNum);
$('#GPSTime').html(carData.GPSTime);
$('#Speed').html(parseFloat(carData.Speed).toFixed(1)+'km/h');
$('#Mileage').html(parseFloat(carData.Mileage).toFixed(1)+'km');
$('#DirectStr').html(carData.DirectStr);
$('#carStatus').html(carData.CarStatusStr);
$('#alarm').html(carData.StatusDes);
$('#carGroup').html(carData.HoldName);
//console.log(carData.AllDayTel);
if(!carData.AllDayTel || carData.AllDayTel == ''){
$('#carTel').parent().hide();
}else{
$('#carTel').html(carData.AllDayTel);
$('#carTel').click(function(){
var phone = Number($(this).text());
plus.device.dial(phone,true);
});
}
if(carData.OilNum>-1){
$('#OilNum').parent().show();
$('#OilNum').html(parseFloat(carData.OilNum).toFixed(1)+'L');
}else{
$('#OilNum').parent().hide();
}
});
//根据方向不同指定不同图标type为状态:正常,离线,报警,可不传
function directionToImg(item) {
var CarStatus=null;
if(item.CarStatusStr.indexOf('报警')>-1 || item.StatusDes.indexOf('报警')>-1){
CarStatus = 'warn';
if(item.Speed == 0){
return {img:"../img/direction/"+ CarStatus + "_00.png",name:""};
}
}else if(item.CarStatusStr.indexOf('在线')>-1){
CarStatus = 'online';
if(item.Speed == 0){
return {img:"../img/direction/"+ CarStatus + "_00.png",name:""};
}
}else if(item.CarStatusStr.indexOf('离线')>-1){
CarStatus = 'offline';
if(item.Speed == 0){
return {img:"../img/direction/"+ CarStatus + "_00.png",name:""};
}
}
// console.log(item.DirectStr);
if(item.DirectStr == '东北'){
return {img:"../img/direction/"+ CarStatus + "_02.png",name:"东北"};
}else if (item.DirectStr == '正东') {
return {img:"../img/direction/"+ CarStatus +"_03.png",name:"正东"};
}else if (item.DirectStr == '东南') {
return {img:"../img/direction/"+ CarStatus +"_04.png",name:"东南"};
}else if (item.DirectStr == '正南') {
return {img:"../img/direction/"+ CarStatus +"_05.png",name:"正南"};
}else if (item.DirectStr == '西南') {
return {img:"../img/direction/"+ CarStatus +"_06.png",name:"西南"};
}else if (item.DirectStr == '正西') {
return {img:"../img/direction/"+ CarStatus +"_07.png",name:"正西"};
}else if (item.DirectStr == '西北') {
return {img:"../img/direction/"+ CarStatus +"_08.png",name:"西北"};
}else if(item.DirectStr == '正北') {
return {img:"../img/direction/"+ CarStatus +"_01.png",name:"正北"};
}else{
return {img:"../img/direction/"+ CarStatus + "_02.png",name:"东北"};
}
} |
import {
errNull,
errNum,
errMail,
isMail,
isNum,
isWeb
} from "../errorValMess";
const validate = values => {
const errors = {};
if (!values.namaYayasan) {
errors.namaYayasan = errNull;
}
if (!values.alamatYayasan) {
errors.alamatYayasan = errNull;
}
if (!values.emailYayasan) {
errors.emailYayasan = errNull;
} else if (!isMail.test(values.emailYayasan)) {
errors.emailYayasan = errMail;
}
if (!values.website) {
errors.website = errNull;
} else if (!isWeb.test(values.website)) {
errors.website = "Format Website Salah";
}
if (!values.noYayasan) {
errors.noYayasan = errNull;
} else if (!values.noYayasan.match(isNum)) {
errors.noYayasan = errNum;
}
if (!values.jenis) {
errors.jenis = errNull;
}
if (!values.pic) {
errors.pic = errNull;
}
if (!values.jabatan) {
errors.jabatan = errNull;
}
if (!values.namaPendaftar) {
errors.namaPendaftar = errNull;
}
if (!values.emailPendaftar) {
errors.emailPendaftar = errNull;
} else if (!isMail.test(values.emailPendaftar)) {
errors.emailPendaftar = errMail;
}
if (!values.noPendaftar) {
errors.noPendaftar = errNull;
} else if (!values.noPendaftar.match(isNum)) {
errors.noPendaftar = errNum;
}
return errors
};
export default validate;
|
import React from 'react';
import './Card.css';
import CardBanner from './CardBanner';
import CardContent from './CardContent';
// import ClickEvent from './ClickEvent';
function clickEvent(){
window.location.href = 'https://www.reactjs.org';
}
const Container = props => {
return <main className='main' onClick={clickEvent}>
<CardBanner />
<CardContent />
</main>;
};
export default Container; |
import expect from '../expect'
import { List } from 'immutable'
test('<ImmutableIndexed> to have items [exhaustively] satisfying <any>, passing', () =>
expect(
() =>
expect(
List([1, 2, 3]),
'to have items satisfying',
expect.it('to be a number')
),
'not to error'
))
test('<ImmutableIndexed> to have items [exhaustively] satisfying <any>, diff', () =>
expect(
() =>
expect(
List([1, 2, 'text']),
'to have items satisfying',
expect.it('to be a number')
),
'to error',
"expected List [ 1, 2, 'text' ] to have items satisfying expect.it('to be a number')\n\n" +
'[\n' +
' 1,\n' +
' 2,\n' +
" 'text' // should be a number\n" +
']'
))
test('<ImmutableIndexed> to have items [exhaustively] satisfying <assertion>, passing', () =>
expect(
() => expect(List([1, 2, 3]), 'to have items satisfying', 'to be a number'),
'not to error'
))
test('<ImmutableIndexed> to have items [exhaustively] satisfying <assertion>, diff', () =>
expect(
() =>
expect(
List([1, 2, 'text']),
'to have items satisfying',
'to be a number'
),
'to error',
"expected List [ 1, 2, 'text' ] to have items satisfying to be a number\n\n" +
'[\n' +
' 1,\n' +
' 2,\n' +
" 'text' // should be a number\n" +
']'
))
|
'use strict';
const algolia = require('algoliasearch');
const clc = require('cli-color');
const utils = require('./utils');
module.exports = exports = function algoliaIntegration(schema,opts) {
let options = {
indexName: null,
appId: null,
apiKey: null,
selector: null,
defaults: null,
mappings: null,
inflator: null,
filter: null,
filterIgnore: null,
populate: null,
dependency: null,
modelProvider: null,
debug: false
}
for(let key in opts) {
if(key in options) options[key] = opts[key]; //Override default options
}
if(!options.indexName) return console.error(clc.cyanBright('[Algolia-sync]'),' -> ',clc.red.bold('Error'),' -> Invalid index name');
if(!options.appId || !options.apiKey) return console.error(clc.cyanBright('[Algolia-sync]'),' -> ',clc.red.bold('Error'),' -> Invalid algolia identification');
const client = algolia(options.appId,options.apiKey);
var syncronizer = require('./synchronizer')(options,client);
require('./operations').call(schema,options,client,syncronizer);
if (!options.dependency) {
schema.statics.SyncToAlgolia = function(){
return require('./synchronize').call(this,options,client);
}
schema.statics.SyncDocuments = function(items){
if (!items) {
return;
}
items.forEach(function (item) {
item.wasModified = true;
let indices = utils.GetIndexName(item, options.indexName);
if(indices instanceof Array) {
indices.forEach(index => syncronizer.SyncItem(item, client.initIndex(index)));
}else{
syncronizer.SyncItem(item, client.initIndex(indices));
}
});
}
schema.statics.SetAlgoliaSettings = function(settings){
if(!settings) return console.error(clc.cyanBright('[Algolia-sync]'),' -> ',clc.red.bold('Error'),' -> Invalid settings');
return require('./settings').call(this,settings,options,client);
}
}
}
|
var in30Minutes = 1/48;
// cookies part, with "js-cookie" (https://github.com/js-cookie/js-cookie)
var RGPD_warning_has_been_done = Cookies.get('RGPD_warning'); // RGPD_warning unset means this is the first visit
var RGPD_choice_has_been_done = Cookies.get('RGPD_no_cookie');
if (! window.document.jsdom_reader) {
if (! RGPD_warning_has_been_done) {
Cookies.set('RGPD_warning', '1', { expires: 365 });
$("#RGPD_warning").css({'display' : 'block'});
$("#modal_video").modal("show");
} else {
if ((! RGPD_choice_has_been_done) || ((RGPD_choice_has_been_done != 1) && (RGPD_choice_has_been_done != -1))) {
$("#RGPD_warning").css({'display' : 'block'});
} else {
$("#RGPD_warning").css({'display' : 'None'});
};
};
};
$("#no_cookie").click(function(){
$("#RGPD_warning").css({'display' : 'None'});
Cookies.set('RGPD_no_cookie', '1', { expires: 365 });
});
$("#cookie_please").click(function(){
$("#RGPD_warning").css({'display' : 'None'});
Cookies.set('RGPD_no_cookie', '-1', { expires: 365 });
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-140166656-1');
});
function put_all_digits_into_sub(the_string) {
// sub = <sub>12</sub>, for indices
// put_all_digits_into_sub("C43H4O2") -> "C<sub>43</sub>H<sub>4</sub>O<sub>2</sub>"
return String(the_string).replace(
new RegExp("[0-9]+", "gi"),
"<sub>$&</sub>");
};
// https://stackoverflow.com/questions/990904/remove-accents-diacritics-in-a-string-in-javascript
// but we want to match the accented characters with an unaccented character : e -> [éeèëê], so : resine -> r[éeèëê]s[iïî]n[éeèëê]
function get_all_accents_in_a_regexp(the_string) {
var the_lowered_string = the_string.toLowerCase();
var the_string_with_accented_regexp = "";
for (var i = 0; i < the_lowered_string.length; i++) {
var the_char = the_lowered_string.charAt(i);
switch(the_char) {
case "a":
case "à":
case "â":
case "ä":
the_string_with_accented_regexp = the_string_with_accented_regexp + "[aàâä]";
break;
case "e":
case "é":
case "è":
case "ë":
case "ê":
the_string_with_accented_regexp = the_string_with_accented_regexp + "[eéèëê]";
break;
case "i":
case "î":
case "ï":
the_string_with_accented_regexp = the_string_with_accented_regexp + "[iîï]";
break;
case "o":
case "ô":
case "ö":
the_string_with_accented_regexp = the_string_with_accented_regexp + "[oôö]";
break;
case "u":
case "ù":
case "ü":
case "û":
the_string_with_accented_regexp = the_string_with_accented_regexp + "[uùüû]";
break;
case "y":
case "ÿ":
the_string_with_accented_regexp = the_string_with_accented_regexp + "[yÿ]"; // l'Haÿ-les-Roses
break;
default:
the_string_with_accented_regexp = the_string_with_accented_regexp + the_char;
};
};
return the_string_with_accented_regexp;
};
/*
* jQuery UI Autocomplete HTML Extension
*
* Copyright 2010, Scott González (http://scottgonzalez.com)
* Dual licensed under the MIT or GPL Version 2 licenses.
*
* http://github.com/scottgonzalez/jquery-ui-extensions
*/
(function( $ ) {
var proto = $.ui.autocomplete.prototype,
initSource = proto._initSource;
function filter( array, term ) {
var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
return $.grep( array, function(value) {
return matcher.test( $( "<div>" ).html( value.label || value.value || value ).text() );
});
}
$.extend( proto, {
_initSource: function() {
if ( this.options.html && $.isArray(this.options.source) ) {
this.source = function( request, response ) {
response( filter( this.options.source, request.term ) );
};
} else {
initSource.call( this );
}
},
_renderItem: function( ul, item) {
var newText = "<span class='nom_de_l_ingredient'>" + String(item.label.sci_name).replace(
new RegExp(get_all_accents_in_a_regexp(this.term), "gi"),
"<span class='ui-state-highlight'>$&</span>") + "</span>";
if (item.label["from_csv AutresNoms"]) {
newText = newText + "<br /><span class='synonymes'>(" + String(item.label["from_csv AutresNoms"]).replace(
new RegExp(get_all_accents_in_a_regexp(this.term), "gi"),
"<span class='ui-state-highlight'>$&</span>") + ")</span>";
};
if (item.label["from_csv Botanique"]) {
newText = newText + "<br /><span class='synonymes'>(" + String(item.label["from_csv Botanique"]).replace(
new RegExp(get_all_accents_in_a_regexp(this.term), "gi"),
"<span class='ui-state-highlight'>$&</span>") + ")</span>";
};
if (item.label["from_csv NCas"]) {
newText = newText + "<br /><span class='numero_cas'>N° CAS : " + String(item.label["from_csv NCas"]).replace(
new RegExp(get_all_accents_in_a_regexp(this.term), "gi"),
"<span class='ui-state-highlight'>$&</span>") + "</span>";
};
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( $( "<p></p>" )[ this.options.html ? "html" : "text" ]( newText ) )
.appendTo( ul );
}
});
})( jQuery );
/* end of jQuery UI Autocomplete HTML Extension */
/* Définissions de la map*/
var map = L.map('map', {zoomControl: true, attributionControl: false});
/* Dire que la map est disponible dans le cache du serveur à l'adresse suivante */
var tolUrl= '/hot/{z}/{x}/{y}.png';
/* Zoom initial = zoom 5 décalé de 2 sur la gauche et 0 sur la droite*/
the_width_of_the_window = $(window).width();
if (the_width_of_the_window <= 800) {
zoom_initial = 3;
} else if ((the_width_of_the_window > 800) && (the_width_of_the_window <= 1300)) {
zoom_initial = 4;
} else {
zoom_initial = 5;
};
/* Definir les niveau de zoom minimum et maximum*/
var tol = new L.TileLayer(tolUrl, {minZoom: zoom_initial, maxZoom: 13});
// get the parameters of the previous map
var the_previous_map__zoom = Cookies.get('the_previous_map__zoom');
var the_previous_map__latitude = Cookies.get('the_previous_map__latitude');
var the_previous_map__longitude = Cookies.get('the_previous_map__longitude');
/* Définir la taille de la carte */
map.addLayer(tol);
map.setView([the_previous_map__latitude || 2, the_previous_map__longitude || 0, ], the_previous_map__zoom || zoom_initial);
/* Définission de l'icone qui pointe les MP recherchées*/
var mark = L.icon({
iconUrl: '../img/mark.png',
iconSize: [75, 25], // size of the icon
iconAnchor: [35, 13], // point of the icon which will correspond to marker's location
});
/////////////////////////////
/////CREATION DES POP-UP/////
/////////////////////////////
function is_an_ingredient(the_object) {
return (the_object['ingredient'] == 'yes');
};
//We create here the function that will build popups (modals).
function CreatePopUps() {
//Si aucune pop-up ouverte, efface le pointeur si il est présent
map.removeLayer(markers);
//
markers = new L.FeatureGroup();
//
z = map.getZoom() + 6;
//
bb = map.getBounds();
//Definitions des coordonnées géographiques
var lon1 = bb._southWest.lng;
var lon2 = bb._northEast.lng;
var lat1 = bb._southWest.lat;
var lat2 = bb._northEast.lat;
//Utilisation des données géographiques dans l'URL de requête Solr
var URL2 = "/select/?q=*:*&fq=zoom:[0 TO " + z + "]&fq=lat:[" + lat1 + " TO " + lat2 + "]&fq=lon:[" + lon1 + " TO " + lon2 + "]&wt=json&rows=1000";
//
$.ajax({
//
url : URL2,
success : function(data) {
var ok = data.response.docs;
$.each(ok, function( index, value ) {
var latlong = new L.LatLng(ok[index].lat[0], ok[index].lon[0]);
//positionnement de l'icone pointeur, n'est pas utilisé en réalité.
var marker = L.marker(latlong,{icon: mark});
// non-ingredient -> basic modal
if ( ! is_an_ingredient(ok[index]) ) {
marker.on("click", function() {
markofun(ok[index]);
});
} else { // else : ingredient -> link to a new html page
marker.on("click", function() {
var the_map_center = map.getCenter();
var rounded_latitude = Math.round(the_map_center.lat * 100000) / 100000;
var rounded_longitude = Math.round(the_map_center.lng * 100000) / 100000;
var the_map_zoom = map.getZoom();
Cookies.set('the_previous_map__zoom', the_map_zoom, { expires: in30Minutes });
Cookies.set('the_previous_map__latitude', rounded_latitude, { expires: in30Minutes });
Cookies.set('the_previous_map__longitude', rounded_longitude, { expires: in30Minutes });
window.location.href = "../ingredients/" + ok[index]['sci_name'].replace( new RegExp("\\s", "gi"), "_") + ".html";
});
};
markers.addLayer(marker);
});
},
dataType : 'jsonp',
jsonp : 'json.wrf'
});
markers.addTo(map);
};
//definitions de 2 nouvelles variables
var searchMarker = new L.FeatureGroup();
var markers = new L.FeatureGroup();
//pop-ups des boutons du HTML
$(".my-search-bar").on("input", function(){
if ((! this.value) || (this.value == "")) {
if (SPfocus) {
map.removeLayer(SPfocus);
};
}
});
$(".my-search-bar").focus(function() {
$(this).autocomplete('search', $(this).val())
});
/*$(".logomenu").click(function() {
$(".modalmenu").modal("toggle");
});*/
$("#ListeMP").click(function() {
$("#listeMP").modal("show");
});
$("#Listefamilles").click(function() {
$("#listefamilles").modal("show");
});
/*$("#modal_video").click(function() {
$("#vidéo").modal("show");
});
$("#credit").click(function() {
$("#Crédits").modal("toggle");
});
$("#contact").click(function() {
$("#Contacts").modal("toggle");
});
$("#confidentialite").click(function() {
$("#Confidentialite").modal("toggle");
});
$("#source").click(function() {
$("#Source").modal("toggle");
});*/
//pop-up
map.on("moveend", function() {
CreatePopUps();
});
// définition du pointeur valable, celui jaune de google maps
var SPfocus;
var pin1 = L.icon({
iconUrl: '../img/pin1.png',
iconSize: [18, 25], // size of the icon
iconAnchor: [9, 30], // point of the icon which will correspond to marker's location
});
//This little code fixes the width of the suggestions
jQuery.ui.autocomplete.prototype._resizeMenu = function () {
var ul = this.menu.element;
ul.outerWidth(this.element.outerWidth());
}
////////////////////////////////////////
///////FONCTION RECHERCHE///////////////
////////////////////////////////////////
$(function() {
var str;
//définitions des URL de la requete de solr//
var URL_PREFIX_SUGGESTER = "/suggesthandler/?suggest.dictionary=mySuggester&suggest.cfq=yes&suggest.q=";
var URL_PREFIX_SELECTER = "/select/?q=id%3A";
var URL_SUFFIX = "&wt=json";
$(".my-search-bar").autocomplete({
source : function(request, response) {
//envoi de la requête à searchinput, la classe HTML définie dans l'index.html
let the_value_from_the_search_input = this.element.val();
var URL_SUGGESTER = URL_PREFIX_SUGGESTER + the_value_from_the_search_input + URL_SUFFIX;
console.log(URL_SUGGESTER);
$.ajax({
url : URL_SUGGESTER,
success : function(data) {
var step1 = data.suggest.mySuggester[the_value_from_the_search_input.toString()];
if (! step1.suggestions) {
return;
};
var docs = JSON.stringify(step1.suggestions);
var jsonData = JSON.parse(docs);
jsonData.sort(function(a,b) {
a1 = a.term[0].replace(/<b>/g,"").replace(/<\/b>/g,"");
b1 = b.term[0].replace(/<b>/g,"").replace(/<\/b>/g,"");
return(a1.length-b1.length);
});
var ids_as_an_array = [];
$.map(jsonData, function(value, key) {
object_id = value.payload;
ids_as_an_array.push(object_id);
});
if (! ids_as_an_array.length) { // no id no ajax request (otherwise : error in the javascript script)
response();
return;
};
ids_as_a_string = ids_as_an_array.join("%20");
var URL_SELECTER = URL_PREFIX_SELECTER + "(" + ids_as_a_string + ")" + URL_SUFFIX;
console.log(URL_SELECTER);
$.ajax({
url : URL_SELECTER,
success : function(data_from_selecter) {
var the_infos_from_the_selecter = data_from_selecter.response.docs;
response($.map(the_infos_from_the_selecter, function(value, key) {
var sci_name = value.sci_name;
var NCas = value["from_csv NCas"];
return {
label : value,
value : sci_name + " " + NCas
};
}));
},
error : function() {
response();
},
dataType : 'jsonp',
jsonp : 'json.wrf'
});
},
dataType : 'jsonp',
jsonp : 'json.wrf'
});
},
minLength : '1',
autoFocus: true,
html: true,
focus: function() {
// prevent value inserted on focus
return false;
},
select: function(e, ui) {
$(".my-search-bar").blur();
var URL = URL_PREFIX_SELECTER + "\"" + ui.item.label.id + "\"" + URL_SUFFIX;
console.log(URL);
$.ajax({
url : URL,
success : function(data) {
var docs = JSON.stringify(data.response.docs);
var jsonData = JSON.parse(docs);
//C'est ici qu'est géré le niveau d'apparition des zooms. Problème pour zoomviews < 5 car apparaissent trop loin
if (true) {
jsonData[0].zoom < 5
} else {
jsonData[0].zoom = 5
}
map.setView(jsonData[0].coordinates, jsonData[0].zoom);
// virer les marqueurs précédents et réinitier la variable en la redéfinissant
searchMarker.remove();
searchMarker = new L.FeatureGroup();
SPfocus = L.marker(jsonData[0].coordinates, {icon: pin1}).addTo(searchMarker);
SPfocus.on("click", function() {
markofun(jsonData[0]);
});
searchMarker.addTo(map);
},
dataType : 'jsonp',
jsonp : 'json.wrf'
});
}
})
});
////////////////////////////////
/////////////VIDEO//////////////
////////////////////////////////
$(document).ready(function() {
$("#modal_video").on('shown.bs.modal', function(){
$("#video").attr('src', 'https://youtube.com/embed/7IpLYzM72ms');
})
// stop playing the youtube video when I close the modal
$('#modal_video').on('hide.bs.modal', function (e) {
// a poor man's stop video
$("#video").attr('src','');
})
});
function markofun(the_node_as_json, show_the_modal = true) {
//convert \n to <br /> = convert 'json end of line' to 'html end of line'
//var the_node_as_json_2 = {};
//$.each(the_node_as_json, function(the_key, the_value) {
// if ((the_value) && (the_value.replace)) {
// the_node_as_json_2[the_key] = the_value.replace(/\n/g,"<br />");
// };
//});
// the_node_as_json = the_node_as_json_2;
//communs
var the_use = the_node_as_json['from_csv Utilisation'];
var the_type = the_node_as_json['from_csv Type'];
var the_title = the_node_as_json['from_csv Nom'];
var the_aspect = the_node_as_json['from_csv Aspect'];
var the_allergenes = the_node_as_json['from_csv Allergenes'];
var the_tenue = the_node_as_json['from_csv Tenue'];
var the_ifra = the_node_as_json['from_csv IFRA'];
var the_autresd = the_node_as_json['from_csv Autres_Descripteurs'];
var the_price = the_node_as_json['from_csv Prix'];
var the_filiation = the_node_as_json['from_csv Filiation'];
var the_remarques = the_node_as_json['from_csv autresremarques'];
var the_parole = the_node_as_json['from_csv paroledeparfumeur'];
var the_stab = the_node_as_json['from_csv Stabilite'];
var the_utilisation = the_node_as_json['from_csv Utilisation'];
var the_cas = the_node_as_json['from_csv NCas'];
//Naturelles
var the_nbota = the_node_as_json['from_csv Botanique'];
var the_bota = the_node_as_json['from_csv Nom Botanique'];
var the_methode = the_node_as_json['from_csv Extractions'];
var the_origine = the_node_as_json['from_csv Origine geographique'];
var the_componat = the_node_as_json['from_csv composantsmajoritaires'];
var the_pemblem = the_node_as_json['from_csv parfumemblematiques'];
var the_chemotype = the_node_as_json['from_csv chemotype'];
var the_medecine = the_node_as_json['from_csv medecine'];
//Synthétiques
var the_densite = the_node_as_json['from_csv Densite'];
var the_logp = the_node_as_json['from_csv LogP'];
var the_fp = the_node_as_json['from_csv FlashPoint'];
var the_bp = the_node_as_json['from_csv BoilingPoint'];
var the_decouverte = the_node_as_json['from_csv Decouverte'];
var the_synthese = the_node_as_json['from_csv Synthese'];
var the_precurseur = the_node_as_json['from_csv Precurseurs'];
var the_isomerie = the_node_as_json['from_csv Isomerie'];
var the_presencenat = the_node_as_json['from_csv Presencenat'];
var the_molaire = the_node_as_json['from_csv mmolaire'];
var the_fbrute = put_all_digits_into_sub(the_node_as_json['from_csv formulebrute']);
//IFRA
var the_amendment = the_node_as_json['from_csv Amendment'];
var the_cat1 = the_node_as_json['from_csv Category 1'];
var the_cat2 = the_node_as_json['from_csv Category 2'];
var the_cat3 = the_node_as_json['from_csv Category 3'];
var the_cat4 = the_node_as_json['from_csv Category 4'];
var the_cat5 = the_node_as_json['from_csv Category 5'];
var the_cat6 = the_node_as_json['from_csv Category 6'];
var the_cat7 = the_node_as_json['from_csv Category 7'];
var the_cat8 = the_node_as_json['from_csv Category 8'];
var the_cat9 = the_node_as_json['from_csv Category 9'];
var the_cat10 = the_node_as_json['from_csv Category 10'];
var the_cat11 = the_node_as_json['from_csv Category 11'];
var the_commentifra = the_node_as_json['from_csv Commentaires'];
var the_leaveon = the_node_as_json['from_csv Leave on products'];
var the_fcream = the_node_as_json['from_csv Fragrancing cream'];
var the_finef = the_node_as_json['from_csv Fine Fragrance'];
var the_edt = the_node_as_json['from_csv Eau de Toilette'];
var the_fcream = the_node_as_json['from_csv Fragrancing cream'];
var the_rinseoff = the_node_as_json['from_csv Rinse off'];
var the_otherleaveon = the_node_as_json['from_csv Other leave on'];
var the_noskin = the_node_as_json['from_csv Non-skin, incidental skin contact'];
var the_commentary = the_node_as_json['from_csv Commentaires']
if (the_commentary) { // avoid applying .replace to undefined
the_commentary = the_commentary.replace(/\n/g,"<br />"); //convert \n to <br /> = convert json end of line to html end of line
};
var the_type = the_node_as_json['from_csv Type'];
var the_background_color = the_node_as_json['from_csv Couleur'];
if (! (the_background_color)) {
the_background_color = "#FFFFFF"
};
var is_an_ingredient = (the_node_as_json['ingredient'] == "yes");
var is_an_naturelle = (the_node_as_json['from_csv Type'] == "Naturelle");
var is_an_synthetique = (the_node_as_json['from_csv Type'] == "Synthétique");
var is_an_descripteur = (the_node_as_json['from_csv Type'] == "Descripteur");
var nonIFRA = (the_node_as_json['from_csv IFRA'] == "Ingrédient non réglementé");
var IFRAQRA = (the_node_as_json['from_csv IFRA'] == "Restrictions QRA");
var IFRAnonQRA = (the_node_as_json['from_csv IFRA'] == "Restrictions Non QRA");
var IFRAnonQRAspe = ((the_node_as_json['from_csv IFRA'] == "Restrictions Non QRA") && (the_node_as_json['from_csv Fine Fragrance']));
var IFRAspécification = (the_node_as_json['from_csv IFRA'] == "Spécifications");
var displaytable1 = (false);
var displaytable2 = (false);
var displaytable3 = (false);
var displaylogo = (false);
var displayamendment = (false);
var displaycommentaires = (false);
var displayblockifra1 = (true);
var displayblocktable = (true);
if (IFRAQRA) {
displaytable1 = true;
displayamendment = true;
displaycommentaires = true;
displaylogo = true;
};
if (IFRAnonQRA) {
displaytable2 = true;
displayamendment = true;
displaycommentaires = true;
displaylogo = true;
};
if (IFRAnonQRAspe) {
displaytable2 = false;
displaytable3 = true;
displayamendment = true;
displaycommentaires = true;
displaylogo = true;
};
if (IFRAspécification) {
displaycommentaires = true;
displaylogo = true;
};
if (nonIFRA) {
displayblockifra1 = false;
displayblocktable = false;
};
//EMPTY - partie naturelle
$('#modalheader-type').empty();
$('#modaltitle').empty();
$('#modaltitle-fili').empty();
$('#modalbody-remarques').empty();
$('#modalbody-pict').empty();
$('#modalbody-links').empty();
$('#modalbody-price').empty();
$('#modalbody-nbota').empty();
$('#modalbody-bota').empty();
$('#modalbody-origine').empty();
$('#modalbody-aspect').empty();
$('#modalbody-methode').empty();
$('#modalbody-cas').empty();
$('#modalbody-tenue').empty();
$('#modalbody-autresd').empty();
$('#modalbody-ifra').empty();
$('#modalbody-allergenes').empty();
$('#modalbody-componat').empty();
$('#modalbody-pemblem').empty();
$('#modalbody-parole').empty();
$('#modalbody-chemotype').empty();
$('#modalbody-medecine').empty();
$('#modalbody-stab').empty();
$('#modalbody-utilisation').empty();
//EMPTY - partie synthétique
$('#modalheader-type1').empty();
$('#modaltitle1').empty();
$('#modaltitle1-fili').empty();
$('#modalbody-pict1').empty();
$('#modalbody-remarques1').empty();
$('#modalbody-densite1').empty();
$('#modalbody-price1').empty();
$('#modalbody-ncas1').empty();
$('#modalbody-aspect1').empty();
$('#modalbody-autresd1').empty();
$('#modalbody-ifra1').empty();
$('#modalbody-allergenes1').empty();
$('#modalbody-fp1').empty();
$('#modalbody-logp').empty();
$('#modalbody-tenue1').empty();
$('#modalbody-bp1').empty();
$('#modalbody-decouverte1').empty();
$('#modalbody-synthèse').empty();
$('#modalbody-précurseur').empty();
$('#modalbody-isomérie').empty();
$('#modalbody-présencenat').empty();
$('#modalbody-parole1').empty();
$('#modalbody-utilisation1').empty();
$('#modalbody-mmolaire1').empty();
$('#modalbody-fbrute1').empty();
//EMPTY - Descripteurs
$('#modalheader-type2').empty();
$('#modaltitle2').empty();
$('#modalbody-comment2').empty();
//EMPTY - IFRA
//nat
$('#modalbody-amendment').empty();
$('#modalbody-cat1').empty();
$('#modalbody-cat2').empty();
$('#modalbody-cat3').empty();
$('#modalbody-cat4').empty();
$('#modalbody-cat5').empty();
$('#modalbody-cat6').empty();
$('#modalbody-cat7').empty();
$('#modalbody-cat8').empty();
$('#modalbody-cat9').empty();
$('#modalbody-cat10').empty();
$('#modalbody-cat11').empty();
$('#modalbody-commentifra').empty();
$('#modalbody-leaveon').empty();
//synth
$('#modalbody-amendments').empty();
$('#modalbody-cat1s').empty();
$('#modalbody-cat2s').empty();
$('#modalbody-cat3s').empty();
$('#modalbody-cat4s').empty();
$('#modalbody-cat5s').empty();
$('#modalbody-cat6s').empty();
$('#modalbody-cat7s').empty();
$('#modalbody-cat8s').empty();
$('#modalbody-cat9s').empty();
$('#modalbody-cat10s').empty();
$('#modalbody-cat11s').empty();
$('#modalbody-commentifras').empty();
$('#modalbody-leaveons').empty();
$('#modalbody-finef').empty();
$('#modalbody-edt').empty();
$('#modalbody-fcream').empty();
$('#modalbody-otherleaveon').empty();
$('#modalbody-rinseoff').empty();
$('#modalbody-noskin').empty();
//APPEND - Partie Naturelles
$('#modalheader-type').append(the_type);
$('#modaltitle').append(the_title);
$('#modaltitle-fili').append(the_filiation);
$('#modalbody-nbota').append(the_nbota);
$('#modalbody-bota').append(the_bota);
$('#modalbody-allergenes').append(the_allergenes);
$('#modalbody-autresd').append(the_autresd);
$('#modalbody-tenue').append(the_tenue);
$('#modalbody-cas').append(the_cas);
$('#modalbody-origine').append(the_origine);
$('#modalbody-aspect').append(the_aspect);
$('#modalbody-methode').append(the_methode);
$('#modalbody-remarques').append(the_remarques);
$('#modalbody-ifra').append(the_ifra);
$('#modalbody-price').append(the_price);
$('#modalbody-componat').append(the_componat);
$('#modalbody-pemblem').append(the_pemblem);
$('#modalbody-parole').append(the_parole);
$('#modalbody-chemotype').append(the_chemotype);
$('#modalbody-medecine').append(the_medecine);
$('#modalbody-stab').append(the_stab);
$('#modalbody-utilisation').append(the_utilisation);
//APPEND - Partie Synthétique
$('#modalheader-type1').append(the_type);
$('#modaltitle1').append(the_title);
$('#modaltitle1-fili').append(the_filiation);
$('#modalbody-allergenes1').append(the_allergenes);
$('#modalbody-autresd1').append(the_autresd);
$('#modalbody-tenue1').append(the_tenue);
$('#modalbody-ncas1').append(the_cas);
$('#modalbody-densite1').append(the_densite);
$('#modalbody-logp').append(the_logp);
$('#modalbody-aspect1').append(the_aspect);
$('#modalbody-fp1').append(the_fp);
$('#modalbody-remarques1').append(the_remarques);
$('#modalbody-ifra1').append(the_ifra);
$('#modalbody-price1').append(the_price);
$('#modalbody-bp1').append(the_bp);
$('#modalbody-decouverte1').append(the_decouverte);
$('#modalbody-synthèse').append(the_synthese);
$('#modalbody-précurseur').append(the_precurseur);
$('#modalbody-isomérie').append(the_isomerie);
$('#modalbody-présencenat').append(the_presencenat);
$('#modalbody-parole1').append(the_parole);
$('#modalbody-utilisation1').append(the_utilisation);
$('#modalbody-mmolaire1').append(the_molaire);
$('#modalbody-fbrute1').append(the_fbrute);
//APPEND - Partie Descripteurs
$('#modaltitle2').append(the_title);
$('#modalheader-type2').append(the_type);
$('#modalbody-comment2').append(the_use);
//APPEND - IFRA nat
$('#modalbody-amendment').append(the_amendment);
$('#modalbody-cat1').append(the_cat1);
$('#modalbody-cat2').append(the_cat2);
$('#modalbody-cat3').append(the_cat3);
$('#modalbody-cat4').append(the_cat4);
$('#modalbody-cat5').append(the_cat5);
$('#modalbody-cat6').append(the_cat6);
$('#modalbody-cat7').append(the_cat7);
$('#modalbody-cat8').append(the_cat8);
$('#modalbody-cat9').append(the_cat9);
$('#modalbody-cat10').append(the_cat10);
$('#modalbody-cat11').append(the_cat11);
$('#modalbody-commentifra').append(the_commentifra);
$('#modalbody-leaveon').append(the_leaveon);
//APPEND - IFRA synth
$('#modalbody-amendments').append(the_amendment);
$('#modalbody-cat1s').append(the_cat1);
$('#modalbody-cat2s').append(the_cat2);
$('#modalbody-cat3s').append(the_cat3);
$('#modalbody-cat4s').append(the_cat4);
$('#modalbody-cat5s').append(the_cat5);
$('#modalbody-cat6s').append(the_cat6);
$('#modalbody-cat7s').append(the_cat7);
$('#modalbody-cat8s').append(the_cat8);
$('#modalbody-cat9s').append(the_cat9);
$('#modalbody-cat10s').append(the_cat10);
$('#modalbody-cat11s').append(the_cat11);
$('#modalbody-commentifras').append(the_commentifra);
$('#modalbody-leaveons').append(the_leaveon);
$('#modalbody-finef').append(the_finef);
$('#modalbody-edt').append(the_edt);
$('#modalbody-fcream').append(the_fcream);
$('#modalbody-otherleaveon').append(the_otherleaveon);
$('#modalbody-rinseoff').append(the_rinseoff);
$('#modalbody-noskin').append(the_noskin);
//Apparition des images pour les Naturelles et les Synthétiques
if (is_an_ingredient) {
$('#modalbody-pict').empty();
$('#modalbody-pictA').empty();
$('#modalbody-pict1').empty();
$('#modalbody-pict1A').empty();
$('#modalbody-pict').append("<img class='imgmp' src='../img/matieres_premieres/" + the_title + ".jpg' alt='' />");
$('#modalbody-pictA').append("<img class='imgmp' src='../img/matieres_premieres/" + the_title + ".jpg' alt='' />");
$('#modalbody-pict1').append("<img class='imgmp' src='../img/matieres_premieres/" + the_title + ".PNG' alt='' />");
$('#modalbody-pict1A').append("<img class='imgmp' src='../img/matieres_premieres/" + the_title + ".PNG' alt='' />");
};
if (is_an_naturelle) {
$('#naturelleModal .modal-header').css('background-color', the_background_color);
if (show_the_modal) $('#naturelleModal').modal('show');
};
if (is_an_synthetique) {
$('#SynthetiqueModal .modal-header').css('background-color', the_background_color);
if (show_the_modal) $('#SynthetiqueModal').modal('show');
};
if (is_an_descripteur) {
$('#DescripteurModal .modal-header').css('background-color', the_background_color);
if (show_the_modal) $('#DescripteurModal').modal('show');
};
$('title').html('ScenTree - ' + the_title);
if (displaytable1) {
$(".table1").css('display', 'inline-table');
$(".table1").show();
}
else {
$(".table1").css('display', 'none');
};
if (displaytable2) {
$(".table2").css('display', 'inline-table');
$(".table2").show();
}
else {
$(".table2").css('display', 'none');
};
if (displaytable3) {
$(".table3").css('display', 'inline-table');
$(".table3").show();
}
else {
$(".table3").css('display', 'none');
};
if (displaylogo) {
$(".logoifra").css('display', 'block');
$(".logoifra").show();
}
else {
$(".logoifra").css('display', 'none');
};
if (displayamendment) {
$(".amendment").css('display', 'block');
$(".amendment").show();
}
else {
$(".amendment").css('display', 'none');
};
if (displaycommentaires) {
$(".commentaires").css('display', 'block');
$(".commentaires").show();
}
else {
$(".commentaires").css('display', 'none');
};
if (displayblocktable) {
$(".blocktable").css('display', 'block');
}
else {
$(".blocktable").css('display', 'none');
};
if (displayblockifra1 ) {
$(".blockifra1").css('display', 'block');
}
else {
$(".blockifra1").css('display', 'none');
};
};
$("#SynthetiqueModal").on("hide.bs.modal", function (e) {
$(".table1").hide();
$(".table2").hide();
$(".table3").hide();
$(".logoifra").hide();
$(".amendment").hide();
$(".commentaires").hide();
$('title').html("ScenTree - Classification innovante des ingrédients parfum");
var the_map_center = map.getCenter();
var rounded_latitude = Math.round(the_map_center.lat * 100000) / 100000;
var rounded_longitude = Math.round(the_map_center.lng * 100000) / 100000;
var the_map_zoom = map.getZoom();
Cookies.set('the_previous_map__zoom', the_map_zoom, { expires: in30Minutes });
Cookies.set('the_previous_map__latitude', rounded_latitude, { expires: in30Minutes });
Cookies.set('the_previous_map__longitude', rounded_longitude, { expires: in30Minutes });
window.location.href = "../_/index.html";
});
$("#naturelleModal").on("hide.bs.modal", function (e) {
$(".table1").hide();
$(".table2").hide();
$(".table3").hide();
$(".logoifra").hide();
$(".amendment").hide();
$(".commentaires").hide();
$('title').html("ScenTree - Classification innovante des ingrédients parfum");
var the_map_center = map.getCenter();
var rounded_latitude = Math.round(the_map_center.lat * 100000) / 100000;
var rounded_longitude = Math.round(the_map_center.lng * 100000) / 100000;
var the_map_zoom = map.getZoom();
Cookies.set('the_previous_map__zoom', the_map_zoom, { expires: in30Minutes });
Cookies.set('the_previous_map__latitude', rounded_latitude, { expires: in30Minutes });
Cookies.set('the_previous_map__longitude', rounded_longitude, { expires: in30Minutes });
window.location.href = "../_/index.html";
});
$('#DescripteurModal').on("hidden.bs.modal", function (e) {
$('title').html("ScenTree - Classification innovante des ingrédients parfum");
});
/*suppression du copier-coller*/
function addLink() {
var body_element = document.getElementsByTagName('body')[0];
var selection;
selection = window.getSelection();
var pagelink = " ";
var selectiontxt = selection.toString();
var copytext = selectiontxt.substring(0,0)+pagelink;
var newdiv = document.createElement('div');
newdiv.style.position='absolute';
newdiv.style.left='-99999px';
body_element.appendChild(newdiv);
newdiv.innerHTML = copytext;
selection.selectAllChildren(newdiv);
window.setTimeout(function() {
body_element.removeChild(newdiv);
},0);
}
document.oncopy = addLink;
|
$(document).ready(function(){
$('#ticket-search').bind('keyup', function(e){
if(e.keyCode == 13){ // user hit enter key
window.location = $('#ticket-list tbody tr:visible a:first').attr('href');
}
var needles = $(this).val().toLowerCase().split(/\s+/g)
// for each ticket
for(var i = 0; i < TICKETS.length; i++){
var ticket = TICKETS[i];
// add a property to the ticket so the user can type "#<ticket_id>"
// and jump right to the ticket
ticket.id = "#" + ticket.ticket_id
var elements = $('#t1-' + ticket.ticket_id + ", #t2-" + ticket.ticket_id);
elements.hide();
// keep track of how many needles were found
var found_needles = 0;
// try to find all the needles in this ticket
for(var j = 0; j < needles.length; j++){
var needle = needles[j];
// search all the fields of this ticket for the needle
for(var k in ticket){
var haystack = ticket[k];
if(haystack == null) continue;
// found the needle?
if(haystack.toString().toLowerCase().indexOf(needles[j]) != -1){
found_needles++;
break;
}
}
}
// if we found all the needles, then this ticket matches our search
// term
if(found_needles == needles.length){
elements.show();
}
}
});
})
|
const fs = require('fs');
const chalk = require('chalk');
const yargs = require('yargs');
const notes = require('./notes.js');
// add command for a note - takes a title, and body
yargs.command({
command: 'add',
describe: 'Add a new note',
builder: {
title: {
describe: 'Note title',
demandOption: true,
type: 'string'
},
body: {
describe: 'Note body',
demandOption: true,
type: 'string'
}
},
handler(argv) {
notes.addNote(argv.title, argv.body);
}
}).argv;
// remove command for a note - takes a title
yargs.command({
command: 'remove',
describe: 'Remove a note',
builder: {
title: {
describe: 'Note title to remove',
demandOption: true,
type: 'string'
}
},
handler(argv) {
notes.removeNote(argv.title);
}
}).argv;
// list command for a note
yargs.command({
command: 'list',
describe: 'List a note',
handler() {
notes.listAllNotes();
}
}).argv;
// Find command for a note
yargs.command({
command: 'find',
describe: 'Find a note',
builder: {
title: {
describe: 'Find a note',
demandOption: true,
type: 'string'
}
},
handler(argv) {
notes.findNote(argv.title);
}
}).argv;
|
$(function () {
creatPro('s1', 'Surprise Party', '景点:巴厘岛', 'Surprise Party', ".sea-imgList");
creatPro('s2', '海盐味的夏天', '景点:巴厘岛', '海盐味的夏天', ".sea-imgList");
creatPro('s3', 'R.and MRS', '景点:巴厘岛', 'MR.and MRS', ".sea-imgList");
creatPro('s4', 'My girl', '景点:巴厘岛', 'My girl', ".sea-imgList");
creatPro('s5', '摩登的罗曼蒂', '景点:巴厘岛', '摩登的罗曼蒂', ".sea-imgList");
creatPro('s6', 'After 21', '景点:巴厘岛', 'After 21', ".sea-imgList");
creatPro('s7', '最佳情侣', '景点:巴厘岛', '最佳情侣', ".sea-imgList");
creatPro('s8', '棉花糖与白日梦', '景点:巴厘岛', '棉花糖与白日梦', ".sea-imgList");
creatPro('s9', '海上的伊甸园', '景点:马尔代夫', '海上的伊甸园', ".sea-imgList");
creatPro('s10', '与风吻你', '景点:马尔代夫', '与风吻你', ".sea-imgList");
creatPro('s11', '第六感的甜', '景点:马尔代夫', '第六感的甜', ".sea-imgList");
creatPro('s12', '抛洒人间的项链', '景点:马尔代夫', '抛洒人间的项链', ".sea-imgList");
var $li = $(".sea-imgList li");
$li.hover(function(ev){
move.call(this , ev , true);
$(this).find("span").stop().animate({
top: 0
}, 400)
$(this).find("img").css("opacity", 0.6)
$(this).find("p").stop().animate({
bottom: 10
}, 400)
},function(ev){
move.call(this , ev , false);
$(this).find("span").stop().animate({
top: -259
}, 400)
$(this).find("img").css("opacity", 1)
$(this).find("p").stop().animate({
bottom: -32
}, 400)
});
function creatPro(i, h3text1, itext, h3text2, target) {
var li = $('<li></li>');
var a = $('<a></a>');
var divT1 = $('<div class="t1"></div>');
var img = $('<img src="image/pro'+i+'.jpg" alt="">');
var spanT1 = $('<span></span>');
var h3T1 = $('<h3>' + h3text1 + '</h3>');
var i = $('<i>' + itext + '</i>');
var p = $('<p> CHLOE PRE-WEDDING PHOTOGRAPHY STUDIO<br> HIGH-END CUSTOM WEDDING PHOTOGRAPHY</p>');
var divT2 = $('<div class="t2"></div>');
var h3T2 = $('<h3>' + h3text2 + '</h3>');
var spanT2 = $('<span>Oct 01, 2018</span>');
var h4 = $('<h4>' + itext + '</h4>');
var divCover = $('<div class="cover"></div>');
// var pCover = $('<p>'+ h3text1 +'</p>');
// pCover.appendTo(divCover);
divCover.appendTo(divT1);
h3T1.appendTo(spanT1);
i.appendTo(spanT1);
spanT1.appendTo(divT1);
img.appendTo(divT1);
p.appendTo(divT1);
divT1.appendTo(a);
h3T2.appendTo(divT2);
spanT2.appendTo(divT2);
h4.appendTo(divT2);
divT2.appendTo(a);
a.appendTo(li);
var $ul = $(target);
li.appendTo($ul);
}
function move( ev , bool ){
var top = $(this).offset().top;
var bottom = top + $(this).height();
var left = $(this).offset().left;
var right = left + $(this).width();
var x = ev.pageX,
y = ev.pageY;
var sT = Math.abs(y - top),
sB = Math.abs(y - bottom),
sL = Math.abs(x - left),
sR = Math.abs(x - right);
var a = Math.min( sT , sB , sL , sR );
switch ( a )
{
case sT:
if ( bool )
{
$(this).find('.cover').css({
left : 0,
top : '-487px'
}).stop().animate({
top : 0
},400);
}
else
{
$(this).find('.cover').stop().animate({
top : '-487px'
},400);
}
break;
case sB:
if ( bool )
{
$(this).find('.cover').css({
left : 0,
top : '487px'
}).stop().animate({
top : 0
},400);
}
else
{
$(this).find('.cover').stop().animate({
top : '487px'
},400);
}
break;
case sL:
if ( bool )
{
$(this).find('.cover').css({
top : 0,
left : '-286px'
}).stop().animate({
left : 0
},400);
}
else
{
$(this).find('.cover').stop().animate({
left : '-286px'
},400);
}
break;
case sR:
if ( bool )
{
$(this).find('.cover').css({
top : 0,
left : '286px'
}).stop().animate({
left : 0
},400);
}
else
{
$(this).find('.cover').stop().animate({
left : '286px'
},400);
}
break;
}
};
}) |
import React from 'react'
import _ from 'lodash'
const renderPoints = ({ champions, scores }) => {
return champions.map((champion) => {
const points = _.filter(scores, i => i === champion).length
return (
<div className="scores-row" key={champion}>
<div className="scores-col">
{champion}
</div>
<div className="scores-col">
{points}
</div>
</div>
)
})
}
const renderScores = ({ scores }) => {
return scores.map((score, index) => {
// Wouldn't normally use index as key but on this case we can guarantee there'll be no reorder
return (
<div className="scores-row" key={index}>
<div className="scores-col">
{index + 1}
</div>
<div className="scores-col">
{score}
</div>
</div>
)
})
}
const Scores = ({ champions, scores }) => {
return (
<div className="scores-content">
{/* Title */}
<h5 className="scores-title">
Scores
</h5>
{/* List of scores */}
<div className="scores">
<div className="scores-section">
<h6 className="scores-subtitle">
Champions
</h6>
<div className="scores-row">
<p className="scores-col">
<b>Champion</b>
</p>
<p className="scores-col">
<b>Points</b>
</p>
</div>
{renderPoints({ champions, scores })}
</div>
<div className="scores-section">
<h6 className="scores-subtitle">
Rounds
</h6>
<div className="scores-row">
<p className="scores-col">
<b>Round</b>
</p>
<p className="scores-col">
<b>Winner</b>
</p>
</div>
{renderScores({ scores })}
</div>
</div>
</div>
)
}
export default Scores
|
({
navigateToPage: function (component, event, page) {
let navigate = component.get("v.navigateFlow");
navigate(page);
},
navigateToBank: function (component, event) {
let navigation = component.find('navigation');
let pageReference = {
"type": "standard__webPage",
"attributes": {
"url": "https://pekao24.pl/logowanie"
}
};
navigation.navigate(pageReference);
}
}); |
"use strict";
// A class to assist with storing/firing multiple function calls (with zero or more parameters) within the scope of a particular object.
function Events(){
this.onEventFuncs = new Array();
this.onEventArgs = new Array();
this.onEventObjs = new Array();
}
// For example: This event subscription would fire the equivalent of ... function alert("hello")
// eventObj.addSubscription(alert, ["Hello"], window);
Events.prototype.addSubscription = function(functionReference, functionArgumentsArr, objectRefForEvent){
HIPI.framework.Utilities.ensureTypeFunction(functionReference);
HIPI.framework.Utilities.ensureTypeArray(functionArgumentsArr, true);
HIPI.framework.Utilities.ensureTypeObject(objectRefForEvent, true);
if(!functionArgumentsArr)
functionArgumentsArr = new Array();
this.onEventFuncs.push(functionReference);
this.onEventArgs.push(functionArgumentsArr);
this.onEventObjs.push(objectRefForEvent);
};
Events.prototype.clearEvents = function(){
this.onEventFuncs = new Array();
this.onEventArgs = new Array();
this.onEventObjs = new Array();
};
// If an array is given to the fire() method then they will be concatenated on top (to the right) of whatever functional arguments were provided to the subscription.
Events.prototype.fire = function(additionalArguments){
HIPI.framework.Utilities.ensureTypeArray(additionalArguments, true);
for(var eventCounter = 0; eventCounter < this.onEventFuncs.length; eventCounter++){
var eventFunctionArguments = this.onEventArgs[eventCounter];
if(additionalArguments)
eventFunctionArguments = eventFunctionArguments.concat(additionalArguments);
this.onEventFuncs[eventCounter].apply( this.onEventObjs[eventCounter], eventFunctionArguments);
}
};
|
const tabbtns=document.querySelectorAll(".btn-tab");
const articles= document.querySelectorAll(".article-info");
const info=document.querySelector(".infocont");
info.addEventListener("click", function(e){
const id=e.target.dataset.id;
if(id){
tabbtns.forEach((item) => {
item.classList.remove("active");
e.target.classList.add("active");
});
articles.forEach((item) => {
item.classList.remove("active");
});
const showarticle=document.getElementById(id);
showarticle.classList.add("active");
}
})
console.log(info);
|
app
.config(['owmProvider', function(owmProvider) {
owmProvider
.setApiKey('c96cb65f1ab1c8fbb8a4e8de57ec10b0')
.useMetric()
.setLanguage('fr');
}])
.config(function ($httpProvider) {
$httpProvider.interceptors.push('httpInterceptor');
}); |
function focused() {
const fields = Array.from(document.getElementsByTagName('input'));
for (let field of fields){
field.addEventListener('focus', onFocus);
field.addEventListener('blur', onBlur);
}
function onFocus(ev) {
ev.target.parentNode.classList.add('focused');
}
function onBlur(ev) {
ev.target.parentNode.classList.remove('focused');
}
} |
'use strict';
$(function() {
// ドロワー
$('.drawer').drawer();
// スムーススクロール
$('a[href^="#"]').on('click', function() {
// #js-headerがついた要素の高さを取得
let header = $('#js-header').innerHeight();
// 移動速度を指定(ミリ秒)
let speed = 300;
// hrefで指定されたidを取得
let id = $(this).attr("href");
// idの値が#のみだったらターゲットをhtmlタグにしてトップへ戻るようにする
let target = $("#" == id ? "html" : id);
// ページのトップを基準にターゲットの位置を取得
let position = $(target).offset().top - header;
// ターゲットの位置までspeedの速度で移動
$("html, body").animate(
{
scrollTop: position
},
speed
);
return false;
});
// wow
new WOW().init();
// google form
// contactの送信の挙動
let $form = $('#js-form');
$form.submit(function(e) {
$.ajax({
url: $form.attr('action'),
data: $form.serialize(),
type: "POST",
dataType: "xml",
statusCode: {
0: function() {
//送信に成功したときの処理
$form.slideUp();
$('#js-success').slideDown();
},
200: function() {
//送信に失敗したときの処理
$form.slideUp();
$('#js-error').slideDown();
}
}
});
return false;
});
// formの入力確認
let $submit = $('#js-submit');
// #js-submitのinputまたは#js-formのtextareaが変更された時の処理
$('#js-form input, #js-form textarea').on('change', function() {
// 全ての必須項目が入力されていたら$submitの色が変わる処理
if(
// #js-formのtype="text"があるinputのvalueが空ではない時、且つ、
$('#js-form input[type="text"]').val() !== "" &&
// #js-formのtype="email"があるinputのvalueが空ではない時、且つ、
$('#js-form input[type="email"]').val() !== "" &&
// #js-formのname="entry.1250616051"があるinputがチェックされている時、且つ、
$('#js-form input[name="entry.1250616051"]').prop('checked') === true &&
// #js-formのname="entry.1355243199"があるtextareaのvalueが空ではない時
$('#js-form textarea[name="entry.1355243199"]').val() !== ""
) {
// 全ての必須項目が入力された時
// disabled属性をfalseにする
$submit.prop('disabled', false);
$submit.addClass('-active');
} else {
// 必須項目が入力されていない時
// disabled属性をtrueにする
$submit.prop('disabled', true);
$submit.removeClass('-active');
}
});
});
|
const CosmosClient = require('@azure/cosmos').CosmosClient;
const uuidv4 = require('uuid/v4');
const cosmosConfig =
{
connectionString: process.env.COSMOS_CONNECTIONSTRING,
database : process.env.COSMOS_DATABASE
}
const CaseStatuses =
{
Waitting: "Waitting",
Active: "Active",
ClosedByAgent: "ClosedByAgent",
Closed: "Closed"
}
const client = new CosmosClient(cosmosConfig.connectionString);
async function storeConversationReference(reference) {
await client.database(cosmosConfig.database).container(process.env.COSMOS_CONVREFCONTAINER).items.upsert(reference);
}
async function getAgentConvReference(userId) {
// query to return all children in a family
const querySpec = {
query: "SELECT * FROM root r Where r.user.id = @userId ORDER BY r._ts DESC",
parameters: [
{
name: "@userId",
value: userId
}
]
};
const { resources } = await client.database(cosmosConfig.database).container(process.env.COSMOS_CONVREFCONTAINER).items.query(querySpec, {enableCrossPartitionQuery:true}).fetchAll();
return (resources && resources.length > 0) ? resources[0] : null;
};
async function getUserConvReference(userId, convId) {
// query to return all children in a family
const querySpec = {
query: "SELECT * FROM root r Where r.user.id = @userId AND r.conversation.id = @convId ORDER BY r._ts DESC",
parameters: [
{
name: "@userId",
value: userId
},
{
name: "@convId",
value: convId
}
]
};
const { resources } = await client.database(cosmosConfig.database).container(process.env.COSMOS_CONVREFCONTAINER).items.query(querySpec, {enableCrossPartitionQuery:true}).fetchAll();
return (resources && resources.length > 0) ? resources[0] : null;
};
async function createSupportCase(userId, userConversationId)
{
var supportCase =
{
agentId:"",
userId:userId,
supportCaseId:uuidv4(),
status: CaseStatuses.Waitting,
userConversationId: userConversationId
}
await client.database(cosmosConfig.database).container(process.env.COSMOS_SUPPORTCASESCONTAINER).items.upsert(supportCase);
}
async function assignAgentToSupportCase(userId,agentId)
{
//Cosmos doesn't support changing value for partion key field, and as agentId was selected as partition key, we need to recreate the item
var sc = await getWaittingSupportCase(userId);
await client.database(cosmosConfig.database).container(process.env.COSMOS_SUPPORTCASESCONTAINER).item(sc.id, "").delete();
var supportCase =
{
agentId:agentId,
userId:userId,
supportCaseId:sc.supportCaseId,
status: CaseStatuses.Active,
userConversationId: sc.userConversationId
}
await client.database(cosmosConfig.database).container(process.env.COSMOS_SUPPORTCASESCONTAINER).items.upsert(supportCase);
}
async function changeSupportCaseStatus(sc, status)
{
var supportCase =
{
id: sc.id,
agentId:sc.agentId,
userId:sc.userId,
supportCaseId:sc.supportCaseId,
status: status,
userConversationId: sc.userConversationId
}
await client.database(cosmosConfig.database).container(process.env.COSMOS_SUPPORTCASESCONTAINER).item(sc.id, sc.agentId).replace(supportCase);
}
async function getWaittingSupportCase(userId) {
const querySpec = {
query: "SELECT * FROM root r Where r.userId = @userId AND r.status = 'Waitting' ORDER BY r._ts ASC",
parameters: [
{
name: "@userId",
value: userId
}
]
};
const { resources } = await client.database(cosmosConfig.database).container(process.env.COSMOS_SUPPORTCASESCONTAINER).items.query(querySpec, {enableCrossPartitionQuery:true}).fetchAll();
return (resources && resources.length > 0) ? resources[0] : null;
};
async function getOpenedSupportCaseByAgentId(agentId) {
const querySpec = {
query: "SELECT * FROM root r Where r.agentId = @agentId AND r.status = @status ",
parameters: [
{
name: "@status",
value: CaseStatuses.Active
},
{
name: "@agentId",
value: agentId
}
]
};
const { resources } = await client.database(cosmosConfig.database).container(process.env.COSMOS_SUPPORTCASESCONTAINER).items.query(querySpec, {enableCrossPartitionQuery:true}).fetchAll();
return (resources && resources.length > 0) ? resources[0] : null;
};
async function getSupportCaseByUserConvId(userId,userConvId) {
const querySpec = {
query: "SELECT * FROM root r Where r.userId = @userId AND r.userConversationId = @convId ORDER BY r._ts DESC",
parameters: [
{
name: "@userId",
value: userId
},
{
name: "@convId",
value: userConvId
}
]
};
const { resources } = await client.database(cosmosConfig.database).container(process.env.COSMOS_SUPPORTCASESCONTAINER).items.query(querySpec, {enableCrossPartitionQuery:true}).fetchAll();
return (resources && resources.length > 0) ? resources[0] : null;
};
module.exports = {
storeConversationReference,
getAgentConvReference,
getUserConvReference,
createSupportCase,
getOpenedSupportCaseByAgentId,
getSupportCaseByUserConvId,
assignAgentToSupportCase,
changeSupportCaseStatus,
CaseStatuses
} |
import React, { Component } from 'react';
class InputBar extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<form onSubmit={this.props.handler}>
<input name="task" type="text" />
<input type="submit" value="ADD" />
</form>
</div>
);
}
}
export default InputBar;
|
// pages/homepage/homepage.js
Page({
/**
* 页面的初始数据
*/
data: {
indicatorDots: true,
autoplay: true,
interval: 3000,
duration: 1000,
indicatoColor: 'white',
indicatorActiveColor: '#db4b29',
banners: [],
categories: [
{
name: '抢购新茶',
src: '../../images/homepage/home_newtea.png'
},
{
name: '逛逛商城',
src: '../../images/homepage/home_market.png'
},
{
name: '我要取茶',
src: '../../images/homepage/home_gettea.png'
},
{
name: '品牌溯源',
src: '../../images/homepage/home_brand.png'
},
],
notices: [],
newteaList: [],
newsList: []
},
getBannerInfo: function() {
var that = this
wx.request({
url: 'https://www.teaexs.com/app/advertise/image/query.do',
method: 'POST',
header: {
'content-type': 'application/x-www-form-urlencoded'
},
data: {
pageCode: 'APP_index',
pageZoneCode: 'carouse_figure'
},
success: function (res) {
if (res.data.head.code == 0) {
that.setData({
banners: res.data.body
})
if (that.data.banners.length == 1) {
that.setData({
indicatorDots: false
})
}
} else {
}
},
complete: function() {
wx.hideNavigationBarLoading()
wx.stopPullDownRefresh()
}
})
},
getHomeNotice: function() {
var that = this
wx.request({
url: 'https://www.teaexs.com/app/notice/manager/queryPublishedNotice.do',
method: 'POST',
header: {
'content-type': 'application/x-www-form-urlencoded'
},
data: {
page: 1,
pageSize: 5
},
success: function (res) {
if (res.data.head.code == 0) {
that.setData({
notices: res.data.body.rows
})
} else {
}
},
complete: function () {
wx.hideNavigationBarLoading()
wx.stopPullDownRefresh()
}
})
},
getNewTeaList: function () {
var that = this
wx.request({
url: 'https://www.teaexs.com/app/show/productIssue/queryProductIssueList.do',
method: 'POST',
header: {
'content-type': 'application/x-www-form-urlencoded'
},
data: {
},
success: function (res) {
if (res.data.head.code == 0) {
that.setData({
newteaList: res.data.body.priorList.concat(res.data.body.waitList).concat(res.data.body.startList)
.concat(res.data.body.timingList).concat(res.data.body.endList)
})
} else {
}
},
complete: function () {
wx.hideNavigationBarLoading()
wx.stopPullDownRefresh()
}
})
},
getHomeNews: function () {
var that = this
wx.request({
url: 'https://www.teaexs.com/app/notice/news/queryPage.do',
method: 'POST',
header: {
'content-type': 'application/x-www-form-urlencoded'
},
data: {
page: 1,
pageSize: 5
},
success: function (res) {
if (res.data.head.code == 0) {
that.setData({
newsList: res.data.body.rows
})
} else {
}
},
complete: function () {
wx.hideNavigationBarLoading()
wx.stopPullDownRefresh()
}
})
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
this.getBannerInfo()
this.getHomeNotice()
this.getNewTeaList()
this.getHomeNews()
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
wx.showNavigationBarLoading()
this.getBannerInfo()
this.getHomeNotice()
this.getNewTeaList()
this.getHomeNews()
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
}) |
import React from "react";
import PropTypes from "prop-types";
import Popover from "@paprika/popover";
import useI18n from "@paprika/l10n/lib/useI18n";
import IsDarkContext from "../../context";
import { MAXIMUM_NUM_OF_CHARACTER } from "../../constants";
import * as sc from "./Link.styles";
const truncate = str =>
str.length > MAXIMUM_NUM_OF_CHARACTER ? `${str.substring(0, MAXIMUM_NUM_OF_CHARACTER)}...` : str;
function isString(item) {
return typeof item === "string" || item instanceof String;
}
function Link(props) {
const { children, hasOnlyOneChild, href, as, ...moreProps } = props;
const isDark = React.useContext(IsDarkContext);
const I18n = useI18n();
const shouldTruncate = isString(children) && children.length > MAXIMUM_NUM_OF_CHARACTER;
const link = (
<sc.Link data-pka-anchor="breadcrumbs.link" as={as} kind="minor" href={href} isDark={isDark} {...moreProps}>
{hasOnlyOneChild ? <sc.ArrowIcon aria-label={I18n.t("breadcrumbs.aria_back_to")} /> : null}
{shouldTruncate ? truncate(children) : children}
</sc.Link>
);
return (
<sc.ListItem data-pka-anchor="breadcrumbs.list-item">
{shouldTruncate ? (
<Popover isDark isEager>
<Popover.Trigger>{link}</Popover.Trigger>
<Popover.Content>
<Popover.Card>{children}</Popover.Card>
</Popover.Content>
<Popover.Tip />
</Popover>
) : (
link
)}
</sc.ListItem>
);
}
const propTypes = {
children: PropTypes.node,
/** Render as another component instead of Button.Link. */
as: PropTypes.oneOfType([PropTypes.string, PropTypes.elementType]),
hasOnlyOneChild: PropTypes.bool,
/** Url for the link. */
href: PropTypes.string,
};
const defaultProps = {
children: null,
as: null,
hasOnlyOneChild: false,
href: "",
};
Link.displayName = "Breadcrumbs.Link";
Link.propTypes = propTypes;
Link.defaultProps = defaultProps;
export default Link;
|
const csv = require('csv')
const fs = require('fs')
const path = require('path')
//
fs.readFile(path.join(__dirname, './customer-data.csv'), {encoding: 'utf-8'}, function(error, data) {
if (error) return console.error(error)
var converted = '['
csv.parse(data, {}, function(error, output) {
if (error) return console.error(error)
const headers = output.shift()
for (i = 0; i < output.length; i++) {
converted += '{'
for (j = 0; j < headers.length; j++) {
converted += '"' + headers[j] + '":"' + output[i][j] + '"'
if (j != headers.length-1) {
converted += ','
}
}
converted += '}'
if (i != output.length-1) {
converted += ',\n'
}
}
converted += ']'
const parsedJSON = JSON.parse(converted)
// wanted to use it to see if the JSON was formatted correctly.
const convertedAgain = JSON.stringify(parsedJSON)
fs.writeFile(path.join(__dirname, './customer-data.json'), convertedAgain, 'utf-8', function(error) {
if (error) return console.error(error)
console.log('Finished')
})
// console.log(converted)
// console.log(parsedJSON)
})
}) |
const jwt = require("jsonwebtoken");
async function authHeader(req, res, next) {
const auth = req.headers && req.headers.authorization;
if (!auth) {
req.isAuth = false;
return next();
}
const token = auth.split(" ")[1];
if (!token || token.length === 0) {
req.isAuth = false;
return next();
}
let decodedToken;
try {
decodedToken = jwt.verify(token, process.env.TOKEN_KEY);
} catch (error) {
req.isAuth = false;
return next();
}
if (!decodedToken) {
req.isAuth = false;
return next();
}
const { userID } = decodedToken;
req.isAuth = true;
req.userID = userID;
return next();
}
module.exports = authHeader;
|
module.exports = {
rules: {
//'media-query-parentheses-space-inside': 'never'
}
};
|
//前端isLogin
import axios from 'axios';
export function isLoginChecker(){
axios.post("/api/isLogin",
{}
).then(res=>{
if(res.data && res.data.message === true){
console.log("登入者",res.data.data);
return true;
}else{
console.log("未登入");
return false;
}
})
} |
import Service from '@ember/service';
import fetch from 'fetch';
import { get, set, computed } from "@ember/object";
import { assign } from '@ember/polyfills';
import { inject as service } from '@ember/service';
import { reject } from 'rsvp';
export default Service.extend({
configService: service("config"),
userToken: null,
/**
* Contains the fetch api
* This is for testing to make it easy to mock
*/
_fetch: fetch,
/**
* get the assigned token or the default one
*/
token: computed.or("userToken", "configService.APP.settings.api.token"),
/***
*
* @param resource
* @param data - the data to send, this will be JSON.stringified unless options says to form-encode
* @param options - {
* type: 'GET', // 'POST', 'PUT', 'DELETE'
* formEncode: false, // For encode the data instead of JSON.stringify
* sort: { // optional, if specified, will be added to the request
* },
* filter: { // optional, if string, will be added as is, else will be & separated
* },
* page: { // optional, if specified, will be added to the request
* }
*
* }
* @returns {Promise<*>}
*/
async sendRequest({resource, data, options}) {
let fetch = get(this, "_fetch");
// provide for default options
let _options = assign({
timeout: 10000,
type: 'GET'
}, options);
let token = get(this, "token");
// setup the headers
let _headers = Object.assign({
'Authorization': 'Bearer ' + token,
'Content-type': 'application/json'
}, _options.headers || {});
if (data && get(_options, "formEncode")) {
set(_headers, "Content-type", 'application/x-www-form-urlencoded');
data = this.transformJsonToUrlEncode(data);
} else {
if (data === Object(data)) {
data = JSON.stringify(data);
}
}
let request = {
method: get(_options, "type"),
headers: _headers
};
if (data) {
set(request, "body", data);
}
let url = this.buildUrl(resource, _options);
let response = await fetch(url, request);
if (response.ok) {
let json = {};
try {
json = response.json()
} finally {
// empty
}
return json;
} else {
this.handleErrors(response.status);
return reject(response, "Response not valid in apiService");
}
},
handleErrors(status) {
// if (status === 401) {
//
// let authorization = get(this, 'authorizationService');
// authorization.transitionToAuthenticationRoute()
// }
},
buildUrl(resource, options) {
let configService = get(this, "configService");
let url = `${get(configService, "APP.settings.api.host")}${get(configService, "APP.settings.api.basePath")}${resource}`;
let page = this.buildPage(options.page);
let filter = this.buildFilter(options.filter);
let sort = this.buildSort(options.sort);
let paramA = [];
if (page !== "") { paramA.push(page); }
if (filter !== "") { paramA.push(filter); }
if (sort !== "") { paramA.push(sort); }
let params = paramA.join("&");
if (params !== "") { url = `${url}?${params}`; }
return url;
},
urlConstants: computed({
get() {
return {
page: {
number: "page[number]",
size: "page[size]"
},
sort: "sort",
filter: "filter"
}
},
set(k, v) {
return v;
}
}),
buildPage(page) {
if (!page) {
return "";
}
},
buildSort(sort) {
if (!sort) {
return "";
}
},
buildFilter(filter) {
if (!filter) {
return "";
}
},
transformJsonToUrlEncode: function (json) {
let parts = [];
Object.keys(json).forEach( item => {
parts.push(`${item}=${json[item]}`);
});
return parts.join("&");
}
});
|
import React, { createContext, useState } from 'react';
import { AddProducts, FetchProducts, UpdateProduct } from '../api/products';
export const ProductContext = createContext();
const ProductContextProvider = (props) => {
const [products, setProducts] = useState([])
const [productsLoading, setProductsLoading] = useState([])
const fetchProducts = async () => {
setProductsLoading(true)
let data = await FetchProducts();
setProductsLoading(false)
if (data != null) {
setProducts(data)
}
}
const addProduct = async(data) => {
let res = await AddProducts(data);
if (res != null) {
return true;
} else {
return false;
}
}
const updateProduct = async (oldData, ...newData) => {
setProductsLoading(true)
let data = await UpdateProduct(...newData);
setProductsLoading(false)
if (data != null) {
var prevState = [...products];
var index = prevState.indexOf(oldData)
prevState[index] = newData
setProducts(prevState)
} else {
// console.log(data)
alert("naay mali")
}
}
return (
<ProductContext.Provider value={{
products, productsLoading, fetchProducts, addProduct, updateProduct
}}>
{props.children}
</ProductContext.Provider>
)
}
export default ProductContextProvider; |
/**
* @Author: wangxu <ceekey>
* @Date: 2017-05-01 14:58:40
* @Email: xu.wang@ishansong.com
* @Project: terra
* @Filename: api.js
* @Last modified by: ceekey
* @Last modified time: 2017-05-05 13:47:19
*/
'use strict';
let dao = require("../dao/daos");
let api = {};
let R = require('ramda');
class Api {
constructor(props) {}
static * register(next) {
this.body = yield dao.user.register(this.request.fields);
}
static * login(next) {
var result = yield dao.user.login(this.request.fields);
//设置cookies userId
if (!R.isNil(result.data)) {
this.cookies.set("userId", result.data.userId, {maxAge: 1800000});
result.data = true;
}
this.body = result;
}
static * savedoc(){
var result = yield dao.doc.save(this.query.doc);
}
}
module.exports = Api;
|
export const FETCH_ECOTURISMO = 'FETCH_ECOTURISMO';
export const FETCH_ECOTURISMOS = 'FETCH_ECOTURISMOS';
export const REQUEST_LOADING_ECOTURISMO = 'REQUEST_LOADING_ECOTURISMO';
export const REQUEST_REJECTED_ECOTURISMO = 'REQUEST_REJECTED_ECOTURISMO';
|
const buildGround = (w,h,scene) => {
var skyboxMaterial = new BABYLON.SkyMaterial("skyMaterial", scene);
skyboxMaterial.backFaceCulling = false;
var skybox = BABYLON.Mesh.CreateBox("skyBox", 1000.0, scene);
skybox.material = skyboxMaterial;
var setSkyConfig = function (property, from, to) {
var keys = [
{ frame: 0, value: from },
{ frame: 100, value: to }
];
var animation = new BABYLON.Animation("animation", property, 100, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
animation.setKeys(keys);
scene.stopAnimation(skybox);
scene.beginDirectAnimation(skybox, [animation], 0, 100, false, 1000);
};
// window.addEventListener("keydown", function (evt) {
// switch (evt.keyCode) {
// case 49: setSkyConfig("material.inclination", skyboxMaterial.inclination, 0); break; // 1
// case 50: setSkyConfig("material.inclination", skyboxMaterial.inclination, -0.5); break; // 2
// case 51: setSkyConfig("material.luminance", skyboxMaterial.luminance, 0.1); break; // 3
// case 52: setSkyConfig("material.luminance", skyboxMaterial.luminance, 1.0); break; // 4
// case 53: setSkyConfig("material.turbidity", skyboxMaterial.turbidity, 40); break; // 5
// case 54: setSkyConfig("material.turbidity", skyboxMaterial.turbidity, 5); break; // 6
// case 55: setSkyConfig("material.cameraOffset.y", skyboxMaterial.cameraOffset.y, 50); break; // 7
// case 56: setSkyConfig("material.cameraOffset.y", skyboxMaterial.cameraOffset.y, 0); break; // 8
// default: break;
// }
// });
// Set to Day
setSkyConfig("material.inclination", skyboxMaterial.inclination, 0.02);
var mat = new BABYLON.StandardMaterial("mat", scene);
//var texture = new BABYLON.Texture("img/nasim-4248.jpg", scene);
var texture = new BABYLON.Texture("img/nasim-4248.jpg", scene);
mat.diffuseTexture = texture;
mat.diffuseTexture.uScale = 100;
mat.diffuseTexture.vScale = 100;
var faceUV = new Array(6);
faceUV[4] = new BABYLON.Vector4(1, 0, 0, 1);
var box = BABYLON.MeshBuilder.CreateBox("box", { width:w/2,height:1,depth:h/2,faceUV: faceUV }, scene);
box.material = mat;
const ground = BABYLON.MeshBuilder.CreateGround("ground", {width:w, height:h});
const groundlMat = new BABYLON.StandardMaterial("boxMat");
groundlMat.diffuseTexture = new BABYLON.Texture("img/concrete3.jpg");
ground.material = groundlMat;
return ground;
}
const buildCamera = (w,h,scene) =>{
//const camera = new BABYLON.ArcRotateCamera("camera",- Math.PI/2,Math.PI/2, 10, new BABYLON.Vector3(-w/2+50,15,h/2-40));
//camera = new BABYLON.UniversalCamera("MyCamera", new BABYLON.Vector3(0, 4,20), scene);
camera = new BABYLON.UniversalCamera("MyCamera", new BABYLON.Vector3(-20, 4,30), scene);
camera.attachControl(canvas);
camera.speed =0.5;
camera.setTarget(new BABYLON.Vector3(-20, 4,80));
scene.activeCameras.push(camera);
camera.upperBetaLimit = Math.PI / 2;
camera.applyGravity = true;
camera.ellipsoid = new BABYLON.Vector3(1,2, 1);
camera.checkCollisions = true;
$(document).ready(function(){
var timeout;
$('#left').mousedown(function(){
timeout = setInterval(function(){
camera.cameraRotation=new BABYLON.Vector2(0, -Math.PI/720 )
}, 10);
return false;
});
$('#right').mousedown(function(){
timeout = setInterval(function(){
camera.cameraRotation=new BABYLON.Vector2(0, Math.PI/720 )
}, 10);
return false;
});
$(document).mouseup(function(){
clearInterval(timeout);
return false;
});
$('#top').mousedown(function(){
timeout = setInterval(function(){
cameraTarget = camera.getTarget();
let ratio = 800;
let this_x = camera.position.x - (camera.position.x - cameraTarget.x)/ratio;
let this_y = camera.position.y - (camera.position.y - cameraTarget.y)/ratio;
let this_z = camera.position.z - (camera.position.z - cameraTarget.z)/ratio;
this_y = 4;
if(this_x <=-w/2+20){
this_x = -w/2+20;
}else if(this_x >=w/2-20){
this_x=w/2-20;
}
if(this_z <=-h/2+20){
this_z = -h/2+20;
}else if(this_z >=h/2-20){
this_z=h/2-20;
}
camera.position = new BABYLON.Vector3(this_x,this_y,this_z);
}, 10);
return false;
});
$('#down').mousedown(function(){
timeout = setInterval(function(){
cameraTarget = camera.getTarget();
let ratio = 800;
let this_x = camera.position.x + (camera.position.x - cameraTarget.x)/ratio;
let this_y = camera.position.y + (camera.position.y - cameraTarget.y)/ratio;
let this_z = camera.position.z + (camera.position.z - cameraTarget.z)/ratio;
this_y = 4;
if(this_x <=-w/2+20){
this_x = -w/2+20;
}else if(this_x >=w/2-20){
this_x=w/2-20;
}
if(this_z <=-h/2+20){
this_z = -h/2+20;
}else if(this_z >=h/2-20){
this_z=h/2-20;
}
camera.position = new BABYLON.Vector3(this_x,this_y,this_z);
}, 10);
return false;
});
});
// scene.onPointerUp = function (evt,pic) {
// clearInterval(interval);
// }
// scene.onPointerDown = function (evt,pic) {
// interval = setInterval(function(){
// cameraTarget = camera.getTarget();
// let ratio = 800;
// let this_x = camera.position.x - (camera.position.x - cameraTarget.x)/ratio;
// let this_y = camera.position.y - (camera.position.y - cameraTarget.y)/ratio;
// let this_z = camera.position.z - (camera.position.z - cameraTarget.z)/ratio;
// this_y = 5;
// if(this_x <=-w/2+2){
// this_x = -w/2+2;
// }else if(this_x >=w/2){
// this_x=w/2-2;
// }
// if(this_y <=2){
// this_y = 2;
// }
// else if(this_y >=3){
// this_y=3;
// }
// if(this_z <=-h/2+2){
// this_z = -h/2+2;
// }else if(this_z >=h/2-2){
// this_z=h/2-2;
// }
// camera.position = new BABYLON.Vector3(this_x,this_y,this_z);
// }, 20);
// }
return camera;
}
const lamps = (w,h,scene)=>{
let w_h = 40;
const top_light = new BABYLON.HemisphericLight("light", new BABYLON.Vector3(0,300,0));
const bottom_light = new BABYLON.HemisphericLight("light", new BABYLON.Vector3(0,-300,0));
bottom_light.intensity = 0.8;
}
const buildHallLamp = (w,h,scene,color) =>{
const lampLight = new BABYLON.SpotLight("lampLight", BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, -1, 0), Math.PI, 1, scene);
lampLight.diffuse = BABYLON.Color3.White();
lampLight.intensity = 0.5;
const whiteMat = new BABYLON.StandardMaterial("yellowMat");
whiteMat.emissiveColor = BABYLON.Color3.White();
const bulb = new BABYLON.MeshBuilder.CreateSphere("bulb", {});
const bulbCover = BABYLON.MeshBuilder.CreateSphere("bulbCover", {arc:0.5, sideOrientation: BABYLON.Mesh.DOUBLESIDE});
bulbCover.rotation = new BABYLON.Vector3(Math.PI/2,0,0);
bulbCover.scaling = new BABYLON.Vector3(2,2,2);
bulb.material = whiteMat;
bulb.position =new BABYLON.Vector3(0,5.45,0);
bulbCover.position =new BABYLON.Vector3(0,5,0);
lampLight.parent = bulb;
return BABYLON.Mesh.MergeMeshes([bulb,bulbCover], true, false, null, false, true);
}
const BuildBooth_2_ = (w,h,scene,color) =>{
const gray = new BABYLON.StandardMaterial("boxMat");
gray.diffuseColor = new BABYLON.Color3(236/255, 240/255, 241/255);
const kaf = BABYLON.MeshBuilder.CreateCylinder("cylinder", {tessellation:w*h});
kaf.scaling = new BABYLON.Vector3(w,0.1,h);
kaf.position = new BABYLON.Vector3(0,0.5,0);
//top
const top_a = BABYLON.MeshBuilder.CreateCylinder("cylinder", {tessellation:w*h});
top_a.scaling = new BABYLON.Vector3(w,0.1,h);
top_a.position = new BABYLON.Vector3(0,10,0);
top_a.material = color;
const top_b = BABYLON.MeshBuilder.CreateCylinder("cylinder", {tessellation:w*h});
top_b.scaling = new BABYLON.Vector3(w-1,0.85,h-1);
top_b.position = new BABYLON.Vector3(0,9,0);
top_b.material = gray;
const top_c = BABYLON.MeshBuilder.CreateCylinder("cylinder", {tessellation:w*h});
top_c.scaling = new BABYLON.Vector3(w,0.1,h);
top_c.position = new BABYLON.Vector3(0,8,0);
top_c.material = color;
const sotoon = BABYLON.MeshBuilder.CreateCylinder("cylinder", {tessellation:w*h});
sotoon.scaling = new BABYLON.Vector3(1,4,1);
sotoon.position = new BABYLON.Vector3(0,4,0);
sotoon.material = gray;
const stand1 = BuildStand_2(2,4,scene,color);
stand1.translate(new BABYLON.Vector3(-6, 0, -2), 1, BABYLON.Space.WORLD);
const desk1 = BuildDesk_1(5.5,2,scene,color);
desk1.translate(new BABYLON.Vector3(0, 1, -h/2+3), 1, BABYLON.Space.WORLD);
const desk2 = BuildDesk_1(4,2,scene,color);
desk2.rotation = new BABYLON.Vector3(0,Math.PI/3,0);
desk2.translate(new BABYLON.Vector3(-w/3+1, 1, -h/3+1), 1, BABYLON.Space.WORLD);
const desk3 = BuildDesk_1(4,2,scene,color);
desk3.rotation = new BABYLON.Vector3(0,-Math.PI/3,0);
desk3.translate(new BABYLON.Vector3(w/3-1, 1, -h/3+1), 1, BABYLON.Space.WORLD);
return BABYLON.Mesh.MergeMeshes(
[kaf,sotoon,top_a,top_b,top_c,desk1,desk2,desk3,stand1]
, true, false, null, false, true);
}
const BuildBooth_3_ = (w,h,scene,color) =>{
const gray = new BABYLON.StandardMaterial("boxMat");
gray.diffuseColor = new BABYLON.Color3(236/255, 240/255, 241/255);
const kaf = BABYLON.MeshBuilder.CreateCylinder("cylinder", {tessellation:w*h});
kaf.scaling = new BABYLON.Vector3(w,0.1,h);
kaf.position = new BABYLON.Vector3(0,0.5,0);
kaf.material = gray;
const kaf2 = BABYLON.MeshBuilder.CreateCylinder("cylinder", {tessellation:w*h});
kaf2.scaling = new BABYLON.Vector3(w/3,1,h/3);
kaf2.position = new BABYLON.Vector3(0,1,0);
kaf2.material = color;
const sar = BABYLON.MeshBuilder.CreateCylinder("cylinder", {tessellation:w*h});
sar.scaling = new BABYLON.Vector3(w/5,0.5,h/5);
sar.position = new BABYLON.Vector3(0,9.5,0);
sar.material = color;
const sar2 = BABYLON.MeshBuilder.CreateCylinder("cylinder", {tessellation:w*h});
sar2.scaling = new BABYLON.Vector3(w/6,1.5,h/6);
sar2.position = new BABYLON.Vector3(0,10,0);
sar2.material = gray;
const sar3 = BABYLON.MeshBuilder.CreateBox("box", { width:w,height:0.1,depth:h}, scene);
sar3.position.y = 10.5;
sar3.material = color;
return BABYLON.Mesh.MergeMeshes(
[kaf,sar,sar2,sar3,kaf2,]
, true, false, null, false, true);
}
const BuildBooth_4_ = (w,h,scene,color) =>{
}
const buildWindow = (w,h,scene,color) =>{
//چهارچوب
var top_a= BABYLON.MeshBuilder.CreateBox("box", { width:w,height:0.5,depth:0.5}, scene);
top_a.position.y= 1;
var top_b= BABYLON.MeshBuilder.CreateBox("box", { width:w,height:0.5,depth:0.5}, scene);
top_b.position.y= h+1;
var top_c= BABYLON.MeshBuilder.CreateBox("box", { width:0.5,height:h,depth:0.5}, scene);
top_c.position.x= (w/2)-0.25;
top_c.position.y = (h/2) +1;
var top_d= BABYLON.MeshBuilder.CreateBox("box", { width:0.5,height:h,depth:0.5}, scene);
top_d.position = new BABYLON.Vector3((-w/2)+0.25, (h/2)+1, 0);
//خطوط افقی
// var top_e= BABYLON.MeshBuilder.CreateBox("box", { width:w,height:0.25,depth:0.5}, scene);
// top_e.position.y= 2.5;
// var top_f= BABYLON.MeshBuilder.CreateBox("box", { width:w,height:0.25,depth:0.5}, scene);
// top_f.position.y= 4.5;
// var top_g= BABYLON.MeshBuilder.CreateBox("box", { width:w,height:0.25,depth:0.5}, scene);
// top_g.position.y= 6.5;
//خطوط عمودی
var line_ver_1= BABYLON.MeshBuilder.CreateBox("box", { width:0.25,height:h,depth:0.5}, scene);
line_ver_1.position = new BABYLON.Vector3((-w/2)+3.25, (h/2)+1, 0);
var line_ver_2= BABYLON.MeshBuilder.CreateBox("box", { width:0.25,height:h,depth:0.5}, scene);
line_ver_2.position = new BABYLON.Vector3((-w/2)+6.25, (h/2)+1, 0);
var line_ver_3= BABYLON.MeshBuilder.CreateBox("box", { width:0.25,height:h,depth:0.5}, scene);
line_ver_3.position = new BABYLON.Vector3((-w/2)+9.25, (h/2)+1, 0);
var line_ver_4= BABYLON.MeshBuilder.CreateBox("box", { width:0.25,height:h,depth:0.5}, scene);
line_ver_4.position = new BABYLON.Vector3((-w/2)+12.25, (h/2)+1, 0);
var line_ver_5= BABYLON.MeshBuilder.CreateBox("box", { width:0.25,height:h,depth:0.5}, scene);
line_ver_5.position = new BABYLON.Vector3((-w/2)+15.25, (h/2)+1, 0);
var line_ver_6= BABYLON.MeshBuilder.CreateBox("box", { width:0.25,height:h,depth:0.5}, scene);
line_ver_6.position = new BABYLON.Vector3((-w/2)+18.25, (h/2)+1, 0);
var line_ver_7= BABYLON.MeshBuilder.CreateBox("box", { width:0.25,height:h,depth:0.5}, scene);
line_ver_7.position = new BABYLON.Vector3((-w/2)+21.25, (h/2)+1, 0);
var line_ver_8= BABYLON.MeshBuilder.CreateBox("box", { width:0.25,height:h,depth:0.5}, scene);
line_ver_8.position = new BABYLON.Vector3((-w/2)+24.25, (h/2)+1, 0);
var line_ver_9= BABYLON.MeshBuilder.CreateBox("box", { width:0.25,height:h,depth:0.5}, scene);
line_ver_9.position = new BABYLON.Vector3((-w/2)+27.25, (h/2)+1, 0);
var line_ver_10= BABYLON.MeshBuilder.CreateBox("box", { width:0.25,height:h,depth:0.5}, scene);
line_ver_10.position = new BABYLON.Vector3((-w/2)+30.25, (h/2)+1, 0);
var line_ver_11= BABYLON.MeshBuilder.CreateBox("box", { width:0.25,height:h,depth:0.5}, scene);
line_ver_11.position = new BABYLON.Vector3((-w/2)+33.25, (h/2)+1, 0);
var line_ver_12= BABYLON.MeshBuilder.CreateBox("box", { width:0.25,height:h,depth:0.5}, scene);
line_ver_12.position = new BABYLON.Vector3((-w/2)+36.5, (h/2)+1, 0);
var line_ver_13= BABYLON.MeshBuilder.CreateBox("box", { width:0.25,height:h,depth:0.5}, scene);
line_ver_13.position = new BABYLON.Vector3((-w/2)+39.5, (h/2)+1, 0);
var line_ver_14= BABYLON.MeshBuilder.CreateBox("box", { width:0.25,height:h,depth:0.5}, scene);
line_ver_14.position = new BABYLON.Vector3((-w/2)+42.5, (h/2)+1, 0);
top_a.material = top_b.material = top_c.material = top_d.material = color;
line_ver_1.material = line_ver_2.material = line_ver_3.material = line_ver_4.material =line_ver_5.material = line_ver_6.material = line_ver_7.material = color;
line_ver_8.material = line_ver_9.material = line_ver_10.material = line_ver_11.material = line_ver_12.material = line_ver_13.material = line_ver_14.material = color;
return BABYLON.Mesh.MergeMeshes([top_a, top_b, top_c, top_d, line_ver_1,line_ver_2, line_ver_3, line_ver_4, line_ver_5, line_ver_6, line_ver_7, line_ver_8, line_ver_9, line_ver_10, line_ver_11, line_ver_12, line_ver_13, line_ver_14], true, false, null, false, true);
}
const build_door = (w, h, scene, color) =>{
var d_1= BABYLON.MeshBuilder.CreateBox("box", { width:w,height:0.5,depth:0.5}, scene);
d_1.position.y= 1;
var d_2= BABYLON.MeshBuilder.CreateBox("box", { width:w,height:0.5,depth:0.5}, scene);
d_2.position.y= h+1;
var d_3= BABYLON.MeshBuilder.CreateBox("box", { width:0.5,height:h,depth:0.5}, scene);
d_3.position.x= (w/2)-0.25;
d_3.position.y = (h/2) +1;
var d_4= BABYLON.MeshBuilder.CreateBox("box", { width:0.5,height:h,depth:0.5}, scene);
d_4.position = new BABYLON.Vector3((-w/2)+0.25, (h/2)+1, 0);
d_1.material = d_2.material = d_3.material = d_4.material = color;
//خطوط افقی
width_d = 30;
var o_1= BABYLON.MeshBuilder.CreateBox("box", { width:width_d,height:0.25,depth:0.5}, scene);
o_1.position= new BABYLON.Vector3(32.5,4,0);
var o_2= BABYLON.MeshBuilder.CreateBox("box", { width:width_d,height:0.25,depth:0.5}, scene);
o_2.position=new BABYLON.Vector3(32,6.5,0);
var o_3 = BABYLON.MeshBuilder.CreateBox("box", { width:width_d,height:0.25,depth:0.5}, scene);
o_3.position=new BABYLON.Vector3(32,9.5,0);
var o_4 = BABYLON.MeshBuilder.CreateBox("box", { width:width_d,height:0.25,depth:0.5}, scene);
o_4.position=new BABYLON.Vector3(32,12.5,0);
var o_5 = BABYLON.MeshBuilder.CreateBox("box", { width:width_d,height:0.25,depth:0.5}, scene);
o_5.position=new BABYLON.Vector3(32,15.5,0);
var o_6 = BABYLON.MeshBuilder.CreateBox("box", { width:95,height:0.25,depth:0.5}, scene);
o_6.position.y= 19;
var o_7 = BABYLON.MeshBuilder.CreateBox("box", { width:95,height:0.25,depth:0.5}, scene);
o_7.position.y= 22.5;
//افقی چپ!
var o_1_l= BABYLON.MeshBuilder.CreateBox("box", { width:width_d,height:0.25,depth:0.5}, scene);
o_1_l.position= new BABYLON.Vector3(-32.5,4,0);
var o_2_l= BABYLON.MeshBuilder.CreateBox("box", { width:width_d,height:0.25,depth:0.5}, scene);
o_2_l.position=new BABYLON.Vector3(-32,6.5,0);
var o_3_l = BABYLON.MeshBuilder.CreateBox("box", { width:width_d,height:0.25,depth:0.5}, scene);
o_3_l.position=new BABYLON.Vector3(-32,9.5,0);
var o_4_l = BABYLON.MeshBuilder.CreateBox("box", { width:width_d,height:0.25,depth:0.5}, scene);
o_4_l.position=new BABYLON.Vector3(-32,12.5,0);
var o_5_l = BABYLON.MeshBuilder.CreateBox("box", { width:width_d,height:0.25,depth:0.5}, scene);
o_5_l.position=new BABYLON.Vector3(-32,15.5,0);
//خطوط عمودی
var line_ver_d_1= BABYLON.MeshBuilder.CreateBox("box", { width:0.5,height:h,depth:0.5}, scene);
line_ver_d_1.position = new BABYLON.Vector3(-17, (h/2)+1, 0);
var line_ver_d_3= BABYLON.MeshBuilder.CreateBox("box", { width:0.5,height:h,depth:0.5}, scene);
line_ver_d_3.position = new BABYLON.Vector3(-25, (h/2)+1, 0);
var line_ver_d_5= BABYLON.MeshBuilder.CreateBox("box", { width:0.5,height:h,depth:0.5}, scene);
line_ver_d_5.position = new BABYLON.Vector3(-33, (h/2)+1, 0);
var line_ver_d_7= BABYLON.MeshBuilder.CreateBox("box", { width:0.5,height:h,depth:0.5}, scene);
line_ver_d_7.position = new BABYLON.Vector3(-41, (h/2)+1, 0);
var line_ver_d_2= BABYLON.MeshBuilder.CreateBox("box", { width:0.5,height:h,depth:0.5}, scene);
line_ver_d_2.position= new BABYLON.Vector3(17, (h/2)+1, 0);
var line_ver_d_4= BABYLON.MeshBuilder.CreateBox("box", { width:0.5,height:h,depth:0.5}, scene);
line_ver_d_4.position = new BABYLON.Vector3(25, (h/2)+1, 0);
var line_ver_d_6= BABYLON.MeshBuilder.CreateBox("box", { width:0.5,height:h,depth:0.5}, scene);
line_ver_d_6.position = new BABYLON.Vector3(33, (h/2)+1, 0);
var line_ver_d_8= BABYLON.MeshBuilder.CreateBox("box", { width:0.5,height:h,depth:0.5}, scene);
line_ver_d_8.position = new BABYLON.Vector3(41, (h/2)+1, 0);
return BABYLON.Mesh.MergeMeshes([d_1,d_2,d_3,d_4,o_1,o_2,o_3, o_4, o_5, o_6, o_7, o_1_l,o_2_l,o_3_l, o_4_l, o_5_l, line_ver_d_1, line_ver_d_2, line_ver_d_3, line_ver_d_4, line_ver_d_5, line_ver_d_7,line_ver_d_6, line_ver_d_8], true, false, null, false, true);
}
const BuildDesk_1 = (w,h,scene,color) =>{
const gray = new BABYLON.StandardMaterial("boxMat");
gray.diffuseColor = new BABYLON.Color3(236/255, 240/255, 241/255);
const myPath = [
new BABYLON.Vector3(0, 0, 0),
new BABYLON.Vector3(0, h, 0),
];
const miz_a = BABYLON.MeshBuilder.CreateCylinder("tube", {arc:0.5,path: myPath, radius: 0.5, sideOrientation: BABYLON.Mesh.DOUBLESIDE}, scene);
miz_a.scaling = new BABYLON.Vector3(w,h,w);
miz_a.position = new BABYLON.Vector3(0,h/2,0)
miz_a.material = color;
const miz_b = BABYLON.MeshBuilder.CreateCylinder("tube", {arc:0.5,path: myPath, radius: 0.5, sideOrientation: BABYLON.Mesh.DOUBLESIDE}, scene);
miz_b.scaling = new BABYLON.Vector3(w+.1,0.2,w+.1);
miz_b.position = new BABYLON.Vector3(0,0.75,0)
miz_b.material = gray;
const miz_c = BABYLON.MeshBuilder.CreateCylinder("tube", {arc:0.5,path: myPath, radius: 0.5, sideOrientation: BABYLON.Mesh.DOUBLESIDE}, scene);
miz_c.scaling = new BABYLON.Vector3(w+0.1,0.2,w+0.1);
miz_c.position = new BABYLON.Vector3(0,h+.75,0)
miz_c.material = gray;
return BABYLON.Mesh.MergeMeshes(
[miz_a,miz_b,miz_c]
, true, false, null, false, true);
}
const BuildDesk_2 = (w,h,scene,color,logo) =>{
const gray = new BABYLON.StandardMaterial("boxMat");
gray.diffuseColor = new BABYLON.Color3(236/255, 240/255, 241/255);
const logopo = BABYLON.MeshBuilder.CreateCylinder("tube", { sideOrientation: BABYLON.Mesh.DOUBLESIDE}, scene);
logopo.position = new BABYLON.Vector3(0,h/2+0.6,-0.75);
logopo.scaling = new BABYLON.Vector3(1,0.01,1);
logopo.rotation = new BABYLON.Vector3(-Math.PI/2,0,0);
logopo.material = logo;
var desk_a= BABYLON.MeshBuilder.CreateBox("box", { width:w+.2,height:0.2,depth:1.2}, scene);
desk_a.position = new BABYLON.Vector3(0,h/2-0.2,0);
desk_a.material = color;
var desk_b= BABYLON.MeshBuilder.CreateBox("box", { width:w,height:h,depth:1}, scene);
desk_b.position = new BABYLON.Vector3(0,h/2,0);
desk_b.material = gray;
var desk_c= BABYLON.MeshBuilder.CreateBox("box", { width:w+.2,height:0.2,depth:1.2}, scene);
desk_c.position = new BABYLON.Vector3(0,h-0.2,0);
desk_c.material = color;
return BABYLON.Mesh.MergeMeshes(
[desk_a,desk_b,desk_c,logopo]
, true, false, null, false, true);
}
const BuildStand_1 = (w,h,scene,color,img) =>{
const gray = new BABYLON.StandardMaterial("boxMat");
gray.diffuseColor = new BABYLON.Color3(236/255, 240/255, 241/255);
var kaf= BABYLON.MeshBuilder.CreateBox("box", { width:1,height:0.2,depth:1}, scene);
kaf.position = new BABYLON.Vector3(0,1,0);
kaf.material = color;
var pa= BABYLON.MeshBuilder.CreateBox("box", { width:0.2,height:h,depth:0.2}, scene);
pa.position = new BABYLON.Vector3(0,h/2+1,0);
pa.material = color;
var safe= BABYLON.MeshBuilder.CreateBox("box", { width:w/2,height:0.2,depth:w/2}, scene);
safe.rotation = new BABYLON.Vector4(-Math.PI/3,0,0);
safe.position = new BABYLON.Vector3(0,1.4*h,0);
safe.material = color;
const faceUV = [];
for(var i=0;i<=5;i++){
faceUV[i] = new BABYLON.Vector4(0.0, 0.0, 0.0, 1.0); //front face
}
faceUV[4] = new BABYLON.Vector4(0.0, 0, 1.0, 1.0);
var safe2= BABYLON.MeshBuilder.CreateBox("box", { width:w,height:0.2,depth:w,faceUV: faceUV, wrap: true}, scene);
safe2.rotation = new BABYLON.Vector4(-Math.PI/3,0,0);
safe2.position = new BABYLON.Vector3(0,1.5*h,0);
safe2.material = img;
return BABYLON.Mesh.MergeMeshes(
[kaf,pa,safe,safe2]
, true, false, null, false, true);
}
const BuildStand_2 = (w,h,scene,color,img) =>{
const gray = new BABYLON.StandardMaterial("boxMat");
gray.diffuseColor = new BABYLON.Color3(236/255, 240/255, 241/255);
var kaf= BABYLON.MeshBuilder.CreateCylinder("cylinder", {arc:0.5});
kaf.rotation = new BABYLON.Vector4(Math.PI/2,0,Math.PI/2);
kaf.position = new BABYLON.Vector3(0,1,0);
kaf.scaling = new BABYLON.Vector3(w/2,h/3.2,1);
kaf.material = color;
var pa= BABYLON.MeshBuilder.CreateBox("box", { width:w-.2,height:h,depth:0.1}, scene);
pa.position = new BABYLON.Vector3(0,h/2+1.5,0);
pa.material = color;
const faceUV = [];
for(var i=0;i<=5;i++){
faceUV[i] = new BABYLON.Vector4(0.0, 0.0, 0.0, 1.0); //front face
}
faceUV[1] = new BABYLON.Vector4(0.0, 0, 1.0, 1.0);
var pa2= BABYLON.MeshBuilder.CreateBox("box", { width:w-.5,height:h-0.3,depth:0.5,faceUV: faceUV, wrap: true}, scene);
pa2.position = new BABYLON.Vector3(0,h/2+1.5,0);
pa2.material = img;
return BABYLON.Mesh.MergeMeshes(
[kaf,pa,pa2]
, true, false, null, false, true);
}
const BuildStand_3 = (w,h,scene,color) =>{
const gray = new BABYLON.StandardMaterial("boxMat");
gray.diffuseColor = new BABYLON.Color3(236/255, 240/255, 241/255);
const b1= BABYLON.MeshBuilder.CreateBox("box", { width:w,height:0.1,depth:1}, scene);
b1.position = new BABYLON.Vector3(0,1,0);
b1.material = color;
const b2= BABYLON.MeshBuilder.CreateBox("box", { width:w,height:h,depth:0.1}, scene);
b2.position = new BABYLON.Vector3(0,h/2+1,-.45);
b2.material = color;
const b3= BABYLON.MeshBuilder.CreateBox("box", { width:w,height:0.1,depth:2}, scene);
b3.rotation = new BABYLON.Vector4(-Math.PI/6,0,0);
b3.position = new BABYLON.Vector3(0,h+.45+(Math.sin(Math.PI/6)*2),.4);
b3.material = color;
}
const BuildMiddleBooth = (w,h,scene,color) =>{
let bx=20;
let bz=15;
const booth4_a = buildMini4Wall();
const booth4_b = buildMini4Wall();
const booth4_c = buildMini4Wall();
const booth4_d = buildMini4Wall();
booth4_a.scaling = new BABYLON.Vector3(bx,10,bz);
booth4_b.scaling = new BABYLON.Vector3(bx,10,bz);
booth4_c.scaling = new BABYLON.Vector3(bx,10,bz);
booth4_d.scaling = new BABYLON.Vector3(bx,10,bz);
booth4_a.position = new BABYLON.Vector3(w/5,5,h/6);
booth4_b.position = new BABYLON.Vector3(w/5,5,-h/6);
booth4_c.position = new BABYLON.Vector3(-w/5,5,h/6);
booth4_d.position = new BABYLON.Vector3(-w/5,5,-h/6);
}
const buildMini4Wall =()=>{
const kaf = BABYLON.MeshBuilder.CreateBox("box", {width: 3,height:0.15,depth:2, faceUV: faceUV, wrap: true});
kaf.position = new BABYLON.Vector3(0,-.5,0);
const of = BABYLON.MeshBuilder.CreateBox("box", {width: 3,height:1.5,depth:0.01, faceUV: faceUV, wrap: true});
const am1 = BABYLON.MeshBuilder.CreateBox("box", {width: 0.01,height:1.5,depth:2, faceUV: faceUV, wrap: true});
am1.position = new BABYLON.Vector3(.5,0,0);
const am2 = BABYLON.MeshBuilder.CreateBox("box", {width: 0.01,height:1.5,depth:2, faceUV: faceUV, wrap: true});
am2.position = new BABYLON.Vector3(-.5,0,0);
const sar = BABYLON.MeshBuilder.CreateBox("box", {width: 3,height:0.05,depth:2, faceUV: faceUV, wrap: true});
sar.position = new BABYLON.Vector3(0,0.75,0);
return BABYLON.Mesh.MergeMeshes([of,am1,am2,kaf,sar], false, false, null, false, false);
}
const build4Wall = (w,h,scene)=>{
let w_h = 30;
let w_w = w;
const wallMat = new BABYLON.StandardMaterial("boxMat");
wallMat.diffuseTexture = new BABYLON.Texture("img/w2.jpg");
//wallMat.diffuseColor = new BABYLON.Color3(255/255, 255/255, 255/255);
const seton_mat = new BABYLON.StandardMaterial("boxMat");
seton_mat.diffuseTexture = new BABYLON.Texture("img/concrete3.jpg");
const glassMat = new BABYLON.StandardMaterial("boxMat");
glassMat.diffuseColor = new BABYLON.Color3(220/255, 220/255, 220/255);
faceUV = [];
faceUV[0] = new BABYLON.Vector4(w/8, w_h/8, 1.0, 1.0); //front face
faceUV[1] = new BABYLON.Vector4(w/8, w_h/8, 1.0, 1.0); //front face
const wall_b_u = BABYLON.MeshBuilder.CreateBox("box", {width: w+2,height:w_h/4, faceUV: faceUV, wrap: true});
wall_b_u.material = wallMat;
wall_b_u.position = new BABYLON.Vector3(0,7*w_h/8,-h/2);
const wall_b_b = BABYLON.MeshBuilder.CreateBox("box", {width: w+2,height:w_h/2, faceUV: faceUV, wrap: true});
wall_b_b.material = wallMat;
wall_b_b.position = new BABYLON.Vector3(0,w_h/4,-h/2);
// const w_b = BABYLON.SceneLoader.ImportMesh("", "3d_models/", "triangle-window-glass.babylon", scene, function (meshes) {
// meshes[0].scaling = new BABYLON.Vector3(w/4, 1.5*w_h, 0.2);
// meshes[0].position = new BABYLON.Vector3(0,w_h/2,-h/2);
// });
const wall_f_u = BABYLON.MeshBuilder.CreateBox("box", {width: w,height:w_h/4, faceUV: faceUV, wrap: true});
wall_f_u.material = wallMat;
wall_f_u.position = new BABYLON.Vector3(0,7*w_h/8,h/2);
const wall_f_b = BABYLON.MeshBuilder.CreateBox("box", {width: w,height:w_h/2, faceUV: faceUV, wrap: true});
wall_f_b.material = wallMat;
wall_f_b.position = new BABYLON.Vector3(0,w_h/4,h/2);
const wall_l_r = BABYLON.MeshBuilder.CreateBox("box", {width: h,height:w_h,depth:1, faceUV: faceUV, wrap: true});
wall_l_r.material = wallMat;
wall_l_r.rotation = new BABYLON.Vector3(0,-Math.PI/2,0);
wall_l_r.position = new BABYLON.Vector3((w/2),(w_h/2),0);
const wall_l_l = BABYLON.MeshBuilder.CreateBox("box", {width: h,height:w_h, faceUV: faceUV, wrap: true});
wall_l_l.material = wallMat;
wall_l_l.rotation = new BABYLON.Vector3(0,Math.PI/2,0);
wall_l_l.position = new BABYLON.Vector3(-w/2,w_h/2,0);
const roofMat = new BABYLON.StandardMaterial("boxMat");
roofMat.diffuseTexture = new BABYLON.Texture("img/white-diamond.png");
const roof = BABYLON.MeshBuilder.CreateBox("box", {width: w,height:2,depth:h, faceUV: faceUV, wrap: true});
roof.material = roofMat;
roof.position = new BABYLON.Vector3(0,w_h+1,0);
const sotoonMat = new BABYLON.StandardMaterial("boxMat");
sotoonMat.diffuseColor = new BABYLON.Color3(180/255, 180/255, 180/255);
// BABYLON.SceneLoader.ImportMeshAsync("", "3d_models/", "door.babylon", scene,function (meshes) {
// meshes.forEach(mesh => {
// mesh.position = new BABYLON.Vector3(w/2,1,0);
// });
// });
let s_h =1.5;
const s1 = BABYLON.MeshBuilder.CreateBox("box", {width: w,height:s_h, wrap: true});
s1.position = new BABYLON.Vector3(0,w_h-s_h,0);
const s2 = BABYLON.MeshBuilder.CreateBox("box", {width: w,height:s_h, wrap: true});
s2.position = new BABYLON.Vector3(0,w_h-s_h,h/4);
const s3 = BABYLON.MeshBuilder.CreateBox("box", {width: w,height:s_h, wrap: true});
s3.position = new BABYLON.Vector3(0,w_h-s_h,h/2-1);
const s4 = BABYLON.MeshBuilder.CreateBox("box", {width: w,height:s_h, wrap: true});
s4.position = new BABYLON.Vector3(0,w_h-s_h,-h/4);
const s5 = BABYLON.MeshBuilder.CreateBox("box", {width: w,height:s_h, wrap: true});
s5.position = new BABYLON.Vector3(0,w_h-s_h,-h/2+1);
s1.material = s2.material = s3.material = s4.material = sotoonMat;
s_h = 2;
s_options = {width: s_h, height:4,depth:h, wrap: true};
const s6 = BABYLON.MeshBuilder.CreateBox("box", s_options);
s6.position = new BABYLON.Vector3(0,w_h-s_h/2,0);
const s7 = BABYLON.MeshBuilder.CreateBox("box", s_options);
s7.position = new BABYLON.Vector3(w/6,w_h-s_h/2,0);
const s8 = BABYLON.MeshBuilder.CreateBox("box", s_options);
s8.position = new BABYLON.Vector3(2*w/6,w_h-s_h/2,0);
const s9 = BABYLON.MeshBuilder.CreateBox("box", s_options);
s9.position = new BABYLON.Vector3(3*w/6,w_h-s_h/2,0);
const s10 = BABYLON.MeshBuilder.CreateBox("box",s_options);
s10.position = new BABYLON.Vector3(-w/6,w_h-s_h/2,0);
const s11 = BABYLON.MeshBuilder.CreateBox("box", s_options);
s11.position = new BABYLON.Vector3(-2*w/6,w_h-s_h/2,0);
const s12 = BABYLON.MeshBuilder.CreateBox("box", s_options);
s12.position = new BABYLON.Vector3(-3*w/6,w_h-s_h/2,0);
s6.material = s7.material = s8.material = s9.material = s10.material = s11.material = s12.material = sotoonMat;
//ستون
s_h=4;
c_options = {width: s_h, height:w_h,depth:2, wrap: true};
const c1 = BABYLON.MeshBuilder.CreateBox("box", c_options);
c1.position = new BABYLON.Vector3(w/2,w_h/2,-h/2+1);
const c2 = BABYLON.MeshBuilder.CreateBox("box", c_options);
c2.position = new BABYLON.Vector3(w/3,w_h/2,-h/2+1);
const c3 = BABYLON.MeshBuilder.CreateBox("box", c_options);
c3.position = new BABYLON.Vector3(w/6,w_h/2,-h/2+1);
const c4 = BABYLON.MeshBuilder.CreateBox("box", c_options);
c4.position = new BABYLON.Vector3(-w/6,w_h/2,-h/2+1);
const c5 = BABYLON.MeshBuilder.CreateBox("box", c_options);
c5.position = new BABYLON.Vector3(-w/3,w_h/2,-h/2+1);
const c6 = BABYLON.MeshBuilder.CreateBox("box", c_options);
c6.position = new BABYLON.Vector3(-w/2,w_h/2,-h/2+1);
const c7 = BABYLON.MeshBuilder.CreateBox("box", c_options);
c7.position = new BABYLON.Vector3(0,w_h/2,-h/2+1);
const c8 = BABYLON.MeshBuilder.CreateBox("box", c_options);
c8.position = new BABYLON.Vector3(-w/2,w_h/2,h/4-1);
const c9 = BABYLON.MeshBuilder.CreateBox("box", c_options);
c9.position = new BABYLON.Vector3(-w/2,w_h/2,-h/4-1);
const _c1 = BABYLON.MeshBuilder.CreateBox("box", c_options);
_c1.position = new BABYLON.Vector3(w/2,w_h/2,h/2-1);
const _c2 = BABYLON.MeshBuilder.CreateBox("box", c_options);
_c2.position = new BABYLON.Vector3(w/3,w_h/2,h/2-1);
const _c3 = BABYLON.MeshBuilder.CreateBox("box", c_options);
_c3.position = new BABYLON.Vector3(w/6,w_h/2,h/2-1);
const _c4 = BABYLON.MeshBuilder.CreateBox("box", c_options);
_c4.position = new BABYLON.Vector3(-w/6,w_h/2,h/2-1);
const _c5 = BABYLON.MeshBuilder.CreateBox("box", c_options);
_c5.position = new BABYLON.Vector3(-w/3,w_h/2,h/2-1);
const _c6 = BABYLON.MeshBuilder.CreateBox("box", c_options);
_c6.position = new BABYLON.Vector3(-w/2+1,w_h/2,h/2-1);
const _c7 = BABYLON.MeshBuilder.CreateBox("box", c_options);
_c7.position = new BABYLON.Vector3(0,w_h/2,h/2-1);
const _c8 = BABYLON.MeshBuilder.CreateBox("box", c_options);
_c8.position = new BABYLON.Vector3(w/2,w_h/2,h/4-1);
const _c9 = BABYLON.MeshBuilder.CreateBox("box", c_options);
_c9.position = new BABYLON.Vector3(w/2,w_h/2,-h/4-1);
c1.material = c2.material = c3.material = c4.material = c5.material = c6.material = c7.material =c8.material = c9.material= seton_mat;
_c1.material = _c2.material = _c3.material = _c4.material = _c5.material = _c6.material = _c7.material =_c8.material = _c9.material= seton_mat;
//پنجره
var window_y = 14.2;
const black = new BABYLON.StandardMaterial("boxMat");
black.diffuseColor = new BABYLON.Color3(220/255, 220/255, 230/255);
const w_1 =buildWindow(46,7,scene,black);
w_1.translate(new BABYLON.Vector3((-w/6)+(w/12),window_y,h/2), 1, BABYLON.Space.WORLD);
const w_2 =buildWindow(46,7,scene,black);
w_2.translate(new BABYLON.Vector3((w/6)-(w/12),window_y,h/2), 1, BABYLON.Space.WORLD);
const w_3 =buildWindow(46,7,scene,black);
w_3.translate(new BABYLON.Vector3((w/6)+(w/12),window_y,h/2), 1, BABYLON.Space.WORLD);
const w_4 =buildWindow(46,7,scene,black);
w_4.translate(new BABYLON.Vector3((-w/6)-(w/12),window_y,h/2), 1, BABYLON.Space.WORLD);
const w_5 =buildWindow(46,7,scene,black);
w_5.translate(new BABYLON.Vector3((-w/6)-3*(w/12),window_y,h/2), 1, BABYLON.Space.WORLD);
const w_6 =buildWindow(46,7,scene,black);
w_6.translate(new BABYLON.Vector3((w/6)+3*(w/12),window_y,h/2), 1, BABYLON.Space.WORLD);
const w_7 =buildWindow(46,7,scene,black);
w_7.translate(new BABYLON.Vector3((-w/6)+(w/12),window_y,-h/2), 1, BABYLON.Space.WORLD);
const w_8 =buildWindow(46,7,scene,black);
w_8.translate(new BABYLON.Vector3((w/6)-(w/12),window_y,-h/2), 1, BABYLON.Space.WORLD);
const w_9 =buildWindow(46,7,scene,black);
w_9.translate(new BABYLON.Vector3((w/6)+(w/12),window_y,-h/2), 1, BABYLON.Space.WORLD);
const w_10 =buildWindow(46,7,scene,black);
w_10.translate(new BABYLON.Vector3((-w/6)-(w/12),window_y,-h/2), 1, BABYLON.Space.WORLD);
const w_11 =buildWindow(46,7,scene,black);
w_11.translate(new BABYLON.Vector3((-w/6)-3*(w/12),window_y,-h/2), 1, BABYLON.Space.WORLD);
const w_12 =buildWindow(46,7,scene,black);
w_12.translate(new BABYLON.Vector3((w/6)+3*(w/12),window_y,-h/2), 1, BABYLON.Space.WORLD);
}
const ceiling_box = (w,h,scene)=>{
const roof_mat = new BABYLON.StandardMaterial("boxMat");
roof_mat.diffuseTexture = new BABYLON.Texture("img/Sol.jpg");
options = {width:w-1,height:1,depth:h-1};
const b0 = BABYLON.MeshBuilder.CreateBox("box", options);
b0.material = roof_mat;
const b1 = BABYLON.MeshBuilder.CreateBox("box", options);
b1.position = new BABYLON.Vector3(w,0,-h);
const b2 = BABYLON.MeshBuilder.CreateBox("box", options);
b2.position = new BABYLON.Vector3(0,0,-h);
const b3 = BABYLON.MeshBuilder.CreateBox("box", options);
b3.position = new BABYLON.Vector3(-w,0,-h);
const b4 = BABYLON.MeshBuilder.CreateBox("box", options);
b4.position = new BABYLON.Vector3(-w,0,0);
const b5 = BABYLON.MeshBuilder.CreateBox("box", options);
b5.position = new BABYLON.Vector3(-w,0,h);
const b6 = BABYLON.MeshBuilder.CreateBox("box", options);
b6.position = new BABYLON.Vector3(0,0,h);
const b7 = BABYLON.MeshBuilder.CreateBox("box", options);
b7.position = new BABYLON.Vector3(w,0,0);
const b8 = BABYLON.MeshBuilder.CreateBox("box", options);
b8.position = new BABYLON.Vector3(w,0,h);
const l1 = buildHallLamp(1,1,scene,"White");
l1.position = new BABYLON.Vector3(0,-6,0);
return BABYLON.Mesh.MergeMeshes([b0,b1,b2,b3,b4,b5,b6,b7,b8,l1], true, false, null, false, true);
}
const ceiling = (w,h,scene)=>{
let w_h = 29;
ce_w = (w/6)/3;
ce_h = (h/4)/3;
const ce_1 = ceiling_box(ce_w,ce_h,scene);
ce_1.position = new BABYLON.Vector3(3*ce_w/2,w_h,3*ce_h/2);
const ce_2 = ceiling_box(ce_w,ce_h,scene);
ce_2.position = new BABYLON.Vector3(-3*ce_w/2,w_h,-3*ce_h/2);
const ce_3 = ceiling_box(ce_w,ce_h,scene);
ce_3.position = new BABYLON.Vector3(-3*ce_w/2,w_h,3*ce_h/2);
const ce_4 = ceiling_box(ce_w,ce_h,scene);
ce_4.position = new BABYLON.Vector3(3*ce_w/2,w_h,-3*ce_h/2);
const ce_5 = ceiling_box(ce_w,ce_h,scene);
ce_5.position = new BABYLON.Vector3(9*ce_w/2,w_h,-3*ce_h/2);
const ce_6 = ceiling_box(ce_w,ce_h,scene);
ce_6.position = new BABYLON.Vector3(9*ce_w/2,w_h,+3*ce_h/2);
const ce_7 = ceiling_box(ce_w,ce_h,scene);
ce_7.position = new BABYLON.Vector3(9*ce_w/2,w_h,+9*ce_h/2);
const ce_8 = ceiling_box(ce_w,ce_h,scene);
ce_8.position = new BABYLON.Vector3(9*ce_w/2,w_h,-9*ce_h/2);
const ce_9 = ceiling_box(ce_w,ce_h,scene);
ce_9.position = new BABYLON.Vector3(-9*ce_w/2,w_h,-3*ce_h/2);
const ce_10 = ceiling_box(ce_w,ce_h,scene);
ce_10.position = new BABYLON.Vector3(-9*ce_w/2,w_h,+3*ce_h/2);
const ce_11 = ceiling_box(ce_w,ce_h,scene);
ce_11.position = new BABYLON.Vector3(-9*ce_w/2,w_h,+9*ce_h/2);
const ce_12 = ceiling_box(ce_w,ce_h,scene);
ce_12.position = new BABYLON.Vector3(-9*ce_w/2,w_h,-9*ce_h/2);
const ce_13 = ceiling_box(ce_w,ce_h,scene);
ce_13.position = new BABYLON.Vector3(-15*ce_w/2,w_h,-3*ce_h/2);
const ce_14 = ceiling_box(ce_w,ce_h,scene);
ce_14.position = new BABYLON.Vector3(-15*ce_w/2,w_h,+3*ce_h/2);
const ce_15 = ceiling_box(ce_w,ce_h,scene);
ce_15.position = new BABYLON.Vector3(-15*ce_w/2,w_h,+9*ce_h/2);
const ce_16 = ceiling_box(ce_w,ce_h,scene);
ce_16.position = new BABYLON.Vector3(-15*ce_w/2,w_h,-9*ce_h/2);
const ce_17 = ceiling_box(ce_w,ce_h,scene);
ce_17.position = new BABYLON.Vector3(15*ce_w/2,w_h,-3*ce_h/2);
const ce_18 = ceiling_box(ce_w,ce_h,scene);
ce_18.position = new BABYLON.Vector3(15*ce_w/2,w_h,+3*ce_h/2);
const ce_19 = ceiling_box(ce_w,ce_h,scene);
ce_19.position = new BABYLON.Vector3(15*ce_w/2,w_h,+9*ce_h/2);
const ce_20 = ceiling_box(ce_w,ce_h,scene);
ce_20.position = new BABYLON.Vector3(15*ce_w/2,w_h,-9*ce_h/2);
const ce_21 = ceiling_box(ce_w,ce_h,scene);
ce_21.position = new BABYLON.Vector3(3*ce_w/2,w_h,9*ce_h/2);
const ce_22 = ceiling_box(ce_w,ce_h,scene);
ce_22.position = new BABYLON.Vector3(-3*ce_w/2,w_h,-9*ce_h/2);
const ce_23 = ceiling_box(ce_w,ce_h,scene);
ce_23.position = new BABYLON.Vector3(-3*ce_w/2,w_h,9*ce_h/2);
const ce_24 = ceiling_box(ce_w,ce_h,scene);
ce_24.position = new BABYLON.Vector3(3*ce_w/2,w_h,-9*ce_h/2);
}
const build3gosh = (w,h,d) =>{
var kaf0 = BABYLON.MeshBuilder.CreateBox("box", { width:d,height:0.5,depth:d});
kaf0.position =new BABYLON.Vector3(d/2,0.5,d/2)
var kaf1 = BABYLON.MeshBuilder.CreateBox("box", { width:w,height:0.5,depth:d});
kaf1.position =new BABYLON.Vector3(-w/2,0.5,d/2)
var kaf2 = BABYLON.MeshBuilder.CreateBox("box", { width:h,height:0.5,depth:d});
kaf2.position =new BABYLON.Vector3(d/2,0.5,-h/2);
kaf2.rotation =new BABYLON.Vector3(0,Math.PI/2,0);
return BABYLON.Mesh.MergeMeshes(
[kaf0,kaf1,kaf2]
, true, false, null, false, true);
}
function showWorldAxis(size,scene) {
var makeTextPlane = function(text, color, size) {
var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", 50, scene, true);
dynamicTexture.hasAlpha = true;
dynamicTexture.drawText(text, 5, 40, "bold 36px Arial", color , "transparent", true);
var plane = BABYLON.Mesh.CreatePlane("TextPlane", size, scene, true);
plane.material = new BABYLON.StandardMaterial("TextPlaneMaterial", scene);
plane.material.backFaceCulling = false;
plane.material.specularColor = new BABYLON.Color3(0, 0, 0);
plane.material.diffuseTexture = dynamicTexture;
return plane;
};
var axisX = BABYLON.Mesh.CreateLines("axisX", [
BABYLON.Vector3.Zero(), new BABYLON.Vector3(size, 0, 0), new BABYLON.Vector3(size * 0.95, 0.05 * size, 0),
new BABYLON.Vector3(size, 0, 0), new BABYLON.Vector3(size * 0.95, -0.05 * size, 0)
], scene);
axisX.color = new BABYLON.Color3(1, 0, 0);
var xChar = makeTextPlane("X", "red", size / 10);
xChar.position = new BABYLON.Vector3(0.9 * size, -0.05 * size, 0);
var axisY = BABYLON.Mesh.CreateLines("axisY", [
BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, size, 0), new BABYLON.Vector3( -0.05 * size, size * 0.95, 0),
new BABYLON.Vector3(0, size, 0), new BABYLON.Vector3( 0.05 * size, size * 0.95, 0)
], scene);
axisY.color = new BABYLON.Color3(0, 1, 0);
var yChar = makeTextPlane("Y", "green", size / 10);
yChar.position = new BABYLON.Vector3(0, 0.9 * size, -0.05 * size);
var axisZ = BABYLON.Mesh.CreateLines("axisZ", [
BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, size), new BABYLON.Vector3( 0 , -0.05 * size, size * 0.95),
new BABYLON.Vector3(0, 0, size), new BABYLON.Vector3( 0, 0.05 * size, size * 0.95)
], scene);
axisZ.color = new BABYLON.Color3(0, 0, 1);
var zChar = makeTextPlane("Z", "blue", size / 10);
zChar.position = new BABYLON.Vector3(0, 0.05 * size, 0.9 * size);
}
const BuildBooth_gosh = (w,h,d,scene,color) =>{
const gray = new BABYLON.StandardMaterial("boxMat");
gray.diffuseColor = new BABYLON.Color3(236/255, 240/255, 241/255);
const kaf = build3gosh(w,h,d);
const sar_0 = build3gosh(w-.5,h-.5,d-.5);
sar_0.position = new BABYLON.Vector3(0,7.5,0);
const sar_1 = build3gosh(w-1,h-1,d-1);
sar_1.scaling = new BABYLON.Vector3(1,3,1);
sar_1.position = new BABYLON.Vector3(0,7.5,0);
sar_1.material = color;
const sar_2 = build3gosh(w-.5,h-.5,d-.5);
sar_2.position = new BABYLON.Vector3(0,9.5,0);
return BABYLON.Mesh.MergeMeshes(
[kaf,sar_2,sar_1,sar_0]
, true, false, null, false, true);
}
const build_bro = (w,h,link,color,scene) =>{
const bro = BABYLON.MeshBuilder.CreateBox("box", {});
bro.scaling = new BABYLON.Vector3(3,2,0.1);
bro.position= new BABYLON.Vector3(0,8,0);
bro.material = color;
bro.actionManager = new BABYLON.ActionManager(scene);
bro.actionManager.registerAction(
new BABYLON.ExecuteCodeAction(
BABYLON.ActionManager.OnPickUpTrigger,
function () {
alert("this");
}
)
);
return BABYLON.Mesh.MergeMeshes(
[bro]
, true, false, null, false, true);
}
const BuildBooth_1 = (w,h,scene,color) =>{
const gray = new BABYLON.StandardMaterial("boxMat");
gray.diffuseColor = new BABYLON.Color3(236/255, 240/255, 241/255);
var kaf = BABYLON.MeshBuilder.CreateBox("box", { width:w,height:0.5,depth:h}, scene);
kaf.position.y = 0.5;
kaf.material = gray;
var w1 = BABYLON.MeshBuilder.CreateBox("box", { width:0.1,height:10,depth:h}, scene);
w1.position.x = w/2;
w1.position.y = 5;
var w2 = BABYLON.MeshBuilder.CreateBox("box", { width:0.1,height:10,depth:h}, scene);
w2.position.x = -w/2;
w2.position.y = 5;
const backMat = new BABYLON.StandardMaterial("boxMat");
backMat.diffuseTexture = new BABYLON.Texture("img/b1/back.jpg");
var back = BABYLON.MeshBuilder.CreateBox("box", { width:w,height:10,depth:.1}, scene);
back.position.z = h/2-1;
back.position.y = 5;
back.material = backMat;
//desk1
const logo = new BABYLON.StandardMaterial("boxMat");
logo.diffuseTexture = new BABYLON.Texture("img/b1/logo.jpg");
const desk1= BuildDesk_2(3,3,scene,color,logo);
desk1.translate(new BABYLON.Vector3(-w/2+3,0,-h/2+1), 1, BABYLON.Space.WORLD);
const desk2= BuildDesk_2(8,3,scene,color,logo);
desk2.translate(new BABYLON.Vector3(0,0,-h/2+1), 1, BABYLON.Space.WORLD);
const desk3= BuildDesk_2(3,3,scene,color,logo);
desk3.translate(new BABYLON.Vector3(w/2-3,0,-h/2+1), 1, BABYLON.Space.WORLD);
var top_a= BABYLON.MeshBuilder.CreateBox("box", { width:w+1,height:0.2,depth:h+1}, scene);
top_a.position = new BABYLON.Vector3(0,11.6,0);
top_a.material = gray;
const Banner = new BABYLON.StandardMaterial("boxMat");
Banner.diffuseTexture = new BABYLON.Texture("img/b1/banner.jpg");
var top_b= BABYLON.MeshBuilder.CreateBox("box", { width:w,height:2.5,depth:h}, scene);
top_b.position = new BABYLON.Vector3(0,10,0);
top_b.material = Banner;
var top_c= BABYLON.MeshBuilder.CreateBox("box", { width:w+1,height:0.2,depth:h+1}, scene);
top_c.position = new BABYLON.Vector3(0,8.6,0);
top_c.material = gray;
const p1 = new BABYLON.StandardMaterial("boxMat");
p1.diffuseTexture = new BABYLON.Texture("img/b1/p1.jpg");
const stand1 = BuildStand_1(2,2,scene,color,p1);
stand1.translate(new BABYLON.Vector3(w/4,0,-h/2+2), 1, BABYLON.Space.WORLD);
const p2 = new BABYLON.StandardMaterial("boxMat");
p2.diffuseTexture = new BABYLON.Texture("img/b1/p2.jpg");
const stand2 = BuildStand_1(2,2,scene,color,p2);
stand2.translate(new BABYLON.Vector3(-w/4,0,-h/2+2), 1, BABYLON.Space.WORLD);
return BABYLON.Mesh.MergeMeshes(
[kaf,top_a,top_b,top_c,desk1,desk2,desk3,stand1,stand2,w1,w2,back]
, true, false, null, false, true);
}
const BuildBooth_2 = (w,h,scene,color) =>{
const gray = new BABYLON.StandardMaterial("boxMat");
gray.diffuseColor = new BABYLON.Color3(236/255, 240/255, 241/255);
// const faceUV = [];
// for(var i=0;i<=5;i++){
// faceUV[i] = new BABYLON.Vector4(0.0, 0.0, 0.0, 1.0); //front face
// }
// faceUV[5] = new BABYLON.Vector4(0.0, 0, 1.0, 1.0);
// const kafMat = new BABYLON.StandardMaterial("boxMat");
// kafMat.diffuseTexture = new BABYLON.Texture("img/ar.jpeg");
var kafMat = new BABYLON.StandardMaterial("mat", scene);
var texture = new BABYLON.Texture("img/diamond-upholstery.png", scene);
kafMat.diffuseTexture = texture;
kafMat.diffuseTexture.uScale =8;
kafMat.diffuseTexture.vScale = 8;
var faceUV = new Array(6);
faceUV[5] = new BABYLON.Vector4(1, 0, 0, 1);
var kaf = BABYLON.MeshBuilder.CreateBox("box", { width:w,height:0.5,depth:h ,faceUV: faceUV, wrap: true}, scene);
kaf.position.y = 0.5;
kaf.material = kafMat;
var w1 = BABYLON.MeshBuilder.CreateBox("box", { width:0.1,height:10,depth:h}, scene);
w1.position.x = w/2;
w1.position.y = 5;
w1.material = gray;
var w2 = BABYLON.MeshBuilder.CreateBox("box", { width:0.1,height:10,depth:h}, scene);
w2.position.x = -w/2;
w2.position.y = 5;
w2.material = gray;
const backMat = new BABYLON.StandardMaterial("boxMat");
backMat.diffuseTexture = new BABYLON.Texture("img/b2/back.jpg");
var back = BABYLON.MeshBuilder.CreateBox("box", { width:w,height:10,depth:.1}, scene);
back.position.z = h/2-1;
back.position.y = 5;
back.material = backMat;
//desk1
const logo = new BABYLON.StandardMaterial("boxMat");
logo.diffuseTexture = new BABYLON.Texture("img/b2/logo.jpg");
const desk2= BuildDesk_2(8,3,scene,color,logo);
desk2.translate(new BABYLON.Vector3(0,0,-h/2+1), 1, BABYLON.Space.WORLD);
var top_a= BABYLON.MeshBuilder.CreateBox("box", { width:w+1,height:0.2,depth:h+1}, scene);
top_a.position = new BABYLON.Vector3(0,11.6,0);
top_a.material = gray;
const Banner = new BABYLON.StandardMaterial("boxMat");
Banner.diffuseTexture = new BABYLON.Texture("img/b2/banner.jpg");
var top_b= BABYLON.MeshBuilder.CreateBox("box", { width:w,height:2.5,depth:h}, scene);
top_b.position = new BABYLON.Vector3(0,10,0);
top_b.material = Banner;
var top_c= BABYLON.MeshBuilder.CreateBox("box", { width:w+1,height:0.2,depth:h+1}, scene);
top_c.position = new BABYLON.Vector3(0,8.6,0);
top_c.material = gray;
const s1 = new BABYLON.StandardMaterial("boxMat");
s1.diffuseTexture = new BABYLON.Texture("img/b2/s1.jpg");
const stand1 = BuildStand_2(3,5,scene,color,s1);
stand1.translate(new BABYLON.Vector3(w/3,0,-h/2+2), 1, BABYLON.Space.WORLD);
const s2 = new BABYLON.StandardMaterial("boxMat");
s2.diffuseTexture = new BABYLON.Texture("img/b2/s2.jpg");
const stand2 = BuildStand_2(3,5,scene,color,s2);
stand2.translate(new BABYLON.Vector3(-w/3,0,-h/2+2), 1, BABYLON.Space.WORLD);
return BABYLON.Mesh.MergeMeshes(
[kaf,top_a,top_b,top_c,desk2,stand1,stand2,w1,w2,back]
, true, false, null, false, true);
}
const BuildBooth_3 = (w,h,d,scene,color) =>{
const gray = new BABYLON.StandardMaterial("boxMat");
gray.diffuseColor = new BABYLON.Color3(236/255, 240/255, 241/255);
const kaf = build3gosh(w,h,d);
kaf.material = gray;
const sar_0 = build3gosh(w-1,h-1,d+0.5);
sar_0.position = new BABYLON.Vector3(-0.5,8.5,-.5);
sar_0.scaling = new BABYLON.Vector3(1,.5,1);
const sar_1 = build3gosh(w,h,d);
sar_1.scaling = new BABYLON.Vector3(1,5,1);
sar_1.position = new BABYLON.Vector3(0,7.5,0);
const Banner = new BABYLON.StandardMaterial("boxMat");
Banner.diffuseTexture = new BABYLON.Texture("img/b3/banner.jpg");
sar_1.material = Banner;
const sar_2 = build3gosh(w-1,h-1,d+0.5);
sar_2.position = new BABYLON.Vector3(-0.5,11.3,-.5);
sar_2.scaling = new BABYLON.Vector3(1,.5,1);
const logo = new BABYLON.StandardMaterial("boxMat");
logo.diffuseTexture = new BABYLON.Texture("img/b3/logo.jpg");
const desk1= BuildDesk_2(6,3,scene,color,logo);
desk1.translate(new BABYLON.Vector3(-w/2,0,+1), 1, BABYLON.Space.WORLD);
const desk2= BuildDesk_2(3,3,scene,color,logo);
desk2.translate(new BABYLON.Vector3(1,0,-h/2), 1, BABYLON.Space.WORLD);
desk2.rotation = new BABYLON.Vector3(0,Math.PI/2,0);
const p2 = new BABYLON.StandardMaterial("boxMat");
p2.diffuseTexture = new BABYLON.Texture("img/b3/p2.jpg");
const stand2 = BuildStand_1(2,2,scene,color,p2);
stand2.translate(new BABYLON.Vector3(-5*w/6,0,1), 1, BABYLON.Space.WORLD);
const p1 = new BABYLON.StandardMaterial("boxMat");
p1.diffuseTexture = new BABYLON.Texture("img/b3/p1.jpg");
const stand1 = BuildStand_1(2,2,scene,color,p1);
stand1.translate(new BABYLON.Vector3(1,0,-3*h/4), 1, BABYLON.Space.WORLD);
stand1.rotation = new BABYLON.Vector3(0,Math.PI/2,0);
const p4 = new BABYLON.StandardMaterial("boxMat");
p4.diffuseTexture = new BABYLON.Texture("img/b3/p4.jpg");
const stand4 = BuildStand_1(2,2,scene,color,p4);
stand4.translate(new BABYLON.Vector3(1,0,-1*h/4), 1, BABYLON.Space.WORLD);
stand4.rotation = new BABYLON.Vector3(0,Math.PI/2,0);
const p3 = new BABYLON.StandardMaterial("boxMat");
p3.diffuseTexture = new BABYLON.Texture("img/b3/p3.jpg");
const stand3 = BuildStand_1(2,2,scene,color,p3);
stand3.translate(new BABYLON.Vector3(-1*w/6,0,1), 1, BABYLON.Space.WORLD);
return BABYLON.Mesh.MergeMeshes(
[kaf,sar_2,sar_1,desk1,desk2,stand1,stand3,sar_0,stand2,stand4]
, true, false, null, false, true);
}
const BuildBooth_4 = (w,h,scene,color) =>{
const gray = new BABYLON.StandardMaterial("boxMat");
gray.diffuseColor = new BABYLON.Color3(236/255, 240/255, 241/255);
var kaf = BABYLON.MeshBuilder.CreateBox("box", { width:w,height:0.5,depth:h}, scene);
kaf.position.y = 0.5;
kaf.material = gray;
var w1 = BABYLON.MeshBuilder.CreateBox("box", { width:0.1,height:10,depth:h}, scene);
w1.position.x = w/2;
w1.position.y = 5;
var w2 = BABYLON.MeshBuilder.CreateBox("box", { width:0.1,height:10,depth:h}, scene);
w2.position.x = -w/2;
w2.position.y = 5;
const backMat = new BABYLON.StandardMaterial("boxMat");
backMat.diffuseTexture = new BABYLON.Texture("img/b4/back.jpg");
var back = BABYLON.MeshBuilder.CreateBox("box", { width:w,height:10,depth:.1}, scene);
back.position.z = h/2-1;
back.position.y = 5;
back.material = backMat;
//desk1
const logo = new BABYLON.StandardMaterial("boxMat");
logo.diffuseTexture = new BABYLON.Texture("img/b4/logo.png");
const desk1= BuildDesk_2(3,3,scene,color,logo);
desk1.translate(new BABYLON.Vector3(-w/2+3,0,-h/2+1), 1, BABYLON.Space.WORLD);
var top_a= BABYLON.MeshBuilder.CreateBox("box", { width:w+1,height:0.2,depth:h+1}, scene);
top_a.position = new BABYLON.Vector3(0,11.6,0);
top_a.material = gray;
const Banner = new BABYLON.StandardMaterial("boxMat");
Banner.diffuseTexture = new BABYLON.Texture("img/b4/banner.jpg");
var top_b= BABYLON.MeshBuilder.CreateBox("box", { width:w,height:2.5,depth:h}, scene);
top_b.position = new BABYLON.Vector3(0,10,0);
top_b.material = Banner;
var top_c= BABYLON.MeshBuilder.CreateBox("box", { width:w+1,height:0.2,depth:h+1}, scene);
top_c.position = new BABYLON.Vector3(0,8.6,0);
top_c.material = gray;
const s1 = new BABYLON.StandardMaterial("boxMat");
s1.diffuseTexture = new BABYLON.Texture("img/b4/s1.jpg");
const stand1 = BuildStand_2(3,5,scene,color,s1);
stand1.translate(new BABYLON.Vector3(w/3,0,-h/2+2), 1, BABYLON.Space.WORLD);
return BABYLON.Mesh.MergeMeshes(
[kaf,top_a,top_b,top_c,desk1,w1,w2,back,stand1]
, true, false, null, false, true);
}
const BuildBooth_5 = (w,h,scene,color) =>{
const gray = new BABYLON.StandardMaterial("boxMat");
gray.diffuseColor = new BABYLON.Color3(236/255, 240/255, 241/255);
var kaf = BABYLON.MeshBuilder.CreateBox("box", { width:w,height:0.5,depth:h}, scene);
kaf.position.y = 0.5;
kaf.material = gray;
var w1 = BABYLON.MeshBuilder.CreateBox("box", { width:0.1,height:10,depth:h}, scene);
w1.position.x = w/2;
w1.position.y = 5;
var w2 = BABYLON.MeshBuilder.CreateBox("box", { width:0.1,height:10,depth:h}, scene);
w2.position.x = -w/2;
w2.position.y = 5;
const backMat = new BABYLON.StandardMaterial("boxMat");
backMat.diffuseTexture = new BABYLON.Texture("img/b5/back.jpg");
var back = BABYLON.MeshBuilder.CreateBox("box", { width:w,height:10,depth:.1}, scene);
back.position.z = h/2-1;
back.position.y = 5;
back.material = backMat;
//desk1
const logo = new BABYLON.StandardMaterial("boxMat");
logo.diffuseTexture = new BABYLON.Texture("img/b5/logo.png");
var top_a= BABYLON.MeshBuilder.CreateBox("box", { width:w+1,height:0.2,depth:h+1}, scene);
top_a.position = new BABYLON.Vector3(0,11.6,0);
top_a.material = gray;
const Banner = new BABYLON.StandardMaterial("boxMat");
Banner.diffuseTexture = new BABYLON.Texture("img/b5/banner.jpg");
var top_b= BABYLON.MeshBuilder.CreateBox("box", { width:w,height:2.5,depth:h}, scene);
top_b.position = new BABYLON.Vector3(0,10,0);
top_b.material = Banner;
var top_c= BABYLON.MeshBuilder.CreateBox("box", { width:w+1,height:0.2,depth:h+1}, scene);
top_c.position = new BABYLON.Vector3(0,8.6,0);
top_c.material = gray;
const s1 = new BABYLON.StandardMaterial("boxMat");
s1.diffuseTexture = new BABYLON.Texture("img/b5/s1.jpg");
const stand1 = BuildStand_2(3,5,scene,color,s1);
stand1.translate(new BABYLON.Vector3(w/3,0,-h/2+2), 1, BABYLON.Space.WORLD);
const s2 = new BABYLON.StandardMaterial("boxMat");
s2.diffuseTexture = new BABYLON.Texture("img/b5/s2.jpg");
const stand2 = BuildStand_2(3,5,scene,color,s2);
stand2.translate(new BABYLON.Vector3(-w/3,0,-h/2+2), 1, BABYLON.Space.WORLD);
return BABYLON.Mesh.MergeMeshes(
[kaf,top_a,top_b,top_c,stand2,w1,w2,back,stand1]
, true, false, null, false, true);
}
const BuildBooth_6 = (w,h,d,scene,color) =>{
const gray = new BABYLON.StandardMaterial("boxMat");
gray.diffuseColor = new BABYLON.Color3(236/255, 240/255, 241/255);
const kaf = build3gosh(w,h,d);
kaf.material = gray;
const sar_0 = build3gosh(w-1,h-1,d+0.5);
sar_0.position = new BABYLON.Vector3(-0.5,8.5,-.5);
sar_0.scaling = new BABYLON.Vector3(1,.5,1);
const sar_1 = build3gosh(w,h,d);
sar_1.scaling = new BABYLON.Vector3(1,5,1);
sar_1.position = new BABYLON.Vector3(0,7.5,0);
const Banner = new BABYLON.StandardMaterial("boxMat");
Banner.diffuseTexture = new BABYLON.Texture("img/b6/banner.jpg");
sar_1.material = Banner;
const sar_2 = build3gosh(w-1,h-1,d+0.5);
sar_2.position = new BABYLON.Vector3(-0.5,11.3,-.5);
sar_2.scaling = new BABYLON.Vector3(1,.5,1);
const logo = new BABYLON.StandardMaterial("boxMat");
logo.diffuseTexture = new BABYLON.Texture("img/b6/logo.jpg");
const desk1= BuildDesk_2(6,3,scene,color,logo);
desk1.translate(new BABYLON.Vector3(-w/2,0,+1), 1, BABYLON.Space.WORLD);
const desk2= BuildDesk_2(3,3,scene,color,logo);
desk2.translate(new BABYLON.Vector3(1,0,-h/2), 1, BABYLON.Space.WORLD);
desk2.rotation = new BABYLON.Vector3(0,Math.PI/2,0);
const p2 = new BABYLON.StandardMaterial("boxMat");
p2.diffuseTexture = new BABYLON.Texture("img/b6/p2.jpg");
const stand2 = BuildStand_1(2,2,scene,color,p2);
stand2.translate(new BABYLON.Vector3(-5*w/6,0,1), 1, BABYLON.Space.WORLD);
const p1 = new BABYLON.StandardMaterial("boxMat");
p1.diffuseTexture = new BABYLON.Texture("img/b6/p1.jpg");
const stand1 = BuildStand_1(2,2,scene,color,p1);
stand1.translate(new BABYLON.Vector3(1,0,-3*h/4), 1, BABYLON.Space.WORLD);
stand1.rotation = new BABYLON.Vector3(0,Math.PI/2,0);
const p4 = new BABYLON.StandardMaterial("boxMat");
p4.diffuseTexture = new BABYLON.Texture("img/b6/p4.jpg");
const stand4 = BuildStand_1(2,2,scene,color,p4);
stand4.translate(new BABYLON.Vector3(1,0,-1*h/4), 1, BABYLON.Space.WORLD);
stand4.rotation = new BABYLON.Vector3(0,Math.PI/2,0);
const p3 = new BABYLON.StandardMaterial("boxMat");
p3.diffuseTexture = new BABYLON.Texture("img/b6/p3.jpg");
const stand3 = BuildStand_1(2,2,scene,color,p3);
stand3.translate(new BABYLON.Vector3(-1*w/6,0,1), 1, BABYLON.Space.WORLD);
return BABYLON.Mesh.MergeMeshes(
[kaf,sar_2,sar_1,desk1,desk2,stand1,stand3,sar_0,stand2,stand4]
, true, false, null, false, true);
}
const BuildBooth_7 = (w,h,scene,color) =>{
const gray = new BABYLON.StandardMaterial("boxMat");
gray.diffuseColor = new BABYLON.Color3(236/255, 240/255, 241/255);
var kaf = BABYLON.MeshBuilder.CreateBox("box", { width:w,height:0.5,depth:h}, scene);
kaf.position.y = 0.5;
kaf.material = gray;
var w1 = BABYLON.MeshBuilder.CreateBox("box", { width:0.1,height:10,depth:h}, scene);
w1.position.x = w/2;
w1.position.y = 5;
var w2 = BABYLON.MeshBuilder.CreateBox("box", { width:0.1,height:10,depth:h}, scene);
w2.position.x = -w/2;
w2.position.y = 5;
const backMat = new BABYLON.StandardMaterial("boxMat");
backMat.diffuseTexture = new BABYLON.Texture("img/b7/back.jpg");
var back = BABYLON.MeshBuilder.CreateBox("box", { width:w,height:10,depth:.1}, scene);
back.position.z = h/2-1;
back.position.y = 5;
back.material = backMat;
//desk1
const logo = new BABYLON.StandardMaterial("boxMat");
logo.diffuseTexture = new BABYLON.Texture("img/b7/logo.jpg");
const desk2= BuildDesk_2(5,3,scene,color,logo);
desk2.translate(new BABYLON.Vector3(0,0,-h/2+1), 1, BABYLON.Space.WORLD);
var top_a= BABYLON.MeshBuilder.CreateBox("box", { width:w+1,height:0.2,depth:h+1}, scene);
top_a.position = new BABYLON.Vector3(0,11.6,0);
top_a.material = gray;
const Banner = new BABYLON.StandardMaterial("boxMat");
Banner.diffuseTexture = new BABYLON.Texture("img/b7/banner.jpg");
var top_b= BABYLON.MeshBuilder.CreateBox("box", { width:w,height:2.5,depth:h}, scene);
top_b.position = new BABYLON.Vector3(0,10,0);
top_b.material = Banner;
var top_c= BABYLON.MeshBuilder.CreateBox("box", { width:w+1,height:0.2,depth:h+1}, scene);
top_c.position = new BABYLON.Vector3(0,8.6,0);
top_c.material = gray;
const s1 = new BABYLON.StandardMaterial("boxMat");
s1.diffuseTexture = new BABYLON.Texture("img/b7/s1.jpg");
const stand1 = BuildStand_1(2,2,scene,color,s1);
stand1.translate(new BABYLON.Vector3(5,0,-h/2+2), 1, BABYLON.Space.WORLD);
const s2 = new BABYLON.StandardMaterial("boxMat");
s2.diffuseTexture = new BABYLON.Texture("img/b7/s2.jpg");
const stand2 = BuildStand_1(2,2,scene,color,s2);
stand2.translate(new BABYLON.Vector3(-5,0,-h/2+2), 1, BABYLON.Space.WORLD);
const faceUV = [];
for(var i=0;i<=5;i++){
faceUV[i] = new BABYLON.Vector4(0.0, 0.0, 0.0, 1.0); //front face
}
faceUV[1] = new BABYLON.Vector4(0.0, 0, 1.0, 1.0);
const p1Mat = new BABYLON.StandardMaterial("boxMat");
p1Mat.diffuseTexture = new BABYLON.Texture("img/b7/p1.jpg");
var p1= BABYLON.MeshBuilder.CreateBox("box", { width:2,height:3,depth:2, faceUV: faceUV, wrap: true}, scene);
p1.position = new BABYLON.Vector3(10,2.5,-h/2+2);
p1.material = p1Mat;
const p2Mat = new BABYLON.StandardMaterial("boxMat");
p2Mat.diffuseTexture = new BABYLON.Texture("img/b7/p2.jpg");
var p2= BABYLON.MeshBuilder.CreateBox("box", { width:2,height:3,depth:2, faceUV: faceUV, wrap: true}, scene);
p2.position = new BABYLON.Vector3(15,2.5,-h/2+2);
p2.material = p2Mat;
const p3Mat = new BABYLON.StandardMaterial("boxMat");
p3Mat.diffuseTexture = new BABYLON.Texture("img/b7/p3.jpg");
var p3= BABYLON.MeshBuilder.CreateBox("box", { width:3,height:3,depth:2, faceUV: faceUV, wrap: true}, scene);
p3.position = new BABYLON.Vector3(-10,2.5,-h/2+2);
p3.material = p3Mat;
const p4Mat = new BABYLON.StandardMaterial("boxMat");
p4Mat.diffuseTexture = new BABYLON.Texture("img/b7/p4.jpg");
var p4= BABYLON.MeshBuilder.CreateBox("box", { width:3,height:3,depth:2, faceUV: faceUV, wrap: true}, scene);
p4.position = new BABYLON.Vector3(-15,2.5,-h/2+2);
p4.material = p4Mat;
return BABYLON.Mesh.MergeMeshes(
[kaf,top_a,top_b,top_c,desk2,stand1,stand2,w1,w2,back,p1,p2,p3,p4]
, true, false, null, false, true);
}
const BuildBooth_8 = (w,h,scene,color) =>{
const gray = new BABYLON.StandardMaterial("boxMat");
gray.diffuseColor = new BABYLON.Color3(236/255, 240/255, 241/255);
var kaf = BABYLON.MeshBuilder.CreateBox("box", { width:w,height:0.5,depth:h}, scene);
kaf.position.y = 0.5;
kaf.material = gray;
var w1 = BABYLON.MeshBuilder.CreateBox("box", { width:0.1,height:10,depth:h}, scene);
w1.position.x = w/2;
w1.position.y = 5;
var w2 = BABYLON.MeshBuilder.CreateBox("box", { width:0.1,height:10,depth:h}, scene);
w2.position.x = -w/2;
w2.position.y = 5;
const backMat = new BABYLON.StandardMaterial("boxMat");
backMat.diffuseTexture = new BABYLON.Texture("img/b8/back.jpg");
var back = BABYLON.MeshBuilder.CreateBox("box", { width:w,height:10,depth:.1}, scene);
back.position.z = h/2-1;
back.position.y = 5;
back.material = backMat;
//desk1
const logo = new BABYLON.StandardMaterial("boxMat");
logo.diffuseTexture = new BABYLON.Texture("img/b8/logo.jpg");
const desk2= BuildDesk_2(4,3,scene,color,logo);
desk2.translate(new BABYLON.Vector3(0,0,-h/2+1), 1, BABYLON.Space.WORLD);
var top_a= BABYLON.MeshBuilder.CreateBox("box", { width:w+1,height:0.2,depth:h+1}, scene);
top_a.position = new BABYLON.Vector3(0,11.6,0);
top_a.material = gray;
const Banner = new BABYLON.StandardMaterial("boxMat");
Banner.diffuseTexture = new BABYLON.Texture("img/b8/banner.jpg");
var top_b= BABYLON.MeshBuilder.CreateBox("box", { width:w,height:2.5,depth:h}, scene);
top_b.position = new BABYLON.Vector3(0,10,0);
top_b.material = Banner;
var top_c= BABYLON.MeshBuilder.CreateBox("box", { width:w+1,height:0.2,depth:h+1}, scene);
top_c.position = new BABYLON.Vector3(0,8.6,0);
top_c.material = gray;
const p1 = new BABYLON.StandardMaterial("boxMat");
p1.diffuseTexture = new BABYLON.Texture("img/b8/p1.jpg");
const stand1 = BuildStand_1(2,2,scene,color,p1);
stand1.translate(new BABYLON.Vector3(-w/4,0,-h/2+1), 1, BABYLON.Space.WORLD);
const p2 = new BABYLON.StandardMaterial("boxMat");
p2.diffuseTexture = new BABYLON.Texture("img/b8/p2.jpg");
const stand2 = BuildStand_1(2,2,scene,color,p2);
stand2.translate(new BABYLON.Vector3(-w/4-4,0,-h/2+1), 1, BABYLON.Space.WORLD);
const p3 = new BABYLON.StandardMaterial("boxMat");
p3.diffuseTexture = new BABYLON.Texture("img/b8/p3.jpg");
const stand3 = BuildStand_1(2,2,scene,color,p3);
stand3.translate(new BABYLON.Vector3(w/4,0,-h/2+1), 1, BABYLON.Space.WORLD);
const p4 = new BABYLON.StandardMaterial("boxMat");
p4.diffuseTexture = new BABYLON.Texture("img/b8/p4.jpg");
const stand4 = BuildStand_1(2,2,scene,color,p4);
stand4.translate(new BABYLON.Vector3(w/4+4,0,-h/2+1), 1, BABYLON.Space.WORLD);
return BABYLON.Mesh.MergeMeshes(
[kaf,top_a,top_b,top_c,desk2,stand1,stand2,stand3,stand4,w1,w2,back]
, true, false, null, false, true);
}
const BuildBooth_9 = (w,h,scene,color) =>{
const gray = new BABYLON.StandardMaterial("boxMat");
gray.diffuseColor = new BABYLON.Color3(236/255, 240/255, 241/255);
var kaf = BABYLON.MeshBuilder.CreateBox("box", { width:w,height:0.5,depth:h}, scene);
kaf.position.y = 0.5;
kaf.material = gray;
var w1 = BABYLON.MeshBuilder.CreateBox("box", { width:0.1,height:10,depth:h}, scene);
w1.position.x = w/2;
w1.position.y = 5;
var w2 = BABYLON.MeshBuilder.CreateBox("box", { width:0.1,height:10,depth:h}, scene);
w2.position.x = -w/2;
w2.position.y = 5;
const backMat = new BABYLON.StandardMaterial("boxMat");
backMat.diffuseTexture = new BABYLON.Texture("img/b9/back.jpg");
var back = BABYLON.MeshBuilder.CreateBox("box", { width:w,height:10,depth:.1}, scene);
back.position.z = h/2-1;
back.position.y = 5;
back.material = backMat;
//desk1
const logo = new BABYLON.StandardMaterial("boxMat");
logo.diffuseTexture = new BABYLON.Texture("img/b9/logo.jpg");
const desk1= BuildDesk_2(3,3,scene,color,logo);
desk1.translate(new BABYLON.Vector3(-w/2+3,0,-h/2+1), 1, BABYLON.Space.WORLD);
const desk2= BuildDesk_2(8,3,scene,color,logo);
desk2.translate(new BABYLON.Vector3(0,0,-h/2+1), 1, BABYLON.Space.WORLD);
const desk3= BuildDesk_2(3,3,scene,color,logo);
desk3.translate(new BABYLON.Vector3(w/2-3,0,-h/2+1), 1, BABYLON.Space.WORLD);
var top_a= BABYLON.MeshBuilder.CreateBox("box", { width:w+1,height:0.2,depth:h+1}, scene);
top_a.position = new BABYLON.Vector3(0,11.6,0);
top_a.material = gray;
const Banner = new BABYLON.StandardMaterial("boxMat");
Banner.diffuseTexture = new BABYLON.Texture("img/b9/banner.jpg");
var top_b= BABYLON.MeshBuilder.CreateBox("box", { width:w,height:2.5,depth:h}, scene);
top_b.position = new BABYLON.Vector3(0,10,0);
top_b.material = Banner;
var top_c= BABYLON.MeshBuilder.CreateBox("box", { width:w+1,height:0.2,depth:h+1}, scene);
top_c.position = new BABYLON.Vector3(0,8.6,0);
top_c.material = gray;
const p1 = new BABYLON.StandardMaterial("boxMat");
p1.diffuseTexture = new BABYLON.Texture("img/b9/p1.jpg");
const stand1 = BuildStand_1(2,2,scene,color,p1);
stand1.translate(new BABYLON.Vector3(w/4,0,-h/2+2), 1, BABYLON.Space.WORLD);
const p2 = new BABYLON.StandardMaterial("boxMat");
p2.diffuseTexture = new BABYLON.Texture("img/b9/p2.jpg");
const stand2 = BuildStand_1(2,2,scene,color,p2);
stand2.translate(new BABYLON.Vector3(-w/4,0,-h/2+2), 1, BABYLON.Space.WORLD);
return BABYLON.Mesh.MergeMeshes(
[kaf,top_a,top_b,top_c,desk1,desk2,desk3,stand1,stand2,w1,w2,back]
, true, false, null, false, true);
}
const BuildBooth_10 = (w,h,scene,color) =>{
const gray = new BABYLON.StandardMaterial("boxMat");
gray.diffuseColor = new BABYLON.Color3(236/255, 240/255, 241/255);
var kaf = BABYLON.MeshBuilder.CreateBox("box", { width:w,height:0.5,depth:h}, scene);
kaf.position.y = 0.5;
kaf.material = gray;
var w1 = BABYLON.MeshBuilder.CreateBox("box", { width:0.1,height:10,depth:h}, scene);
w1.position.x = w/2;
w1.position.y = 5;
var w2 = BABYLON.MeshBuilder.CreateBox("box", { width:0.1,height:10,depth:h}, scene);
w2.position.x = -w/2;
w2.position.y = 5;
const backMat = new BABYLON.StandardMaterial("boxMat");
backMat.diffuseTexture = new BABYLON.Texture("img/b10/back.jpg");
var back = BABYLON.MeshBuilder.CreateBox("box", { width:w,height:10,depth:.1}, scene);
back.position.z = h/2-1;
back.position.y = 5;
back.material = backMat;
//desk1
const logo = new BABYLON.StandardMaterial("boxMat");
logo.diffuseTexture = new BABYLON.Texture("img/b10/logo.jpg");
const desk1= BuildDesk_2(3,3,scene,color,logo);
desk1.translate(new BABYLON.Vector3(-w/2+3,0,-h/2+1), 1, BABYLON.Space.WORLD);
const desk2= BuildDesk_2(8,3,scene,color,logo);
desk2.translate(new BABYLON.Vector3(0,0,-h/2+1), 1, BABYLON.Space.WORLD);
const desk3= BuildDesk_2(3,3,scene,color,logo);
desk3.translate(new BABYLON.Vector3(w/2-3,0,-h/2+1), 1, BABYLON.Space.WORLD);
var top_a= BABYLON.MeshBuilder.CreateBox("box", { width:w+1,height:0.2,depth:h+1}, scene);
top_a.position = new BABYLON.Vector3(0,11.6,0);
top_a.material = gray;
const Banner = new BABYLON.StandardMaterial("boxMat");
Banner.diffuseTexture = new BABYLON.Texture("img/b10/banner.jpg");
var top_b= BABYLON.MeshBuilder.CreateBox("box", { width:w,height:2.5,depth:h}, scene);
top_b.position = new BABYLON.Vector3(0,10,0);
top_b.material = Banner;
var top_c= BABYLON.MeshBuilder.CreateBox("box", { width:w+1,height:0.2,depth:h+1}, scene);
top_c.position = new BABYLON.Vector3(0,8.6,0);
top_c.material = gray;
const p1 = new BABYLON.StandardMaterial("boxMat");
p1.diffuseTexture = new BABYLON.Texture("img/b10/p1.jpg");
const stand1 = BuildStand_1(2,2,scene,color,p1);
stand1.translate(new BABYLON.Vector3(w/4,0,-h/2+2), 1, BABYLON.Space.WORLD);
const p2 = new BABYLON.StandardMaterial("boxMat");
p2.diffuseTexture = new BABYLON.Texture("img/b10/p2.jpg");
const stand2 = BuildStand_1(2,2,scene,color,p2);
stand2.translate(new BABYLON.Vector3(-w/4,0,-h/2+2), 1, BABYLON.Space.WORLD);
return BABYLON.Mesh.MergeMeshes(
[kaf,top_a,top_b,top_c,desk1,desk2,desk3,stand1,stand2,w1,w2,back]
, true, false, null, false, true);
}
const BuildBooth_11 = (w,h,d,scene,color) =>{
const gray = new BABYLON.StandardMaterial("boxMat");
gray.diffuseColor = new BABYLON.Color3(236/255, 240/255, 241/255);
const kaf = build3gosh(w,h,d);
kaf.material = gray;
const sar_0 = build3gosh(w-1,h-1,d+0.5);
sar_0.position = new BABYLON.Vector3(-0.5,8.5,-.5);
sar_0.scaling = new BABYLON.Vector3(1,.5,1);
const sar_1 = build3gosh(w,h,d);
sar_1.scaling = new BABYLON.Vector3(1,5,1);
sar_1.position = new BABYLON.Vector3(0,7.5,0);
const Banner = new BABYLON.StandardMaterial("boxMat");
Banner.diffuseTexture = new BABYLON.Texture("img/b11/banner.jpg");
sar_1.material = Banner;
const sar_2 = build3gosh(w-1,h-1,d+0.5);
sar_2.position = new BABYLON.Vector3(-0.5,11.3,-.5);
sar_2.scaling = new BABYLON.Vector3(1,.5,1);
const logo = new BABYLON.StandardMaterial("boxMat");
logo.diffuseTexture = new BABYLON.Texture("img/b11/logo.jpg");
const desk1= BuildDesk_2(6,3,scene,color,logo);
desk1.translate(new BABYLON.Vector3(-w/2,0,+1), 1, BABYLON.Space.WORLD);
const desk2= BuildDesk_2(3,3,scene,color,logo);
desk2.translate(new BABYLON.Vector3(1,0,-h/2), 1, BABYLON.Space.WORLD);
desk2.rotation = new BABYLON.Vector3(0,Math.PI/2,0);
const p2 = new BABYLON.StandardMaterial("boxMat");
p2.diffuseTexture = new BABYLON.Texture("img/b11/p2.jpg");
const stand2 = BuildStand_1(2,2,scene,color,p2);
stand2.translate(new BABYLON.Vector3(-5*w/6,0,1), 1, BABYLON.Space.WORLD);
const p1 = new BABYLON.StandardMaterial("boxMat");
p1.diffuseTexture = new BABYLON.Texture("img/b11/p1.jpg");
const stand1 = BuildStand_1(2,2,scene,color,p1);
stand1.translate(new BABYLON.Vector3(1,0,-3*h/4), 1, BABYLON.Space.WORLD);
stand1.rotation = new BABYLON.Vector3(0,Math.PI/2,0);
const p4 = new BABYLON.StandardMaterial("boxMat");
p4.diffuseTexture = new BABYLON.Texture("img/b11/p4.jpg");
const stand4 = BuildStand_1(2,2,scene,color,p4);
stand4.translate(new BABYLON.Vector3(1,0,-1*h/4), 1, BABYLON.Space.WORLD);
stand4.rotation = new BABYLON.Vector3(0,Math.PI/2,0);
const p3 = new BABYLON.StandardMaterial("boxMat");
p3.diffuseTexture = new BABYLON.Texture("img/b11/p3.jpg");
const stand3 = BuildStand_1(2,2,scene,color,p3);
stand3.translate(new BABYLON.Vector3(-1*w/6,0,1), 1, BABYLON.Space.WORLD);
return BABYLON.Mesh.MergeMeshes(
[kaf,sar_2,sar_1,desk1,desk2,stand1,stand3,sar_0,stand2,stand4]
, true, false, null, false, true);
}
const BuildBooth_12 = (w,h,scene,color) =>{
const gray = new BABYLON.StandardMaterial("boxMat");
gray.diffuseColor = new BABYLON.Color3(236/255, 240/255, 241/255);
var kaf = BABYLON.MeshBuilder.CreateBox("box", { width:w,height:0.5,depth:h}, scene);
kaf.position.y = 0.5;
kaf.material = gray;
var w1 = BABYLON.MeshBuilder.CreateBox("box", { width:0.1,height:10,depth:h}, scene);
w1.position.x = w/2;
w1.position.y = 5;
var w2 = BABYLON.MeshBuilder.CreateBox("box", { width:0.1,height:10,depth:h}, scene);
w2.position.x = -w/2;
w2.position.y = 5;
const backMat = new BABYLON.StandardMaterial("boxMat");
backMat.diffuseTexture = new BABYLON.Texture("img/b12/back.jpg");
var back = BABYLON.MeshBuilder.CreateBox("box", { width:w,height:10,depth:.1}, scene);
back.position.z = h/2-1;
back.position.y = 5;
back.material = backMat;
//desk1
const logo = new BABYLON.StandardMaterial("boxMat");
logo.diffuseTexture = new BABYLON.Texture("img/b12/logo.png");
var top_a= BABYLON.MeshBuilder.CreateBox("box", { width:w+1,height:0.2,depth:h+1}, scene);
top_a.position = new BABYLON.Vector3(0,11.6,0);
top_a.material = gray;
const Banner = new BABYLON.StandardMaterial("boxMat");
Banner.diffuseTexture = new BABYLON.Texture("img/b12/banner.jpg");
var top_b= BABYLON.MeshBuilder.CreateBox("box", { width:w,height:2.5,depth:h}, scene);
top_b.position = new BABYLON.Vector3(0,10,0);
top_b.material = Banner;
var top_c= BABYLON.MeshBuilder.CreateBox("box", { width:w+1,height:0.2,depth:h+1}, scene);
top_c.position = new BABYLON.Vector3(0,8.6,0);
top_c.material = gray;
const s1 = new BABYLON.StandardMaterial("boxMat");
s1.diffuseTexture = new BABYLON.Texture("img/b12/s1.jpg");
const stand1 = BuildStand_2(3,5,scene,color,s1);
stand1.translate(new BABYLON.Vector3(w/3,0,-h/2+2), 1, BABYLON.Space.WORLD);
const s2 = new BABYLON.StandardMaterial("boxMat");
s2.diffuseTexture = new BABYLON.Texture("img/b12/s2.jpg");
const stand2 = BuildStand_2(3,5,scene,color,s2);
stand2.translate(new BABYLON.Vector3(-w/3,0,-h/2+2), 1, BABYLON.Space.WORLD);
return BABYLON.Mesh.MergeMeshes(
[kaf,top_a,top_b,top_c,stand2,w1,w2,back,stand1]
, true, false, null, false, true);
}
const BuildBooth_13 = (w,h,scene,color) =>{
const gray = new BABYLON.StandardMaterial("boxMat");
gray.diffuseColor = new BABYLON.Color3(236/255, 240/255, 241/255);
var kaf = BABYLON.MeshBuilder.CreateBox("box", { width:w,height:0.5,depth:h}, scene);
kaf.position.y = 0.5;
kaf.material = gray;
var w1 = BABYLON.MeshBuilder.CreateBox("box", { width:0.1,height:10,depth:h}, scene);
w1.position.x = w/2;
w1.position.y = 5;
var w2 = BABYLON.MeshBuilder.CreateBox("box", { width:0.1,height:10,depth:h}, scene);
w2.position.x = -w/2;
w2.position.y = 5;
const backMat = new BABYLON.StandardMaterial("boxMat");
backMat.diffuseTexture = new BABYLON.Texture("img/b13/back.jpg");
var back = BABYLON.MeshBuilder.CreateBox("box", { width:w,height:8.5,depth:.1}, scene);
back.position.z = h/2-1;
back.position.y = 4.5;
back.material = backMat;
//desk1
const logo = new BABYLON.StandardMaterial("boxMat");
logo.diffuseTexture = new BABYLON.Texture("img/b13/logo.png");
const desk1= BuildDesk_2(3,3,scene,color,logo);
desk1.translate(new BABYLON.Vector3(-w/2+3,0,-h/2+1), 1, BABYLON.Space.WORLD);
var top_a= BABYLON.MeshBuilder.CreateBox("box", { width:w+1,height:0.2,depth:h+1}, scene);
top_a.position = new BABYLON.Vector3(0,11.6,0);
top_a.material = gray;
const Banner = new BABYLON.StandardMaterial("boxMat");
Banner.diffuseTexture = new BABYLON.Texture("img/b13/banner.jpg");
var top_b= BABYLON.MeshBuilder.CreateBox("box", { width:w,height:2.5,depth:h}, scene);
top_b.position = new BABYLON.Vector3(0,10,0);
top_b.material = Banner;
var top_c= BABYLON.MeshBuilder.CreateBox("box", { width:w+1,height:0.2,depth:h+1}, scene);
top_c.position = new BABYLON.Vector3(0,8.6,0);
top_c.material = gray;
const s1 = new BABYLON.StandardMaterial("boxMat");
s1.diffuseTexture = new BABYLON.Texture("img/b13/s1.jpg");
const stand1 = BuildStand_2(3,5,scene,color,s1);
stand1.translate(new BABYLON.Vector3(w/3,0,-h/2+2), 1, BABYLON.Space.WORLD);
return BABYLON.Mesh.MergeMeshes(
[kaf,top_a,top_b,top_c,w1,w2,back,stand1,desk1]
, true, false, null, false, true);
}
const BuildBooth_14 = (w,h,d,scene,color) =>{
const gray = new BABYLON.StandardMaterial("boxMat");
gray.diffuseColor = new BABYLON.Color3(236/255, 240/255, 241/255);
const kaf = build3gosh(w,h,d);
kaf.material = gray;
const sar_0 = build3gosh(w-1,h-1,d+0.5);
sar_0.position = new BABYLON.Vector3(-0.5,8.5,-.5);
sar_0.scaling = new BABYLON.Vector3(1,.5,1);
const sar_1 = build3gosh(w,h,d);
sar_1.scaling = new BABYLON.Vector3(1,5,1);
sar_1.position = new BABYLON.Vector3(0,7.5,0);
const Banner = new BABYLON.StandardMaterial("boxMat");
Banner.diffuseTexture = new BABYLON.Texture("img/b14/banner.jpg");
sar_1.material = Banner;
const sar_2 = build3gosh(w-1,h-1,d+0.5);
sar_2.position = new BABYLON.Vector3(-0.5,11.3,-.5);
sar_2.scaling = new BABYLON.Vector3(1,.5,1);
const logo = new BABYLON.StandardMaterial("boxMat");
logo.diffuseTexture = new BABYLON.Texture("img/b14/logo.jpg");
const desk1= BuildDesk_2(6,3,scene,color,logo);
desk1.translate(new BABYLON.Vector3(-w/2,0,+1), 1, BABYLON.Space.WORLD);
const desk2= BuildDesk_2(3,3,scene,color,logo);
desk2.translate(new BABYLON.Vector3(1,0,-h/2), 1, BABYLON.Space.WORLD);
desk2.rotation = new BABYLON.Vector3(0,Math.PI/2,0);
const p2 = new BABYLON.StandardMaterial("boxMat");
p2.diffuseTexture = new BABYLON.Texture("img/b14/p2.jpg");
const stand2 = BuildStand_1(2,2,scene,color,p2);
stand2.translate(new BABYLON.Vector3(-5*w/6,0,1), 1, BABYLON.Space.WORLD);
const p1 = new BABYLON.StandardMaterial("boxMat");
p1.diffuseTexture = new BABYLON.Texture("img/b14/p1.jpg");
const stand1 = BuildStand_1(2,2,scene,color,p1);
stand1.translate(new BABYLON.Vector3(1,0,-3*h/4), 1, BABYLON.Space.WORLD);
stand1.rotation = new BABYLON.Vector3(0,Math.PI/2,0);
const p4 = new BABYLON.StandardMaterial("boxMat");
p4.diffuseTexture = new BABYLON.Texture("img/b14/p4.jpg");
const stand4 = BuildStand_1(2,2,scene,color,p4);
stand4.translate(new BABYLON.Vector3(1,0,-1*h/4), 1, BABYLON.Space.WORLD);
stand4.rotation = new BABYLON.Vector3(0,Math.PI/2,0);
const p3 = new BABYLON.StandardMaterial("boxMat");
p3.diffuseTexture = new BABYLON.Texture("img/b14/p3.jpg");
const stand3 = BuildStand_1(2,2,scene,color,p3);
stand3.translate(new BABYLON.Vector3(-1*w/6,0,1), 1, BABYLON.Space.WORLD);
return BABYLON.Mesh.MergeMeshes(
[kaf,sar_2,sar_1,desk1,desk2,stand1,stand3,sar_0,stand2,stand4]
, true, false, null, false, true);
}
const BuildBooth_15 = (w,h,scene,color) =>{
const gray = new BABYLON.StandardMaterial("boxMat");
gray.diffuseColor = new BABYLON.Color3(236/255, 240/255, 241/255);
var kaf = BABYLON.MeshBuilder.CreateBox("box", { width:w,height:0.5,depth:h}, scene);
kaf.position.y = 0.5;
kaf.material = gray;
var w1 = BABYLON.MeshBuilder.CreateBox("box", { width:0.1,height:10,depth:h}, scene);
w1.position.x = w/2;
w1.position.y = 5;
var w2 = BABYLON.MeshBuilder.CreateBox("box", { width:0.1,height:10,depth:h}, scene);
w2.position.x = -w/2;
w2.position.y = 5;
const backMat = new BABYLON.StandardMaterial("boxMat");
backMat.diffuseTexture = new BABYLON.Texture("img/b15/back.jpg");
var back = BABYLON.MeshBuilder.CreateBox("box", { width:w,height:10,depth:.1}, scene);
back.position.z = h/2-1;
back.position.y = 5;
back.material = backMat;
//desk1
const logo = new BABYLON.StandardMaterial("boxMat");
logo.diffuseTexture = new BABYLON.Texture("img/b15/logo.jpg");
const desk2= BuildDesk_2(5,3,scene,color,logo);
desk2.translate(new BABYLON.Vector3(0,0,-h/2+1), 1, BABYLON.Space.WORLD);
var top_a= BABYLON.MeshBuilder.CreateBox("box", { width:w+1,height:0.2,depth:h+1}, scene);
top_a.position = new BABYLON.Vector3(0,11.6,0);
top_a.material = gray;
const Banner = new BABYLON.StandardMaterial("boxMat");
Banner.diffuseTexture = new BABYLON.Texture("img/b15/banner.jpg");
var top_b= BABYLON.MeshBuilder.CreateBox("box", { width:w,height:2.5,depth:h}, scene);
top_b.position = new BABYLON.Vector3(0,10,0);
top_b.material = Banner;
var top_c= BABYLON.MeshBuilder.CreateBox("box", { width:w+1,height:0.2,depth:h+1}, scene);
top_c.position = new BABYLON.Vector3(0,8.6,0);
top_c.material = gray;
const s1 = new BABYLON.StandardMaterial("boxMat");
s1.diffuseTexture = new BABYLON.Texture("img/b15/s1.jpg");
const stand1 = BuildStand_1(2,2,scene,color,s1);
stand1.translate(new BABYLON.Vector3(5,0,-h/2+2), 1, BABYLON.Space.WORLD);
const s2 = new BABYLON.StandardMaterial("boxMat");
s2.diffuseTexture = new BABYLON.Texture("img/b15/s2.jpg");
const stand2 = BuildStand_1(2,2,scene,color,s2);
stand2.translate(new BABYLON.Vector3(-5,0,-h/2+2), 1, BABYLON.Space.WORLD);
const faceUV = [];
for(var i=0;i<=5;i++){
faceUV[i] = new BABYLON.Vector4(0.0, 0.0, 0.0, 1.0); //front face
}
faceUV[1] = new BABYLON.Vector4(0.0, 0, 1.0, 1.0);
const p1Mat = new BABYLON.StandardMaterial("boxMat");
p1Mat.diffuseTexture = new BABYLON.Texture("img/b15/p1.jpg");
var p1= BABYLON.MeshBuilder.CreateBox("box", { width:2,height:3,depth:2, faceUV: faceUV, wrap: true}, scene);
p1.position = new BABYLON.Vector3(10,2.5,-h/2+2);
p1.material = p1Mat;
const p2Mat = new BABYLON.StandardMaterial("boxMat");
p2Mat.diffuseTexture = new BABYLON.Texture("img/b15/p2.jpg");
var p2= BABYLON.MeshBuilder.CreateBox("box", { width:2,height:3,depth:2, faceUV: faceUV, wrap: true}, scene);
p2.position = new BABYLON.Vector3(15,2.5,-h/2+2);
p2.material = p2Mat;
const p3Mat = new BABYLON.StandardMaterial("boxMat");
p3Mat.diffuseTexture = new BABYLON.Texture("img/b15/p3.jpg");
var p3= BABYLON.MeshBuilder.CreateBox("box", { width:3,height:3,depth:2, faceUV: faceUV, wrap: true}, scene);
p3.position = new BABYLON.Vector3(-10,2.5,-h/2+2);
p3.material = p3Mat;
const p4Mat = new BABYLON.StandardMaterial("boxMat");
p4Mat.diffuseTexture = new BABYLON.Texture("img/b15/p4.jpg");
var p4= BABYLON.MeshBuilder.CreateBox("box", { width:3,height:3,depth:2, faceUV: faceUV, wrap: true}, scene);
p4.position = new BABYLON.Vector3(-15,2.5,-h/2+2);
p4.material = p4Mat;
return BABYLON.Mesh.MergeMeshes(
[kaf,top_a,top_b,top_c,desk2,stand1,stand2,w1,w2,back,p1,p2,p3,p4]
, true, false, null, false, true);
}
const BuildBooth_16 = (w,h,scene,color) =>{
const gray = new BABYLON.StandardMaterial("boxMat");
gray.diffuseColor = new BABYLON.Color3(236/255, 240/255, 241/255);
var kaf = BABYLON.MeshBuilder.CreateBox("box", { width:w,height:0.5,depth:h}, scene);
kaf.position.y = 0.5;
kaf.material = gray;
var w1 = BABYLON.MeshBuilder.CreateBox("box", { width:0.1,height:10,depth:h}, scene);
w1.position.x = w/2;
w1.position.y = 5;
var w2 = BABYLON.MeshBuilder.CreateBox("box", { width:0.1,height:10,depth:h}, scene);
w2.position.x = -w/2;
w2.position.y = 5;
const backMat = new BABYLON.StandardMaterial("boxMat");
backMat.diffuseTexture = new BABYLON.Texture("img/b16/back.jpg");
var back = BABYLON.MeshBuilder.CreateBox("box", { width:w,height:10,depth:.1}, scene);
back.position.z = h/2-1;
back.position.y = 5;
back.material = backMat;
//desk1
const logo = new BABYLON.StandardMaterial("boxMat");
logo.diffuseTexture = new BABYLON.Texture("img/b16/logo.png");
const desk2= BuildDesk_2(8,3,scene,color,logo);
desk2.translate(new BABYLON.Vector3(0,0,-h/2+1), 1, BABYLON.Space.WORLD);
var top_a= BABYLON.MeshBuilder.CreateBox("box", { width:w+1,height:0.2,depth:h+1}, scene);
top_a.position = new BABYLON.Vector3(0,11.6,0);
top_a.material = gray;
const Banner = new BABYLON.StandardMaterial("boxMat");
Banner.diffuseTexture = new BABYLON.Texture("img/b16/banner.jpg");
var top_b= BABYLON.MeshBuilder.CreateBox("box", { width:w,height:2.5,depth:h}, scene);
top_b.position = new BABYLON.Vector3(0,10,0);
top_b.material = Banner;
var top_c= BABYLON.MeshBuilder.CreateBox("box", { width:w+1,height:0.2,depth:h+1}, scene);
top_c.position = new BABYLON.Vector3(0,8.6,0);
top_c.material = gray;
const s1 = new BABYLON.StandardMaterial("boxMat");
s1.diffuseTexture = new BABYLON.Texture("img/b16/s1.jpg");
const stand1 = BuildStand_2(3,5,scene,color,s1);
stand1.translate(new BABYLON.Vector3(w/3,0,-h/2+2), 1, BABYLON.Space.WORLD);
const s2 = new BABYLON.StandardMaterial("boxMat");
s2.diffuseTexture = new BABYLON.Texture("img/b16/s2.jpg");
const stand2 = BuildStand_2(3,5,scene,color,s2);
stand2.translate(new BABYLON.Vector3(-w/3,0,-h/2+2), 1, BABYLON.Space.WORLD);
//const bro = build_bro(1,1,'b16',color,scene);
return BABYLON.Mesh.MergeMeshes(
[kaf,top_a,top_b,top_c,desk2,stand1,stand2,w1,w2,back]
, true, false, null, false, true);
}
|
const largestPalindrome = () => {
let max = 0
for(let i=100; i<1000; i++){
for(let j=100; j<1000; j++){
let product = i*j
if(product > max && product.toString() === product.toString().split("").reverse().join("")){
max = product
}
}
}
return max
}
console.log(largestPalindrome()) //906609
|
import React from "react";
import { useRef , useState } from "react";
import "../App.css";
import useWebAnimations from "@wellyshen/use-web-animations";
export const RedQueen = (prop) => {
console.log(prop.playback);
const {playback} = prop;
console.log(playback);
const {ref , playState , getAnimation} = useWebAnimations({
keyframes: {
transform: "translateY(0%)" ,
transform: "translateY(-100%)"
} ,
playbackRate: 1,
animationOptions: {
direction: "reverse" ,
duration: 600,
easing: 'steps(7 , end)' ,
iterations: Infinity ,
}
})
var animation = getAnimation()
try {
animation.updatePlaybackRate(animation.playbackRate + playback);
// }
try{
console.log(animation.playbackRate);
setInterval(() => {
if(animation.playbackRate > 1 ){
animation.playbackRate -= 0.5;
}
else{
animation.playbackRate = 0.9;
}
}, 4000);
}
finally{
}
} catch (error) {
}
return (
<div>
<div id="red-queen_and_alice">
<img ref={ref}
id="red-queen_and_alice_sprite"
src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/641/sprite_running-alice-queen_small.png"
alt="Alice and the Red Queen running to stay in place."
/>
</div>
</div>
);
};
|
import { combineReducers } from 'redux'
import search from './search/search'
export const reducers = combineReducers({ search })
|
import React from 'react';
import CircularProgress from '@material-ui/core/CircularProgress';
import {withStyles} from "@material-ui/styles";
import styles from "svm_assets/jss/views/demo.js";
class Plot extends React.Component {
render () {
const {classes} = this.props;
return (
<article>
{this.props.plot.image ? (
<img alt="Plot" id="plot"
className={classes.plot}
src={this.props.plot.image &&
`data:image/png;base64,${this.props.plot.image}`}/>
): <CircularProgress id="loading-plot" />}
</article>
)
}
}
export default withStyles(styles)(Plot); |
var contentDiv = document.getElementById("content");
var x, y, angle = 0;
for (var i = 0; i < 5; i++) {
x = Math.round(Math.cos(angle) * 100);
y = Math.round(Math.sin(angle) * 100);
angle += 5;
var currentDiv = document.createElement("div");
currentDiv.className = 'moving';
currentDiv.style.position = "absolute";
currentDiv.style.top = (200 + y) + "px";
currentDiv.style.left = (300 + x) + "px";
contentDiv.appendChild(currentDiv);
}
function onMoveDivsButtonClick() {
angle = 0;
setInterval(function () {
for (var j = 0; j < contentDiv.childElementCount; j++) {
var div = contentDiv.children[j];
div.style.left = (300 + 100 * Math.cos(angle)) + "px";
div.style.top = (200 + 100 * Math.sin(angle)) + "px";
angle += 5;
}
angle += 0.2;
}, 100);
}
moveDivsButton = document.getElementById('btn-move-divs');
moveDivsButton.addEventListener('click', onMoveDivsButtonClick); |
mainApp.directive('persondirective', ['$q', 'invokeServerService', function ($q, invokeServerService) {
return {
restrict: 'E',
replace: "true",
scope: {
ngModel: '=ngModel',
frmName: '@name',
options: '='
},
templateUrl: '../app/pages/shared/person/person.html',
link: function (scope, q) {
scope.internalControl = scope.options || {};
scope.internalControl.fillCity = function (provinceId) {
var deferred = $q.defer();
invokeServerService.Post('/Base/GetCity', { provinceId: provinceId }).success(function (result) {
scope.ngModel.cityDropDownDS = result;
deferred.resolve();
});
return deferred.promise;
}
},
controller: function ($scope, invokeServerService) {
$scope.myPromise = invokeServerService.Post('/Base/GetProvince', {}).success(function (result) {
$scope.stateDropDownDS = result;
});
$scope.changeDropDownstate = function (provinceId) {
invokeServerService.Post('/Base/GetCity', { provinceId: provinceId }).success(function (result) {
$scope.ngModel.cityDropDownDS = result;
});
}
$scope.searchPerson = function () {
invokeServerService.Post("/Base/SearchPerson", { nationalCode: $scope.ngModel.nationalCode })
.success(function (result) {
$scope.changeDropDownstate(result.state.Id);
$scope.ngModel = result;
});
}
$scope.personModalAction = function (action) {
if (action == 'save') {
if ($scope.personForm.$valid)
$scope.$parent.personModalAction(action);
}
else {
$scope.$parent.personModalAction(action);
}
}
}
};
}]); |
import 'babel-polyfill';
import '~/styles.less';
import { setup } from '~/frontpage';
history.pushState({}, 'Scroll animations', '/');
setup();
|
class Spinner {
constructor() {
this.spinnerWrapper;
}
showSpinner() {
this.spinnerWrapper = document.createElement("div");
this.spinnerWrapper.className = "layout-center";
this.spinner = document.createElement("div");
this.spinner.className = "lds-dual-ring";
this.spinnerWrapper.appendChild(this.spinner);
document.body.appendChild(this.spinnerWrapper);
}
hideSpinner() {
document.body.removeChild(this.spinnerWrapper);
}
}
export default Spinner;
|
const colors = require("tailwindcss/colors");
module.exports = {
purge: [
"./src/pages/**/*.{js,ts,jsx,tsx}",
"./src/components/**/*.{js,ts,jsx,tsx}",
],
darkMode: false, // or 'media' or 'class'
theme: {
screens: {
sm: "420px",
md: "768px",
lg: "976px",
xl: "1250px",
},
maxWidth: {
main: "1280px",
dialog: "500px",
},
colors: {
gray: colors.coolGray,
blue: colors.lightBlue,
red: colors.rose,
pink: colors.fuchsia,
indigo: colors.indigo,
white: colors.white,
black: colors.black,
pitari: "#fff4ef",
},
fontFamily: {
main: [
"Avenir",
"Helvetica Neue",
"Helvetica",
"Arial",
"Hiragino Sans",
"ヒラギノ角ゴシック",
"YuGothic",
"Yu Gothic",
"メイリオ",
"Meiryo",
"MS Pゴシック",
"MS PGothic",
"sans-serif",
],
},
extend: {
spacing: {
128: "32rem",
144: "36rem",
},
borderRadius: {
"4xl": "2rem",
},
width: {
cardPc: "400px",
cardSp: "95vw",
},
height: {
cardPc: "247px",
cardSp: "100%",
},
maxWidth: {
cardPc: "400px",
}
},
},
variants: {
extend: {},
},
plugins: [],
};
|
import Vue from 'vue'
import Vuex from 'vuex'
import hello from './modules/hello/helloModule'
import hello2 from './modules/hello/hello2Module'
import step4 from './modules/step4Module'
import step5 from './modules/step5Module'
import step7 from './modules/step7Module'
Vue.use(Vuex)
export default new Vuex.Store({
modules: {
hello,
hello2,
step4,
step5,
step7,
},
});
|
import React from "react";
import ThemeProvider from "@material-ui/styles/ThemeProvider";
import theme from "./app/themes";
import Home from "./app/containers/home-container";
/**
* Root component of the App
*/
export default class App extends React.Component {
render() {
return (
<ThemeProvider theme={theme}>
<Home />
</ThemeProvider>
);
}
}
|
let playersNames=['Player-1','Player-2'];
let playersSymbols=['X','O'];
let allowedMoves=[1,2,3,4,5,6,7,8,9];
let gamePlay;
let currentPlayerNumber=0;
const loadGame=function(){
gamePlay=new GamePlay(playersNames,playersSymbols,allowedMoves);
startGame();
};
const startGame=function(){
document.getElementById('gameBoard').addEventListener("click",updateMoves);
displayPlayersTurn(playersNames[currentPlayerNumber]);
};
const updateMoves=function(event){
if(gamePlay.updatePlayerMove(playersNames[currentPlayerNumber%2],+event.target.id)){
event.target.innerText=gamePlay.getPlayerSymbol(playersNames[currentPlayerNumber%2]);
if(gamePlay.hasAnyWon()){
displayAndEndGame(playersNames[currentPlayerNumber%2]+" won!!");
}else if(gamePlay.isGameDraw()){
displayAndEndGame("Game draw!!");
}else{
currentPlayerNumber++;
displayPlayersTurn(playersNames[currentPlayerNumber%2]);
}
}
};
const displayAndEndGame=function(message){
document.getElementById('gameBoard').removeEventListener("click",updateMoves);
document.getElementById("displayGameStatistics").innerText=message;
document.getElementById('gameBoard').style.backgroundColor = "#7C7777";
};
const displayPlayersTurn=function(playerName){
document.getElementById("displayGameStatistics").innerText=playerName+"\'s turn";
}
window.onload=loadGame;
|
import firebase from 'firebase';
import 'firebase/firestore';
export default async function getUserMail(mail) {
const db = firebase.firestore();
let email = mail;
if(!mail)
email = "default@gmail.com";
var result = null;
await db.collection('users').where("email", "==", email)
.get()
.then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
result = {user: doc.id, data:doc.data()};
});
})
.catch(function(error) {
console.log(error);
result = error;
});
return result;
} |
function validate(key, value) {
let errorMessage = "";
const emailRegex = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
const latinRegex = /^[a-zA-z0-9!@#№$%^&*()_+=.,:;~{}/|-]+$/g;
switch (key) {
case "email":
if (!value) errorMessage = "E-mail is required";
else if (!emailRegex.test(value)) errorMessage = "Please enter a valid email address";
break;
case "username":
if (!value) errorMessage = "Username is required";
break;
case "signUpPassword":
if (!value) errorMessage = "Password is required";
else if (value.length < 8) errorMessage = "Use at least 8 characters";
else if (value === value.toLowerCase() || value === value.toUpperCase())
errorMessage = "Use upper and lower case characters";
else if (!latinRegex.test(value)) errorMessage = "Latin characters only";
break;
case "signInPassword":
if (!value) errorMessage = "Password is required";
break;
case "confirmPassword":
if (!value) errorMessage = "Password is required";
break;
default:
return null;
}
return errorMessage;
}
export default validate;
|
App.NewItemView = Backbone.View.extend({
events: {
'submit #new-item-form': 'save',
'click #save': 'save',
'click #cancel': 'close',
'click .icon-close': 'removeImage'
},
template: App.TemplateCache.get('#new-item-template'),
initialize: function() {
_.bindAll(this, 'save');
Backbone.Validation.bind(this);
Backbone.pubSub.trigger('header-hide', this);
Backbone.pubSub.trigger('header-default', this);
// Listen for image upload and pass to current model
Backbone.pubSub.on('image-upload-complete', function() {
console.log('image-upload-complete, trigger');
this.setImagePath();
}, this);
},
render: function() {
var markup = this.model.toJSON();
this.$el.html(this.template(markup)).fadeIn('fast');
return this;
},
setImagePath: function() {
this.model.set('image', App.imager.image_store);
console.log('this.model.set -> setImagePath', App.imager.image_store);
this.updatePlaceholder(App.imager.image_store[3]);
},
save: function(e) {
e.preventDefault();
var self = this;
var data = $('#new-item-form').serializeObject();
var value = $(e.currentTarget).val();
var slugVal = App.convertToSlug($('#category').val());
data.slug = slugVal;
this.model.set(data);
console.log('this.model.set -> save', data);
if(this.model.isValid(true)) {
this.model.save(data, {
success: function(response, model) {
console.log('this.model.save -> success', data);
self.close();
App.router.navigate('#/view/' + model.id);
}
});
}
},
updatePlaceholder: function(src) {
var placeholder = $('.upload-placeholder'),
path = src;
// clear placeholder
// TODO: this may eventually be an array
// handle it, hacky
placeholder.empty();
$('#upload-placeholder').empty();
// add image + close button
placeholder.append('<img />').append('<a />').fadeIn('fast');
// find image + add image src
placeholder.find('img').attr('src', App.imager.image_store[0]);
// find close button add icon + href
placeholder
.find('a')
.addClass('icon-close')
.attr('href', '#')
.attr('data-id', path);
},
removeImage: function(e) {
e.preventDefault();
var $self = $(e.target).closest('.media-block'),
image_id = $self.data('id');
if (image_id) {
$.get('api/remove/' + image_id, function(data) {
$self.find('img, a').remove();
$self.append('<div />').addClass('.progress-bar-indication');
Backbone.pubSub.trigger('image-remove', this);
})
.fail(function() {
console.log('Failed to remove the image.');
});
}
},
close: function() {
console.log('Kill:App.NewItemView ', this);
this.unbind();
this.remove();
App.categoryService('dispose');
App.router.navigate('#/');
}
}); |
import React, { Component } from "react";
import {Modal, Form, Input, TreeSelect, Tree} from 'antd';
import { connect } from 'react-redux';
import { fetchAppPermissionAction, addAppPermissionAction } from '../../../store/action';
import { arrToTree } from '../../../utils/tools';
const TreeNode = Tree.TreeNode;
@connect(({ appDetail }) => {
return { appDetail }
}, {
fetchAppPermissionAction, addAppPermissionAction
})
export default class RolePermission extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
const { appDetail: { appid } } = this.props;
if (appid) {
this.loadPermission(appid)
}
}
loadPermission = (appid) => {
this.props.fetchAppPermissionAction(appid)
}
componentWillReceiveProps(nextProps) {
if (this.props.appDetail.appid != nextProps.appDetail.appid) {
this.loadPermission(nextProps.appDetail.appid)
}
}
loopTreeNode = (data) => data.map((item) => {
if(item.children) {
return <TreeNode value={item.code} title={item.title} key={item.code}>
{this.loopTreeNode(item.children)}
</TreeNode>
}
return <TreeNode value={item.code} title={item.title} key={item.code}/>
})
render() {
const { appDetail: { permissions }, checkedKeys=[],onChange } = this.props;
const menusTree = arrToTree({arr: permissions})
const treeDom = this.loopTreeNode(menusTree);
if (!permissions || permissions.length == 0) {
return <span>暂无权限或加载中</span>
}
return (
<div>
<Tree
defaultExpandAll={true}
checkable
defaultCheckedKeys={checkedKeys}
onCheck={onChange}
placeholder="Please select">
{treeDom}
</Tree>
</div>
)
}
} |
self.__precacheManifest = (self.__precacheManifest || []).concat([
{
"revision": "8a79673303e319d1c1b5a7b04c6771fc",
"url": "/index.html"
},
{
"revision": "b764a997e1f3c1254b02",
"url": "/static/css/main.81f1aaa3.chunk.css"
},
{
"revision": "4b027ebc2d55da024d26",
"url": "/static/js/2.4f6b64a5.chunk.js"
},
{
"revision": "c64c486544348f10a6d6c716950bc223",
"url": "/static/js/2.4f6b64a5.chunk.js.LICENSE.txt"
},
{
"revision": "b764a997e1f3c1254b02",
"url": "/static/js/main.79caf694.chunk.js"
},
{
"revision": "7aa6500c718108e45853",
"url": "/static/js/runtime-main.c94271d8.js"
}
]); |
import React from 'react'
import ReactDOM from 'react-dom'
import storage from './helpers/storage'
import { Provider } from 'react-redux'
import { HashRouter } from 'react-router-dom'
import App from './app'
import configureStore from './reducks/configureStore'
const bootstrap = async () => {
const data = await storage.get('settings')
const store = await configureStore({ settings: { data } })
ReactDOM.render(
<Provider store={store}>
<HashRouter>
<App />
</HashRouter>
</Provider>,
document.getElementById('root')
)
}
bootstrap()
|
function judegHasKity (dom, num) {
var len = dom.find('.sale-kity-box').length;
console.log(len);
if (!len || len < num) {
dom.parent().hide();
dom.parent().siblings('.sc-not-goods-wrapper').fadeIn();
}
}
function delKity () {
$('.sale-kity-del').on('click', function () {
var thisPa = $(this).parent().parent().parent().parent();
var thisPa1 = $(this).parent().parent().parent();
console.log(thisPa);
judegHasKity(thisPa, 2);
thisPa1.fadeOut();
setTimeout(function () {
thisPa1.remove();
judegHasKity(thisPa, 1);
}, 500);
})
}
$(function () {
delKity();
}) |
'use strict';
const MAX_ASCII_CHAR_CODE = 127;
const internals = {};
internals.ipv4 = new RegExp(/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/);
internals.ipv6 = new RegExp(/(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/);
internals.MacAddress = new RegExp(/^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$/);
internals.FQDN = new RegExp(/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9]$/);
internals.validRegFlags = ['g', 'i', 'm', 'u', 'y'];
internals.alphaReg = new RegExp(/^[A-Za-z]+$/);
internals.numericReg = new RegExp(/^[0-9]+$/);
internals.alphaNumericReg = new RegExp(/^[A-Za-z0-9]+$/);
exports.isError = (value) => {
return value instanceof Error;
};
exports.isNan = (value) => {
return value !== value;
};
exports.isObj = (value) => {
return (!!value) && (value.constructor === Object);
};
exports.isString = (value) => {
return (!!value) && (value.constructor === String);
};
exports.isArray = (value) => {
return (!!value) && (value.constructor === Array);
};
exports.isDate = (value) => {
return (!!value) && (value.constructor === Date);
};
exports.isRegex = (value) => {
return (!!value) && (value.constructor === RegExp);
};
exports.isFunction = (value) => {
return (!!value) && (value.constructor === Function);
};
exports.isNumber = (value) => {
return (!!value) && (value.constructor === Number) && (isFinite(value));
};
exports.isUndefined = (value) => {
return value === void 0;
};
exports.isNull = (value) => {
return value === null;
};
exports.isEmpty = (value) => {
return exports.isUndefined(value) || exports.isNull(value);
};
exports.isObjectID = (value) => {
if (!value) {
return false;
}
return (/^[0-9a-fA-F]{24}$/).test(value);
};
exports.isFQDN = (value) => {
if (!exports.isString(value)) {
return false;
}
return internals.FQDN.test(value);
};
exports.isIp = (value) => {
if (!exports.isString(value)) {
return false;
}
return internals.ipv4.test(value) || internals.ipv6.test(value);
};
exports.isIp6 = (value) => {
if (!exports.isString(value)) {
return false;
}
return internals.ipv6.test(value);
};
exports.isIp4 = (value) => {
if (!exports.isString(value)) {
return false;
}
return internals.ipv4.test(value);
};
exports.isMac = (value) => {
if (!exports.isString(value)) {
return false;
}
return internals.MacAddress.test(value);
};
exports.isInt8 = (value) => {
// -128 to 127
return Number.isInteger(value) ? value >= -128 && value <= 127 : false;
};
exports.isUint8 = (value) => {
// 0 to 255
return Number.isInteger(value) ? value >= 0 && value <= 255 : false;
};
exports.isInt16 = (value) => {
// -32,768 to 32,767
return Number.isInteger(value) ? value >= -32768 && value <= 32767 : false;
};
exports.isUint16 = (value) => {
// 0 to 65,535
return Number.isInteger(value) ? value >= 0 && value <= 65535 : false;
};
exports.isInt32 = (value) => {
// -2,147,483,648 to 2,147,483,647
return Number.isInteger(value) ? value >= -2147483648 && value <= 2147483647 : false;
};
exports.isUint32 = (value) => {
// 0 to 4,294,967,295
return Number.isInteger(value) ? value >= 0 && value <= 4294967295 : false;
};
exports.isAscii = (value) => {
// charcode upto 127
if (!exports.isString(value)) {
return false;
}
for (let i = 0; i < value.length; ++i) {
if (value.charCodeAt(i) > MAX_ASCII_CHAR_CODE) {
return false;
}
}
return true;
};
exports.isDateString = (value) => {
if (!exports.isString(value)) {
return false;
}
return (new Date(value).toString() !== 'Invalid Date') && (!isNaN(new Date(value)));
};
exports.isRegexString = (value) => {
if (!exports.isString(value)) {
return false;
}
const firstChar = value[0];
const lastChar = value[value.length - 1];
if ((firstChar === '/') && (lastChar === '/' || ~internals.validRegFlags.indexOf(lastChar))) {
return true;
}
return false;
};
exports.isAlpha = (value) => {
if (!exports.isString(value)) {
return false;
}
return internals.alphaReg.test(value);
};
exports.isNumeric = (value) => {
if (!exports.isString(value)) {
return false;
}
return internals.numericReg.test(value);
};
exports.isAlphaNumeric = (value) => {
if (!exports.isString(value)) {
return false;
}
return internals.alphaNumericReg.test(value);
};
exports.isUpperCase = (value) => {
if (!exports.isString(value)) {
return false;
}
return value === value.toUpperCase();
};
exports.isLowerCase = (value) => {
if (!exports.isString(value)) {
return false;
}
return value === value.toLowerCase();
};
|
var app = require("express")();
var http = require("http").Server(app);
var io = require("socket.io")(http);
var fs = require("fs");
var color = require("colors");
console.log("app.js - " + "[Spacey] Loaded initial requirements".green);
var bitmap = require("./modules/bitmap.js");
var database = require("./modules/database.js");
app.use(require("express").static('public'));
app.get("/", function(req, res) {
console.log("app.js - " + "[Spacey] A User Requested /".blue);
fs.readFile("public/index.html", "utf-8", function(err, data) {
res.send(data);
});
});
io.sockets.on('connection', function(socket){
var clientIp = socket.request.connection.remoteAddress;
console.log("app.js - " + "[Spacey] ".green + "A User Connected From ".blue + clientIp);
database.returnRandomSpaceman( function(data) {
socket.emit('map', JSON.stringify(data));
});
socket.on('disconnect', function(){
console.log("app.js - " + "[Spacey] ".green + "A User Disconnected".blue);
});
});
//database.clearSpaceman(function(){});
database.getSpacemen(function(data){console.log(data);console.log("Listed Spacemen");});
// database.getNumberOfSpacemen(function(data){console.log(data);console.log("Listed Number of Spacemen");});
bitmap.makeBaseGenerations(database);
database.manipulateEntry("5645ee25e99ada3c3731d6b0", "change", bitmap);
http.listen(3000, function() {
console.log("app.js - " + "[Spacey] Running at ".green + "http://localhost:3000".blue);
setTimeout(function() {
database.connectToMongo();
}, 1000);
}); |
function doLogin(){
//alert('g');
$('#redbg_view').removeClass('pt-page-moveFromTop');
$('#updiv_view').removeClass('pt-page-moveToTopFade hide');
//锁消失的场景
$('#Getred').addClass('pt-page-rotateSlideOut');
//rotateYDIV();
$('#updiv_view').addClass('pt-page-moveToTopFade');
$('#redbg_view').addClass('pt-page-moveToBottomEasing');
setTimeout(function(){
$('#Getred').css('display','none');
},500);
setTimeout(function(){
createTableItem();
createTableItem();
createTableItem();
setTimeout(function(){
$('#updiv_view').removeClass('pt-page-moveIconUp');
$('#redbg_view').removeClass('pt-page-moveToBottomEasing');
$('#updiv_view').css('display','none');
$('#redbg_view').css('display','none');
//$('#Success_view').addClass('pt-page-rotateRightSideFirst');
},1250);
},200);
}
var x,y,ny=0,rotYINT
function rotateYDIV()
{
y=document.getElementById("Getred")
clearInterval(rotYINT)
rotYINT=setInterval(1)
}
function startYRotate()
{
ny=ny+1
y.style.transform="rotateY(" + ny + "deg)"
y.style.webkitTransform="rotateY(" + ny + "deg)"
y.style.OTransform="rotateY(" + ny + "deg)"
y.style.MozTransform="rotateY(" + ny + "deg)"
if (ny==180 || ny>=360)
{
clearInterval(rotYINT)
if (ny>=360){ny=0}
}
}
//动态生成table_cell
function createTableItem() {
$('#mui-table-view').append(
'<li class=\"mui-table-view-cell mui-media\" style=\"height: 4rem;\">' +
'<img class=\"mui-media-object mui-pull-left\" src=\"../images/shuijiao.jpg\" style=\"border-radius:0.3rem;\">' +
'<div class=\"mui-media-body\" style=\"color:white;display:inline-block;font-size:0.8rem\">lv' +
'<p class=\"mui-ellipsis\" style=\"font-size:0.8rem;margin-top:0.2rem;\">' + 18079104948 +
'</p>' + '</div>' + '<div class=\"mui-media-right\" style=\"font-size:0.8rem;\">' +
'抢到' + '5M流量红包' + '<p class=\"mui-ellipsis\" style=\"text-align:right;font-size:0.6rem;margin-top:0.2rem;\">' + '5M' +
'</p>' + '</div>' + '</li>'
);
} |
const express = require('express');
const mysql = require('mysql');
const router = express.Router();
const db = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'sensordb',
multipleStatements: true
});
function convertDate(d) {
const date = new Date(d);
const year = date.getFullYear();
let m = date.getMonth() + 1;
let day = date.getDate();
day = parseInt(day) < 10 ? `0${day}` : day;
return day + "/" + m + "/" + year;
}
router.get('/', (req, res, next) => {
let sql = 'SELECT currentLevel, ppmVal, dateSensed, levels FROM current_state WHERE DATE_FORMAT(dateSensed, "%d") = DATE_FORMAT(NOW(), "%d");';
sql += 'SELECT currentLevel, ppmVal, dateSensed, levels FROM current_state WHERE DATE_FORMAT(dateSensed, "%d") < DATE_FORMAT(NOW(), "%d") LIMIT 5;';
sql += 'SELECT currentLevel FROM current_state WHERE DATE_FORMAT(dateSensed, "%d") = DATE_FORMAT(NOW(), "%d");';
db.query(sql, [1, 2, 3], (err, data) => {
if (err) throw err;
res.render('index', {
sensorData: data[0],
pastData: data[1],
levelCheck: data[2],
convertDate: convertDate
});
});
});
module.exports = router;
exports.convertDate = convertDate(); |
/**
* Created by dgarrett on 12/24/13.
*/
RamModule.factory('faqsDao', function($http, dataCache, utilityService, logging) {
var faqsDao = {};
var thisModule = 'faqsDao'
var i = -1;
faqsDao.data = [
{id: ++i, title: 'What browsers does th site support?', text:
'This site has been tested on Google Chrome, Firefox, Apple Safari and Internet Explorer 10. ' +
'Older versions of Microsoft Internet Explorer (IE 8 and earlier) will not work. ' +
'This site is designed to run on mobile, tablet and desktop computers - any platform that ' +
'can run a web browser and JavaScript.'
},
{id: ++i, title: 'What is this service?', text:
'Rate A Meeting allows meeting attendees to rate the value of a meeting. ' +
'You create a meeting specifying the date and description. ' +
'Each meeting has a unique six digit number which you give to ' +
'meeting attendees who can then enter this number ' +
'and a rating at http://www.rateAMeeting.com. ' +
'Meeting attendees can rate a meeting starting on the day of the meeting and up to ' +
'two days after the meeting.'
},
{id: ++i, title: 'What are "Current", "Future" and "Past" meetings?', text:
'These meeting "categories" group meetings by whether or not they can be rated now or in the future. For "Past", ' +
'the meetings are so far in the past that they can no longer be rated. For "Current" ' +
'the meetings are occurring today or in the last two days and can be rated. For "Future" ' +
'the meetings are scheduled for a date after today and so can not yet be rated. There ' +
'is also a difference in how the meeting lists are sorted. "Past" meetings lists show the most recent ' +
'meeting first and the oldest meeting last. "Current" and "Future" meetings lists show the earliest meetings ' +
'first and the latest last. Note also that for the free account you can only see a maximum of ' +
'30 meetings for each category.'
},
{id: ++i, title: 'When can people rate a meeting?', text:
'Meetings can be rated on the day they take place, up to two days after. To accommodate different '+
'time zones, rating may open a day before the meeting and close up to two days after the' +
' scheduled meeting date.'
},
{id: ++i, title: 'Does this cost anything?', text:
'This service is completely free. But there are limits to how many meetings you can see in each view.'},
{id: ++i, title: 'What are the limits for free account?', text:
'Free accounts will only show you a maximum of 30 Meetings in the Current, Future, and Past Meetings Lists.'
},
{id: ++i, title: 'Can this site run on any device?', text:
'Yes! As long as the device can run a web page and JavaScript. This site has been designed to run on ' +
'any platform: smart phones, tablets, desktops. To sign on and define meetings we save a session ' +
'cookie on your device, but it contains no personal information and is not used outside of this website. ' +
'Not only can your audience rate meetings from any device, but you can also add, edit and delete ' +
'meetings from a smart phone or any other web browser enabled platform.'
},
{id: ++i, title: 'Are the two three digit numbers unique?', text:
'Sort of. To keep the numbers short we may reuse numbers, but a number is verified unique ' +
'within a 60 day window, 30 days before your meeting and 30 days after. ' +
'This allows us to keep the numbers simple but still ensure that people do not accidentally ' +
'rate the wrong meeting.'
},
{id: ++i, title: 'Can I use my browser forward and back buttons? Bookmarks?', text:
'Yes! This site supports complete navigation using the browser forward, back and history features. ' +
'You can also bookmark any page within the application.'
}
];
return faqsDao;
}); |
/*
* setSelVal('#sel', json.ajly); //下拉赋值
* setRadioVal('#radio', true); //单选赋值
* setCheckVal('#check', true); //多选赋值
* selDisable('#saly',true); //下拉禁用
* checkDisable("#check",true); //多选禁用
* radioDisable("#radio",true); //单选禁用
* inputDisable("#text",true); //输入框禁用
* 注:以上方法 第一个参数是jQuery对象或选择器,并非一定是id。
*
* 下拉表单:
* 例:<select class="inputSel" multiple="multiple"> 多选下拉
* 例:<select class="inputSel" data-edit="true"> 可编辑下拉(输入显示匹配选项供选择)
* 例:<select class="inputSel" data-edit="true" data-diy="true"> 可随意编辑下拉(输入的内容可自成选项供选择)
*/
var jq=jQuery;
var ir='inputRadio',
ic='inputCheck',
is='inputSel';
var r='radio',
rc='radio_checked',
rd='radio_disable',
rcd='radio_checked_disable',
c='checkbox',
cc='checkbox_checked',
cd='checkbox_disable',
ccd='checkbox_checked_disable',
w='select_box',
d='select_showbox',
l='select_option';
jq(function(){
radioInit(jq('.inputRadio'));//单选框
checkboxInit(jq('.inputCheck'));//复选框
selectInit(jq('.inputSel'));//下拉框
jq('body,.Wdate').click(function(e){
if(!jq(e.target).parents('.select_box').length && !jq(e.target).parents('.select_option').length){
jq('.select_box').removeClass('active');
jq('.select_option').hide();
}
});
jq('input[readOnly]').keydown(function(e) {
if(e.keyCode==8){
e.preventDefault();
}
});
});
/**
* 根据父元素对象初始化 参数为form的jQuery对象
* @param $dom
*/
function initFormByParent($dom){
checkboxInit($dom.find('.inputCheck'));//复选框
radioInit($dom.find('.inputRadio'));//单选框
selectInit($dom.find('.inputSel'));
}
/**
* 根据 form ID 初始化
* @param formId
*/
function initForm(formId){
checkboxInit(jQuery('#'+formId+' .inputCheck'));//复选框
radioInit(jQuery('#'+formId+' .inputRadio'));//单选框
selectInit(jQuery('#'+formId+' .inputSel'));
}
//单选框
function radioInit(obj)
{ var radioBoxs=ifdom(obj);
radioBoxs.each(function(){
var o=jq(this),name=o.attr('name'),cAttr=o.attr('checked'),dAttr=o.attr('disabled'),checked,disabled;
if(cAttr){
checked=rc;
jq('.'+ir+'[name="'+name+'"]').siblings('.'+r).removeClass(rc);
jq('.'+ir+'[name="'+name+'"]').siblings('.'+ir+'[name="'+name+'"]').removeAttr('checked');
if(dAttr){ disabled=rcd; }else{ disabled=''; }
}else{
checked='';
if(dAttr){ disabled=rd;}else{disabled='';}
}
var spanBox=jq('<span class="'+r+' '+checked+' '+disabled+'" name="'+name+'"></span>');
o.next('.'+r).remove();
o.after(spanBox);
radioEvent(o.parent());
});
}
function radioEvent(obj){
obj.click(function(){
var spanBox=jq(this).find('.'+r),radioBox=jq(this).find('.'+ir),name=radioBox.attr('name');
if(radioBox.attr('disabled')){
return;
}else{
if(spanBox.hasClass(rc)){
return;
}else{
jq('.'+ir+'[name="'+name+'"]').removeAttr('checked').next('.'+r).removeClass(rc);
spanBox.addClass(rc);
radioBox.attr('checked', 'checked'); // 单选按钮的选中 会让其他同name的checkbox取消选中。
jq('.inputCheck[name="'+name+'"]').next('.checkbox_checked').removeClass('checkbox_checked');
}
}
if(radioBox.attr("onchange")){
radioBox.trigger('change');
}else{
radioBox.trigger('click');
}
return false;
});
}
//复选框
function checkboxInit(obj)
{
var checkBoxs=ifdom(obj);
checkBoxs.each(function(){
var o=jq(this),name=jq(this).attr('name'),cAttr=o.attr('checked'),dAttr=o.attr('disabled'),checked,disabled;
if(cAttr){
checked=cc;
if(dAttr){ disabled=ccd; }else{ disabled=''; }
}else{
checked='';
if(dAttr){ disabled=cd; }else{ disabled=''; }
}
var spanBox=jq('<span class="'+c+' '+checked+' '+disabled+'" name="'+name+'"></span>');
o.next('.'+c).remove();
o.after(spanBox);
checkBoxEvent(o.parent());
});
}
function checkBoxEvent(obj){
obj.click(function(e){
var spanBox=jq(this).find('.'+c);
var checkBox=jq(this).find('.'+ic);
if(checkBox.attr('disabled')){
return;
}else{
if(spanBox.hasClass(cc)){
spanBox.removeClass(cc);
checkBox.removeAttr('checked');
}else{
spanBox.addClass(cc);
checkBox.attr('checked', 'checked');
}
}
checkBox.trigger('change');
return false;
});
}
//下拉框
function selectInit(obj)
{
var selects=ifdom(obj);
selects.each(function(){
var $sel=jq(this),
className=$sel.attr('class'),
$selPrev=$sel.prev('.'+w),
disabled=$sel.attr('disabled')=='disabled'?'sel_disabled':'',
readonly=$sel.attr('disabled')=='disabled'?'readonly':'',
edit=$sel.attr('data-edit'),
$wrap=jq('<div class="'+w+' '+disabled+'">'+
'<div class="'+d+'"></div>'+
'</div>');
$selPrev.remove(),jq('.'+l+'[data-sel="'+$sel.attr('id')+'"]').remove(),$sel.before($wrap);
if(className.length>10){
className=className.replace(is+' ','');
$wrap.addClass(className);
}
if($sel[0].style.width){$wrap.css('width',$sel[0].style.width);}
if(edit){
$wrap.find('.'+d).html('<input class="select_input" type="text" '+readonly+' >');
}
var options=$sel.find('option'),
selected_option=options.filter(':selected'),
val=[];
for(var i=0;i<selected_option.length;i++)
{
val.push(selected_option.eq(i).text());
}
if(edit){
$wrap.find('.'+d).children().val(val.join('、'));
}else{
$wrap.find('.'+d).text(val.join('、'));
}
selectEvent($sel);
});
}
function selectEvent($sel){
var $wrap=$sel.prev(),
$div=$wrap.find('.'+d),
$input=$div.find('input'),
$list=jq('.'+l+'[data-sel="'+$wrap.attr('data-index')+'"]'),
mul=$sel.attr('multiple');
$div.click(function(){
if($sel.attr('disabled')){
return;
}else{
if($wrap.hasClass('active')){
hideList($wrap,$list);
//$input.blur();
}else{
if(!$wrap.attr('data-index')){
$wrap.attr('data-index',inputUuid());
createOptions($sel);
$list=jq('.'+l+'[data-sel="'+$wrap.attr('data-index')+'"]');
}
$list.children().removeClass('sel_hide');
showList($wrap,$div,$list);
}
}
});
$div.children().on('keyup',function(e){
if(jq(this).attr('readonly')){
return false;
}
if(e.keyCode){
var hiddens = 0,
inputVal= jq(this).val(),
search = inputVal.toLowerCase();
search=jq.trim(search);
if(!search){
if(!$sel.find('option[value=""]').length) {
$sel.append(jq('<option value=""></option>'));
}
$sel.val('');
}
$list.find('li.sel_visible').removeClass('sel_hide');
var addli=jq('<li class="sel_none">无匹配项</li>');
hiddens = $list.find('li.sel_visible').filter(function (i, li) {
return jQuery(li).text().toLowerCase().indexOf(search) < 0;
}).addClass('sel_hide').length;
$list.find('li').removeClass('selected');
if ($list.find('li.sel_visible').length == hiddens){
if(!$list.find('.sel_none').length){
if($sel.attr('data-diy')!='true'){
$list.append(addli);
}else{
$list.hide();
}
}
}else{
$list.show();
jq('.sel_none').remove();
$list.find('li.sel_visible').not('.sel_hide').eq(0).addClass('selected');
}
setListHeight($div,$list);
}
}).on('blur',function(){
if(jq(this).attr('readonly')){
return false;
}
var inputVal= jq(this).val(),
lied=$list.find('.selected'),
txt=lied.text(),
val=lied.attr('data-value');
if(inputVal==$sel.val()){
return false;
}
if($sel.attr('data-diy')=='true'){
$list.find('li').removeClass('selected');
var l=0;
$sel.find('option').each(function(){
if(jq(this).text()==inputVal){
l+=1;
}
});
if(l>0){
$sel.find('.addOption').remove();
//val=jq(this).attr('value');
$sel.val(val);
$list.find('li[data-value="'+val+'"]').addClass('selected');
}else{
if(!$sel.find('.addOption').length) {
$sel.append(jq('<option class="addOption"></option>'));
}
$sel.find('.addOption').attr('value',inputVal).text(inputVal);
$sel.val(inputVal);
}
}else{
if($list.find('.sel_none').length){
$list.hide();
$list.find('li.sel_visible').removeClass('sel_hide');
jq('.sel_none').remove();
jq(this).val('');
$list.find('li.sel_visible').eq(0).addClass('selected');
$sel.val('');
}else{
jq(this).val(txt);
$sel.val(val);
}
}
$sel.trigger('change');
});
}
function createOptions($sel){
var $wrap=$sel.prev(),
options=$sel.find('option').not('.addOption'),
multiple=$sel.attr('multiple')=='multiple'?'sel_multiple':'',
$list=jq('<ul class="'+l+' '+multiple+'" data-sel="'+$wrap.attr('data-index')+'" style="width:'+$wrap.outerWidth()+'px;z-index:99999999;"></ul>').appendTo('body');
var liHtml='';
for(var n=0;n<options.length;n++){
var selected=options.eq(n).is(':selected')?'selected':'';
liHtml+='<li class="sel_visible '+selected+'" data-value="'+options.eq(n).attr("value")+'">'+options.eq(n).text()+'</li>';
}
$list.html(liHtml);
var $li=$list.children('.sel_visible');
$li.on('mousedown',function(event){
if($sel.attr('multiple')){
jq(this).toggleClass('selected');
var val=[],
lied=$list.find('.selected');
for(var i=0;i<lied.length;i++){
val.push(lied.eq(i).attr('data-value'))
}
setSelVal($sel,val.join(','));
}else{
event.preventDefault();
var val=jq(this).attr('data-value');
setSelVal($sel,val);
hideList($wrap,$list);
}
});
$li.on('mouseover',function(e){
jq(this).addClass('hover');
var txtW=jq(this).text().length*parseInt(jq(this).css('font-size'));
if(txtW>jq(this).width()){
var xx=e.pageX+20;
var yy=e.pageY+5;
jq('body').append('<span class="tips" style="font-size:12px;padding:0 5px; border:1px solid #dee5ef; background-color: #f7faff; position:absolute; top:'+yy+'px; left:'+xx+'px; z-index:99999999;">'+jq(this).text()+'</span>');
}
}).on('mouseout',function(){
jq(this).removeClass('hover');
jq('.tips').remove();
});
}
function showList($wrap,$div,$list){
jq('.select_box').removeClass('active');
jq('.select_option').hide();
if($list.find('li.sel_visible').length > 0) {
$wrap.addClass('active');
$list.show();
setListHeight($div,$list);
}
}
function hideList($wrap,$list){
$wrap.removeClass('active');
$list.hide();
}
function setListHeight($div,$list){
var optionHeight=$list.find('li.sel_visible').height(),
optionLength=$list.find('li.sel_visible').not('.sel_hide').length,
listHeight=optionHeight*optionLength,
maxSize=$div.parent().siblings('select').attr('data-size');
var maxHeight;
if(!maxSize){
maxHeight=200;
}else{
maxHeight=maxSize*optionHeight;
}
if(listHeight>maxHeight)
{
$list.css('height',maxHeight+'px');
}else{
$list.css('height','auto');
}
var eventType = 'mousewheel';
if (document.mozHidden !== undefined) {
eventType = 'DOMMouseScroll';
}
jq(document).not($list).on(eventType, function(event) {
hideList($div.parent(),$list);
});
$list.on(eventType, function(event) {
event.stopPropagation();
var scrollTop = this.scrollTop,
scrollHeight = this.scrollHeight,
height = this.clientHeight;
var delta = (event.originalEvent.wheelDelta) ? event.originalEvent.wheelDelta : -(event.originalEvent.detail || 0);
if ((delta > 0 && scrollTop <= delta) || (delta < 0 && scrollHeight - height - scrollTop <= -1 * delta)) {
this.scrollTop = delta > 0? 0: scrollHeight;
event.preventDefault();
return false;
}
});
var parentHeight = jq(window).height();
if(!parentHeight){
parentHeight = jq(document).height();
}
var topHeight=$div.offset().top-jq(window).scrollTop()+$list.height()+$div.outerHeight(); //计算出 list 的底部离window顶部高度
var botHeight=($div.offset().top-jq(window).scrollTop()) - $list.height(); //计算下拉框顶部离window顶部距离 与 list之差
$list.css('left',$div.offset().left-1)
if(topHeight>parentHeight){ //高度超出父元素总高度(window) 则显示在上方
if(botHeight>0){
$list.css('top',$div.offset().top-$list.height());
//$list.css('top',-$list.height()-11); // 此行替换上行 可调整下拉选择框的位置是紧挨文字or紧挨边框
}else{
//上方高度不够 需要重新计算list高度
if((parentHeight-topHeight) >= botHeight){ //下方高度比上方大 则显示在下方
$list.css('height', $list.height() + (parentHeight - topHeight)); //计算差值 调低list高度
$list.css('top',$div.offset().top+$div.outerHeight());
//$list.css('top',$div.outerHeight()+9);
}else{ //上方高度比下方大
$list.css('height', $list.height() + botHeight); //计算差值 调低list高度
$list.css('top',$div.offset().top-$list.height());
//$list.css('top',-$list.height()-11);
}
}
}else{
$list.css('top',$div.offset().top+$div.outerHeight());
}
}
//判断dom是元素还是对象
function ifdom(obj){
var domObj;
if(typeof(obj) != "object"){ domObj = jq(obj); }else{ domObj=obj; }
return domObj;
}
//动态设置单选框选中
function setRadioVal(obj,value){
var radioBox=ifdom(obj),
spanBox=radioBox.next(),
name=radioBox.attr('name'),
otherRadio=jq('input[type="radio"][name="'+name+'"]').not(radioBox),
otherSpan=otherRadio.next();
if(value==true){
spanBox.addClass(rc);
otherRadio.attr('checked',false);
otherSpan.removeClass(rc);
}else{
spanBox.removeClass(rc);
}
radioBox.attr('checked',value);
}
//单选框不可用
function radioDisable(obj,value){
var radioBox=ifdom(obj),
spanBox=radioBox.next(),
cAttr=radioBox.attr('checked');
radioBox.attr('disabled',value);
if(value==true){
if(cAttr){ spanBox.addClass(rcd); }else{ spanBox.addClass(rd); }
}else{
if(cAttr){ spanBox.removeClass(rcd); }else{ spanBox.removeClass(rd); }
}
}
//动态设置复选框选中
function setCheckVal(obj,value){
var checkBox=ifdom(obj),
spanBox=checkBox.next();
checkBox.attr('checked',value);
if(value==true){ spanBox.addClass(cc); }else{ spanBox.removeClass(cc); }
}
//复选框不可用
function checkDisable(obj,value){
var checkBox=ifdom(obj),
spanBox=checkBox.next(),
cAttr=checkBox.attr('checked');
checkBox.attr('disabled',value);
if(value==true){
if(cAttr){ spanBox.addClass(ccd); }else{ spanBox.addClass(cd); }
}else{
if(cAttr){ spanBox.removeClass(ccd); }else{ spanBox.removeClass(cd); }
}
}
//动态设置选中下拉框值
function setSelVal(obj,value,triggerChange){
var selObj=ifdom(obj);
if(selObj.attr('multiple')){
var selDiv=selObj.prev(),
selList=jq('.select_option[data-sel="'+selDiv.attr("data-index")+'"]');
if(!value){
selObj.find('option').attr('selected',false);
selObj.val('');
selDiv.find('.select_showbox').text('');
}else{
var vals=value.split(',');
var strs = [],selectedIndex;
selObj.find('option').attr('selected',false);
selList.find('li').removeClass('selected');
for(var len=0;len<vals.length;len++){
if(vals[len]){
selObj.find('option').each(function(){
if(jq(this).attr('value')==vals[len]){
selectedIndex=jq(this).index();
strs.push(jq(this).text());
}
});
selObj.find('option').eq(selectedIndex).attr('selected',true);
selList.find('li').eq(selectedIndex).addClass('selected');
}
}
selDiv.find('.select_showbox').text(strs.join('、'));
}
}else{
selObj.val(value);
var selDiv=selObj.prev(),
selList=jq('.select_option[data-sel="'+selDiv.attr("data-index")+'"]'),
val=selObj.find('option:selected').val()
txt=selObj.find('option:selected').text(),
//selectedIndex=selObj.prop('selectedIndex');
selectedIndex=selObj.find('option:selected').index();
if(selObj.attr('data-edit')){
selDiv.find('.select_input').val(txt);
}else{
selDiv.find('.select_showbox').text(txt);
}
selList.find('li').removeClass('selected');
selList.find('li').eq(selectedIndex).addClass('selected');
if(selObj.attr('data-diy') && val!=value){
selObj.find('option').attr('selected',false);
selList.find('li').removeClass('selected');
if(!selObj.find('.addOption').length) {
selObj.append(jq('<option class="addOption"></option>'));
}
selObj.find('.addOption').attr('value',value).text(value);
selObj.val(value);
selDiv.find('.select_input').val(value);
}
}
if(triggerChange !=false){
selObj.trigger('change');
}
}
// 设置输入框禁用(text) 需要把td加背景色
function inputDisable(obj, value){
var selObj=ifdom(obj);
selObj.attr('disabled',value);
var selDiv=selObj.parentsUntil('td');
if(value==true){
selDiv.addClass('disablecolor');
selObj.addClass('disablecolor');
}else{
selDiv.removeClass('disablecolor');
selObj.removeClass('disablecolor');
}
}
//下拉框不可用
function selDisable(obj,value){
var selObj=ifdom(obj);
selObj.attr('disabled',value);
var selDiv=selObj.prev();
if(value==true){
selDiv.addClass('sel_disabled');
selObj.parent().addClass('disablecolor');
if(selObj.attr('data-edit')){
selDiv.find('.select_input').attr('readonly','readonly');
}
}else{
selDiv.removeClass('sel_disabled');
selObj.parent().removeClass('disablecolor');
if(selObj.attr('data-edit')){
selDiv.find('.select_input').removeAttr('readonly');
}
}
}
function inputUuid() {
var s = [];
var hexDigits = "0123456789abcdef";
for (var i = 0; i < 36; i++) {
s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
}
s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
s[8] = s[13] = s[18] = s[23] = "-";
var uuid = s.join("");
return uuid;
} |
$(document).ready(function() {
var clickCount = 0;
var charClicked = "";
var attackChar = "";
var defendChar = "";
var attackHealth = 0;
var defendHealth = 0;
var deadDefenders = [];
var gameStatus = "";
var defenderIsActive = false;
var resetButton = $("<button>");
resetButton.attr("id", "resetBtn");
resetButton.text("Reset");
var kenobi = {
name: "Obi-Wan Kenobi",
health: 120,
attack: 9,
counterAttack: 12,
isClicked: false,
}
var skywalker = {
name: "Luke Skywalker",
health: 140,
attack: 6,
counterAttack: 18,
isClicked: false,
}
var vader = {
name: "Darth Vader",
health: 100,
attack: 9,
counterAttack: 24,
isClicked: false,
}
var maul = {
name: "Darth Maul",
health: 160,
attack: 6,
counterAttack: 15,
isClicked: false,
}
//populate the starting health points
$("#kenobi-hp").text(kenobi.health);
$("#skywalker-hp").text(skywalker.health);
$("#vader-hp").text(vader.health);
$("#maul-hp").text(maul.health);
function selectDefender(defender, setAttacker) {
if (defender.isClicked) return;
defendChar.isClicked = true;
$("#p1").text("");
$("#p2").text("");
if (defender === kenobi) {
$("#kenobi-div").appendTo("#defender").css({
"background-color": "#000000",
"color": "#ffffff"});
} else if (defender === skywalker) {
$("#skywalker-div").appendTo("#defender").css({
"background-color": "#000000",
"color": "#ffffff"});
} else if (defender === vader) {
$("#vader-div").appendTo("#defender").css({
"background-color": "#000000",
"color": "#ffffff"});
} else if (defender === maul) {
$("#maul-div").appendTo("#defender").css({
"background-color": "#000000",
"color": "#ffffff"});
}
}
function selectAttacker(attacker) {
if (attacker.isClicked) return;
attackChar.isClicked = true;
if (attacker === kenobi) {
$("#kenobi-div").appendTo("#your-char");
$("#skywalker-div").appendTo("#enemy-attack").css("background-color", "#ff0000");
$("#vader-div").appendTo("#enemy-attack").css("background-color", "#ff0000");
$("#maul-div").appendTo("#enemy-attack").css("background-color", "#ff0000");
} else if (attacker === skywalker) {
$("#skywalker-div").appendTo("#your-char");
$("#kenobi-div").appendTo("#enemy-attack").css("background-color", "#ff0000");
$("#vader-div").appendTo("#enemy-attack").css("background-color", "#ff0000");
$("#maul-div").appendTo("#enemy-attack").css("background-color", "#ff0000");
} else if (attacker === vader) {
$("#vader-div").appendTo("#your-char");
$("#kenobi-div").appendTo("#enemy-attack").css("background-color", "#ff0000");
$("#skywalker-div").appendTo("#enemy-attack").css("background-color", "#ff0000");
$("#maul-div").appendTo("#enemy-attack").css("background-color", "#ff0000");
} else if (attacker === maul) {
$("#maul-div").appendTo("#your-char");
$("#kenobi-div").appendTo("#enemy-attack").css("background-color", "#ff0000");
$("#skywalker-div").appendTo("#enemy-attack").css("background-color", "#ff0000");
$("#vader-div").appendTo("#enemy-attack").css("background-color", "#ff0000");
}
}
function attackHealthCalc(attHealth) {
attHealth = attHealth - defendChar.counterAttack;
return attHealth;
}
function defenderHealthCalc(defHealth) {
defHealth = defHealth - attackPower;
return defHealth;
}
//determines what to do based on characters health and calls the function to write the html messages.
function attackDefend(attackObj, defendObj, aPower) {
//calculates the defenders health after attack
defendHealth = defenderHealthCalc(defendHealth, attackPower);
//calculates the attackers health after attack
if (defendHealth > 0) {
attackHealth = attackHealthCalc(attackHealth);
}
if (defendObj === kenobi) {
$("#kenobi-hp").text(defendHealth);
} else if (defendObj === skywalker){
$("#skywalker-hp").text(defendHealth);
} else if (defendObj === vader){
$("#vader-hp").text(defendHealth);
} else if (defendObj === maul){
$("#maul-hp").text(defendHealth);
}
if (defendHealth <= 0) {
//new defender logic
gameStatus = "defenderDead";
defenderIsActive = false;
deadDefenders.push(defendObj);
if (defendObj === kenobi) {
$("#kenobi-div").hide();
} else if (defendObj === skywalker){
$("#skywalker-div").hide();
} else if (defendObj === vader){
$("#vader-div").hide();
} else if (defendObj === maul){
$("#maul-div").hide();
}
} else if (attackHealth <= 0) {
//game over logic
gameStatus = "gameover";
} else {
//continue attack logic
gameStatus = "continue";
}
if (deadDefenders.length >= 3) {
gameStatus = "alldefendersDead"
}
if (attackObj === kenobi) {
$("#kenobi-hp").text(attackHealth);
} else if (attackObj === skywalker){
$("#skywalker-hp").text(attackHealth);
} else if (attackObj === vader){
$("#vader-hp").text(attackHealth);
} else if (attackObj === maul){
$("#maul-hp").text(attackHealth);
}
writeHtml(gameStatus, defendObj, aPower);
}
//write html messages based on attack results
function writeHtml(gameOptions, dObject, attackPwr,) {
if (gameOptions === "gameover") {
$("#p1").text("You have been defeated... GAME OVER!!").css({
"color": "#ff0000",
"font-size": "25px"
});
$("#p2").text("");
$("#text-display").show().append(resetButton);
$("#resetBtn").show().on("click", function() {
resetGame();
})
defenderIsActive = true;
}else if (gameOptions === "defenderDead") {
$("#p1").text("You have defeated " + dObject.name + " ,choose another enemy");
$("#p2").text("");
}else if (gameOptions === "alldefendersDead") {
$("#p1").text("You Won!!! GAME OVER!!").css({
"color": "#00e600",
"font-size": "25px"
});
$("#p2").text("");
$("#text-display").append(resetButton);
$("#resetBtn").show().on("click", function() {
resetGame();
})
}else if (gameOptions === "continue") {
$("#p1").text("You attacked " + dObject.name + " for " + attackPwr + " damage.");
$("#p2").text(dObject.name + " attacked you back for " + dObject.counterAttack + " damage.");
}
}
function resetGame () {
clickCount = 0;
charClicked = "";
attackChar = "";
defendChar = "";
attackHealth = 0;
defendHealth = 0;
deadDefenders = [];
gameStatus = "";
defenderIsActive = false;
kenobi.isClicked = false;
skywalker.isClicked = false;
vader.isClicked = false;
maul.isClicked = false;
$("#kenobi-div").show().appendTo("#top-selection").css({
"background-color": "#ffffff",
"color": "#000000"});
$("#skywalker-div").show().appendTo("#top-selection").css({
"background-color": "#ffffff",
"color": "#000000"});
$("#vader-div").show().appendTo("#top-selection").css({
"background-color": "#ffffff",
"color": "#000000"});
$("#maul-div").show().appendTo("#top-selection").css({
"background-color": "#ffffff",
"color": "#000000"});
$("#kenobi-hp").text(kenobi.health);
$("#skywalker-hp").text(skywalker.health);
$("#vader-hp").text(vader.health);
$("#maul-hp").text(maul.health);
$("#p1").text("");
$("#p1").text("").css({
"color": "#ffffff",
"font-size": "100%"
});
$("#p2").text("");
$("#resetBtn").hide();
}
//captures the click to see which character was clicked
$(".char-div").on("click", function() {
charClicked = ($(this).attr("value"));
if (clickCount === 0) { //first click sets the attacker
if (charClicked === "kenobi") {
attackChar = kenobi;
} else if (charClicked === "skywalker") {
attackChar = skywalker;
} else if (charClicked === "vader") {
attackChar = vader;
}
else if (charClicked === "maul") {
attackChar = maul;
}
selectAttacker(attackChar);
clickCount++;
attackHealth = attackChar.health;
attackPower = attackChar.attack;
} else if (clickCount > 0) { //remaining clicks select the defender
if (defenderIsActive) return;
charClicked = ($(this).attr("value"));
if (charClicked === "kenobi") {
defendChar = kenobi;
} else if (charClicked === "skywalker") {
defendChar = skywalker;
} else if (charClicked === "vader") {
defendChar = vader;
}
else if (charClicked === "maul") {
defendChar = maul;
}
if(defendChar === attackChar) return;
defenderIsActive = true;
selectDefender(defendChar, attackChar);
defendHealth = defendChar.health;
}
})
$("#attack-btn").on("click", function() {
if (gameStatus === "gameover") return;
if (!defenderIsActive) return;
attackDefend(attackChar, defendChar,attackPower);
attackPower += attackChar.attack;
})
});
|
import React from 'react';
import './OrderProducts.css';
import test from '../../../Resources/Picture/Products/NikonLens.jpg';
const OrderProducts = (props) => {
return (
<div className='orderproduct__card'>
<div className='product__imageContainer'>
<img className='product__image' src={props.image} alt='product.png' />
</div>
<div className='product__footer'>
<div className='product__info'>
<div className='product__name'>{props.name}</div>
<div className='product__price'>Price: ${props.price}</div>
</div>
</div>
</div>
);
};
export default OrderProducts;
|
import React from 'react'
import axios from 'axios'
import seta from '../img/botao.png'
import styled from 'styled-components'
import lixeira from '../img/lixeira.png'
const ButtonImg = styled.img`
width: 20px;
object-fit: cover;
display: block;
`
const Conteiner = styled.div `
display: block;
width: 500px;
margin: auto;
text-align: center;
-webkit-box-shadow: 0px 2px 8px -2px rgba(34, 34, 34, 0.4);
-moz-box-shadow: 0px 2px 8px -2px rgba(34, 34, 34, 0.4);
box-shadow: 0px 5px 8px -2px rgba(34, 34, 34, 0.4);
background-color: #8B795E;
`
const ImageButton = styled.img `
width:20px;
`
const TudoDiv = styled.div `
font-family: 'Roboto Mono';
color:#FFEFDB;
`
const Button = styled.button `
margin-top: 5px;
border: none;
background-color: transparent;
cursor:pointer;
`
const ButtonVoltar = styled.button `
border: none;
cursor: pointer;
font-family: 'Roboto Mono';
margin: 5px 0 0 10px;
:hover{
color: #FF4500;
}
`
const Input = styled.input `
height:22px;
border: none;
background-color:#E8E8E8;
margin-right: 5px;
text-align: center;
`
const Div = styled.div `
display: flex;
justify-content: center;
`
const Background =styled.div `
background-color: black;
`
export default class MusicaArtista extends React.Component {
state = {
music: "",
artist: "",
url:"" ,
musicas: []
}
inputMusica = (e) => {
this.setState({music: e.target.value})
}
inputArtista = (e) => {
this.setState({artist: e.target.value})
}
inputUrl = (e) => {
this.setState({url: e.target.value})
}
componentDidMount () {
this.verMusicas()
}
verMusicas = () => {
const url = `https://us-central1-labenu-apis.cloudfunctions.net/labefy/playlists/${this.props.playListId}/tracks`
axios.get(url, {
headers: {
Authorization: "elaini-coelho-molina"
}
}).then((res) => {
this.setState({musicas: res.data.result.tracks})
console.log(res.data.result.tracks)
})
.catch((err) => {
alert("Error: " + err.message)
})
}
adcMusica = (id) => {
const url = `https://us-central1-labenu-apis.cloudfunctions.net/labefy/playlists/${this.props.playListId}/tracks`
const body = {
name: this.state.music,
artist: this.state.artist,
url: this.state.url
}
axios.post(url,body, {
headers: {
Authorization: "elaini-coelho-molina"
}
}).then((res) => {
alert("Musica adicionada!")
this.verMusicas()
this.setState({ music: "",
artist: "",
url:""})
}).catch((err) => {
alert("ERROR")
})
}
deleteMusica = (id) => {
const url = `https://us-central1-labenu-apis.cloudfunctions.net/labefy/playlists/${this.props.playListId}/tracks/${id}`
axios.delete(url, {
headers: {
Authorization: "elaini-coelho-molina"
}
})
.then((res) => {
this.verMusicas(id)
this.setState({})
})
.catch((err) => {
alert("Erro")
})
}
getEmbledUrl = (url) => {
const urlQuebrada = url.split('watch?v=')
const videoId = urlQuebrada[1]
const youtube = 'https://youtube.com/embed/'
return youtube + videoId
}
render() {
const MusicasNaLista = this.state.musicas.map((lista) => {
return(
<div key={lista.id} >
<Conteiner>
<h2>{lista.artist}</h2>
<h3>{lista.name}</h3>
<Button onClick={() => this.deleteMusica(lista.id)} ><ImageButton src={lixeira} /></Button>
<iframe width="100%" height="300"
src={this.getEmbledUrl(lista.url)} title="YouTube video player"
frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen></iframe>
</Conteiner>
</div>
)
})
return(
<Background>
<ButtonVoltar onClick={this.props.irParaListPlay} >Voltar</ButtonVoltar>
<Div>
<Input
placeholder="MUSIC"
value={this.state.music}
onChange={this.inputMusica}
/>
<Input
placeholder="ARTIST"
value={this.state.artist}
onChange={this.inputArtista}
/>
<Input
placeholder="URL"
type="url"
value={this.state.url}
onChange={this.inputUrl}
/>
<button onClick={this.adcMusica} ><ButtonImg src={seta}/></button>
</Div>
<TudoDiv>
{MusicasNaLista}
</TudoDiv>
</Background>
)
}
} |
module.exports = targets => {
targets.of('@magento/pwa-buildpack').specialFeatures.tap((flags) => {
flags[targets.name] = {
esModules: true,
cssModules: true,
graphqlQueries: true,
rootComponents: true,
i18n: true
};
});
};
|
export function showModalElement(classModalParentElememntCSS, timerModal){
const modalWrapper = document.querySelector(classModalParentElememntCSS);
if(modalWrapper.classList.contains('show')) return;
modalWrapper.classList.toggle('show');
document.body.style.overflow='hidden';
if(timerModal){
clearTimeout(timerModal);
}
}
export function closModalElement(classModalParentElememntCSS){
const modalWrapper = document.querySelector(classModalParentElememntCSS);
if (!modalWrapper.classList.contains('show')) return;
modalWrapper.classList.toggle('show');
document.body.style.overflow='';
}
export function showModalElementScroll(){
if(document.documentElement.clientHeight + pageYOffset == document.documentElement.scrollHeight){
showModalElement('.modal');
window.removeEventListener('scroll', showModalElementScroll);
}
}
export function modal(classModalParentElememntCSS,classModalClosElement, classModalOpenElement, timerModal){
const modalWrapper = document.querySelector(classModalParentElememntCSS);
const modalClose = document.querySelector(classModalClosElement);
const modalOpen = document.querySelectorAll(classModalOpenElement);
window.addEventListener('keydown', (event)=>{
if (event.key !== 'Escape') return;
closModalElement(classModalParentElememntCSS);
})
window.addEventListener('scroll', showModalElementScroll);
modalWrapper.addEventListener('click', (event)=>{
const target = event.target;
if (target !== modalClose && target !== modalWrapper) return;
closModalElement(classModalParentElememntCSS);
})
modalOpen.forEach(item =>{
item.addEventListener('click', () => showModalElement(classModalParentElememntCSS, timerModal))
})
}
|
import Auth from "./auth";
const bodyParser = require('body-parser');
var express = require('express')
const app = express();
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({extended: false})); // support encoded bodies
export const router = express.Router()
router.post('/login', (req, res) => {
const {email, parola, tip} = req.body;
if (email && parola) {
Auth.findByEMailAndPassword(email, parola, tip, (err, user) => {
if (err) {
res.send(err);
} else {
if (user.length != 0 && parola == user[0].parola) {
res.status(201).send({body: user[0].id});
} else {
res.status(400).send({error: "Invalid credentials"});
}
}
}
);
}
}); |
import config from '../app/config'
import Contact from '../store/contact.jsx'
import db from '../store/database.jsx'
import Skype from './static.jsx'
import striptags from 'striptags'
import {AllHtmlEntities} from 'html-entities'
import {clear} from '../util/index.jsx'
import {millisecondsId, isSkypeUsername} from '../util/index.jsx'
import {toArray, each, isObject, isEmpty} from 'lodash'
export default async function processProfile(profile) {
profile.contacts = profile.contacts
.filter(c => 'skype' === c.type && !c.blocked && config.exlude.indexOf(c.id) < 0)
const exclude = ['avatar_url', 'display_name_source', 'name',
'person_id', 'auth_certificate', 'blocked', 'type']
profile.contacts.forEach(function (contact) {
exclude.forEach(function (key) {
delete contact[key]
})
})
clear(profile)
await api.send('skype/profile', {id: profile.login}, profile)
const existing = await db.contact
.filter(c => profile.login === c.account)
.toArray()
const g = millisecondsId()
const contacts = []
const entities = new AllHtmlEntities()
profile.contacts.forEach(function (c) {
if (isSkypeUsername(c.id)) {
const id = profile.login + '~' + c.id
const found = existing.find(x => id === x.id)
const contact = {
type: config.Type.PERSON,
id,
account: profile.login,
login: c.id,
name: c.display_name,
authorized: c.authorized ? 1 : 0,
status: found ? found.status : config.Status.NONE,
time: found ? found.time : g.next().value
}
if (c.authorized && db.INVITED === contact.status) {
contact.status = config.Status.NONE
}
contacts.push(contact)
}
})
const absent = contacts
.filter(c => !existing.find(x => c.id == x.id))
.map(c => c.id)
profile.conversations.forEach(function (c) {
const chatId = /19:([0-9a-f]+)@thread\.skype/.exec(c.id)
if (chatId) {
const login = chatId[1]
const id = profile.login + '~' + login
const found = existing.find(x => id === x.id)
const available = isObject(c.threadProperties)
&& c.threadProperties.topic
&& !c.threadProperties.lastleaveat
// && !isEmpty(c.lastMessage)
if (available) {
try {
const name = striptags(entities.decode(c.threadProperties.topic))
.replace(/\s+/g, ' ')
.trim()
contacts.push({
type: config.Type.CHAT,
id,
account: profile.login,
login,
name,
authorized: 1,
status: found ? found.status : config.Status.NONE,
time: found ? found.time : g.next().value
})
}
catch (ex) {
console.error(ex)
}
}
else if (found) {
absent.push(id)
}
}
})
await db.contact.bulkDelete(absent)
await db.contact.bulkPut(contacts)
Skype.emit('contacts', {profile})
Contact.emit('update', {account: profile.login})
}
|
"use strict";
function generateClassRecordSummary(scores) {
const Exam1 = [];
const Exam2 = [];
const Exam3 = [];
const Exam4 = [];
const Exams = [];
const StudentGrades = [];
for (let student in scores) {
let examScores = scores[student]['scores']['exams'];
let exerciseScores = scores[student]['scores']['exercises'];
let avgExamScore = averageExamScore(examScores);
let exerciseScore = exerciseScoresTotal(exerciseScores);
let numericGrade = numericalGrade(avgExamScore, exerciseScore);
let alphaGrade = letterGrade(numericGrade);
StudentGrades.push(`${numericGrade} (${alphaGrade})`);
collectExamData(Exam1, Exam2, Exam3, Exam4, examScores);
}
generateExamStatistics(Exam1, Exam2, Exam3, Exam4, Exams);
return {
studentGrades: StudentGrades,
exams: Exams,
};
}
function averageExamScore(scores) {
let total = scores.reduce(sum);
return total / scores.length;
}
function exerciseScoresTotal(scores) {
return scores.reduce(sum);
}
function sum(score1, score2) {
return score1 + score2;
}
function numericalGrade(examAvgScore, exerciseTotalScore) {
return Math.round((examAvgScore * 0.65) + (exerciseTotalScore * 0.35));
}
function letterGrade(numericalGrade) {
if (numericalGrade >= 93) {
return 'A';
} else if (numericalGrade >= 85) {
return 'B';
} else if (numericalGrade >= 77) {
return 'C';
} else if (numericalGrade >= 69) {
return 'D';
} else if (numericalGrade >= 60) {
return 'E';
} else {
return 'F';
}
}
function collectExamData(exam1, exam2, exam3, exam4, examScores) {
exam1.push(examScores[0]);
exam2.push(examScores[1]);
exam3.push(examScores[2]);
exam4.push(examScores[3]);
}
function examStats(exam) {
let stats = {};
stats['average'] = averageExamScore(exam);
stats['minimum'] = Math.min(...exam);
stats['maximum'] = Math.max(...exam);
return stats;
}
function generateExamStatistics(exam1, exam2, exam3, exam4, combined) {
[exam1, exam2, exam3, exam4].forEach(exam => combined.push(examStats(exam)));
}
let studentScores = {
student1: {
id: 123456789,
scores: {
exams: [90, 95, 100, 80],
exercises: [20, 15, 10, 19, 15],
},
},
student2: {
id: 123456799,
scores: {
exams: [50, 70, 90, 100],
exercises: [0, 15, 20, 15, 15],
},
},
student3: {
id: 123457789,
scores: {
exams: [88, 87, 88, 89],
exercises: [10, 20, 10, 19, 18],
},
},
student4: {
id: 112233445,
scores: {
exams: [100, 100, 100, 100],
exercises: [10, 15, 10, 10, 15],
},
},
student5: {
id: 112233446,
scores: {
exams: [50, 80, 60, 90],
exercises: [10, 0, 10, 10, 0],
},
},
};
console.log(generateClassRecordSummary(studentScores));
|
import React, { Component } from 'react';
import './register.css';
class Register extends Component {
constructor(props) {
super(props);
this.state = {
email: null,
username: null,
password: null
}
this.handleChange = props.handleChange.bind(this);
}
render() {
return (
<form className="form-control-sm" onSubmit={(e) => this.props.handleSubmit(e, this.state, true)}>
<div className="form-group">
<label htmlFor="email">Email address</label>
<input className="form-control" type="email" onChange={this.handleChange} name="email" placeholder="Email"/>
<small>We'll never share your email with anyone else.</small>
</div>
<div className="form-group">
<label htmlFor="username">Username</label>
<input className="form-control" type="text" onChange={this.handleChange} name="username" placeholder="Username"/>
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input className="form-control" type="password" onChange={this.handleChange} name="password" placeholder="******"/>
<small>We'll never share your rassword with anyone else.</small>
</div>
<button className="btn btn-outline-primary" to="/" type="submit">Register</button>
</form>
)
}
}
export default Register; |
import { initializeApp } from 'firebase/app';
import { getAuth, onAuthStateChanged } from 'firebase/auth';
const firebaseConfig = {
apiKey: "AIzaSyDQbcWmccXbr775SiEaIKOCVjB7r31bRPM",
authDomain: "powa-wise-app.firebaseapp.com",
projectId: "powa-wise-app",
storageBucket: "powa-wise-app.appspot.com",
messagingSenderId: "64295682989",
appId: "1:64295682989:web:b73e83ed57cb301aa25724",
measurementId: "G-X6TFN5QS03"
};
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
console.log('Hello world');
onAuthStateChanged(auth, user => {
if(user == null){
console.log('No user');
} else {
console.log('logged in');
}
}); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.