text
stringlengths
7
3.69M
/* Conjunto de funciones que crean la base de datos y la llenan con datos generados con el módulo Faker. */ const faker = require('faker'); const lodash = require('lodash'); //Módulo usado para generar números random. const path = require('path'); //Módulo para creación de rutas de directorios y archivos. const helpers = require('../helpers'); //Módulo que incluye los helpers globales. const tablas = require('./tablasDD'); // Módulo con los objetos que definen las tablas de la base de datos. const conexionMysql = require('./conexionMysql'); //Modulo para obtener conexión a MYSQL const {fakerConfig }= require('../config'); /** * Esta función elimina las tablas definidas en módulo tablasDD de la base de datos si es que existen. * @param {Object} conexion - Conexión a Mysql */ async function eliminarTablas(conexion) { //Desactivamos el check de foreign keys para eliminar las tablas que contengan foreign keys. await conexion.query( ` SET foreign_key_checks = 0;` ); for (const tabla in tablas) { await conexion.query( ` DROP TABLE IF EXISTS ${tablas[tabla].nombre} ` ); } //Volvemos a activar el check de foreign keys de nuevo. await conexion.query( ` SET foreign_key_checks = 1;` ); helpers.log(`Tablas eliminadas`); } /** * Crea las tablas del array de tablas del módulo tablasDD si es que no existen en la base de datos. * @param {Object} conexion - Conexión a Mysql */ async function crearTablas(conexion) { for (const tabla in tablas) { await conexion.query( ` CREATE TABLE IF NOT EXISTS ${tablas[tabla].nombre} ${tablas[tabla].columnas} ` ); } helpers.log(`Tablas creadas`); } /** * Esta función inserta determinado número de usuarios con datos generado * automáticamente por Faker, usando una conexion a MYSQL. * * @param {number} numeroDeUsuarios - Número de usuarios que se desea insertar * en la tabla. * @param {Object} conexion - Conexión a MYSQL */ async function llenarTablaUsuarios(numeroDeUsuarios, conexion) { for (let i = 0; i < numeroDeUsuarios; i++) { const nombre = faker.name.findName(); const biografia = faker.lorem.paragraph(fakerConfig.usuarios.parrafosBiografia); const email = faker.internet.email(); const contraseña = faker.internet.password(); const avatar = path.join( faker.system.directoryPath(), faker.system.fileName() ); await conexion.query( ` INSERT INTO usuarios ( nombre, biografia, email, contraseña, avatar, fecha, codigo_validacion, ultimo_cambio_contraseña) VALUES( ?, ?, ?, SHA2(?,512), ? ,?,?, ?) `, [ nombre, biografia, email, contraseña, avatar, helpers.formatearDateMysql(new Date()), helpers.generateRandomString(), helpers.formatearDateMysql(new Date()), ] ); } helpers.log(`Insertados ${numeroDeUsuarios} registros en la tabla usuarios`); } /** * Esta función inserta un número determinado de experiencias con datos * generados automáticamente por Faker, usando una conexion a MYSQL. * * @param {number} numeroDeExperiencias * @param {Object} conexion */ async function llenarTablaExperiencias(numeroDeExperiencias, conexion) { const { experiencias } = fakerConfig; for (let i = 0; i < numeroDeExperiencias; i++) { const fecha_insert = helpers.formatearDateMysql(new Date()); const nombre = faker.commerce.productName(); const descripcion = faker.lorem.paragraph(experiencias.parrafosDescripcion); const precio = lodash.random(experiencias.precio.minimo, experiencias.precio.maximo); const ubicacion = faker.address.city(); const rating = lodash.random(experiencias.rating.minimo, experiencias.rating.maximo); const plazasTotales = lodash.random(experiencias.plazas.minimas, experiencias.plazas.maximas); const fechaInicial = helpers.formatearDateMysql(faker.date.recent()); const fechaFinal = helpers.formatearDateMysql(faker.date.future()); const idAutor= 1; await conexion.query( ` INSERT INTO experiencias (fecha_insert, nombre, descripcion, fecha_inicial, fecha_final,rating,precio,ubicacion,plazas_totales, id_autor) VALUES(?,?,?,?,?,?,?,?,?,?) `, [ fecha_insert, nombre, descripcion, fechaInicial, fechaFinal, rating, precio, ubicacion, plazasTotales, idAutor, ] ); } helpers.log( `Insertados ${numeroDeExperiencias} registros en la tabla experiencias` ); } /** * Esta función inserta en la tabla usuarios al usuario administrador, tomando * como credenciales las variables de entorno ADMIN_EMAIL, ADMIN_NAME y ADMIN_PASSWORD * * @param {Object} conexion */ async function crearAdministrador(conexion) { await conexion.query( ` INSERT INTO usuarios ( nombre, email, contraseña, fecha, privilegios, activo ) VALUES( ?, ?, SHA2(?,512), ? ,?,?) `, [ process.env.ADMIN_NAME, process.env.ADMIN_EMAIL, process.env.ADMIN_PASSWORD, helpers.formatearDateMysql(new Date()), "admin", true, ] ); helpers.log("Cuenta de administrador creada"); } /** Configura completamente la base de datos */ async function config() { const { RESET_DB } = process.env; let conexion; try { conexion = await conexionMysql(); if (RESET_DB === 'true') { //Si la variable de entorno RESET_DB es true reseteamos la base de datos. await eliminarTablas(conexion); await crearTablas(conexion); await crearAdministrador(conexion); await llenarTablaUsuarios(fakerConfig.usuarios.cantidad, conexion); await llenarTablaExperiencias(fakerConfig.experiencias.cantidad, conexion); } else if (RESET_DB === 'false') { //De lo contrario sólo creamos las tablas si no existen. await crearTablas(conexion); } else { throw new Error('Valor de variable de entorno RESET_DB no válido') } } catch (error) { helpers.logError(error); } finally { if (conexion) { conexion.release(); } } } module.exports = { config };
let express = require('express') let request = require('request') let router = express.Router() let UserModel = require('../models/user.model') /** * Auxiliar function to response * @param {*} status * @param {*} content */ var sendJsonResponse = (res, status, content) => { res.status(status) res.json(content) } /** * POST new PESSO FÍSICA * ValidationTODO: */ router.post('/conductor/clientes-pessoas-fisicas', (req, res, next) => { const data = { 'nome': req.body.nome, 'nomeMae': req.body.nomeMae, 'dataNascimento': req.body.dataNascimento, 'sexo': req.body.sexo, 'cpf': req.body.cpf, 'numeroIdentidade': req.body.numeroIdentidade, 'orgaoExpedidorIdentidade': req.body.orgaoExpedidorIdentidade, 'unidadeFederativaIdentidade': req.body.unidadeFederativaIdentidade, 'dataEmissaoIdentidade': req.body.dataEmissaoIdentidade, 'idEstadoCivil': req.body.idEstadoCivil, 'idProfissao': req.body.idProfissao, 'idNaturezaOcupacao': req.idNaturezaOcupacao, 'idNacionalidade': req.body.idNacionalidade, 'idOrigemComercial': req.body.idOrigemComercial, 'idProduto': req.body.idProduto, 'numeroAgencia': req.body.numeroAgencia, 'numeroContaCorrente': req.body.numeroContaCorrente, 'email': req.body.email, 'diaVencimento': req.body.diaVencimento, 'nomeImpresso': req.body.nomeImpresso, 'nomeEmpresa': req.body.nomeEmpresa, 'valorRenda': req.body.valorRenda, 'canalEntrada': req.body.canalEntrada, 'valorPontuacao': req.body.valorPontuacao, 'telefones': [ { 'idTipoTelefone': req.body.telefones[0].idTipoTelefone, 'ddd': req.body.telefones[0].ddd, 'telefone': req.body.telefones[0].telefone, 'ramal': req.body.telefones[0].ramal } ], 'enderecos': [ { 'idTipoEndereco': req.body.enderecos[0].idTipoEndereco, 'cep': req.body.enderecos[0].cep, 'logradouro': req.body.enderecos[0].logradouro, 'numero': req.body.enderecos[0].numero, 'complemento': req.body.enderecos[0].complemento, 'pontoReferencia': req.body.enderecos[0].pontoReferencia, 'bairro': req.body.enderecos[0].bairro, 'cidade': req.body.enderecos[0].cidade, 'uf': req.body.enderecos[0].uf, 'pais': req.body.enderecos[0].pais, 'enderecoCorrespondencia': req.body.enderecos[0].enderecoCorrespondencia } ], 'limiteGlobal': req.body.limiteGlobal, 'limiteMaximo': req.body.limiteMaximo, 'limiteParcelas': req.body.limiteParcelas, 'limiteConsignado': req.body.limiteConsignado, 'nomeReferencia1': req.body.nomeReferencia1, 'enderecoReferencia1': req.body.enderecoReferencia1, 'nomeReferencia2': req.body.nomeReferencia2, 'enderecoReferencia2': req.body.enderecoReferencia2 } const options = { url: `${process.env.BASE_URL_CONDUCTOR}/clientes-pessoas-fisicas`, method: 'POST', headers: { 'Content-Type': 'application/json', 'access_token': process.env.ACCESS_TOKEN, 'client_id': process.env.CLIENT_ID }, json: data } request.post(options, (_err, httpResponse, body) => { sendJsonResponse(res, httpResponse.statusCode, body) }) }) /** * POST new PESSO JURÍDICA * ValidationTODO: */ router.post('/conductor/clientes-pessoas-juridicas', (req, res, next) => { const data = { 'razaoSocial': req.body.razaoSocial, 'nomeFantasia': req.body.nomeFantasia, 'cnpj': req.body.cnpj, 'inscricaoEstadual': req.body.inscricaoEstadual, 'dataAberturaEmpresa': req.body.dataAberturaEmpresa, 'idOrigemComercial': req.body.idOrigemComercial, 'idProduto': req.body.idProduto, 'numeroBanco': req.body.numeroBanco, 'numeroAgencia': req.body.numeroAgencia, 'numeroContaCorrente': req.body.numeroContaCorrente, 'email': req.body.email, 'diaVencimento': req.body.diaVencimento, 'nomeImpresso': req.body.nomeImpresso, 'valorRenda': req.body.valorRenda, 'canalEntrada': req.body.canalEntrada, 'valorPontuacao': req.body.valorPontuacao, 'telefones': [ { 'idTipoTelefone': req.body.telefones[0].idTipoTelefone, 'ddd': req.body.telefones[0].ddd, 'telefone': req.body.telefones[0].telefone, 'ramal': req.body.telefones[0].ramal } ], 'enderecos': [ { 'idTipoEndereco': 2, 'cep': req.body.enderecos[0].cep, 'logradouro': req.body.enderecos[0].logradouro, 'numero': req.body.enderecos[0].numero, 'complemento': req.body.enderecos[0].complemento, 'pontoReferencia': req.body.enderecos[0].pontoReferencia, 'bairro': req.body.enderecos[0].bairro, 'cidade': req.body.enderecos[0].cidade, 'uf': req.body.enderecos[0].uf, 'pais': req.body.enderecos[0].pais, 'enderecoCorrespondencia': req.body.enderecos[0].enderecoCorrespondencia } ], 'socios': [ { 'nome': req.body.socios[0].nome, 'cpf': req.body.socios[0].cpf, 'dataNascimento': req.body.socios[0].dataNascimento, 'sexo': req.body.socios[0].sexo, 'numeroIdentidade': req.body.socios[0].numeroIdentidade, 'orgaoExpedidorIdentidade': req.body.socios[0].orgaoExpedidorIdentidade, 'unidadeFederativaIdentidade': req.body.socios[0].unidadeFederativaIdentidade, 'dataEmissaoIdentidade': req.body.socios[0].dataEmissaoIdentidade, 'estadoCivil': req.body.socios[0].estadoCivil, 'profissao': req.body.socios[0].profissao, 'nacionalidade': req.body.socios[0].nacionalidade, 'email': req.body.socios[0].email, 'telefones': [ { 'idTipoTelefone': req.body.telefones[0].idTipoTelefone, 'ddd': req.body.telefones[0].ddd, 'telefone': req.body.telefones[0].telefone, 'ramal': req.body.telefones[0].ramal } ] } ], 'referenciasComerciais': [ { 'razaoSocial': req.body.referenciasComerciais[0].razaoSocial, 'nomeContrato': req.body.referenciasComerciais[0].nomeContrato, 'ddd': req.body.referenciasComerciais[0].ddd, 'telefone': req.body.referenciasComerciais[0].telefone, 'email': req.body.referenciasComerciais[0].email } ], 'limiteGlobal': req.body.limiteGlobal, 'limiteMaximo': req.body.limiteMaximo, 'limiteParcelas': req.body.limiteParcelas } const options = { url: `${process.env.BASE_URL_CONDUCTOR}/clientes-pessoas-juridicas`, method: 'POST', headers: { 'Content-Type': 'application/json', 'access_token': process.env.ACCESS_TOKEN, 'client_id': process.env.CLIENT_ID }, json: data } request.post(options, (_err, httpResponse, body) => { sendJsonResponse(res, httpResponse.statusCode, body) }) }) router.get('/person', (req, res) => { if (req.query.name) { res.send(`You have requested a person ${req.query.name}`) } else { res.send('You have requested a person') } }) router.get('/person/:name', (req, res) => { res.send(`You have requested a person ${req.params.name}`) }) router.get('/error', (req, res) => { throw new Error('This is forced error.') }) module.exports = router
/*********************************************************************** * MODULE `models` * Provides functions to handle model objects within the platform. **********************************************************************/ /** * Declare variables */ var debug = require('debug')('models') , mod_users = require('./users') , mod_posts = require('./posts') , mod_comments = require("./comments"); /** * Module init(), to provide models for a given database connection. * * @param Object database The Database object to initialize models with. * @return Object An object with property names linking to models. */ module.exports = function init(database) { var models = {} // The final object to be returned. , onConnected // A Promise reference. ; debug('installing models for database:', database.uri); // Create a Promise that fulfills on modules loaded. onConnected = new Promise( (resolve, reject) => { // Since model init requires a valid mongodb Database handle, // wait for `database` to connect and provide one. database.then(db => { try { // Init each imported module. models.users = mod_users(db); // Initialize Users model. models.posts = mod_posts(db); // Initialize Post model. models.comments = mod_comments(db); // Initialize Comments model. debug('module initialized'); } catch(e) { debug('FAILED to initialize module'); reject(e); } // Unless a reject's been triggered, the promise will return the // updated `models` object. resolve(models); }, reject); }); // Provide `then()` on the `models` object, bound to the promise. models.then = onConnected.then.bind(onConnected); // Provide `catch()` on the `models` object, bound to the promise. models.catch = onConnected.catch.bind(onConnected); // Return return models; }
module.exports = { host : "localhost", port : 7788, bundle : "assets" };
let telephone = window.localStorage.getItem("telephone"); let search = location.search; let list = search.split("="); let productId = list[1]; console.log(telephone); console.log(search); console.log(list); console.log(productId); var totalFee = 0; var orderNo = 0; // 进去立即购买页面 调buyNow接口 function buyNow() { $.ajax({ url: "https://zhixianzhai.com/buyNow", type: "post", dataType: "json", data: { openId: window.localStorage.getItem("openId"), productId: productId }, success: function(res) { if (res.code === 200) { // 订单编号 orderNo = res.data.orderNo; totalFee = res.data.totalFee; console.log(orderNo); var menu = res.data.productList[0]; console.log(menu); var htmls = template("productTemplate", { result: res.data.productList, amounts: res.data.amounts }); $(".product-box").html(htmls); // 价格 $(".pay-money").html("合计:" + menu.productPrice + "元"); } } }); } // 点击进入退换货政策 function ex() { location.href = "exchange.html"; } // 点击收货地址 function adda() { location.href = "addAddress.html"; } // 获取指定用户所有地址 调getAllAddressByOpenId接口 function getAllAddressByOpenId() { $.ajax({ url: "https://zhixianzhai.com/getAllAddressByOpenId", type: "post", dataType: "json", data: { openId: window.localStorage.getItem("openId") }, success: function(res) { if (res.code === 200 && res.data.length > 0) { let result = res.data[0]; console.log(result); // 姓名 $(".address-name").html(result.userName); // 手机号 $(".address-tel").html(result.telephone); // 地址 $(".address-detail").html(result.addressDetail); } } }); } // 点击去支付 跳转页面 function goPay() { $("#btn-car3").click(function() { var istrue = false; var inp = $(".checkbox-list-input"); for (var i = 0; i < inp.length; i++) { if (inp.eq(i).prop("checked")) { istrue = true; break; } } if (!istrue) { alert( "该笔订单内包含不可退换货/款的商品。付款前请务必详阅并知晓相关政策,并勾选确认" ); return; } else if ( window.localStorage.getItem( "addressObject" ) == "" || window.localStorage.getItem( "addressObject" ) == null || window.localStorage.getItem( "addressObject" ) == undefined ) { alert("请添加地址"); } else { location.href = "payResult.html?totalFee=" + totalFee + "&orderNo=" + orderNo; } }); } $(document).ready(function() { if (productId === undefined || productId === null) { //来自购物车结算 settleAccounts(); } else { //来自立即购买 buyNow(); } let addressString = localStorage.getItem("addressObject"); if (addressString === undefined || addressString === null) { getAllAddressByOpenId(); } else { let addressObject = JSON.parse(addressString); $(".address-name").html(addressObject.userName); $(".address-tel").html(addressObject.telephone); $(".address-detail").html(addressObject.addressDetail); } }); function settleAccounts() { $.ajax({ url: "https://zhixianzhai.com/settleAccounts", type: "post", dataType: "json", data: { openId: window.localStorage.getItem("openId") }, success: function(res) { if (res.code === 200) { // 订单编号 orderNo = res.data.orderNo; totalFee = res.data.totalFee; var htmls = template("productTemplate", { result: res.data.productList, amounts: res.data.amounts }); $(".product-box").html(htmls); $(".pay-money").html("合计:" + totalFee + "元"); } } }); }
TRPG = {'public' : {'id' : '1367153330780' } ,'adm' : 'Hstk4c7N953EnBQns' ,'getUserNick' : function(_id) { if (_.isArray(_id)) { return ( _.map( _id ,function(_id) { return TRPG.getUserNick(_id); } ) ).join('、'); } else { return Meteor.users.findOne({'_id' : _id}).profile.nick; } } ,'options' : {'roomStatus' : ['申請中', '招募中', '進行中', '已結束'] ,'characterStatus' : ['創建中', '進行中'] ,'messageType' : {'chat' : '聊天' ,'dice' : '擲骰' ,'outside' : '場外' ,'system' : '系統' ,'room' : '資訊' } } }
import React from 'react'; import {Provider} from 'react-redux'; import {MuiThemeProvider} from '@material-ui/core/styles'; import CssBaseline from '@material-ui/core/CssBaseline'; import configureStore from 'store'; import rootSaga from 'sagas'; import AppRoutes from 'Routes'; import theme from 'ui/theme'; const store = configureStore(); store.runSaga(rootSaga); const App = () => ( <MuiThemeProvider theme={theme}> <Provider store={store}> <React.Fragment> <CssBaseline /> <AppRoutes history={store.history} /> </React.Fragment> </Provider> </MuiThemeProvider> ); export default App;
setInterval(function(){ document.getElementsByClassName("i2p6rm4e")[0].click() var ranNum = Math.floor(Math.random() * (8 - 5)) + 5; document.getElementsByClassName("bsnbvmp4")[ranNum].click() }, 300);
function drawJumping(playerY) { clearPlayer() ctx.save(); ctx.translate(playerX, canvas.height - playerY) ctx.fillRect(-playerRadius, -playerRadius, playerRadius * 2, playerRadius * 2); ctx.restore(); playerX += playerMoveSpeed; } function clearPlayer() { ctx.clearRect(0, 100, canvas.width, canvas.height); if (playerX >= canvas.width - playerRadius) { level++; start() } if (collision(level)) { gameoverAudio.play() lostCount++; reset() } } function drawInfo() { ctx.clearRect(0, 0, 650, 100); ctx.fillText("Failed: " + lostCount, 100, 60); ctx.fillText(level + "/" + (levelMap.length - 1), 600, 60); }
var express = require('express'); var router = express.Router(); const http = require('http'); /* GET home page. */ router.get('*', function(req, res, next) { const fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl; console.log(fullUrl); console.log ('req.connection.remoteAddress', req.connection.remoteAddress); console.log(`req.headers['x-forwarded-for']`, req.headers['x-forwarded-for']); console.log(`req.origin`, req.origin); const options = { // host to forward to host: 'www.httpbin.org', // port to forward to port: 80, // path to forward to path: '/get', // request method method: 'GET', // headers to send headers: req.headers, }; const creq = http .request(options, pres => { // set encoding var str = '' pres.setEncoding('utf8'); // set http status code based on proxied response // ores.writeHead(pres.statusCode); // wait for data pres.on('data', chunk => { // ores.write(chunk); str += chunk; }); pres.on('close', () => { // closed, let's end client request as well // ores.end(); }); pres.on('end', () => { // finished, let's finish client request as well res.send(JSON.parse(str)); // ores.end(); }); }) .on('error', e => { // we got an error console.log(e.message); try { // attempt to set error message and http status // ores.writeHead(500); // ores.write(e.message); } catch (e) { // ignore } // ores.end(); }); creq.end(); }); router.post('*', function(req, res, next) { console.log(req.body); const fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl; console.log(fullUrl); res.send(fullUrl) }); module.exports = router;
module.exports = { /** Testnet **/ api_host: 'testnet-api.phemex.com', ws_host: 'testnet.phemex.com', api_key: 'your-testnet-apiKey', secret: 'your-testnet-secret', /** Prod **/ // api_host: 'api.phemex.com', // ws_host: 'phemex.com', // url: 'wss://phemex.com/ws/', // apiKey: 'your-prod-apiKey', // secret: 'your-prod-secret', };
const formidable = require('formidable'); const _ = require('lodash'); const fs = require('fs'); const Carros = require('../modelos/modelo.carros'); const {errorHandler} = require('../helpers/dberrorHandler'); const { normalize } = require('path'); //insercion de nuevo vehiculo function nuevo(req,res){ let form = new formidable.IncomingForm() form.keepExtensions = true form.parse(req, (err, fields, files) => { if (err) { return res.status(400).json({ error: "La imagen no pudo ser cargada" }) } const { marca, descripcion, modelo, motor, kilometraje, precio, estado, cajaCambios, comentario } = fields let carros = new Carros(fields); if (files.imagen) { if (files.imagen.size > 1000000) { return res.status(400).json({ error: "Esta imagen es muy pesada" }) } carros.imagen.data = fs.readFileSync(files.imagen.path) carros.imagen.contentType = files.imagen.type } carros.save((err, result) => { if (err) { return res.status(400).json({ error: errorHandler(error) }) } res.json({mensaje:"Informacion guardada"}); }) }) } //Despliegue de datos de los vehiculos function mostrar(req,res){ let orden = req.query.order ? req.query.order : '-1'; let sortBy = req.query.sortBy ? req.query.sortBy : 'createdAt'; Carros.find() .select("-imagen") .sort([[sortBy, orden]]) .exec((err, data) => { if (err) { return res.status(400).json({ error: "Informacion no encontrada" }); } res.json(data); }) } //funcion para desplegar los 10 vehiculos mas recientes function mostrarRecientes(req,res){ let orden = req.query.order ? req.query.order : '-1'; let sortBy = req.query.sortBy ? req.query.sortBy : 'createdAt'; Carros.find().limit(10) .select("-imagen") .sort([[sortBy, orden]]) .exec((err, data) => { if (err) { return res.status(400).json({ error: "Informacion no encontrada" }); } res.json(data); }) } //Funcion para desplegar los detalles de un vehiculo function detallesVehiculo(req, res){ req.carros.imagen = undefined; return res.json(req.carros); } //funcion para eliminar function eliminar(req,res){ let carros = req.carros; carros.remove((err,data) => { if (err) { return res.status(400).json({ error:errorHandler(err) }); } res.json({mensaje:"Informacion Eliminada"}); }) } // buscar y mostrar un vehiculo por su id function mostrarCarrosById(req,res,next,id){ Carros.findById(id).exec((err,carros) => { if (err || !carros) { return res.status(400).json({ error:"Informacion no encontrada" }); } req.carros = carros; next(); }); } // metodo para desplegar la imagen function mostrarImg(req, res, next){ if (req.carros.imagen.data) { res.set('Content-Type', req.carros.imagen.contentType) return res.send(req.carros.imagen.data) } next(); } module.exports = { nuevo, mostrar, mostrarRecientes, detallesVehiculo, eliminar, mostrarCarrosById, mostrarImg }
export let SIGN_UP_START = "SIGN_UP_START"; export let SIGN_UP_SUCCESS = "SIGN_UP_SUCCESS"; export let SIGN_UP_FAILED = "SIGN_UP_FAILED"; export let SIGN_UP_ERROR_RESET = "SIGN_UP_ERROR_RESET"; export let LOGIN_START = "LOGIN_START"; export let LOGIN_SUCCESS = "LOGIN_SUCCESS"; export let LOGIN_FAILED = "LOGIN_FAILED"; export let LOGIN_ERROR_RESET = "LOGIN_ERROR_RESET"; export let GET_USER_SUCCESS = "GET_USER_SUCCESS"; export let GET_USER_FAILED = "GET_USER_FAILED"; export let UPDATE_USER_START = "UPDATE_USER_START"; export let UPDATE_USER_SUCCESS = "UPDATE_USER_SUCCESS"; export let UPDATE_USER_FAILED = "UPDATE_USER_FAILED"; export let UPDATE_PASSWORD_START = "UPDATE_PASSWORD_START"; export let UPDATE_PASSWORD_SUCCESS = "UPDATE_PASSWORD_SUCCESS"; export let UPDATE_PASSWORD_FAILED = "UPDATE_PASSWORD_FAILED"; const INITIAL_STATE = { // login: false, user: null, error: null, loading: false, }; let authReducer = (state = INITIAL_STATE, action) => { switch (action.type) { case SIGN_UP_START: return { ...state, error: null, loading: true, }; case SIGN_UP_SUCCESS: return { ...state, loading: false, error: null, // login: true, user: action.payload, }; case SIGN_UP_FAILED: return { ...state, loading: false, error: action.payload, }; case SIGN_UP_ERROR_RESET: return { ...state, error: null, }; case LOGIN_START: return { ...state, loading: true, }; case LOGIN_SUCCESS: return { ...state, loading: false, user: action.payload, error: null, }; case LOGIN_FAILED: return { ...state, loading: false, error: action.payload, }; case LOGIN_ERROR_RESET: return { ...state, error: null, }; case GET_USER_SUCCESS: return { ...state, user: action.payload, }; case GET_USER_FAILED: return { ...state, user: null, loading: false, }; case UPDATE_USER_START: return { ...state, loading: true, error: null, }; case UPDATE_USER_SUCCESS: return { ...state, loading: false, user: action.payload, }; case UPDATE_USER_FAILED: return { ...state, loading: false, error: action.payload, }; case UPDATE_PASSWORD_START: return { ...state, loading: true, error: null, }; case UPDATE_PASSWORD_SUCCESS: return { ...state, loading: false, user: action.payload, }; case UPDATE_PASSWORD_FAILED: return { ...state, loading: false, error: action.payload, }; default: return state; } }; export default authReducer;
function getImageAsset(img_id, slug, size=null, crop=null, quality=null) { $.ajax({ url: '/' + assetBaseUrl + '/get_asset/', data: { 'type': 'image', 'slug': slug, 'size': size, 'crop': crop, 'quality': quality }, dataType: 'json', success: function(data) { var docElement = document.getElementById(img_id); if(docElement != null) { docElement.src = data['url']; return true; } else { console.log('Error: No element named: ' + img_id) return false; } }, error: function() { console.log("AJAX Error"); } }); } function getFileAsset(div_id, slug) { if (assetBaseUrl == null) { console.log("Error: Base Asset app URL is not set"); return false; } $.ajax({ url: '/' + assetBaseUrl + '/get_asset/', data: { 'type': 'file', 'slug': slug }, dataType: 'json', success: function(data) { var docElement = document.getElementById(div_id); if (docElement != null) { docElement.href = data['url']; return true; } else { console.log("Error: No element named: " + div_id) return false; } }, error: function() { console.log("AJAX Error"); } }); }
const dtUtils = require('./date-utils'); //======================================================================================== const HEADER = ["Дата", "Тепло, Гкал", "Расход воды, м3", "Темп. на город, С", "Темп. оборотной, С", "Давление после котла, МПа", "Давление до котла, МПа", "Темп. дымовых до ЭКО, С", "Разрежение в топке, Па" ]; //dt, sum(w_38), sum(q_39), avg(T_41), avg(T_42), avg(P_19), avg(P_18), avg(T_10), avg(P_36) function tableHeader() { return HEADER.map(el => "<th>" + el + "</th>").join(""); } //============================================================================== function formHourRow(row) { const hourRow = []; for (const prop in row) { if (row.hasOwnProperty(prop)) { if (prop !== "id") { prop == "dt" ? hourRow.push( dtUtils.getDateTimeFromMySql(row[prop]) ) : hourRow.push(row[prop].toFixed(3)); }; } } return hourRow; }; //============================================================================== module.exports = { getTableHeader: tableHeader, formHourRow : formHourRow };
import { cacheAdapterEnhancer } from "axios-extensions"; import LRU from "lru-cache"; const ONE_HOUR = 1000 * 60 * 60; // 教程 // https://github.com/nuxt-community/axios-module/issues/99 export default function ({ $axios, ssrContext }) { const defaultCache = process.server ? ssrContext.$axCache : new LRU({ maxAge: ONE_HOUR }); const defaults = $axios.defaults; // https://github.com/kuitos/axios-extensions defaults.adapter = cacheAdapterEnhancer(defaults.adapter, { enabledByDefault: false, cacheFlag: "useCache", defaultCache, }); }
import React, { Component } from 'react'; import {connect} from 'react-redux'; import NoobSectionList from '../components/noobSectionList'; import '../App.css'; // These will become the props of this component const mapStateToProps = (state) => { return { sections: state.designer.sections, resizingControlId: state.designer.resizingControlId } } // These will become the props of this component const mapDispatchToProps = (dispatch) => { return { onSelectControl: (control) => { //debugger dispatch({ type: 'SELECT_CONTROL', // pass the entire control, not just the ID, because we need to display the control props // in the Control Props pane control }); }, onResizerMouseDown: (control, e) => { console.log('[DEBUG][RESIZERMOUSEDOWN] control:' + control.controlId); dispatch({ type: 'RESIZE_CONTROL_START', control }); }, onSectionMouseUp: (sectId, e, newSize) => { console.log('[DEBUG][SECTIONMOUSEUP] sectid:' + sectId); dispatch({ type: 'SECTION_MOUSE_UP', sectId, newSize }); }, onMoveControl: (droppedControl, destControl) => { console.log('[DEBUG][MovedControl] sectid'); dispatch({ type: 'MOVE_CONTROL', droppedControl, destControl }); }, onControlTypeSelected: (controlType, control) => { console.log('[DEBUG][onControlTypeSelected]'); dispatch({ type: 'SET_CONTROL_TYPE', controlType, selectedControl: control, }); } /* No need to track the mouse movement here, since the mouse movement will not cause a permanent state change onSectionMouseMove: (sectId, e) => { // Ideally: dispatch only if there is control that is resizing // console.log('[DEBUG][SECTIONMOUSE MOVE] sectid:' + sectId); dispatch({ type: 'SECTION_MOUSE_MOVE', sectId, // to let the neighbouring controls that they are potentially affected mouseMoveEvent: e }); } */ } }; export default connect(mapStateToProps, mapDispatchToProps)(NoobSectionList);
import React from "react"; import { Grid, Text, Button } from "../elements"; import { useSelector, useDispatch } from "react-redux"; import { actionCreators as userActions } from "../redux/modules/user"; import { history } from '../redux/configureStore' import { apiKey, realtime } from '../shared/Firebase' import NotiBadge from "./NotiBadge"; const GrayButton = { backgroundColor: "#CBCBCB", borderRadius: 3, width: 80, height: 36, marginLeft: 10, borderWidth: 0.7, } const Header = (props) => { const dispatch = useDispatch(); const is_login = useSelector((state) => state.user.is_login); const user_id = useSelector((state) => state.user.user?.uid) const _session_key = `firebase:authUser:${apiKey}:[DEFAULT]` const is_session = sessionStorage.getItem(_session_key) ? true : false const notiCheck = () => { const notiDB = realtime.ref(`noti/${user_id}`) notiDB.update({ read: true }) if (history.location.pathname !== "/notice") history.push('/notice'); } return is_login && is_session ? ( <React.Fragment> <Grid is_flex padding="8px 16px" row backgroundColor="#2c2c2c"> <Grid row _onClick={() => { history.push('/') }}> <Text margin="0px" size="24px" color="white" bold>꼬스타</Text> </Grid> <Grid is_flex row justify="flex-end" position="relative"> <Button containerStyle={GrayButton} text="내 정보" _onClick={() => { history.push('/mypage') }} /> <NotiBadge> <Button containerStyle={GrayButton} text="알림" _onClick={() => notiCheck()} /> </NotiBadge> <Button containerStyle={GrayButton} text="로그아웃" _onClick={() => { dispatch(userActions.logOut()) sessionStorage.removeItem(_session_key) }} /> </Grid> </Grid> </React.Fragment> ) : ( <React.Fragment> <Grid is_flex row padding="8px 16px" backgroundColor="#2c2c2c"> <Grid is_flex row _onClick={() => { history.push('/') }}> <Text margin="0px" size="24px" color="white" bold>꼬리스타그램</Text> </Grid> <Grid is_flex row justify="flex-end"> <Button containerStyle={GrayButton} text="로그인" _onClick={() => { history.push('/login') }} /> <Button containerStyle={GrayButton} text="회원가입" _onClick={() => { history.push('/signup') }} /> </Grid> </Grid> </React.Fragment> ) } Header.defaultProps = {} export default Header;
const express = require('express'), path = require('path'), rootPath = path.normalize(__dirname + '/../'), router = express.Router(), { ObjectivesController,HomeController,EndPointsController,AssessmentsController } = require('./controllers'); module.exports = function (app) { router.get('/', HomeController.index); router.get('/objective', ObjectivesController.index); router.post('/objective', ObjectivesController.store); router.get('/objective/:id', ObjectivesController.show); router.put('/objective/:id', ObjectivesController.update); router.delete('/objective/:id', ObjectivesController.remove); router.get('/endpoint', EndPointsController.index); router.post('/endpoint/:objectiveId', EndPointsController.store); router.get('/endpoint/:id', EndPointsController.show); router.put('/endpoint/:id', EndPointsController.update); router.delete('/endpoint/:id', EndPointsController.remove); router.get('/assessment', AssessmentsController.index); router.post('/assessment', AssessmentsController.store); router.get('/assessment/:id', AssessmentsController.show); router.put('/assessment/:id', AssessmentsController.update); router.delete('/assessment/:id', AssessmentsController.remove); app.use('/api', router); };
import React from "react" import Image from "../Image/Index" import UserTitle from "../User/Title" import Link from "../../components/Link/index"; import SocialShare from "../SocialShare/Index" import Like from "../Like/Index" import Favourite from "../Favourite/Index" import Dislike from "../Dislike/Index" import ShortNumber from "short-number" import CensorWord from "../CensoredWords/Index" import Translate from "../../components/Translate/Index"; import { renderToString } from 'react-dom/server' class Index extends React.Component { constructor(props) { super(props) this.state = { audio: props.audio } } static getDerivedStateFromProps(nextProps, prevState) { if(typeof window == "undefined" || nextProps.i18n.language != $("html").attr("lang")){ return null; } if(prevState.localUpdate){ return {...prevState,localUpdate:false} } else if (nextProps.audio && nextProps.audio != prevState.audio) { return { audio: nextProps.audio } } else{ return null } } render() { let item = this.state.audio return ( <React.Fragment> { this.props.pageInfoData.appSettings["audio_advgrid"] == 1 ? <div className="ThumbBox-wrap audio-container"> <Link href={`/audio`} customParam={`audioId=${item.custom_url}`} as={`/audio/${item.custom_url}`}> <a className="ThumbBox-link" onClick={this.props.closePopUp}> <div className="ThumbBox-coverImg"> <span> <Image image={item.image} title={item.title} imageSuffix={this.props.pageInfoData.imageSuffix} /> </span> </div> </a> </Link> <div className="miniplay"> { this.props.song_id != item.audio_id || this.props.pausesong_id == item.audio_id ? <div className="playbtn" onClick={() => this.props.playSong(item.audio_id,item)}> <i className="fas fa-play"></i> </div> : <div className="playbtn" onClick={() => this.props.pauseSong(item.audio_id,item)}> <i className="fas fa-pause" ></i> </div> } </div> <div className="ThumbBox-Title hide-on-expand"> <div className="PlayIcon"> <span className="material-icons-outlined"> play_arrow </span> </div> <div className="title ellipsize2Line"> <h4 className="m-0">{<CensorWord {...this.props} text={item.title} />}</h4> </div> </div> <div className="ItemDetails"> <div className="d-flex justify-content-between VdoTitle "> <Link href={`/audio`} customParam={`audioId=${item.custom_url}`} as={`/audio/${item.custom_url}`}> <a className="ThumbBox-Title-expand d-flex align-items-center" onClick={this.props.closePopUp}> <div className="PlayIcon"> <span className="material-icons-outlined"> play_arrow </span> </div> <div className="title ellipsize2Line"> <h4 className="m-0">{<CensorWord {...this.props} text={item.title} />}</h4> </div> </a> </Link> { this.props.canDelete || this.props.canEdit ? <div className="moreOptions"> <a href="#" className="icon-Dvert" data-bs-toggle="dropdown" aria-expanded="false"> <span className="material-icons"> more_vert </span> </a> <ul className="dropdown-menu dropdown-menu-end moreOptionsShow"> { this.props.canEdit ? <li> <Link href="/create-audio" customParam={`audioId=${item.custom_url}`} as={`/create-audio/${item.custom_url}`}> <a className="addPlaylist addEdit" title={Translate (this.props, "Edit")}> <span className="material-icons" data-icon="edit"></span> {Translate(this.props, "Edit")} </a> </Link> </li> : null } { this.props.canDelete ? <li> <a className="addPlaylist addDelete" title={Translate(this.props, "Delete")} href="#" onClick={this.deleteAudio}> <span className="material-icons" data-icon="delete"></span> {Translate(this.props, "Delete")} </a> </li> : null } { this.props.canEdit ? <li> <a href="#" className="addPlaylist addEdit" onClick={this.analytics} title={Translate(this.props, "Analytics")}> <span className="material-icons" data-icon="show_chart"></span> {Translate(this.props, "Analytics")} </a> </li> : null } <SocialShare {...this.props} buttonHeightWidth="30" tags={item.tags} url={`/audio/${item.custom_url}`} title={renderToString(<CensorWord {...this.props} text={item.title} />)} imageSuffix={this.props.pageInfoData.imageSuffix} media={item.image} /> </ul> </div> : null } </div> <div className="Vdoinfo d-flex flex-column"> <UserTitle childPrepend={true} className="user" data={item} ></UserTitle> <span className="videoViewDate"> <span title="play"> <i className="fas fa-play"></i>{" "} {`${ShortNumber(item.play_count ? item.play_count : 0)}`}{" "}{this.props.t("play_count", { count: item.play_count ? item.play_count : 0 })} </span> </span> </div> <div className="likeDislike-Wrap mt-2"> <ul className="likeDislike-List"> <li> <Like icon={true} {...this.props} like_count={item.like_count} item={item} type="audio" id={item.audio_id} />{" "} </li> <li> <Dislike icon={true} {...this.props} dislike_count={item.dislike_count} item={item} type="audio" id={item.audio_id} />{" "} </li> <li> <Favourite icon={true} {...this.props} favourite_count={item.favourite_count} item={item} type="audio" id={item.audio_id} />{" "} </li> <SocialShare {...this.props} hideTitle={true} buttonHeightWidth="30" url={`/audio/${item.custom_url}`} title={item.title} imageSuffix={this.props.pageInfoData.imageSuffix} media={item.image} /> </ul> </div> </div> </div> : <div key={item.audio_id} className={`${this.props.from_user_profile ? 'adiodiv' : "adiodiv"}`}> <div className="audio-grid"> <div className="audioGrid-content"> <div className="audio-track-img"> <Link href={`/audio`} customParam={`audioId=${item.custom_url}`} as={`/audio/${item.custom_url}`}> <a className="d-block"> <Image image={item.image} title={item.title} imageSuffix={this.props.pageInfoData.imageSuffix} /> </a> </Link> <div className="audioPlayBtn-wrap"> { this.props.song_id != item.audio_id || this.props.pausesong_id == item.audio_id ? <div className="audioPlayBtn" onClick={() => this.props.playSong(item.audio_id,item)}> <i className="fas fa-play"></i> </div> : <div className="audioPlayBtn" onClick={() => this.props.pauseSong(item.audio_id,item)}> <i className="fas fa-pause"></i> </div> } </div> </div> <div className="audioName"> <Link href={`/audio`} customParam={`audioId=${item.custom_url}`} as={`/audio/${item.custom_url}`}> <a className="d-block"> <CensorWord {...this.props} text={item.title} /> </a> </Link> </div> <UserTitle childPrepend={true} className="audioUserName d-inline-flex align-items-center user" data={item} ></UserTitle> <div className="LikeDislikeWrap audiolikedisshr mt-3"> <ul className="LikeDislikeList"> <li> <Like icon={true} {...this.props} like_count={item.like_count} item={item} type="audio" id={item.audio_id} />{" "} </li> <li> <Dislike icon={true} {...this.props} dislike_count={item.dislike_count} item={item} type="audio" id={item.audio_id} />{" "} </li> <li> <Favourite icon={true} {...this.props} favourite_count={item.favourite_count} item={item} type="audio" id={item.audio_id} />{" "} </li> <SocialShare {...this.props} hideTitle={true} buttonHeightWidth="30" url={`/audio/${item.custom_url}`} title={item.title} imageSuffix={this.props.pageInfoData.imageSuffix} media={item.image} /> <li> <span title="play"> <i className="fas fa-play"></i>&nbsp;&nbsp; {`${ShortNumber(item.play_count ? item.play_count : 0)}`}{this.props.t("play_count", { count: item.play_count ? item.play_count : 0 })} </span> </li> </ul> </div> </div> </div> </div> } </React.Fragment> ) } } export default Index
var FintDefaults= { categories:[ {'rowid':'1',description:'Income',parent:''}, {'rowid':'2',description:'Taxable Income',parent:'1'}, {'rowid':'3',description:'Non Taxable Income',parent:'1'}, {'rowid':'4',description:'Expenses',parent:''}, {'rowid':'5',description:'Business Expenses',parent:'4'}, {'rowid':'6',description:'Personal Expenses',parent:'4'}, {'rowid':'7',description:'Phone',parent:'5'}, {'rowid':'8',description:'Stationery',parent:'5'}, {'rowid':'9',description:'Repairs/Maintenance',parent:'5'}, {'rowid':'10',description:'Electricity',parent:'5'}, {'rowid':'11',description:'Interest',parent:'5'}, {'rowid':'12',description:'Rent',parent:'5'}, {'rowid':'13',description:'Other',parent:'5'}, {'rowid':'14',description:'Food',parent:'6'}, {'rowid':'15',description:'Car',parent:'6'}, {'rowid':'16',description:'Electricity',parent:'6'}, {'rowid':'17',description:'Other',parent:'6'}, {'rowid':'18',description:'Phone',parent:'6'}, {'rowid':'19',description:'Clothing',parent:'6'}, {'rowid':'20',description:'Entertainment',parent:'6'} , {'rowid':'21',description:'Internal Transfer',parent:''} ], rules:[ {'rowid':'1',rule:'"TRANSFER FROM NICHOLAS GRAHAM- NGHENVIRONMENTAL"',category:'2'}, {'rowid':'2',rule:'"TO CSA OFFICIAL RECEIP"',category:'17'}, {'rowid':'3',rule:'"CALTEX"',category:'15'}, {'rowid':'4',rule:'"TRANSFER FROM ATO"',category:'3'}, {'rowid':'5',rule:'"TRANSFER FROM HCU"',category:'2'}, {'rowid':'6',rule:'"TRANSFER FROM RYAN B E"',category:'3'}, {'rowid':'7',rule:'"ANZ INTERNET BANKING FUNDS TFER TRANSFER" NEAR/1 "TO 012525576016945"',category:'21'}, {'rowid':'8',rule:'"ANZ INTERNET BANKING BPAY TELSTRA CORP LTD"',category:'18'} ], accounts:[ {'rowid':'1',description:'ANZ Day to Day',accountnumber:'11111111111'}, {'rowid':'2',description:'ANZ Saver',accountnumber:'22222222222'}, {'rowid':'3',description:'ANZ Credit Card',accountnumber:'333333333333'}, {'rowid':'4',description:'ING Saver',accountnumber:'444444444444'} ] }
//task 11 function findChar(str1,str2){ var strArray1=Array.from(new Set([...str1])); var strArray2=Array.from(new Set([...str2])); var comArr=strArray1.filter(function(d,ix){ return strArray2.indexOf(d)!=-1; }); console.log(comArr); } findChar('lnknyufsbfbdivobwiuvblKDBVBUIHBVBJKB','klnhbj,hybvlbvsjklbvDHIYGBYISFBUI')
export default [ { name: "test", path: "/test", component: () => import(/* webpackChunkName: "views/Home" */ `../views/Home`), children: [ { name: "test1", path: "/test/test1", component: () => import(/* webpackChunkName: "views/Test1" */ `../views/Test1`) }, { name: "test2", path: "/test/test2", component: () => import(/* webpackChunkName: "views/Test2" */ `../views/Test2`) }, ], }, ];
import React, { Component } from 'react' import { Form, Label, Segment, Modal, Header, Button, Dropdown } from 'semantic-ui-react' import DropDownTools from '../DropDowns/tools.js' import DropDownMaterials from '../DropDowns/materials.js' import DropDownEdging from '../DropDowns/edging.js' import DropDownPath from '../DropDowns/path.js' export default class NewWalkForm extends Component { constructor(props) { super(props) this.state = { name: '', tools: '', materials: '', edging: '', path: '' } } handleChange = (event) => { //console.log(event.target.name) //console.log(event.target.value) //console.log(event) this.setState({ [event.target.name]: event.target.value }) } handleSubmit = (event) => { event.preventDefault() this.props.createWalk(this.state) this.setState({ name: '', author: '', tools: '', materials: '', edging: '', path: '' }) } render() { //console.log("New Walk form") //console.log(this.state) return ( <Segment> <h4> Create your new walk:</h4> <Form onSubmit={this.handleSubmit}> <Label>Name:</Label> <Form.Input type="text" name="name" value={this.state.name} placeholder="Enter a name" onChange={this.handleChange} /> <Label>Tools:</Label> <DropDownTools name="tools"/> <Label>Materials:</Label> <DropDownMaterials /> <Label>Edging:</Label> <DropDownEdging /> <Label>Decorative Path:</Label> <DropDownPath /> <Button type="Submit">Create Your New Walk</Button> </Form> </Segment> ) } }
import Bookmarks from './bookmarks'; import {Images} from './bookmarks'; import {rateLimit} from '../../modules/rate-limit.js'; import {can} from '../../modules/permissions.js'; import cheerio from 'cheerio'; import {default as urlParser} from 'url'; export const addBookmark = new ValidatedMethod({ name: 'bookmarks.add', validate: new SimpleSchema({ url: { type: String }, folderId: { type: String }, }).validator(), run({ url, folderId }) { if(can.create.bookmark(folderId)){ // if(!urlParser.parse(url).hostname){ // throw new Meteor.Error("url-invalid", "The url is not valid"); // } if(!Bookmarks.findOne({ folderId: folderId, url: {$regex: "(https?:\/\/(www.)?)?" + url + "\/?$"} })){ return Bookmarks.insert({ title: url, url: url, folderId: folderId, views: 0, createdAt: new Date() }); } else{ throw new Meteor.Error("url-found", "Url already saved in folder"); } } }, }); export const addAndRefreshBookmark = new ValidatedMethod({ name: 'bookmarks.addAndRefresh', validate: new SimpleSchema({ url: { type: String }, folderId: { type: String }, }).validator(), run({ url, folderId }) { addBookmark.call({url, folderId}, (error, bookmarkId) => { if(!error && bookmarkId) { refreshBookmark.call({bookmarkId}, (error) => { if(error) console.log(error); }); } else { console.log(error); } }); }, }); export const removeBookmark = new ValidatedMethod({ name: 'bookmarks.remove', validate: new SimpleSchema({ bookmarkId: { type: String }, }).validator(), run({ bookmarkId }) { if(can.delete.bookmark(bookmarkId)){ Images.remove({bookmarkId}) Bookmarks.remove(bookmarkId); } }, }); export const removeBookmarksInFolder = new ValidatedMethod({ name: 'bookmarks.removeInFolder', validate: new SimpleSchema({ folderId: { type: String }, }).validator(), run({ folderId }) { if(can.delete.folder(folderId)){ Images.remove({folderId}); Bookmarks.remove({folderId}); } }, }); export const updateBookmark = new ValidatedMethod({ name: 'bookmarks.update', validate: new SimpleSchema({ bookmarkId: { type: String }, data: {type: Object}, "data.title": { type: String }, "data.url": { type: String }, "data.image": { type: String, optional: true }, "data.folderId": { type: String }, }).validator(), run({ bookmarkId, data }) { if(can.edit.bookmark(bookmarkId)){ return Bookmarks.update(bookmarkId, { $set: { title: data.title, url: data.url, image: data.image, folderId: data.folderId } }); } }, }); export const incBookmarkViews = new ValidatedMethod({ name: 'bookmarks.incViews', validate: new SimpleSchema({ bookmarkId: { type: String }, }).validator(), run({ bookmarkId }) { Bookmarks.update(bookmarkId, {$inc: {views: 1}}); }, }); export const refreshBookmark = new ValidatedMethod({ name: 'bookmarks.refresh', validate: new SimpleSchema({ bookmarkId: { type: String }, }).validator(), run({ bookmarkId }) { const bookmark = Bookmarks.findOne(bookmarkId); this.unblock(); if(Meteor.isServer){ const endpoint = 'http://api.embed.ly/1/extract?'; const key = 'key=debadfdc8d8446589361951747d38242'; const url = '&url=' + bookmark.url ; const options = '&maxwidth=500'; const target = endpoint + key + url + options; HTTP.get(target, function(err,response){ if(response && response.statusCode === 200){ const json = JSON.parse(response.content); Bookmarks.update(bookmarkId, { $set: { url: decodeURIComponent(json.url), title: json.title, favicon: json.favicon_url, image: (json.images[0] === undefined) ? null : json.images[0].url } }); } else if(response && response.statusCode === 400){ console.log(response); Bookmarks.remove(bookmarkId); } else if(response && _.contains([401, 403, 404, 500, 501, 503], response.statusCode)) { console.log(response); let bUrl = bookmark.url; if(!urlParser.parse(bookmark.url).protocol){ bUrl = 'http://' + bUrl; } HTTP.get(bUrl, function(err,response){ if(response && response.statusCode === 200){ $ = cheerio.load(response.content); Bookmarks.update(bookmarkId, { $set: { title: $('title').text(), favicon: $('link[rel="icon"]').first().attr('href'), image: $('img').first().attr('src'), url: urlParser.parse(bUrl).href } }); } else{ console.log(response); if(response && _.contains([400, 401, 403, 404, 500, 501, 503], response.statusCode)){ Bookmarks.remove(bookmarkId); } } }); } }); const webshot = require('webshot'); const opts = { phantomPath: require('phantomjs-prebuilt').path, quality: 80, streamType: 'jpg', screenSize: { width: 1024, height: 800 }, userAgent: 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko)' + ' Ubuntu Chromium/55.0.2883.87 Chrome/55.0.2883.87 Safari/537.36' } webshot(bookmark.url, opts, function(err, renderStream) { if(err){ console.log(err); return err; } let imageBuffers = []; renderStream.on('data', Meteor.bindEnvironment(function (data) { imageBuffers.push(data); })); renderStream.on('end', Meteor.bindEnvironment(function () { let imageBuffer = Buffer.concat(imageBuffers); let imageFile = new FS.File(); imageFile.attachData(imageBuffer, {type: 'image/jpg'}); imageFile.folderId = bookmark.folderId; imageFile.bookmarkId = bookmarkId; Images.insert(imageFile, Meteor.bindEnvironment(function (err, result) { Bookmarks.update(bookmarkId, { $set: {webshotId: result._id} }); })); })); }); } }, }); export const grabBookmarks = new ValidatedMethod({ name: 'bookmarks.grab', validate: new SimpleSchema({ targetUrl: { type: String }, externalOnly: { type: Boolean }, folderId: { type: String }, }).validator(), run({ targetUrl, externalOnly, folderId }) { this.unblock(); if(Meteor.isServer){ const hostname = urlParser.parse(targetUrl).hostname HTTP.get(targetUrl, function(err,response){ if(response && response.statusCode === 200){ $ = cheerio.load(response.content); $('body').find('a').each((i, elem) => { const link = $(elem).attr('href'); if(externalOnly && !link.includes(hostname)){ if(urlParser.parse(link).hostname != null){ addAndRefreshBookmark.call({ url: link, folderId: folderId }, null); } } else if(!externalOnly){ if(urlParser.parse(link).hostname != null){ addAndRefreshBookmark.call({ url: link, folderId: folderId }, null); } } }); } else{ console.log(response); } }); } }, }); rateLimit({ methods: [ addBookmark, addAndRefreshBookmark, removeBookmark, removeBookmarksInFolder, updateBookmark, incBookmarkViews, refreshBookmark, grabBookmarks ], limit: 5, timeRange: 1000, });
import React from 'react' export default class PlanetCard extends React.Component{ render(){ return( <div class="media text-primary "> <div className='ImageField'> <img src="https://il.tpu.ru/static/assets/thumbnail/539e172312d3f9f614f4ea39c9739ed1/2372b8fa382d7c64/c0a6935f77a91716.jpg" class="planetImage" alt="..." /> </div> <div class="media-body"> <h5 class="mt-0">Top-aligned media</h5> <ul className="list-group list-group-flush card-part"> <li className="list-group-item card-part br-white">Популяция:</li> <li className="list-group-item card-part br-white">Расположение:</li> <li className="list-group-item card-part br-white">Планета:</li> </ul> </div> </div> ) } }
function ready () { console.log("Page Ready"); done.onclick = function () { let el1 = document.createElement('p'); let el2 = document.createElement('p'); let el3 = document.createElement('p'); let feeling = document.forms.feeling; let better = document.forms.better; let symptoms = document.forms.symptoms; if (feeling = "eight" || "nine" || "ten"){ el1.innerHTML = "You said you were feeling pretty good. Congrats, you're making progress!" } if (feeling = "six" || "seven"){ el1.innerHTML = "You said you were feeling okay. It could be a little better, but keep up the good work!" } if (feeling = "one" || "two" || "three" || "four" || "five"){ el1.innerHTML = "You said you were feeling pretty bad. Sorry you feel this way! But don't worry, you can do it!" } if (better = "better"){ el2.innerHTML = "You said you feel better than you did yesterday. Good work, you're improving!" } if (better = "same"){ el2.innerHTML = "You said you feel about the same as you did yesterday." } if (better = "worse"){ el2.innerHTML = "You said you were feeling worse than you did yesterday. But that's okay, tomorrow will be better." } if (sympotms = "anxious"){ el3.innerHTML = } if (sympotms = "depressed"){ el3.innerHTML = } if (sympotms = "tired"){ el3.innerHTML = } if (sympotms = "confused"){ el3.innerHTML = } if (sympotms = "distant"){ el3.innerHTML = } if (sympotms = "hurting"){ el3.innerHTML = } if (sympotms = "bored"){ el3.innerHTML = } if (sympotms = "lonely"){ el3.innerHTML = } if (sympotms = "overwhelmed"){ el3.innerHTML = } answers.append(el1) answers.append(el2) answers.append(el3) } } document.addEventListener("DOMContentLoaded", ready);
const express = require('express'); const hbs = require('hbs'); const app = express(); app.set('view engine', 'hbs'); hbs.registerPartials(__dirname + '/views/partials'); app.use(express.static('public')); app.get('/', (req, res) => { res.render('home.hbs', { pageTitle: "Welcome", pageContent: "Welcome to Home page" }); }); app.get('/about', (req, res) => { res.render('about.hbs', { pageTitle: "About Us", pageContent: "Welcome to About page" }); }); app.get('/dashboard', (req, res) => { res.render('dashboard.hbs', { pageTitle: "Dashboard", pageContent: "Welcome to Dashboard page" }); }); app.get('/shortcuts', (req, res) => { res.render('shortcuts.hbs', { pageTitle: "Shortcuts", pageContent: "Welcome to Shortcuts page" }); }); app.get('/overview', (req, res) => { res.render('overview.hbs', { pageTitle: "Overview", pageContent: "Welcome to Overview page" }); }); app.get('/events', (req, res) => { res.render('events.hbs', { pageTitle: "Events", pageContent: "Welcome to Events page" }); }); app.get('/services', (req, res) => { res.render('services.hbs', { pageTitle: "Services", pageContent: "Welcome to Services page" }); }); app.get('/contact', (req, res) => { res.render('contact.hbs', { pageTitle: "Contact Us", pageContent: "Welcome to Contact page" }); }); app.listen(process.env.PORT || 3000, () => { console.log(`Server is up and running at ${process.env.PORT}`); });
import { combineReducers } from 'redux'; import bookLibrary from './bookLibrary'; const appReducer = combineReducers({ bookLibrary }); const rootReducer = (state, action) => { return appReducer(state, action); }; export default rootReducer;
const User = require("../../models/user.models"); const jwt = require("jsonwebtoken"); const bcrypt = require("bcrypt"); const { APPSECRET } = require("../../config"); var smtpTransport = require("nodemailer-smtp-transport"); function usernameChecker(username) { User.findOne({username},(err,user)=>{ if(err){ return false } if(user){ return true } }) } exports.register = (req, res) => { const { email, password, phone_number, first_name, last_name, DOB, username, package, position, securedanswer, securedquestion, sponsors_fullname, sponsors_username, } = req.body; User.findOne({ email }, (err, user) => { if (err) { res.status(403).json({ message: "email already exist", error: err, }); } if (user) { res.status(403).json({ message: `email already exist`, }); } if (!user) { User.findOne({username},(err,user)=>{ if(err){ return res.status(400).json({ message:'username already exist' }) } if(user){ return res.status(400).json({ message:'username already exist' }) } if(!user){ const hash = bcrypt.hashSync(password, 10); if(sponsors_username){ User.findOne({username:sponsors_username},(err,user)=>{ if(user){ if (err) { res.status(400).json({ message: "an error occured", }); } const newUser = new User({ email, phone_number, first_name, last_name, DOB, username, package, position, securedanswer, securedquestion, sponsors_fullname, sponsors_username, password: hash, }); newUser .save() .then((newuser) => { res.status(201).json({ message: "account created successfully", user: { id: newuser._id, }, }); }) .catch((err) => { res.status(400).json(err); }); }else{ return res.status(404).json({ message:'sponsors username does not exist' }) } }) } else{ const newUser = new User({ email, phone_number, first_name, last_name, DOB, username, package, position, securedanswer, securedquestion, sponsors_fullname, sponsors_username, password: hash, }); newUser .save() .then((newuser) => { res.status(201).json({ message: "account created successfully", user: { id: newuser._id, }, }); }) .catch((err) => { res.status(400).json(err); }); } } }) } }); }; exports.login = (req, res) => { const { email, password } = req.body; User.findOne({ email }, (err, user) => { if (err) { return res.status(400).json({ message: "an error occured ", }); } if (!user) { return res.status(404).json({ message: "account does not exist", }); } if (user) { let isPasswordValid = bcrypt.compareSync(password, user.password); if (isPasswordValid) { let token = jwt.sign( { data: { id: user._id, role: user.role }, }, APPSECRET ); res.status(200).json({ token, message: "login successful", user: { _id: user._id, role: user.role, email:user.email, paymentProof:user.paymentProof?user.paymentProof:null }, }); } else { res.status(400).json({ message: "invalid password", }); } } }); }; exports.userProfile = (req, res) => { User.findOne({ _id: req.params.id }) .then((user) => { res.status(200).json({ user, status: true, }); }) .catch((err) => { res.status(400).json({ error: err, status: false, }); }); }; exports.userProfile2 = (req, res) => { User.findOne({ _id: req.user.data.id }) .then((user) => { res.status(200).json({ user, status: true, }); }) .catch((err) => { res.status(400).json({ error: err, status: false, }); }); }; exports.userProfile1 = (req, res) => { User.findOne({ username: req.params.username },(err,user)=>{ if(err){ res.status(400).json({ error: err, status: false, }); } if(user){ res.status(200).json({ user, status: true, }); } if(!user){ res.status(400).json({ error: err, status: false, }); } }) }; exports.makePayment = (req, res) => { const { name, price } = req.body; if(req.file){ let proofimg = req.file.path; const paymentProof = { name, price, proofimg }; User.findOne({ _id: req.params.id }) .then((user) => { user.paymentProof = paymentProof; user.save().then(() => { res.status(200).json({ message: "payment recieved", status: true, }); }); }) .catch((err) => { res.status(400).json({ message: "please attach proof of payment, e.g : image or PDF", status: false, }); }); } else{ res.status(400).json({ message: "please upload image", status: false, }); } }; exports.updatePersonalDets=(req,res)=>{ const {first_name,last_name,gender,DOB}=req.body let data={ first_name,last_name,gender,DOB } let file if(req.file){ file=req.file.path; data={ ...data, profilePic:file } } User.findOneAndUpdate({_id:req.user.data.id},data,(err,user)=>{ if(err){ return res.status(400).json({ message:'personal details failed to update' }) } else{ return res.status(200).json({ message:'profile details updated successfully' }) } }) } exports.updateBankDets=(req,res)=>{ const {bank_name,account_name,account_number}=req.body User.findOneAndUpdate({_id:req.user.data.id}, {bankdets:{bank_name,account_name,account_number}},(err,user)=>{ if(err){ return res.status(400).json({ message:'bank details failed to update' }) } else{ return res.status(200).json({ message:'bank details updated successfully' }) } }) } exports.updateContactDets=(req,res)=>{ const {email,phone_number,address,city,country}=req.body User.findOneAndUpdate({_id:req.user.data.id}, {email,phone_number,address,city,country},(err,user)=>{ if(err){ return res.status(400).json({ message:'personal details failed to update' }) } if(user){ return res.status(200).json({ message:'profile details updated successfully' }) } }) } exports.users=(req,res)=>{ User.find({}) .then((result) => { res.status(200).json({ users:result, status:true }) }).catch((err) => { res.status(200).json({ err, status:false }) }); } exports.userDownlines = (req, res) => { User.findOne({ username: req.params.username }) .then((user) => { res.status(200).json({ downlines:user.downlines, status: true, }); }) .catch((err) => { res.status(400).json({ error: err, status: false, }); }); }; exports.resetpassword = (req, res) => { const { email, type } = req.body; if (type === "user") { User.findOne({ email }) .then((user) => { if (!user) { return res.status(401).json({ message: `The email address + ${email} is not associated with any account. Double-check your email address and try again.`, }); } user.generatePasswordReset(); user.save().then((user) => { let link = "http://" + req.headers.origin + req.body.path +"?token="+ user.resetPasswordToken; sendmailtouser = async () => { const nodemailer = require("nodemailer"); let transporter = nodemailer.createTransport( smtpTransport({ host: "tummyfirstmart.com", port: 465, secure: true, // true for 465, false for other ports auth: { user: process.env.NODEMAILER_USERNAME, // generated ethereal user pass: process.env.NODEMAILER_PASSWORD, // generated ethereal password }, connectionTimeout: 5 * 60 * 1000, // 5 min tls: { // do not fail on invalid certs rejectUnauthorized: false, }, }) ); let info = await transporter .sendMail({ from: '"Tummyfirst" <hello@tummyfirstmart.com>', // sender address to: user.email, subject: "Password change request", text: `Hi ${user.first_name} \n Please click on the following link ${link} to reset your password. \n\n If you did not request this, please ignore this email and your password will remain unchanged.\n`, }) .then((response) => { res.send(response); }) .catch((error) => { res.json({ message: "error occured!", message1: error, }); }); }; sendmailtouser(); }); }); } if (type === "admin" || type === "superadmin") { Admin.findOne({ email }).then((user) => { if (!user) { return res.status(401).json({ message: `The email address + ${email} is not associated with any account. Double-check your email address and try again.`, }); } user.generatePasswordReset(); user.save().then((user) => { let link = "http://" + req.body.host + req.body.path +"?token="+ user.resetPasswordToken; sendmailtouser = async () => { const nodemailer = require("nodemailer"); let transporter = nodemailer.createTransport( smtpTransport({ host: "tummyfirstmart.com", port: 465, secure: true, // true for 465, false for other ports auth: { user: process.env.NODEMAILER_USERNAME, // generated ethereal user pass: process.env.NODEMAILER_PASSWORD, // generated ethereal password }, connectionTimeout: 5 * 60 * 1000, // 5 min tls: { // do not fail on invalid certs rejectUnauthorized: false, }, }) ); let info = await transporter .sendMail({ from: '"tummyfirst" <tummyfirstmart.com>', // sender address to: user.email, subject: "Password change request", text: `Hi ${user.first_name} \n Please click on the following link ${link} to reset your password. \n\n If you did not request this, please ignore this email and your password will remain unchanged.\n`, }) .then((response) => { res.status(200).json({ message: "A reset email has been sent to " + user.email + ".", response, }); }) .catch((error) => { res.json({ message: "error occured!", message1: error, }); }); }; sendmailtouser(); }); }); } }; exports.reset = (req, res) => { User.findOne({ resetPasswordToken: req.params.token, resetPasswordExpires: { $gt: Date.now() }, }) .then((user) => { if (!user){ return res .status(401) .json({ message: "Password reset token is invalid or has expired." }); } else{ //Redirect user to form with the email address res.json(200).json({ user }) } }) .catch((err) => res.status(500).json({ message: err.message })); }; exports.resetPasswordChange = (req, res) => { User.findOne({resetPasswordToken: req.params.token, resetPasswordExpires: {$gt: Date.now()}}) .then((user) => { const hashPassword =null if (!user) return res.status(401).json({message: 'Password reset token is invalid or has expired.'}); const hash = bcrypt.genSalt(10, function(err, salt) { if (err) return callback(err); bcrypt.hash(req.body.password, salt, function(err, hash) { //Set the new password user.password = hash; user.resetPasswordToken = undefined; user.resetPasswordExpires = undefined; // Save user.save((err) => { if (err) return res.status(500).json({message: err.message}); res.status(200).json({ message:`Successfully reset password you can now login with new password` }) }); }); }); }); }; exports.requestWithdrawal=(req,res)=>{ User.findOneAndUpdate({_id:req.user.data.id},{requestWithdrawal:true},(err,user)=>{ if(err){ return res.status(400).json({ message:'an error occured' }) } if(user){ user.withdrawals.push({ fullName:`${user.first_name} ${user.last_name}`, username:user.username, balance:user.pv, bankDetails:user.bankDetails, email:user.email, id:user._id, }) user.save() .then(()=>{ return res.status(200).json({ message:'withdrawal request received successfully' }) }) } else{ return res.status(404).json({ message:'user not found' }) } }) } exports.requestWithdrawalFood=(req,res)=>{ User.findOneAndUpdate({_id:req.user.data.id},{requestWithdrawalFood:true},(err,user)=>{ if(err){ return res.status(400).json({ message:'an error occured' }) } if(user){ user.save() .then(()=>{ return res.status(200).json({ message:'withdrawal request received successfully' }) }) } else{ return res.status(404).json({ message:'user not found' }) } }) }
import React from 'react'; import '../assets/animations.css' const Loader = ( <div className="loading loading-dots"> <span className="sr-only">Loading</span> </div> ); export default Loader;
export default { name: 'PreviewTitle', props: { title: { type: String, default: '' }, location: { type: String, default: '' } }, render() { let { location } = this let template if (!this.title) location = '' switch (location) { case 'top': template = <div class="preview-table"><div class="preview-table-title-top">{this.title}</div>{this.$slots.default}</div> break case 'left': template = <div class="preview-table"><div class="preview-table-title-left"> {this.title}:</div><div class="preview-table-title-left-content">{this.$slots.default}</div></div> break default: template = <div class="preview-table">{this.$slots.default}</div> break } return template } }
var bcrypt = require('bcrypt'); exports.cryptPassword = function(password) { return bcrypt.hashSync(password, 10); }; exports.comparePassword = function(password, hash) { return bcrypt.compareSync(password, hash); };
import TechSpecs from "./TechSpecs"; export default TechSpecs;
var boardSize = 8; var colors = { RED: 0, BLUE: 1, SILVER: 2, GREEN: 3, YELLOW: 4, DEFAULT: 5, NUMCOLORS: 6 } var colorNames = ["crimson", "steelblue", "silver", "green", "yellowgreen"]; var timerVar; // Load the updateText on first load for now window.onload = function () { // newSeed(); newGame8(); }; function helpButton() { var txt = "1. Dots are Robots.\n2. Chip with G is Goal.\n3. Robots can go horizontal or vertical and can't jump over walls or players.\n4. Robots can also not change direction until they hit a wall or another Robot.\n5. Goal: Take same-colored Robot to Goal in less steps than other players.\n6. Check Result by clicking \"Show Solution\""; confirm(txt); }; function newGame8() { boardSize = 8; generateGame(); } function newGame10() { boardSize = 10; generateGame(); } function newGame12() { boardSize = 12; generateGame(); } function loadGame() { } function generateGame() { startTimer(); drawBoard(); } function startTimer() { // Output the result in an element with id="demo" var timerDuration = 180; clearInterval(timerVar); timerVar = setInterval(function () { timerDuration -= 1; var minutes = Math.floor(timerDuration / 60); var seconds = Math.floor(timerDuration % 60); if (seconds < 10) { var stylish = "<span>"; if (timerDuration < 10) { stylish = "<span style=\"background-color: red\">" } document.getElementById("Timer").innerHTML = stylish + minutes + ":0" + seconds + "</span>"; } else { document.getElementById("Timer").innerHTML = minutes + ":" + seconds; } // If the count down is over, write some text if (timerDuration < 0) { clearInterval(timerVar); document.getElementById("Timer").innerHTML = "EXPIRED!!"; } }, 1000); } function drawBoard() { var rows = boardSize; var cols = rows; // var top_walls = placeWalls(); var players = placePlayers(); var chipLocation = chipLocationF(); var chipColor = chipColorF(); var tbl = document.getElementById('GameTable'), tr; tbl.innerHTML = ""; tbl.classList.add("grid"); for (var i = 0; i < rows; ++i) { tr = tbl.insertRow(); for (var j = 0; j < cols; ++j) { var td = tr.insertCell(); td.classList.add("cell"); // Define Center if (i == rows / 2 - 1) { if (j == cols / 2 - 1) { td.classList.add("cell-top-border"); td.classList.add("cell-left-border"); td.classList.add("cell-center"); } if (j == cols / 2) { td.classList.add("cell-top-border"); td.classList.add("cell-right-border"); td.classList.add("cell-center"); } } if (i == rows / 2) { if (j == cols / 2 - 1) { td.classList.add("cell-bottom-border"); td.classList.add("cell-left-border"); td.classList.add("cell-center"); } if (j == cols / 2) { td.classList.add("cell-bottom-border"); td.classList.add("cell-right-border"); td.classList.add("cell-center"); } } // Place Walls // Default Walls if (i == 0 && j == cols / 2) { td.classList.add("cell-left-border"); } if (i == rows / 2 && (j == 0 || j == cols - 1)) { td.classList.add("cell-top-border"); } if (i == rows - 1 && j == cols / 2) { td.classList.add("cell-left-border"); } // Place walls // Place Players var player = "<span>"; if (players["RED"] === i * cols + j) { player = "<span class = \"red-player\">"; } if (players["BLUE"] === i * cols + j) { player = "<span class = \"blue-player\">"; } if (players["GREEN"] === i * cols + j) { player = "<span class = \"green-player\">"; } if (players["SILVER"] === i * cols + j) { player = "<span class = \"silver-player\">"; } if (players["YELLOW"] === i * cols + j) { player = "<span class = \"yellow-player\">"; } // Place Chip if (i * cols + j === chipLocation) { player = "<span class = \"cell-chip\" style = \"background-color: "; player += colorNames[chipColor]; player += "\">G"; } player += "</span>"; td.innerHTML = player; } } } function placeWalls() { } function placePlayers() { var players = { "RED": 4, "BLUE": 32, "GREEN": 21, "SILVER": 52, "YELLOW": 57 }; return players; } function chipColorF() { return colors.RED; } function chipLocationF() { return 37; }
$("#submit").click((event) => { let token = $("[name='__RequestVerificationToken']").val() let data = { Email: $("#loginEmail").val(), Password: $("#loginPassword").val(), RememberMe: $("#loginRememberMe").val(), __RequestVerificationToken: token } var url = $("#loginForm").attr('action') $.ajax({ type: "POST", url: url, data: data, dataType: "json", success: function (resp) { if (resp && resp.token) { //window.location.href = data.redirect; let user = JSON.parse(decodeJwt(resp.token)) user.token = resp.token localStorage.setItem('user', JSON.stringify(user)) localStorage.setItem('verificationToken', token) if (resp.returnUrl != null) { location = resp.returnUrl } } }, error: function (resp) { document.open() document.write(resp.responseText) document.close() } }) }) function decodeJwt(token) { var base64Url = token.split('.')[1]; var base64 = base64Url.replace('-', '+').replace('_', '/'); return window.atob(base64); };
import Vue from 'vue' import VeeValidate from 'vee-validate' import VueMoment from 'vue-moment' import './plugins/vuetify' import App from './App.vue' import router from './router/index' import store from './store/index' Vue.use(VeeValidate) Vue.use(VueMoment) Vue.config.productionTip = false // Set the default theme of application let theme = localStorage.getItem('theme'); if(theme === null) { localStorage.setItem('theme', 'dark'); } new Vue({ router, store, render: h => h(App) }).$mount('#app')
import { getHeroeById } from './bases/08-imp-exp' // const promesa = new Promise( (resolve, reject) => { // setTimeout(() => { // // Tarea // // 1. Importar el getHeroeById // // 2. Obtener el héroe 2 // // 3. Mostrar el héroe 2 en la consola // const heroe = getHeroeById(2); // resolve(heroe); // // reject('No se pudo encontrar el héroe'); // }, 2000); // }); // promesa.then((heroe) => { // console.log('héroe', heroe); // }) // .catch(err => console.warn(err)); const getHeroeByIdAsync = (id) => { return new Promise( (resolve, reject) => { setTimeout(() => { const heroe = getHeroeById(id); if(heroe){ resolve(heroe); } else { reject('No se pudo encontrar el héroe'); } }, 2000); }); } getHeroeByIdAsync(4) .then(console.log) .catch(console.warn); // .then(heroe => console.log('Heroe', heroe)) // .catch(err => console.warn(err));
import React, { useState, useEffect } from 'react'; import { useRouter } from 'next/router' import Link from 'next/link' import styles from '../../styles/Questions.module.scss' function Part1({props}) { const router = useRouter({}) const id = router.pathname const dataQuestions = props.state.items.filter(item=>item.nameComponent === id) const data = dataQuestions[0] const [quest1, setQuest1] = useState('') const [quest2, setQuest2] = useState('') const [quest3, setQuest3] = useState('') const [quest4, setQuest4] = useState('') const [color1, setColor1] = useState('') const [color2, setColor2] = useState('') const [color3, setColor3] = useState('') const [color4, setColor4] = useState('') const [percent, setPercent] = useState(0) const [count, setCount] = useState(0) useEffect(() => { setPercent(count*(100/(data && data.answer.length))) }, [count]) if(!data) return <Link href={"/"}>404 back to menu</Link> const checkButton = () => { setCount(0) if(data.answer[0] == quest1){ setCount(prev => prev+1) setColor1('green') }else{ setColor1('red') } if(data.answer[1] == quest2){ setCount(prev => prev+1) setColor2('green') }else{ setColor2('red') } if(data.answer[2] == quest3){ setCount(prev => prev+1) setColor3('green') }else{ setColor3('red') } if(data.answer[3] == quest4){ setCount(prev => prev+1) setColor4('green') }else{ setColor4('red') } } const showButton = () => { setQuest1(data.answer[0]) setQuest2(data.answer[1]) setQuest3(data.answer[2]) setQuest4(data.answer[3]) setColor1('red') setColor2('red') setColor3('red') setColor4('red') } const clearButton = () => { setQuest1('') setQuest2('') setQuest3('') setQuest4('') setColor1('') setColor2('') setColor3('') setColor4('') setCount(0) setPercent(0) } return ( <div> <div style={{marginTop: 50}}> <h2>Question 1 – 4</h2> <div style={{width: '50%'}}>Play ► and Listen the audio, complete the notes below by filling the gaps. Write no more than two words and/or a number for each answer. </div> </div> <div style={{marginTop: 50}}> <div className={styles.title}> <b>NOTES ON ISLAND HOTEL</b> </div> <div className={styles.description}> Type of room required <span style={{textDecoration: 'underline'}}>Double room</span> </div> <div className={styles.title}> <b>Time</b> </div> <div className={styles.description}> ・The length of stay: approximately 2 weeks </div> <div className={styles.description}> ・Starting date: 25th April </div> <div className={styles.title}> <b>Temperature</b> </div> <div className={styles.description}> ・Up to <input onChange={e=>setQuest1(e.currentTarget.value)} value={quest1} className={styles.input} style={{color: color1, fontWeight: 'bold'}}></input> °C </div> <div className={styles.description}> ・Erratic weather </div> <div className={styles.title}> <b>Transport</b> </div> <div className={styles.description}> ✔︎ Pick-up service is provided </div> <div className={styles.description}> ✔︎ Normally transfer to the airport takes about<input onChange={e=>setQuest2(e.currentTarget.value)} value={quest2} className={styles.input} style={{color: color2, fontWeight: 'bold'}}></input> </div> <div className={styles.title}> <b>Facilities</b> </div> <div className={styles.description}> ✔︎ En-suite facilities and a<input onChange={e=>setQuest3(e.currentTarget.value)} value={quest3} className={styles.input} style={{color: color3, fontWeight: 'bold'}}></input> </div> <div className={styles.description}> ✔︎ Gym and spa facilities </div> <div className={styles.description}> ✔︎ A large outdoor swimming pool </div> <div className={styles.description}> ✔︎ Three standard<input onChange={e=>setQuest4(e.currentTarget.value)} value={quest4} className={styles.input} style={{color: color4, fontWeight: 'bold'}}></input> </div> </div> {count!=0 && <div style={{marginTop: 30}}> You have scored {percent} % ( {count} / {data && data.answer.length} ) </div>} <div style={{display: 'flex', marginTop: 50}}> <div onClick={checkButton} className={styles.buttonCheck} style={{background: '#4c87c7', color: 'white'}}><b>Check</b></div> <div onClick={showButton} className={styles.button} style={{color: '#4c87c7'}}><b>Show</b></div> <div onClick={clearButton} className={styles.button} style={{color: '#4c87c7'}}><b>Clear</b></div> </div> </div> ) } export default Part1
import mongoose from "mongoose" import CommentService from "./CommentService" let Schema = mongoose.Schema let ObjectId = Schema.Types.ObjectId let _schema = new Schema({ description: { type: String, default: '' }, list: { type: ObjectId, ref: 'List' }, user: { type: ObjectId, ref: 'User' }, board: { type: ObjectId, ref: 'Board' }, comment: [{ type: ObjectId, ref: 'Comment' }], order: { type: Number, required: true, default: 0 }, }) _schema.pre('deleteMany', function (next) { //lets find all the lists and remove them Promise.all([ CommentService.deleteMany({ list: this._conditions._id }), ]) .then(() => next()) .catch(err => next(err)) }) //cascade delete the comments _schema.pre('findOneAndRemove', function (next) { //lets find all the lists and remove them Promise.all([ CommentService.deleteMany({ task: this._conditions._id }) ]) .then(() => next()) .catch(err => next(err)) }) export default mongoose.model('Task', _schema)
let mongoose = require('mongoose'); let ProductSchema = new mongoose.Schema({ type: String, name:String, price:{type:Number,min:0,max:999}, likes: {type: Number, default: 0} }, { collection: 'products' }); module.exports = mongoose.model('Product', ProductSchema);
module.exports = { findAll: function(req,data){ return new Promise(function(resolve, reject) { req.getConnection(function(err,connection){ const condition = [] let sql = 'SELECT '+(data && data.column ? data.column : "*")+' FROM pages where 1 = 1' if(data.type){ condition.push(data.type) sql += " and type = ?" } if(data.name){ condition.push(data.name.toLowerCase()) sql += " and LOWER(label) LIKE CONCAT('%', ?, '%') " } if(data.page_url){ condition.push(data.page_url.toLowerCase()) sql += " and LOWER(url) LIKE CONCAT('%', ?, '%') " } if(data.url){ condition.push(data.url) sql += " and url = ?" } sql += " ORDER BY pages.page_id DESC" if(data.limit){ condition.push(data['limit']) sql += " LIMIT ?" } if(data.offset){ condition.push(data['offset']) sql += " OFFSET ?" } connection.query(sql,condition,function(err,results,fields) { if(err) reject("") if(results){ const level = JSON.parse(JSON.stringify(results)); resolve(level); }else{ resolve(""); } }) }) }); }, findByType: function(type,req,res){ return new Promise(function(resolve, reject) { req.getConnection(function(err,connection){ connection.query('SELECT * FROM pages WHERE type = ?',[type],function(err,results,fields) { let pageData = {} if(results && results.length){ const page = JSON.parse(JSON.stringify(results)); pageData = page[0] delete pageData["page_id"] delete pageData["label"] delete pageData["custom"] delete pageData["banner_image"] if(!pageData['banner']) delete pageData["banner"] if(pageData.type != "terms" && pageData.type != "privacy"){ delete pageData["content"] } delete pageData["url"] if(!pageData.custom_tags){ delete pageData.custom_tags } delete pageData["view_count"] //increase page view count connection.query('UPDATE pages SET view_count = view_count + 1 WHERE type = ?',[type],function(err,results,fields) { }) }else{ pageData.title = req.appSettings.page_default_title pageData.description = req.appSettings.page_default_description pageData.keywords = req.appSettings.page_default_keywords pageData.image = req.appSettings.page_default_image } resolve(pageData) }) }) }); }, findById: function(id,req,res){ return new Promise(function(resolve, reject) { req.getConnection(function(err,connection){ connection.query('SELECT * FROM pages WHERE page_id = ?',[id],function(err,results,fields) { if(err) reject("") if(results){ const level = JSON.parse(JSON.stringify(results)); resolve(level[0]); }else{ resolve(""); } }) }) }); } }
/** * Application configuration */ var devConfig = { database: 'mongodb://localhost/sbz' }; var prodConfig = { database: 'mongodb://mongodb/sbz' }; function configuration() { switch (process.env.NODE_ENV) { case 'development': return devConfig; case 'production': return prodConfig; default: return devConfig; } } module.exports = configuration();
import { GetObjectsDOM } from "../../global/utils/utils"; import { getAllData } from "../firebase/firestore"; import Data from './data'; ((GetObjectsDOM, getAllData, Data) => { const collectionName = 'profile'; const ObjectsDOM = ObjectsDOM || {}; const IdObjectsDOM = { ContainerProfile: 'profile_container', }; GetObjectsDOM(IdObjectsDOM, ObjectsDOM); const getHTML = (data) => `<p tabindex="0">${data.paragraph}</p>`; const DataProfile = new Data(getAllData, collectionName); DataProfile.setData(ObjectsDOM.ContainerProfile, getHTML); })(GetObjectsDOM, getAllData, Data);
import React, { Component } from 'react'; import "bootstrap/dist/css/bootstrap.min.css"; import { BrowserRouter as Router, Route, Link } from "react-router-dom"; import CreateTodo from "./components/create-todo.component"; import EditTodo from "./components/edit-todo.component"; import TodosList from "./components/todos-list.component"; import logo from "./logo.png"; class App extends Component { render() { return ( <Router> <div className="container-fluid"> <nav className="navbar navbar-expand navbar-dark bg-dark"> <div className="navbar-nav"> <div className="navbar-brand d-inline-block"><a href="/"><img src={logo} width="30" height="40" alt="Todo Logo" /></a></div> <div> <a className="nav-item nav-link d-inline-block" href="/">Todos</a> <a className="nav-item nav-link d-inline-block" href="/create">Create</a> </div> </div> </nav> <Route path="/" exact component={TodosList} /> <Route path="/edit/:id" component={EditTodo} /> <Route path="/create" component={CreateTodo} /> </div> </Router> ); } } export default App;
(function () { 'use strict'; angular.module('app').directive('poolSummaryCharts', function () { return { scope: { topCardStatsTitle: '=', topGraphCards: '=', bottomCardStatsTitle: '=', bottomGraphCards: '=', chartsHidden: '=', controllerId: '=' }, restrict: 'AE', templateUrl: '/app/directives/poolSummaryCharts.html', controller: function ($scope, $element) { var graphAnalysis = (function () { Chart.defaults.global.animation = false; var whiteColor = '#FFFFCC'; var blueColor = 'rgba(29,151,152,0.5)'; var blackColor = 'rgba(6,6,6,0.7)'; var redColor = 'rgba(216,90,91,0.8)'; var greenColor = 'rgba(74,106,41,0.8)'; var whiteColor_highlight = '#FFFFCC'; var blueColor_highlight = '#33CCFF'; var blackColor_highlight = 'rgba(0,0,0,0.7)'; var redColor_highlight = '#CC0000'; var greenColor_highlight = '#99FF99'; var cardType_creature_color = greenColor; var cardType_creature_color_highlight = greenColor_highlight; var cardType_sorcery_color = redColor; var cardType_sorcery_color_highlight = redColor_highlight; var cardType_instant_color = blueColor; var cardType_instant_color_highlight = blueColor_highlight; var cardType_enchantment_color = whiteColor; var cardType_enchantment_color_highlight = whiteColor_highlight; var cardType_land_color = '#006600'; var cardType_land_color_highlight = '#00CC66'; var cardType_planeswalker_color = '#FF0066'; var cardType_planeswalker_color_highlight = '#FF3399'; var cardType_artifact_color = blackColor; var cardType_artifact_color_highlight = blackColor_highlight; var barChartColor = '#dedede'; var highlightColor = 'rgb(51,51,51)'; var costBarChart_fillColor = barChartColor; var costBarChart_strokeColor = barChartColor; var costBarChart_highlightFill = highlightColor; var costBarChart_highlightStroke = highlightColor; var cardType_creature = 0; var cardType_sorcery = 1; var cardType_instant = 2; var cardType_enchantment = 3; var cardType_land = 4; var cardType_planeswalker = 5; var cardType_artifact = 6; function GraphSetting(chartId, width, height) { var self = this; self.chartId = chartId; self.width = width; self.height = height; self.$graph = null; self.get$graph = function () { if (self.$graph == null) { self.$graph = document.getElementById(self.chartId); } return self.$graph; } self.getGraphContext = function () { return self.get$graph().getContext('2d'); } } function GraphAnalysis(colorSymbolGraphSettings, manaCurveGraphSettings, cardTypesGraphSettings) { var self = this; self.colorSymbolGraphSettings = colorSymbolGraphSettings; self.manaCurveGraphSettings = manaCurveGraphSettings; self.cardTypesGraphSettings = cardTypesGraphSettings; self.resetCanvas = function (graphSettings) { var canvasHolder = graphSettings.getGraphContext(); while (canvasHolder.firstChild) { canvasHolder.removeChild(canvasHolder.firstChild); } var canvas = document.createElement("canvas"); canvas.width = graphSettings.width; canvas.height = graphSettings.height; canvasHolder.appendChild(canvas); } self.resetAllCanvas = function () { self.resetCanvas(self.colorSymbolGraphSettings); self.resetCanvas(self.cardTypesGraphSettings); self.resetCanvas(self.manaCurveGraphSettings); } self.collectGraphData = function (cardData) { var colorInfo = []; for (var i = 0; i < 5; i++) { colorInfo[i] = 0; } var cardCosts = []; var maxCardCostShown = 7; for (var i = 0 ; i < maxCardCostShown + 1; i++) { cardCosts[i] = 0; } var cardTypes = []; for (var i = 0; i < 7; i++) { cardTypes[i] = 0; } for (var i = 0; i < cardData.length; i++) { var thisCardCost = cardData[i].Cost; var colorlessCost = parseInt(thisCardCost.charAt(0), 10); for (var j = 1; j < thisCardCost.length; j++) { switch (thisCardCost.charAt(j)) { case "W": colorInfo[0] = colorInfo[0] + 1; break; case "U": colorInfo[1] = colorInfo[1] + 1; break; case "B": colorInfo[2] = colorInfo[2] + 1; break; case "R": colorInfo[3] = colorInfo[3] + 1; break; case "G": colorInfo[4] = colorInfo[4] + 1; break; case "C": colorInfo[5] = colorInfo[5] + 1; } } var totalCost = colorlessCost + thisCardCost.length - 1; if (totalCost < maxCardCostShown) { cardCosts[totalCost] = cardCosts[totalCost] + 1; } else { cardCosts[maxCardCostShown] = cardCosts[maxCardCostShown] + 1; } var currentCardType = cardData[i].Type; for (var k = 0; k < currentCardType.length; k++) { switch (currentCardType[k]) { case "C": cardTypes[cardType_creature] = cardTypes[cardType_creature] + 1; break; case "S": cardTypes[cardType_sorcery] = cardTypes[cardType_sorcery] + 1; break; case "I": cardTypes[cardType_instant] = cardTypes[cardType_instant] + 1; break; case "E": cardTypes[cardType_enchantment] = cardTypes[cardType_enchantment] + 1; break; case "L": cardTypes[cardType_land] = cardTypes[cardType_land] + 1; break; case "A": cardTypes[cardType_artifact] = cardTypes[cardType_artifact] + 1; break; case "P": cardTypes[cardType_planeswalker] = cardTypes[cardType_planeswalker] + 1; break; } } } var fullInfo = { colorInfo: colorInfo, totalCosts: cardCosts, cardTypes: cardTypes }; return fullInfo; } self.displayChartsForCards = function (cardData) { self.resetAllCanvas(); var colorData = self.collectGraphData(cardData); setUpColorPieChart(colorData.colorInfo); setUpManaCurveBarChart(colorData.totalCosts); setUpTypeBarChart(colorData.cardTypes); } function setUpTypeBarChart(typeData) { var data = [ { value: typeData[cardType_creature], color: cardType_creature_color, highlight: cardType_creature_color_highlight, label: "Creature" }, { value: typeData[cardType_sorcery], color: cardType_sorcery_color, highlight: cardType_sorcery_color_highlight, label: "Sorcery" }, { value: typeData[cardType_instant], color: cardType_instant_color, highlight: cardType_instant_color_highlight, label: "Instant" }, { value: typeData[cardType_enchantment], color: cardType_enchantment_color, highlight: cardType_enchantment_color_highlight, label: "Enchantment" }, { value: typeData[cardType_land], color: cardType_land_color, highlight: cardType_land_color_highlight, label: "Land" }, { value: typeData[cardType_planeswalker], color: cardType_planeswalker_color, highlight: cardType_planeswalker_color_highlight, label: "Planeswalker" }, { value: typeData[cardType_artifact], color: cardType_artifact_color, highlight: cardType_artifact_color_highlight, label: "Artifact" } ]; var myPieChart = new Chart(cardTypesSettings.getGraphContext()).Pie(data, { }); } function setUpManaCurveBarChart(manaData) { var data = { labels: ["0", "1", "2", "3", "4", "5", "6", "7+"], datasets: [ { label: "Mana Curve", fillColor: costBarChart_fillColor, strokeColor: costBarChart_strokeColor, highlightFill: costBarChart_highlightFill, highlightStroke: costBarChart_highlightStroke, data: [manaData[0], manaData[1], manaData[2], manaData[3], manaData[4], manaData[5], manaData[6], manaData[7]] } ] }; var myBarChart = new Chart(getBarChartElement()).Bar(data, { }); } function setUpColorPieChart(colorData) { var data = [ { value: colorData[0], color: whiteColor, highlight: whiteColor_highlight, label: "White" }, { value: colorData[1], color: blueColor, highlight: blueColor_highlight, label: "Blue" }, { value: colorData[2], color: blackColor, highlight: blackColor_highlight, label: "Black" }, { value: colorData[3], color: redColor, highlight: redColor_highlight, label: "Red" }, { value: colorData[4], color: greenColor, highlight: greenColor_highlight, label: "Green" } ]; var myPieChart = new Chart(getPieChartElement()).Pie(data, { }); } } return { GraphSetting: GraphSetting, GraphAnalysis: GraphAnalysis }; })(); var graphWidth = 200; var graphHeight = 200; $scope.fixedCharts = false; $scope.hideCharts = function () { $scope.chartsHidden = true; trackEvent($scope.controllerId, 'toggle-charts'); }; var topCharts = new graphAnalysis.GraphAnalysis( new graphAnalysis.GraphSetting('colorPieChartsContainer', graphWidth, graphHeight), new graphAnalysis.GraphSetting('manaCurveBarChartContainer', graphWidth, graphHeight), new graphAnalysis.GraphSetting('typePieChartContainer', graphWidth, graphHeight) ); $scope.$watch(function () { return $scope.topGraphCards; }, function (newVal, oldVal) { topCharts.resetAllCanvas(); topCharts.displayChartsForCards($scope.topGraphCards); }, true); if ($scope.bottomGraphCards != null) { var bottomCharts = new graphAnalysis.GraphAnalysis( new graphAnalysis.GraphSetting('colorPieChartsContainer-bottom', graphWidth, graphHeight), new graphAnalysis.GraphSetting('manaCurveBarChartContainer-bottom', graphWidth, graphHeight), new graphAnalysis.GraphSetting('typePieChartContainer-bottom', graphWidth, graphHeight) ); $scope.$watch(function () { return $scope.bottomGraphCards; }, function (newVal, oldVal) { bottomCharts.resetAllCanvas(); bottomCharts.displayChartsForCards($scope.topGraphCards); }, true); } } } }); })();
'use strict'; const Path = require('path'); const Hapi = require('hapi'); const Inert = require('inert'); const route = require('./routes'); const settings = require('./config/settings'); const plugins = require('./config/plugin_config'); /**************server config********/ let option={ host: 'localhost', port:3333, routes: { files: { relativeTo: Path.join(__dirname, 'static') } } }; //Create a Hapi server let server = new Hapi.Server(option); server.register(plugins,function (err) { server.views({ engines: { 'html': { module: require('handlebars') } }, relativeTo:__dirname, path:'static/templates' }); if(err) { console.log(err); throw err; } }); route.forEach(function (api) { server.route(api); }); //Export the server to be required elsewhere. module.exports = server;
// 定数の設定 var chunkSize = 32; var chunkPad = 2; // チャンクを管理するためのクラス // 現在のところ、voxelArrayの中に入る値は // { v: ボクセルID値, f: ボクセルフラグ値 } // ボクセルID: 0x0 - 0xffffff = 24bit RGBAカラー // 0x1000000 - = ボクセルID0からのテクスチャボクセル // ボクセルフラグ: 未定 function Chunk(entity, chunker, lo, hi, fn) { lo[0]--; lo[1]--; lo[2]--; hi[0]++; hi[1]++; hi[2]++; var dims = [hi[2]-lo[2], hi[1]-lo[1], hi[0]-lo[0]] this.voxelArray = ndarray(new Array(dims[2] * dims[1] * dims[0]), dims); this.mesh = undefined; this.rigidBodyArray = []; // 初期値の設定 for (var k = lo[2]; k < hi[2]; k++) for (var j = lo[1]; j < hi[1]; j++) for(var i = lo[0]; i < hi[0]; i++) { this.voxelArray.set(k-lo[2], j-lo[1], i-lo[0], fn(i, j, k)); } // 親となるエンティティを記録 this.parentEntity = entity; this.parentChunker = chunker; }; Chunk.prototype = { get: function(x, y, z) { return this.voxelArray.get(x, y, z); }, set: function(x, y, z, v) { this.voxelArray.set(x, y, z, v); }, destroyRigidBody: function() { var app = pc.Application.getApplication(); for (var i = 0; i < this.rigidBodyArray.length; i++) { app.systems.rigidbody.removeBody(this.rigidBodyArray[i]); Ammo.destroy(this.rigidBodyArray[i].getCollisionShape()); Ammo.destroy(this.rigidBodyArray[i]); } this.rigidBodyArray = []; }, getRigidBodyArray: function() { return this.rigidBodyArray; }, setRigidBody: function(x, y, z, parentEntityScale, rigidBodyBoxScale) { printDebugMessage("(x, y, z) = (" + x + ", " + y + ", " + z + " parentEntityScale = " + parentEntityScale + " rigidBodyBoxScale = " + rigidBodyBoxScale, 8); var mass = 0; // Static volume which has infinite mass var cleanUpTarget = {}; var localVec = new Ammo.btVector3(parentEntityScale.x * rigidBodyBoxScale.x * vx2.meshScale * 0.5, parentEntityScale.y * rigidBodyBoxScale.y * vx2.meshScale * 0.5, parentEntityScale.z * rigidBodyBoxScale.z * vx2.meshScale * 0.5); var shape = new Ammo.btBoxShape(localVec); var entityPos = this.parentEntity.getPosition(); var entityRot = this.parentEntity.getLocalRotation(); var localPos = new pc.Vec3(x, y, z); localPos.x = (localPos.x) * vx2.meshScale * parentEntityScale.x; localPos.y = (localPos.y) * vx2.meshScale * parentEntityScale.y; localPos.z = (localPos.z) * vx2.meshScale * parentEntityScale.z; localPos = entityRot.transformVector(localPos); var transformPos = new pc.Vec3(); transformPos.add2(entityPos, localPos); var ammoQuat = new Ammo.btQuaternion(); ammoQuat.setValue(entityRot.x, entityRot.y, entityRot.z, entityRot.w); var startTransform = new Ammo.btTransform(); startTransform.setIdentity(); startTransform.getOrigin().setValue(transformPos.x, transformPos.y, transformPos.z); startTransform.setRotation(ammoQuat); localVec.setValue(0, 0, 0); var motionState = new Ammo.btDefaultMotionState(startTransform); var bodyInfo = new Ammo.btRigidBodyConstructionInfo(mass, motionState, shape, localVec); var body = new Ammo.btRigidBody(bodyInfo); body.chunk = this; body.entity = this.parentEntity; // This is necessary to have collision event work. body.localPos = localPos; body.setRestitution(0.5); body.setFriction(0.5); body.setDamping(0.5, 0.5); localVec.setValue(0, 0, 0); body.setLinearFactor(localVec); localVec.setValue(0, 0, 0); body.setAngularFactor(localVec); // 生成した剛体を登録する this.rigidBodyArray.push(body); Ammo.destroy(localVec); Ammo.destroy(ammoQuat); Ammo.destroy(startTransform); Ammo.destroy(motionState); Ammo.destroy(bodyInfo); var app = pc.Application.getApplication(); app.systems.rigidbody.addBody(body, pc.BODYGROUP_STATIC, pc.BODYMASK_NOT_STATIC); body.forceActivationState(pc.BODYFLAG_ACTIVE_TAG); body.activate(); }, createPlayCanvasRigidBody: function() { var pos = this.parentEntity.getPosition(); var entityScale = this.parentEntity.getLocalScale(); var totalRigidBodyNum = 0; var chunkRigidBodyNum = 0; var volume = this.voxelArray.data; var mark = []; var dimsX = this.voxelArray.shape[2], dimsY = this.voxelArray.shape[1], dimsXY = dimsX * dimsY; // Sweep over Y axis var d = 1, u = (d + 1) % 3, v = (d + 2) % 3, x = [0, 0, 0], dimsD = this.voxelArray.shape[d], dimsU = this.voxelArray.shape[u], dimsV = this.voxelArray.shape[v], xd, xv, xu, n; while (x[d] < dimsD) { xd = x[d]; for(x[v] = 0; x[v] < dimsV; ++x[v]) { xv = x[v]; for(x[u] = 0; x[u] < dimsU; ++x[u]) { xu = x[u]; var a = 0x00000000; if (xd === 0 || xd === dimsD - 1 || xu === 0 || xu === dimsU - 1 || xv === 0 || xv === dimsV - 1) { if (mark[x[2] + dimsX * x[1] + dimsXY * x[0] ] === undefined) { a = volume[x[2] + dimsX * x[1] + dimsXY * x[0] ].v; } else { a = 0; } } else if ((volume[x[2] - 1 + dimsX * x[1] + dimsXY * x[0] ].v === 0 || mark [x[2] - 1 + dimsX * x[1] + dimsXY * x[0] ] !== undefined) || (volume[x[2] + 1 + dimsX * x[1] + dimsXY * x[0] ].v === 0 || mark [x[2] + 1 + dimsX * x[1] + dimsXY * x[0] ] !== undefined) || (volume[x[2] + dimsX * (x[1] + 1) + dimsXY * x[0] ].v === 0 || mark [x[2] + dimsX * (x[1] + 1) + dimsXY * x[0] ] !== undefined) || (volume[x[2] + dimsX * (x[1] - 1) + dimsXY * x[0] ].v === 0 || mark [x[2] + dimsX * (x[1] - 1) + dimsXY * x[0] ] !== undefined) || (volume[x[2] + dimsX * x[1] + dimsXY * (x[0] - 1) ].v === 0 || mark [x[2] + dimsX * x[1] + dimsXY * (x[0] - 1) ] !== undefined) || (volume[x[2] + dimsX * x[1] + dimsXY * (x[0] + 1) ].v === 0 || mark [x[2] + dimsX * x[1] + dimsXY * (x[0] + 1) ] !== undefined)) { if (mark[x[2] + dimsX * x[1] + dimsXY * x[0] ] === undefined) { a = volume[x[2] + dimsX * x[1] + dimsXY * x[0] ].v; } else { a = 0; } } if (a !== 0) { // Found the origin point. Scan voxel and create as large as possible box rigid body var xx = x.slice(0); var max = [0, 0, 0]; max[d] = dimsD; max[v] = dimsV; max[u] = dimsU; maxValid = [false, false, false]; printDebugMessage("a = " + a.toString(16) + " (x, y, z) = (" + xx[2] + ", " + xx[1] + ", " + xx[0] + ") scale = " + entityScale, 8); while (xx[d] < max[d]) { for(xx[v] = x[v]; xx[v] < max[v]; ++xx[v]) { for (xx[u] = x[u]; xx[u] < max[u]; ++xx[u]) { var aa; if (mark[xx[2] + dimsX * xx[1] + dimsXY * xx[0] ] === undefined) { aa = volume[xx[2] + dimsX * xx[1] + dimsXY * xx[0] ].v; } else { aa = 0; } if (aa === 0) { if (maxValid[u] === false) { // Found new uMax max[u] = xx[u]; maxValid[u] = true; printDebugMessage("Found uMax: " + max[u], 8); } break; } } if (maxValid[u] === false) { // Exit from the loop without finding the new uMax max[u] = xx[u]; maxValid[u] = true; printDebugMessage("Found uMax: " + max[u], 8); } if (xx[u] < max[u]) { if (maxValid[v] === false) { // Found new vMax max[v] = xx[v]; maxValid[v] = true; printDebugMessage("Found vMax: " + max[v], 8); } break; } } if (maxValid[v] === false) { // Exit from the loop without finding the new uMax max[v] = xx[v]; maxValid[v] = true; printDebugMessage("Found vMax: " + max[v], 8); } if (xx[v] < max[v]) { if (maxValid[d] === false) { // Found new dMax max[d] = xx[d]; maxValid[d] = true; printDebugMessage("Found dMax: " + max[d], 8); } break; } ++xx[d]; } // Mark voxel as used for (xx[d] = x[d]; xx[d] < max[d]; ++xx[d]) { for (xx[v] = x[v]; xx[v] < max[v]; ++xx[v]) { for (xx[u] = x[u]; xx[u] < max[u]; ++xx[u]) { mark[xx[2] + dimsX * xx[1] + dimsXY * xx[0]] = 1; } } } var rigidBodyBoxScale = new pc.Vec3(max[2] - x[2] - vx2.rigidBodyGap, max[1] - x[1] - vx2.rigidBodyGap, max[0] - x[0] - vx2.rigidBodyGap); var chunker = this.parentChunker; this.setRigidBody((x[2] + max[2]) * 0.5 + chunker.coordinateOffset[0] + chunker.chunkSize * this.position[2], (x[1] + max[1]) * 0.5 + chunker.coordinateOffset[1] + chunker.chunkSize * this.position[1], (x[0] + max[0]) * 0.5 + chunker.coordinateOffset[2] + chunker.chunkSize * this.position[0], entityScale, rigidBodyBoxScale); chunkRigidBodyNum += 1; } } } ++x[d]; } if (chunkRigidBodyNum === 0) { this.empty = true; printDebugMessage("chunkRigidBodyNum: " + chunkRigidBodyNum, 1); } } };
import 'regenerator-runtime/runtime' import React, { useState, useEffect, useMemo, useRef, useLayoutEffect } from 'react' import { useStateCovidData, idToStateData } from './data/stateCovidDataService' import { useTrendData } from './data/stateTrendDataService' import { usePolicyData } from './data/policyDataService' import USMap from './charts/USMap' import StateTooltip from './components/StateTooltip' import PolicyChart from './charts/PolicyChart' import Modal from './layout/Modal' import DataLoading from './components/DataLoading' import styles from './hero.modules.css' const Hero = () => { const [stateData, isStateDataLoading] = useStateCovidData() const [trendData, isTrendDataLoading ] = useTrendData() const [policyData, isPolicyDataLoading ] = usePolicyData() const [hoverStateId, setHoverStateId] = useState(null) const hoverStateData = hoverStateId ? idToStateData(hoverStateId, stateData) : null const [focusedStateId, setFocusedStateId] = useState(null) const focusedData = useMemo(() => { if(isTrendDataLoading || isPolicyDataLoading || focusedStateId === null) { return null } const stateTrendData = trendData.filter( obj => obj.id == focusedStateId )[0] return { rollup: idToStateData(focusedStateId, stateData), casesRaw: stateTrendData.casesRaw, casesSpline: stateTrendData.casesSpline, positivitySpline: stateTrendData.positivitySpline, policy: policyData.filter( obj => obj.id == focusedStateId )[0] } }, [focusedStateId, isTrendDataLoading, isPolicyDataLoading]) // Metrics for sizing various things const heroRef = useRef() const [metrics, setMetrics] = useState({}) useLayoutEffect( () => { setMetrics(heroRef.current.getBoundingClientRect().toJSON()) }, [heroRef.current] ) useEffect( () => { const onResize = () => { setMetrics(heroRef.current.getBoundingClientRect().toJSON()) } window.addEventListener('resize', onResize) return () => { window.removeEventListener('resize', onResize) } }, [heroRef]) const [mousePosition, setMousePosition] = useState({x: null, y: null}) const updateMousePosition = event => { const bounds = heroRef.current.getBoundingClientRect() setMousePosition({ x: event.clientX - bounds.left, y: event.clientY - bounds.top }) } useEffect( () => { document.addEventListener('mousemove', updateMousePosition) return () => { document.removeEventListener('mousemove', updateMousePosition) } }, []) return (<div className={styles.root} ref={heroRef}> {(hoverStateData && focusedData == null) && ( <StateTooltip data={hoverStateData} x={mousePosition.x} y={mousePosition.y} xRange={[0, metrics.width]} /> )} {focusedData && ( <Modal title={`History of cases in ${focusedData.rollup.STATE}`} onClose={ () => setFocusedStateId(null) } > <PolicyChart rawCasesSeries={focusedData.casesRaw} trendCasesSeries={focusedData.casesSpline} positivitySeries={focusedData.positivitySpline} policyData={focusedData.policy} /> </Modal> )} { isStateDataLoading || isTrendDataLoading ? ( <DataLoading /> ):( <USMap data={stateData} setHoverStateId={setHoverStateId} setFocusedStateId={setFocusedStateId}/> )} </div>) } export default Hero;
import React, {Component} from 'react'; import classy from '../../utils/classy'; import style from './CrestPoint.module.scss'; import slackLogo from './images/slack-logo-icon.png'; import {Col, Row, Container } from 'react-bootstrap'; import { Section } from '../../components'; import {Link} from 'react-router-dom'; import { Modal, DownloadModal, Button } from '../../components'; import lake from './images/black-lake.svg'; import frontTreeline from './images/front-treeline.png'; import backTreeline from './images/back-treeline.png'; import castle from './images/castle.png'; import mainDarkHill from './images/main-ground.png'; import tree from './images/tree.svg'; import trees from './images/trees.svg'; import cloudLeft from './images/cloud-1.svg'; import cloudRight from './images/cloud-2.svg'; import crest from './images/crest.png'; import tenRed from './images/+10.svg'; import twentyFive from './images/+25.svg'; import fifty from './images/+50.svg'; import tenYellow from './images/+10.svg'; export default class HouseCupHero extends Component { render() { return( <div className={style.crestPoint}> <img src={twentyFive} className={classy(style.points, style.twentyFive)}/> <img src={fifty} className={classy(style.points, style.fifty)}/> <img src={tenYellow} className={classy(style.pointsTen, style.tenYellow)}/> <img src={tenRed} className={classy(style.pointsTen, style.tenRed)}/> </div> ); } }
import clientApi from '@/api/client' import userApi from '@/api/user' import invoiceApi from '@/api/invoice' import commonJS from '@/common/common' export default { data () { return { types: [{ code: 'Z3', name: '3%专票' }, { code: 'Z6', name: '6%专票' }, { code: 'P3', name: '3%普票' }, { code: 'P6', name: '6%普票' } ], table: { content: [], totalElements: 0, pageable: { pageNumber: commonJS.getPageNumber('invoiceList.pageNumber'), pageSize: commonJS.getPageSize('invoiceList.pageSize') } }, page: { pageSizes: [10, 30, 50, 100, 300] }, currentRow: null, searchDialog: false, search: { clientId: null, amId: null, candidateChineseName: null, type: null, status: true, createDateStart: null, createDateEnd: null }, clients: [], consultants: [] } }, methods: { // 清空搜索条件 clearQueryCondition () { this.search = { clientId: null, amId: null, candidateChineseName: null, type: null, status: true, createDateStart: null, createDateEnd: null } }, // 格式化开票类型 formatType (row, column, cellvalue, index) { if (cellvalue === 'Z3') { return '3%专票' } else if (cellvalue === 'Z6') { return '6%专票' } else if (cellvalue === 'P3') { return '3%普票' } else if (cellvalue === 'P6') { return '6%普票' } }, // 通过id发票信息 deleteById () { if (this.checkSelectRow()) { this.$confirm('确认要删除 ' + this.currentRow.clientChineseName + '-' + this.currentRow.candidateChineseName + '的发票信息吗?', '确认信息', { distinguishCancelAndClose: true, confirmButtonText: '确定', cancelButtonText: '取消' }).then(() => { invoiceApi.deleteById(this.currentRow.id).then(res => { if (res.status === 200) { if (res.data.length > 0) { this.$message.error(res.data) } else { this.$message({ message: '删除成功!', type: 'success', showClose: true }) // 删除后刷新列表 this.query() } } else { this.$message.error('删除失败!') } }) }) } }, formatCancel (row, column, cellvalue, index) { if (typeof (cellvalue) !== 'undefined') { if (cellvalue === '1') { return '作废' } } return '正常' }, formatDate (row, column, cellvalue, index) { if (typeof (cellvalue) !== 'undefined' && cellvalue !== null && cellvalue !== '') { return cellvalue.substr(0, 10) } return '' }, // 检查是否选择了一条记录 checkSelectRow () { if (this.currentRow === null) { this.$message({ message: '请选择一条记录!', type: 'info', showClose: true }) return false } return true }, // 新增 add () { this.$router.push('/salary/invoice') }, // 修改 modify () { if (this.checkSelectRow()) { this.$router.push({ path: '/salary/invoice', query: { mode: 'modify', invoice: this.currentRow } }) } }, // 查看 detail () { if (this.checkSelectRow()) { this.$router.push({ path: '/salary/invoice', query: { mode: 'detail', invoice: this.currentRow } }) } }, // 查询后台数据 query () { window.localStorage['invoiceList.pageNumber'] = this.table.pageable.pageNumber window.localStorage['invoiceList.pageSize'] = this.table.pageable.pageSize this.searchDialog = false let query = { 'currentPage': this.table.pageable.pageNumber, 'pageSize': this.table.pageable.pageSize, 'search': this.search } invoiceApi.queryPage(query).then(res => { if (res.status !== 200) { this.$message.error({ message: '查询失败,请联系管理员!' }) return } this.table = res.data this.table.pageable.pageNumber = this.table.pageable.pageNumber + 1 }) }, // 行变化 rowChange (val) { this.currentRow = val }, // 页尺寸变化 sizeChange (val) { this.table.pageable.pageSize = val this.query() }, // 当前页变化 currentChange (val) { this.table.pageable.pageNumber = val this.query() }, // 上一页 点击 prevClick (val) { this.table.pageable.pageNumber = val this.query() }, // 下一页 点击 nextClick (val) { this.table.pageable.pageNumber = val this.query() }, // 搜索对话框,确定按钮 sureSearchDialog () { this.table.pageable.pageNumber = 1 this.table.pageable.pageSize = 10 this.query() } }, created () { // 获取所有“客户”信息 clientApi.findAllOrderByChineseName().then(res => { if (res.status === 200) { this.clients = res.data } }) userApi.findAllEnabled().then(res => { if (res.status === 200) { this.consultants = res.data } }) this.query() } }
import React from 'react' import FontAwesomeIcon from '@fortawesome/react-fontawesome' import Link from '../Link'; import faHeart from '@fortawesome/fontawesome-free-solid/faHeart'; import faGithub from '@fortawesome/fontawesome-free-brands/faGithub'; import styled from 'styled-components'; import { palette } from '../../cssResources'; const Wrapper = styled.footer` font-size: 16px; padding-bottom: 30px; .Footer__heart { color: ${palette.red}; } .Footer__github { font-size: 20px; } `; const Footer = () => { return ( <Wrapper> Made with <FontAwesomeIcon icon={faHeart} className="Footer__heart"/> by <Link href="http://yiotis.net" target="_blank" rel="noopener noreferrer">Yiotis Kaltsikis</Link> &mdash; Check it out on <Link href="https://github.com/giotiskl/chmodbro" target="_blank" rel="noopener noreferrer"><FontAwesomeIcon className="Footer__github" icon={faGithub}/> GitHub</Link>! </Wrapper> ) }; export default Footer;
/** * * Mike Sherov */ const scoresDyDay = [ [100, 99, 98], [97, 96, 95], [94, 93, 92] ]; function average(arr) { const sum = arr.reduce((acc, item) => acc + item, 0); return sum / arr.length; } const scores = scoresDyDay.reduce((scores, current) => scores.concat(current), []); console.log(average(scores)); //array.prototype.flat - node 11.0.0 console.log(average(scoresDyDay.flat()));
$(document).ready(function() { /////////////////////////////////////////////////////////////////// $(window).scroll(function(){ checkNav(); }); function checkNav(){ if($( window ).width() > 768){ var gerWH = 400; if($(window).scrollTop() > gerWH){ showStickyMenu(); }else{ hideStickyMenu(); } } } checkNav(); ///////// function showStickyMenu(){ //$('#header').css({'position':'fixed', 'z-index':99999}); //$('header #top-bar').fadeOut('fast'); $('#header').addClass('makeSticky'); } function hideStickyMenu(){ //$('#header').fadeOut('fast'); //$('#header').css({'position':'relative'}); //$('header #top-bar').fadeIn('fast'); $('#header').removeClass('makeSticky'); } });
import React from 'react'; const Bar = props => { // console.log('props in Bar', props); if (props.value > 0) { return ( <div style={{ width: '300px', display: 'grid', gridTemplateColumns: '10% 45% 45%', height: '30px', padding: '2px 0px' }} > <div style={{ padding: '4px', fontSize: '12px', borderRight: '1px solid black' }}>{props.month}</div> <div style={{ width: '100%', display: 'flex', justifyContent: 'flex-end' }}> <span style={{ backgroundColor: 'red', width: '0%', height: '90%', borderTopLeftRadius: '10px', borderBottomLeftRadius: '10px', marginTop: '2px' }} > {' '} </span> </div> <div style={{ width: '100%', display: 'flex', justifyContent: 'flex-start' }}> <span style={{ backgroundColor: 'blue', width: `${props.value}%`, height: '90%', borderTopRightRadius: '10px', borderBottomRightRadius: '10px', padding: '3px 0px', marginTop: '2px' }} > {' '} </span> </div> </div> ); } else { return ( <div style={{ width: '300px', display: 'grid', gridTemplateColumns: '10% 45% 45%', height: '30px', padding: '2px 0px' }} > <div style={{ padding: '4px', fontSize: '12px', borderRight: '1px solid black' }}>{props.month}</div> <div style={{ width: '100%', display: 'flex', justifyContent: 'flex-end' }}> <span style={{ backgroundColor: 'red', width: `${props.value * -1}%`, height: '90%', borderTopLeftRadius: '10px', borderBottomLeftRadius: '10px', marginTop: '2px' }} > {' '} </span> </div> <div style={{ width: '100%', display: 'flex', justifyContent: 'flex-start' }}> <span style={{ backgroundColor: 'blue', width: '0%', height: '90%', borderTopRightRadius: '10px', borderBottomRightRadius: '10px', padding: '3px 0px', marginTop: '2px' }} > {' '} </span> </div> </div> ); } }; export default Bar;
import './estilos.scss'; import $ from "jquery"; import './banner1.png'; import './banner2.png'; import './computadora.jpg'; import './presentacion.jpg'; import './presentacionbanner.jpg'; import './map-point.png'; import './bytexbyte.ico'; let linkquienes = document.getElementById("linkquienes"); let linkmision = document.getElementById("linkmision"); let linkvision = document.getElementById("linkvision"); let linkobjr = document.getElementById("linkobjr"); let linkubi = document.getElementById("linkubi"); let botonescondido = document.getElementById("botonescondido"); let collapsibleNavId = document.getElementById("collapsibleNavId"); let imagen1 = document.getElementById("imagen1"); let imagen2 = document.getElementById("imagen2"); let imagen3 = document.getElementById("imagen3"); let imagen4 = document.getElementById("imagen4"); let imagen5 = document.getElementById("imagen5"); let imagen6 = document.getElementById("imagen6"); window.onload = () => { let pantallaCarga = document.getElementById("pantallaCarga"); pantallaCarga.setAttribute("hidden", "hidden"); } $("#linkquienes").click(function () { $('html,body').animate({ scrollTop: $("#quienessomos").offset().top }, 1000); }); $("#linkmision").click(function () { $('html,body').animate({ scrollTop: $("#mision").offset().top }, 1000); }); $("#linkvision").click(function () { $('html,body').animate({ scrollTop: $("#vision").offset().top }, 1000); }); $("#linkobjr").click(function () { $('html,body').animate({ scrollTop: $("#obrealizado").offset().top }, 1000); }); $("#linkubi").click(function () { $('html,body').animate({ scrollTop: $("#ubicanos").offset().top }, 1000); }); let esconderboton = () => { botonescondido.setAttribute("class", "navbar-toggler d-lg-none collapsed"); botonescondido.setAttribute("aria-expanded", "false"); collapsibleNavId.setAttribute("class", "collapse navbar-collapse"); } let redireccion = () => { location = "https://www.google.com/intl/es/photos/about/" } linkquienes.onclick = () => { esconderboton(); } linkmision.onclick = () => { esconderboton(); } linkvision.onclick = () => { esconderboton(); } linkobjr.onclick = () => { esconderboton(); } linkubi.onclick = () => { esconderboton(); } $(document).ready(function () { $('.zoom').hover(function () { $(this).addClass('transition'); }, function () { $(this).removeClass('transition'); }); });
import axios from 'axios' import config from '../config' import Promise from 'bluebird' import { browserHistory } from 'react-router' /* ----------------- ACTION TYPES ------------------ */ const SET_CURRENT_RESTAURANT = "SET_CURRENT_RESTAURANT" const SEARCH_CATEGORY = "SEARCH_CATEGORY" const SEARCH_LOCATION = "SEARCH_LOCATION" const FOUND_RESTAURANTS = "FOUND_RESTAURANTS" const GET_MENU = "GET_MENU" const GET_DISHES = "GET_DISHES" const GET_FAVORITES = "GET_FAVORITES" const SET_FOUND_RESTAURANT_INDEX = "SET_FOUND_RESTAURANT_INDEX" const RESET_RESTAURANT_INDEX = "RESET_RESTAURANT_INDEX" /* ------------ ACTION CREATORS ------------------ */ export const setCurrentRestaurant = restaurant => ({type: SET_CURRENT_RESTAURANT, restaurant}) export const searchCategory = category => ({type: SEARCH_CATEGORY, category}) export const searchLocation = location => ({type: SEARCH_LOCATION, location}) export const foundRestaurants = restaurants => ({type: FOUND_RESTAURANTS, restaurants}) export const getMenu = menu => ({ type: GET_MENU, menu}) export const getDishes = dishes => ({type: GET_DISHES, dishes}) export const getFavorites = favorites => ({type: GET_FAVORITES, favorites}) export const setFoundRestaurantIndex = number => ({type: SET_FOUND_RESTAURANT_INDEX, number}) export const resetRestaurauntIndex = () => ({type: RESET_RESTAURANT_INDEX}) /* ------------ REDUCER ------------------ */ export default function reducer (restaurants = { currentRestaurant: {}, category: "", location: "", foundRestaurants: [], foundRestaurantIndex: 0, showRestaurants: [], menu: {}, dishes: {}, favorites: [] }, action) { switch (action.type) { case SET_CURRENT_RESTAURANT: return Object.assign({}, restaurants, {currentRestaurant: action.restaurant}) case SEARCH_CATEGORY: return Object.assign({}, restaurants, {category: action.category}) case SEARCH_LOCATION: return Object.assign({}, restaurants, {location: action.location}) case FOUND_RESTAURANTS: return Object.assign({}, restaurants, {foundRestaurants: action.restaurants}) case SET_FOUND_RESTAURANT_INDEX: return Object.assign({}, restaurants, {foundRestaurantIndex: restaurants.foundRestaurantIndex + action.number, showRestaurants: restaurants.foundRestaurants.slice(restaurants.foundRestaurantIndex, restaurants.foundRestaurantIndex + 5)}) case RESET_RESTAURANT_INDEX: return Object.assign({}, restaurants, {foundRestaurantIndex: 0, showRestaurants: restaurants.foundRestaurants.slice(0, 5)}) case GET_MENU: return Object.assign({}, restaurants, {menu: action.menu}) case GET_DISHES: return Object.assign({}, restaurants, {dishes: action.dishes}) case GET_FAVORITES: return Object.assign({}, restaurants, {favorites: [...restaurants.favorites, action.favorites]}) default: return restaurants; } } /* ------------ THUNK CREATORS ------------------ */ export const favoriteDish = (terms) => (dispatch) => { const {dish, restaurant, currentUser} = terms axios.post(`/api/user/${currentUser.id}/favorites`, {favorite: {dish_id: dish.id, restaurant_id: restaurant.id}}) .then(res => dispatch(getFavorites(res.data))) } export const fetchFavorites = (currentUser) => dispatch => { axios.get(`/api/user/${currentUser.id}/favorites`) .then(favorites => dispatch(getFavorites(favorites.data))) } export const changeRestaurant = (restaurant_id) => dispatch => { axios.get(`/api/restaurant/${restaurant_id}`) .then(restaurant => { dispatch(setCurrentRestaurant(restaurant.data)) }) } export const fetchMenu = (id) => dispatch => { axios.get(`/api/restaurant/${id}/menu`) .then((menu) => { dispatch(getMenu(menu.data)) }) } export const searchMenus = (searchTerms) => dispatch => { const {category, location} = searchTerms axios.get(`https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/search?cuisine=${category}&instructionsRequired=false&number=20`, { headers: { "X-Mashape-Key": config.MASHAPE_KEY, "X-Mashape-Host": "spoonacular-recipe-food-nutrition-v1.p.mashape.com" } }).then(res => {return Promise.map(res.data.results, function(dish) { return axios.post('/api/dish', {dish: { name: dish.title, category: [category.toLowerCase()]}}) }) }).then(res => res.map(ele => ele.data)) .then(dishes => dispatch(getDishes(dishes))) } export const searchRestaurants = (searchTerms, history) => dispatch => { const {category, location} = searchTerms axios.post('/api/restaurant/yelp', {restaurant: {searchCat: category, searchLoc: location}}) .then(result => { return Promise.map(result.data.businesses, (restaurant) => { const info = { name: restaurant.name, category: [category.toLowerCase(), restaurant.categories[0].title], yelp_url: restaurant.id, address: `${restaurant.location.address1}, ${restaurant.location.city}, ${restaurant.location.state} ${restaurant.location.zip_code}` , latitude: restaurant.coordinates.latitude, longitude: restaurant.coordinates.longitude, price_range: restaurant.price, url: restaurant.url, featured_image: restaurant.image_url, user_rating: restaurant.rating, votes: restaurant.review_count, phone_numbers: restaurant.display_phone, transactions: restaurant.transactions } return axios.post('/api/restaurant', info) }) }) .then(restaurants => dispatch(foundRestaurants(restaurants.map(restaurant => restaurant.data)))) .then(()=> dispatch(resetRestaurauntIndex())) }
import React from 'react'; import LinkedinLogo from 'app/assets/linkedin.png'; import GitHubLogo from 'app/assets/github.png'; import UpworkLogo from 'app/assets/upwork.png'; import { Container, Wrapper } from './Footer.style'; import Tabs from './Tabs'; const Footer = ({ ...props }) => { const links = [ { index: 0, name: 'GitHub', link: 'https://github.com/mohammedmagdyismael', image: GitHubLogo, }, { index: 1, name: 'UpWork', link: 'https://www.upwork.com/freelancers/~01beb4e017cbe2a6ff', image: UpworkLogo, }, { index: 2, name: 'Linkedin', link: 'https://www.linkedin.com/in/mohammedmagdyismael/', image: LinkedinLogo, } ] return ( <Container> <Wrapper> <Tabs links={links} /> </Wrapper> </Container> ) } export default Footer;
import AppBar from 'material-ui/AppBar'; import Toolbar from 'material-ui/Toolbar'; import Typography from 'material-ui/Typography'; import Button from 'material-ui/Button'; import IconButton from 'material-ui/IconButton'; import MenuIcon from 'material-ui-icons/Menu'; import { withStyles } from 'material-ui/styles'; import React, { Component } from 'react'; import PropTypes from 'prop-types'; const styles = { root: { width: '100%' }, flex: { flex: 1 }, main: { padding: '0 40px' }, menuButton: { marginLeft: -12, marginRight: 20 } }; class DefaultLayout extends Component { render() { let { classes } = this.props; return ( <div className={classes.root}> <AppBar position="static"> <Toolbar> <IconButton className={classes.menuButton} color="contrast" aria-label="Menu" > <MenuIcon /> </IconButton> <Typography type="title" color="inherit" className={classes.flex}> MyMovieLibrary </Typography> <Button color="contrast">Login</Button> </Toolbar> </AppBar> <main className={classes.main}>{this.props.children}</main> </div> ); } } DefaultLayout.propTypes = { children: PropTypes.element, classes: PropTypes.object }; export default withStyles(styles)(DefaultLayout);
import React, { Component } from 'react'; import { connect } from 'react-redux'; import * as actions from './actions'; import { MyStylesheet } from './styles'; import Construction from './construction'; import { radioOpen, radioClosed, removeIconSmall, CheckedBox, EmptyBox } from './svg' import { EquipmentOwnership, formatDateStringDisplay, CreateCostID } from './functions'; import PurchaseDate from './purchasedate'; import SaleDate from './saledate'; import AccountID from './accountid' import EquipmentDate from './equipmentdate'; import { Link } from 'react-router-dom'; import MakeID from './makeids' import Frequency from './frequency'; class ViewEquipment extends Component { constructor(props) { super(props); this.state = { render: '', width: 0, height: 0, activecostid: '', purchasecalender: true, purchasedateday: '', purchasedatemonth: '', purchasedateyear: '', saledateday: '', saledatemonth: '', saledateyear: '', salecalender: true, equipmentcalender: true, equipmentdateday: '', equipmentdateyear: '', equipmentdatemonth: '', spinner: false } this.updateWindowDimensions = this.updateWindowDimensions.bind(this) } componentDidMount() { window.addEventListener('resize', this.updateWindowDimensions); this.updateWindowDimensions(); this.equipmentdatedefault() } componentWillUnmount() { window.removeEventListener('resize', this.updateWindowDimensions); } updateWindowDimensions() { this.setState({ width: window.innerWidth, height: window.innerHeight }); } equipmentdatedefault() { const equipmentdatemonth = () => { let month = new Date().getMonth() + 1; if (month < 10) { month = `0${month}` } return month; } const equipmentdateday = () => { let day = new Date().getDate(); if (day < 10) { day = `0${day}` } return day; } const equipmentdateyear = () => { let year = new Date().getFullYear(); return year; } this.setState({ equipmentdateyear: equipmentdateyear(), equipmentdatemonth: equipmentdatemonth(), equipmentdateday: equipmentdateday() }) } removeequipmentcost(cost) { const construction = new Construction(); const myuser = construction.getuser.call(this); if (myuser) { if (window.confirm(`Are you sure you want to delete ${cost.detail}?`)) { const equipment = this.getequipment() if (equipment) { const i = construction.getequipmentkeybyid.call(this, equipment.equipmentid) const mycost = construction.getcostbyid.call(this, equipment.equipmentid, cost.costid); if (mycost) { const j = construction.getequipmentcostskeybyid.call(this, equipment.eequipmentid, cost.costid) myuser.company.equipment[i].ownership.cost.splice(j, 1); this.props.reduxUser(myuser) this.setState({ render: 'render', activecostid: false }) } } } } } showequipmentcost(cost) { const styles = MyStylesheet(); const construction = new Construction(); const regularFont = construction.getRegularFont.call(this) const removeIcon = construction.getremoveicon.call(this) const reoccurring = (cost) => { if(cost.hasOwnProperty("reoccurring")) { return cost.reoccurring.frequency; } } const getactivecostbackground = (costid) => { if (this.state.activecostid === costid) { return ({ backgroundColor: '#F2C4D2' }) } else { return; } } return ( <div style={{ ...styles.generalFlex }} key={cost.costid}> <div style={{ ...styles.flex5, ...regularFont, ...styles.bottomMargin15, ...styles.generalFont, ...getactivecostbackground(cost.costid) }} onClick={() => { this.makeequipmentcostactive(cost.costid) }}> {formatDateStringDisplay(cost.timein)} Cost:${Number(cost.cost).toFixed(2)} Detail: {cost.detail} {reoccurring(cost)} </div> <div style={{ ...styles.flex1 }}> <button style={{ ...styles.generalButton, ...removeIcon }} onClick={() => { this.removeequipmentcost(cost) }}>{removeIconSmall()} </button> </div> </div> ) } showequipmentcosts(equipment) { let equipmentcosts = []; if (equipment.hasOwnProperty("ownership")) { if (equipment.ownership.hasOwnProperty("cost")) { // eslint-disable-next-line equipment.ownership.cost.map(cost => { equipmentcosts.push(this.showequipmentcost(cost)) }) } } return equipmentcosts; } handledetail(detail) { const construction = new Construction(); let myuser = construction.getuser.call(this); const makeID = new MakeID(); if (myuser) { const equipment = this.getequipment() if (equipment) { let i = construction.getequipmentkeybyid.call(this, equipment.equipmentid); if (this.state.activecostid) { const mycost = construction.getcostbyid.call(this, equipment.equipmentid, this.state.activecostid) if (mycost) { let j = construction.getequipmentcostskeybyid.call(this, equipment.equipmentid, this.state.activecostid) myuser.company.equipment[i].ownership.cost[j].detail = detail; this.props.reduxUser(myuser) this.setState({ render: 'render' }) } } else { let costid = makeID.costid.call(this); const year = this.state.equipmentdateyear; const day = this.state.equipmentdateday; const month = this.state.equipmentdatemonth; const datein = `${year}-${month}-${day}`; let newcost = CreateCostID(costid, 0, detail, datein) if (equipment.ownership.hasOwnProperty("cost")) { myuser.company.equipment[i].ownership.cost.push(newcost) } else { myuser.company.equipment[i].ownership.cost = [newcost] } this.props.reduxUser(myuser) this.setState({ activecostid: costid, render: 'render' }) } } } } handlecost(cost) { const construction = new Construction(); let myuser = construction.getuser.call(this); const makeID = new MakeID(); if (myuser) { const equipment = this.getequipment() if (equipment) { let i = construction.getequipmentkeybyid.call(this, equipment.equipmentid); if (this.state.activecostid) { const mycost = construction.getcostbyid.call(this, equipment.equipmentid, this.state.activecostid) if (mycost) { let j = construction.getequipmentcostskeybyid.call(this, equipment.equipmentid, this.state.activecostid) myuser.company.equipment[i].ownership.cost[j].cost = cost; this.props.reduxUser(myuser) this.setState({ render: 'render' }) } } else { let costid = makeID.costid.call(this); const year = this.state.equipmentdateyear; const day = this.state.equipmentdateday; const month = this.state.equipmentdatemonth; const datein = `${year}-${month}-${day}`; let detail = ""; let newcost = CreateCostID(costid, cost, detail, datein) if (equipment.ownership.hasOwnProperty("cost")) { myuser.company.equipment[i].ownership.cost.push(newcost) } else { myuser.company.equipment[i].ownership.cost = [newcost] } this.props.reduxUser(myuser) this.setState({ activecostid: costid, render: 'render' }) } } } } showaccountcost(equipment) { const styles = MyStylesheet(); const construction = new Construction(); const regularFont = construction.getRegularFont.call(this) const equipmentdate = new EquipmentDate(); const headerFont = construction.getHeaderFont.call(this) const frequency = new Frequency(); const buttonWidth = () => { if (this.state.width > 1200) { return ({ width: '60px' }) } else if (this.state.width > 600) { return ({ width: '50px' }) } else { return ({ width: '40px' }) } } const getreoccuring = (equipment) => { if (this.state.activecostid) { const cost = construction.getcostbyid.call(this, equipment.equipmentid, this.state.activecostid) if (cost) { if (cost.hasOwnProperty("reoccurring")) { return (CheckedBox()) } else { return (EmptyBox()) } } else { return (EmptyBox()) } } else { return (EmptyBox()) } } const showfrequency = (equipment) => { if (this.state.activecostid) { const cost = construction.getcostbyid.call(this, equipment.equipmentid, this.state.activecostid) if (cost.hasOwnProperty("reoccurring")) { return (frequency.showFrequency.call(this)) } } } const Reoccurring = (equipment) => { if (this.state.activecostid) { return (<div style={{ ...styles.generalContainer }}> <button style={{ ...styles.generalButton, ...buttonWidth() }} onClick={() => this.handlereoccurring()}> {getreoccuring(equipment)}</button> <span style={{ ...regularFont, ...styles.generalFont }}> Reoccurring Cost </span> {showfrequency(equipment)} </div> ) } } return ( <div style={{ ...styles.generalFlex }}> <div style={{ ...styles.flex1 }}> <div style={{ ...styles.generalContainer, ...styles.bottomMargin15 }}> <span style={{ ...styles.generalFont, ...headerFont, ...styles.boldFont }}>Ownership Costs</span> </div> <div style={{ ...styles.generalFlex, ...styles.bottomMargin15 }}> <div style={{ ...styles.flex1 }}> <div style={{ ...styles.generalContainer, ...styles.generalFont, ...regularFont, ...styles.bottomMargin15, ...styles.addRightMargin }}> {equipmentdate.showequipmentdate.call(this)} </div> <div style={{ ...styles.generalContainer, ...styles.generalFont, ...regularFont }}> <span style={{ ...styles.generalFont, ...regularFont }}> Detail </span> <br /> <input type="text" style={{ ...styles.generalFont, ...regularFont }} value={this.getdetail(equipment)} onChange={event => { this.handledetail(event.target.value) }} /> </div> </div> </div> <div style={{ ...styles.generalContainer, ...styles.bottomMargin15 }}> <span style={{ ...styles.generalFont, ...regularFont }}> Cost</span> <br /> <input type="text" style={{ ...styles.generalFont, ...regularFont }} value={this.getcost(equipment)} onChange={event => { this.handlecost(event.target.value) }} /> </div> {Reoccurring(equipment)} <div style={{ ...styles.generalFlex }}> <div style={{ ...styles.flex1 }}> {this.showequipmentcosts(equipment)} </div> </div> </div> </div> ) } handleworkinghours(workinghours) { const construction = new Construction(); let myuser = construction.getuser.call(this); if (myuser) { const equipment = construction.getmyequipmentbyid.call(this, this.props.match.params.equipmentid) if (equipment) { let i = construction.getequipmentkeybyid.call(this, this.props.match.params.equipmentid) myuser.company.equipment[i].ownership.workinghours = workinghours; this.props.reduxUser(myuser) this.setState({ render: 'render' }) } } } handleloaninterest(loaninterest) { const construction = new Construction(); let myuser = construction.getuser.call(this); if (myuser) { if (this.props.match.params.equipmentid) { const myequipment = construction.getmyequipmentbyid.call(this, this.props.match.params.equipmentid); if (myequipment) { const i = construction.getequipmentkeybyid.call(this, this.props.match.params.equipmentid) myuser.company.equipment[i].ownership.loaninterest = loaninterest; this.props.reduxUser(myuser) this.setState({ render: 'render' }) } } } } getpurchasevalue(equipment) { if (equipment.hasOwnProperty("ownership")) { return equipment.ownership.purchase } } getaccountid() { const construction = new Construction(); const equipment = construction.getmyequipmentbyid.call(this, this.props.match.params.equipmentid) let accountid = ""; if (equipment) { if (equipment.accountid) { accountid = equipment.accountid } } return accountid } handleaccountid(accountid) { const construction = new Construction(); let myuser = construction.getuser.call(this); if (myuser) { if (this.props.match.params.equipmentid) { const myequipment = construction.getmyequipmentbyid.call(this, this.props.match.params.equipmentid) if (myequipment) { let i = construction.getequipmentkeybyid.call(this, this.props.match.params.equipmentid) myuser.company.equipment[i].accountid = accountid; this.props.reduxUser(myuser) this.setState({ render: 'render' }) } } } } getequipment() { const construction = new Construction(); return construction.getmyequipmentbyid.call(this, this.props.match.params.equipmentid) } makeequipmentcostactive(costid) { const construction = new Construction(); const equipment = this.getequipment() if (equipment) { if (this.state.activecostid === costid) { this.setState({ activecostid: false }) this.equipmentdatedefault() } else { const cost = construction.getcostbyid.call(this, equipment.equipmentid, costid) if (cost) { const equipmentdateyear = cost.timein.substring(0, 4) const equipmentdatemonth = cost.timein.substring(5, 7); const equipmentdateday = cost.timein.substring(8, 10); this.setState({ activecostid: costid, equipmentdateday, equipmentdatemonth, equipmentdateyear }) } } } } getloaninterest(equipment) { if (equipment.hasOwnProperty("ownership")) { return equipment.ownership.loaninterest } } getresalevalue(equipment) { if (equipment.hasOwnProperty("ownership")) { return equipment.ownership.resalevalue; } } getworkinghours(equipment) { if (equipment.hasOwnProperty("ownership")) { return equipment.ownership.workinghours; } } equipmentdetail(equipment) { const styles = MyStylesheet(); const construction = new Construction(); const bidField = construction.getbidfield.call(this); const purchasedate = new PurchaseDate(); const saledate = new SaleDate(); const regularFont = construction.getRegularFont.call(this); const headerFont = construction.getHeaderFont.call(this) const getsaledate = () => { if (this.state.width > 1200) { return ( <div style={{ ...styles.generalFlex, ...styles.bottomMargin15 }}> <div style={{ ...styles.flex2 }}> {saledate.showsaledate.call(this)} </div> <div style={{ ...styles.flex1 }}> <span style={{ ...regularFont, ...styles.generalFont }}> Resale Value </span> <br /> <input type="text" style={{ ...styles.generalFont, ...regularFont, ...bidField }} value={this.getresalevalue(equipment)} onChange={event => { this.handleresalevalue(event.target.value) }} /> </div> </div>) } else { return ( <div style={{ ...styles.generalContainer, ...styles.bottomMargin15 }}> <div style={{ ...styles.generalContainer }}> {saledate.showsaledate.call(this)} </div> <div style={{ ...styles.generalContainer }}> <span style={{ ...regularFont, ...styles.generalFont }}> Resale Value </span> <br /> <input type="text" style={{ ...styles.generalFont, ...regularFont, ...bidField }} value={this.getresalevalue(equipment)} onChange={event => { this.handleresalevalue(event.target.value) }} /> </div> </div>) } } const getpurchasedate = () => { if (this.state.width > 1200) { return (<div style={{ ...styles.generalFlex, ...styles.bottomMargin15 }}> <div style={{ ...styles.flex2 }}> {purchasedate.showpurchasedate.call(this)} </div> <div style={{ ...styles.flex1 }}> <span style={{ ...regularFont, ...styles.generalFont }}> Purchase Value</span> <br /> <input type="text" style={{ ...styles.generalFont, ...regularFont, ...bidField }} value={this.getpurchasevalue(equipment)} onChange={event => { this.handlepurchasevalue(event.target.value) }} /> </div> </div>) } else { return ( <div style={{ ...styles.generalContainer, ...styles.bottomMargin15 }}> <div style={{ ...styles.generalContainer }}> {purchasedate.showpurchasedate.call(this)} </div> <div style={{ ...styles.generalContainer }}> <span style={{ ...regularFont, ...styles.generalFont }}> Purchase Value</span> <br /> <input type="text" style={{ ...styles.generalFont, ...regularFont, ...bidField }} value={this.getpurchasevalue(equipment)} onChange={event => { this.handlepurchasevalue(event.target.value) }} /> </div> </div>) } } if (equipment.hasOwnProperty("ownership")) { return (<div style={{ ...styles.generalFlex, ...regularFont, ...styles.generalFont, ...styles.bottomMargin15 }}> <div style={{ ...styles.flex1 }}> <div style={{ ...styles.generalContainer, ...styles.bottomMargin15 }}> <span style={{ ...styles.generalFont, ...headerFont, ...styles.boldFont }}>Ownership</span> </div> {getpurchasedate()} {getsaledate()} <div style={{ ...styles.generalFlex }}> <div style={{ ...styles.flex1 }}> <span style={{ ...regularFont, ...styles.generalFont }}> Estimated Annual Working Hours </span> <input type="text" style={{ ...styles.generalFont, ...regularFont }} value={this.getworkinghours(equipment)} onChange={event => { this.handleworkinghours(event.target.value) }} /> </div> <div style={{ ...styles.flex1 }}> <span style={{ ...regularFont, ...styles.generalFont }}> Loan Interest </span> <br /> <input type="text" style={{ ...styles.generalFont, ...regularFont, ...bidField }} value={this.getloaninterest(equipment)} onChange={event => { this.handleloaninterest(event.target.value) }} /> </div> </div> </div> </div>) } } handlepurchasevalue(purchasevalue) { const construction = new Construction(); let myuser = construction.getuser.call(this); if (myuser) { const myequipment = construction.getmyequipmentbyid.call(this, this.props.match.params.equipmentid); if (myequipment) { console.log(myequipment) const i = construction.getequipmentkeybyid.call(this, this.props.match.params.equipmentid) myuser.company.equipment[i].ownership.purchase = purchasevalue; this.props.reduxUser(myuser) this.setState({ render: 'render' }) } } } handleresalevalue(resalevalue) { const construction = new Construction(); let myuser = construction.getuser.call(this); if (myuser) { if (this.props.match.params.equipmentid) { const myequipment = construction.getmyequipmentbyid.call(this, this.props.match.params.equipmentid); if (myequipment) { const i = construction.getequipmentkeybyid.call(this, this.props.match.params.equipmentid) myuser.company.equipment[i].ownership.resalevalue = resalevalue; this.props.reduxUser(myuser) this.setState({ render: 'render' }) } } } } createOwnership() { let workinghours = 0; let purchasedate = `${this.state.purchasedateyear}-${this.state.purchasedatemonth}-${this.state.purchasedateday}` let saledate = `${this.state.saledateyear}-${this.state.saledatemonth}-${this.state.saledateday}` let loaninterest = 0; let resalevalue = 0; let ownership = EquipmentOwnership(workinghours, purchasedate, saledate, loaninterest, resalevalue) return ownership; } handleownership(type, add) { const construction = new Construction(); const myuser = construction.getuser.call(this) if (myuser) { const equipment = construction.getmyequipmentbyid.call(this, this.props.match.params.equipmentid) if (equipment) { const i = construction.getequipmentkeybyid.call(this, this.props.match.params.equipmentid) if (type === 'owned') { if (add) { if (!equipment.hasOwnProperty("ownership")) { myuser.company.equipment[i].ownership = this.createOwnership() } if (equipment.hasOwnProperty("rented")) { delete myuser.company.equipment[i].rented } } } else if (type === 'rented') { if (add) { if (equipment.hasOwnProperty("ownership")) { myuser.company.equipment[i].rented = true; } } else { if (equipment.hasOwnProperty("rented")) { delete myuser.company.equipment[i].rented } } } } } this.props.reduxUser(myuser) this.setState({ render: 'render' }) } setDefaultState(equipment) { if (equipment.hasOwnProperty("ownership")) { const purchasedateyear = equipment.ownership.purchasedate.substring(0, 4) const purchasedatemonth = equipment.ownership.purchasedate.substring(5, 7); const purchasedateday = equipment.ownership.purchasedate.substring(8, 10); const saledateyear = equipment.ownership.saledate.substring(0, 4) const saledatemonth = equipment.ownership.saledate.substring(5, 7); const saledateday = equipment.ownership.saledate.substring(8, 10); this.setState({ purchasedateyear, purchasedatemonth, purchasedateday, saledateyear, saledatemonth, saledateday }) } } setDefault() { let defaults = true; if (!this.state.purchasedateyear && !this.state.purchasedatemonth && !this.state.purchasedateday && !this.state.saledateyear && !this.state.saledatemonth && !this.state.saledateday) { defaults = false; } return defaults } getdetail(equipment) { const construction = new Construction(); let detail = ""; if (this.state.activecostid) { const cost = construction.getcostbyid.call(this, equipment.equipmentid, this.state.activecostid) if (cost) { detail = cost.detail; } } return detail; } getcost(equipment) { const construction = new Construction(); let getcost = ""; if (this.state.activecostid) { const cost = construction.getcostbyid.call(this, equipment.equipmentid, this.state.activecostid) if (cost) { getcost = cost.cost; } } return getcost; } handleFrequency(amount) { const construction = new Construction(); const myuser = construction.getuser.call(this) if (myuser) { const equipment = this.getequipment() if (equipment) { const i = construction.getequipmentkeybyid.call(this, equipment.equipmentid) if (this.state.activecostid) { const cost = construction.getcostbyid.call(this, equipment.equipmentid, this.state.activecostid) if (cost) { if (cost.hasOwnProperty("reoccurring")) { const j = construction.getequipmentcostskeybyid.call(this, equipment.equipmentid, this.state.activecostid) myuser.company.equipment[i].ownership.cost[j].reoccurring.frequency = amount; this.props.reduxUser(myuser) this.setState({ render: 'render' }) } } } } } } getfrequency() { const construction = new Construction(); const equipment = this.getequipment() if (equipment) { if (this.state.activecostid) { const cost = construction.getcostbyid.call(this, equipment.equipmentid, this.state.activecostid) if (cost.hasOwnProperty("reoccurring")) { return cost.reoccurring.frequency; } } } } handlereoccurring() { const construction = new Construction(); const myuser = construction.getuser.call(this) if (myuser) { const equipment = this.getequipment() if (equipment) { const i = construction.getequipmentkeybyid.call(this, equipment.equipmentid) if (this.state.activecostid) { const cost = construction.getcostbyid.call(this, equipment.equipmentid, this.state.activecostid) if (cost) { const j = construction.getequipmentcostskeybyid.call(this, equipment.equipmentid, this.state.activecostid) if (cost.hasOwnProperty("reoccurring")) { delete myuser.company.equipment[i].ownership.cost[j].reoccurring } else { myuser.company.equipment[i].ownership.cost[j].reoccurring = { frequency: '' } } this.props.reduxUser(myuser) this.setState({ render: 'render' }) } } } } } makematerialactive(materialid) { if (this.state.activematerialid === materialid) { this.setState({ activematerialid: false }) } else { this.setState({ activematerialid: materialid }) } } validatematerial(material) { const construction = new Construction(); const myprojects = construction.getmyprojects.call(this); let validate = true; let validatemessage = ""; const materialid = material.materialid; if (myprojects.hasOwnProperty("length")) { // eslint-disable-next-line myprojects.map(myproject => { if (myproject.hasOwnProperty("schedulematerials")) { // eslint-disable-next-line myproject.schedulematerials.mymaterial.map(mymaterial => { if (mymaterial.mymaterialid === materialid) { validate = false; validatemessage += `Could not delete material ${material.material}, exists inside schedule materials Project ID ${myproject.projectid}` } }) } if (myproject.hasOwnProperty("actualmaterials")) { // eslint-disable-next-line myproject.actualmaterials.mymaterial.map(mymaterial => { if (mymaterial.mymaterialid === materialid) { validate = false; validatemessage += `Could not delete material ${material.material}, exists inside actual materials Project ID ${myproject.projectid}` } }) } }) } return { validate, validatemessage } } removematerial(material) { const construction = new Construction(); if (window.confirm(`Are you sure you want to delete ${material.material}?`)) { const validate = this.validatematerial(material); if (validate.validate) { let myuser = construction.getuser.call(this); const mymaterial = construction.getmymaterialfromid.call(this,material.materialid) if(mymaterial) { const i = construction.getmaterialkeybyid.call(this, material.materialid); myuser.company.materials.mymaterial.splice(i, 1); this.props.reduxUser(myuser); this.setState({ activematerialid: false, message: '' }) } } else { this.setState({ message: validate.validatemessage }) } } } showmymaterial(mymaterial) { const styles = MyStylesheet(); const regularFont = this.getRegularFont(); const removeIcon = this.getremoveicon(); let account = ""; let csi = ""; if (mymaterial.accountid) { let myaccount = this.getaccountbyid(mymaterial.accountid) account = ` ${myaccount.accountname}` } if (mymaterial.csiid) { let csiid = mymaterial.csiid; let mycsi = this.getcsibyid(csiid); csi = `${mycsi.csi} - ${mycsi.title}` } return (<div style={{ ...styles.generalFlex, ...this.getactivematerialbackground(mymaterial.materialid) }} key={mymaterial.materialid}> <div style={{ ...styles.flex1, ...styles.generalFont, ...regularFont }}> <span onClick={() => { this.makematerialactive(mymaterial.materialid) }}>{mymaterial.material} {mymaterial.unitcost}/{mymaterial.unit} Account:{account} Construction:{csi}</span> <button style={{ ...styles.generalButton, ...removeIcon }} onClick={() => { this.removematerial(mymaterial) }}>{removeIconSmall()} </button> </div> </div>) } getactivematerialbackground(materialid) { if (this.state.activematerialid === materialid) { return ({ backgroundColor: '#F2C4D2' }) } else { return; } } render() { const accountid = new AccountID(); const construction = new Construction(); const myuser = construction.getuser.call(this) const regularFont = construction.getRegularFont.call(this) const headerFont = construction.getHeaderFont.call(this) const styles = MyStylesheet(); const buttonWidth = () => { if (this.state.width > 1200) { return ({ width: '90px' }) } else if (this.state.width > 600) { return ({ width: '60px' }) } else { return ({ width: '45px' }) } } if (myuser) { if (myuser.hasOwnProperty("company")) { const equipmentid = this.props.match.params.equipmentid; const equipment = construction.getmyequipmentbyid.call(this, equipmentid) if (equipment) { const ownershipbox = (equipment) => { if (equipment.hasOwnProperty("ownership") && !equipment.rented) { return ( <div style={{ ...styles.generalContainer }}> <button style={{ ...styles.generalButton, ...buttonWidth() }} onClick={() => { this.handleownership('owned', false) }}>{radioClosed()}</button> </div> ) } else { return ( <div style={{ ...styles.generalContainer }}> <button style={{ ...styles.generalButton, ...buttonWidth() }} onClick={() => { this.handleownership('owned', true) }}>{radioOpen()}</button> </div> ) } } const rentedbox = (equipment) => { if (equipment.hasOwnProperty("rented")) { if (equipment.rented) { return ( <div style={{ ...styles.generalContainer }}> <button style={{ ...styles.generalButton, ...buttonWidth() }} onClick={() => { this.handleownership('rented', false) }}>{radioClosed()}</button> </div> ) } else { return ( <div style={{ ...styles.generalContainer }}> <button style={{ ...styles.generalButton, ...buttonWidth() }} onClick={() => { this.handleownership('rented', true) }}>{radioOpen()}</button> </div> ) } } else { return ( <div style={{ ...styles.generalContainer }}> <button style={{ ...styles.generalButton, ...buttonWidth() }} onClick={() => { this.handleownership('rented', true) }}>{radioOpen()}</button> </div> ) } } if (equipment.hasOwnProperty("ownership") && !this.setDefault()) { this.setDefaultState(equipment) } const equipmentrate =(equipment) => { if(equipment.hasOwnProperty("ownership")) { let equipmentrate = construction.calculateequipmentratebyownership.call(this, equipment.equipmentid) if(equipmentrate) { return(<div style={{...styles.generalContainer, ...styles.alignCenter, ...styles.bottomMargin15}}> <span style={{...styles.generalFont,...regularFont}}>Equipment Rate is ${Number(equipmentrate).toFixed(2)}/hr</span> </div>) } } } return ( <div style={{ ...styles.generalContainer }}> <div style={{ ...styles.generalContainer, ...styles.alignCenter, ...styles.bottomMargin15 }}> <Link to={`/${myuser.profile}/company/${myuser.company.url}/equipment/${equipment.equipmentid}`} style={{ ...styles.generalLink, ...styles.generalFont, ...headerFont, ...styles.boldFont }}>/{equipment.equipment}</Link> </div> <div style={{ ...styles.generalFlex, ...styles.bottomMargin15 }}> <div style={{ ...styles.flex1 }}> <span style={{ ...regularFont, ...styles.generalFont }}>Owned</span> {ownershipbox(equipment)} </div> <div style={{ ...styles.flex1 }}> <span style={{ ...regularFont, ...styles.generalFont }}>Rented</span> {rentedbox(equipment)} </div> </div> {accountid.showaccountmenu.call(this)} {this.equipmentdetail(equipment)} {this.showaccountcost(equipment)} {equipmentrate(equipment)} {construction.showsavecompany.call(this)} </div> ) } else { return (<div style={{ ...styles.generalContainer, ...regularFont }}> <span style={{ ...styles.generalFont, ...regularFont }}>Equipment Not Found</span> </div>) } } else { return (<div style={{ ...styles.generalContainer, ...regularFont }}> <span style={{ ...styles.generalFont, ...regularFont }}>You need a company to view equipment</span> </div>) } } else { return (<div style={{ ...styles.generalContainer, ...regularFont }}> <span style={{ ...styles.generalFont, ...regularFont }}>Please Login to View Equipment </span> </div>) } } } function mapStateToProps(state) { return { myusermodel: state.myusermodel, navigation: state.navigation, project: state.project, allusers: state.allusers, allcompanys: state.allcompanys, csis: state.csis } } export default connect(mapStateToProps, actions)(ViewEquipment);
var dataList = [{ "bankNumber": "123456", "bankName": "交通银行", "bankCount": "18000", "bankStartDate": [0, 2], "bankEndDate": [0, 27], "differ": 48 }, { "bankNumber": "58585", "bankName": "民生银行", "bankCount": "50000", "bankStartDate": [0, 15], "bankEndDate": [1, 4], "differ": 51 }];
$(function() { var search_list = $(".text"); function appendProgramminglog (prolog) { var html = `<div class="textonly"> <div class="text__left"> <div class="text__image" style="background-image: url(${prolog.image});"></div> </div> <div class="text__right"> <div class="text__title"> <a href = "/programminglogs/${prolog.id}" data-method="get" class: "content__right__top--title">${prolog.title}</a> </div> <div class="text__bottom"> <div class="text__time"> ${prolog.created_at} </div> <div class="user__name"> <img src=${prolog.user_image} class = "icon_image"> <div class="content__right__bottom--username"> <a href = "/users/${prolog.id}" data-method="get" class: "content__right__bottom--userName--btn">${prolog.name}</a> </div> </div> <span style="background-color: #EEEEEE; color: #666666; border-radius: 5px; padding: 5px">${prolog.tags.name}</span> <div class="good"> <i class="fas fa-heart"></i> ${prolog.likes} </div> </div> </div> </div>` search_list.append(html); } function appendErrMsgToHTML(msg) { var html = `<div class="content__right__bottom--username">${ msg }</div>` search_list.append(html); } $(".search-input").on("keyup", function() { var input = $(".search-input").val(); $.ajax({ type: 'GET', url: '/programminglogs/search', data: { keyword: input }, dataType: 'json' }) .done(function(prologs) { search_list.empty(); if (prologs.length !== 0) { prologs.forEach(function(prolog){ appendProgramminglog(prolog); }); } else { appendErrMsgToHTML("一致する投稿がありません"); } }) .fail(function() { alert('error'); }); }); });
import styled from 'styled-components'; const StarInfoWrapper = styled.div` height: 20px; font-family: "Helvetica Neue"; font-size: 14px; line-height: 1.43; color: #484848; `; export default StarInfoWrapper
export const options = { role: "searchbox", selectorsWithImplicitRole: ["input[type='search']:not([list])"] };
var gulp = require('gulp'), combineCSS = require('combine-css'), sass = require('gulp-sass'), minifyCSS = require('gulp-minify-css'), concat = require('gulp-concat'); var paths = { css: 'assets/js/**/*', images: 'assets/images/**/*' }; /* Convert scss to css */ gulp.task('sass', function () { gulp.src('./assets/scss/*.scss') .pipe(sass()) .pipe(gulp.dest('./assets/css')); }); /* combine css files */ gulp.task('combine', function() { gulp.src('./assets/css/*.css') .pipe(combineCSS({ lengthLimit: 256,//2KB prefix: 'combined-', selectorLimit: 4080 })) .pipe(gulp.dest('./assets/combinedCSS')); }); /* concat css files */ gulp.task('concat-css', function() { gulp.src(['./assets/css/bitsy_main.css', './assets/css/bitsy_form.css']) .pipe(concat('bitsy.css')) .pipe(gulp.dest('./assets/tmp')) }); /* minimize css */ gulp.task('minify-css', function() { gulp.src('./assets/tmp/bitsy.css') .pipe(minifyCSS({keepBreaks:true})) .pipe(gulp.dest('./public/css/')) }); gulp.task('default', [ 'sass', 'concat-css', 'minify-css' ]);
$(function() { // enable star ratings for review#new and review#edit $('#rateyo').rateYo({ numStars: 10, maxValue: 10, rating: $('#review_rating').val(), fullStar: true, onSet: function(rating, rateYoInstance) { $('#review_rating').val(rating); } }); });
(function () { "use strict" angular.module('starter.services', []) function Categories($http) { return { all: function () { return $http.get("http://roscontrol.rocket-web.ru/") }, get: function (categoryId) { return $http.get("http://roscontrol.rocket-web.ru/category/" + categoryId) }, getProducts: function (categoryId) { return $http.get("http://roscontrol.rocket-web.ru/category/products/" + categoryId) }, getProduct: function (productId) { return $http.get("http://roscontrol.rocket-web.ru/product/" + productId) } } } Categories.$inject = ['$http']; angular .module('starter.services') .service('Categories', Categories); })()
// Auth0Manager.js const axios = require("axios") const ManagementClient = require("auth0").ManagementClient /** * * How this works: * 1. Requests an access token using client_id and client_secret * 2. Uses the access token to create a new ManagementClient * 3. Use the ManagementClient to interact with the API: https://auth0.github.io/node-auth0/module-management.ManagementClient.html * */ module.exports = (function() { let managementClient return { init, getClient, updateClient, } /** * Create a management client */ function init() { return getToken() .then(data => data.access_token) .then(token => { const managementClient = new ManagementClient({ domain: `${process.env.GATSBY_AUTH0_DOMAIN}`, token, audience: `https://${process.env.GATSBY_AUTH0_DOMAIN}/api/v2/`, }) // set it so we can use it in our other methods this.managementClient = managementClient return true }) .catch(err => err) } /** * Get an access token from the Auth0 API * We will use this access token to connect to the management API * To get a token, we need to provide client_id and client_secret * Both of these can be found in the APIs section of Auth0 dashboard */ function getToken() { // get the info we need const clientId = process.env.GATSBY_AUTH0_MANAGE_CLIENT_ID const clientSecret = process.env.GATSBY_AUTH0_MANAGE_SECRET const url = `https://${process.env.GATSBY_AUTH0_DOMAIN}/oauth/token` // make the call to the API via POST return axios .post(url, { client_id: clientId, client_secret: clientSecret, grant_type: "client_credentials", audience: `https://${process.env.GATSBY_AUTH0_DOMAIN}/api/v2/`, }) .then(res => res.data) .catch(err => err) } /** * Make a call to the Management API to get all the data for a certain client * All the things that are available in the dashboard can be accessed here * @param string clientId */ function getClient(clientId = null) { if (!clientId) { clientId = process.env.GATSBY_AUTH0_MANAGE_CLIENT_ID } return this.managementClient .getClient({ client_id: clientId }) .then(client => client) .catch(err => err) } /** * Take data and update the Auth0Client * This can be used to update the entire client via API instead of in the dashboard * Very helpful if moving settings from local to a production environment * * @param {Object} data The data that will overwrite anything in our dashboard * @param {String} clientId The client that we want to update */ function updateClient(data, clientId = null) { if (!clientId) clientId = process.env.GATSBY_AUTH0_MANAGE_CLIENT_ID return this.managementClient .updateClient({ client_id: clientId }, data) .then(client => client) .catch(err => err) } })()
import * as posts from './posts'; export { posts };
import React from 'react'; import ReactDOM from 'react-dom'; import dragula from 'react-dragula'; import NotificationSystem from 'react-notification-system'; import { Router, Route, Link, hashHistory } from 'react-router'; import Api from '../../services/Api'; var levels = { /* min and max levels for menu items */ min: 0, max: 2 } class Menu extends React.Component { constructor(props) { super(props); this.state = { pages: [], newPageValue: '', pageHover: false, hoveredPage: '' }; } componentDidMount = () => { var draggable = ReactDOM.findDOMNode(this.refs.dragulable); /* makes the blocks draggable by using "handle" class elements in block's jsx */ var drake = dragula([draggable], { moves: function (el, draggable, handle) { return handle.className === 'handle'; } }); this.setState({ pages: this.props.pages }); this.moveItems(drake, this.props.pages); this._notificationSystem = this.refs.notificationSystem; } componentWillReceiveProps = (nextProps) => { this.setState({ pages: nextProps.pages }); } handleChange = (event) => { this.setState({ newPageValue: event.target.value }); } createPage = (event) => { var self = this; Api .post('/pages', {name: this.state.newPageValue, container_id: this.props.container.id, sequence: this.state.pages.length}) .then(function (item) { self.setState({ pages: self.state.pages.concat(item), newPageValue: '' }); self.props.addPage(item); }) .catch(function () { self.setState({ error: 'There was a problem creating a new container' }); }); event.target.value = ''; } deletePage = (page) => { var self = this; this._notificationSystem.addNotification({ title: 'Confirmer la suppression', message: 'Voulez-vous supprimer la page ' + page.name + ' ?', level: 'success', position: 'tc', timeout: '10000', action: { label: 'Oui', callback: function() { Api .del('/pages/' + page.id) .then(function() { self.setState({ pages: self.state.pages.filter((i, _) => i['id'] !== page.id) }); }) .catch(function () { self.setState({ error: 'There was a problem deleting a new container' }); }); if (parseInt(self.props.activePage) == page.id) { window.location = "/#/containers/" + self.props.container.id + "/" + self.props.pages[0].id; } } } }); } moveItems(drake, pages) { drake.on('drag', function(element, source) { var index = [].indexOf.call(element.parentNode.children, element); }); var self = this; drake.on('drop', function(element, target, source, sibling) { var index = [].indexOf.call(element.parentNode.children, element) var updated_sequence = []; $(source).children().each(function(i) { updated_sequence.push({ id: $(this).data('id'), sequence: i, container_id: self.props.container.id }); }); self.props.dragAction(updated_sequence); }); } _handleKeyPress = (event) => { if (event.key === 'Enter') this.createPage(event); } handleLevelClick(page, way, event) { /* changes the level of a page in the menu */ var newLevel = page.level; if (way == "add") newLevel += 1; if (way == "remove") newLevel -= 1; this.props.levelizePage(page.id, newLevel); } activeHover = (page) => { this.setState({ pageHover: true, hoveredPage: page.id }); } hoverFalse = () => { this.setState({ pageHover: false}); } render() { var self = this; return ( <div className="sidebar menu" role="navigation"> <NotificationSystem ref="notificationSystem" /> <h2 className="zone-header"><i className="fa fa-bars"></i> Menu</h2> <ul className="side-menu" ref="dragulable"> { this.state.pages.map((page, i) => { return ( <li key={page.id} data-pos={i} data-id={page.id} className={page.id == this.props.activePage ? "level-"+page.level+" active" : "level-"+page.level} > <div className="handle" title="Déplacer la page"></div> <div className="menu-content"> <Link className="page-link-menu" to={"/containers/"+self.props.container.id+"/"+page.id}> {page.name} </Link> <div className="option-page"> { page.level > levels.min ? <button onClick={self.handleLevelClick.bind(self, page, "remove")} title="Retirer un niveau"> <i className="fa fa-chevron-left fa-fw"></i> </button> : null } { (page.level <= levels.max) && (page != this.props.pages[0]) ? <button onClick={self.handleLevelClick.bind(self, page, "add")} title="Ajouter un niveau"> <i className="fa fa-chevron-right fa-fw"></i> </button> : null } <button className="page-delete" onClick={this.deletePage.bind(self, page)} title="Supprimer la page"> <span className="fa-stack fa-lg"> <i className="fa fa-trash-o fa-stack-1x"></i> <i className="fa fa-ban fa-stack-2x"></i> </span> </button> </div> </div> </li> ); })} </ul> <div id="add_new_page" className="input-group"> <span className="input-group-addon" onClick={this.createPage}> <i className="fa fa-plus fa-fw"></i> </span> <input type="text" id="new_page" className="form-control " value={this.state.newPageValue} onChange={this.handleChange} onKeyPress={this._handleKeyPress} autoComplete="off" placeholder="Ajouter une page..." /> </div> { this.state.newPageValue ? <button onClick={this.createPage} className="btn-success"><i className="fa fa-check"></i></button> : null } </div> ); } } export default Menu;
import React from "react"; import Header from "../components/Home/Header"; import MainContainer from "../components/Home/MainContainer"; import styles from "../styles/home.module.css"; const Home = () => { return ( <> <Header /> <MainContainer /> </> ); }; export default Home;
import { CosmeticsStoreServiceProvider, CosmeticsStoreServiceConsumer } from './component'; export { CosmeticsStoreServiceProvider, CosmeticsStoreServiceConsumer }; //export { default } from './component';
module.exports = "mongodb://username:pass@host:27017/dbname"
let inventory = []; function inventoryAddItem(item = []) { for (let i = 0; i <= item.length - 1; i -= -1) { inventory[i] = item[i]; } return inventory; } function makeAvailable(element) { document.getElementById("invBttn").style.color = "green"; } function makeUnavailable(element) { document.getElementById("invBttn").style.color = "white"; } /*document.addEventListener("keydown", function (event) { if (event.keycode === 9) { if (document.getElementById("inventorySpace").style.display === "block") { document.getElementById("inventorySpace").style.display = "none"; } else { document.getElementById("inventorySpace").style.display = "block"; } console.log("Ahoj"); } }) */
$(function(){ $('#pageToolbar').Paging({pagesize:10,count:4,current:1,toolbar:true}); }); //tabs切换 $(".tabBtns li").click(function(){ $(this).find("a").addClass('active').parent().siblings().find("a").removeClass('active'); $(".list_tabs:visible").hide(); var index = $(".tabBtns li").index($(this)); $(".list_tabs:eq("+index+")").show(); });
export function HorizontalField({ label, children }) { return ( <div className="field is-horizontal"> <div className="field-label is-normal"> <label className="label">{label}</label> </div> <div className="field-body">{children}</div> </div> ); }
var React = require('react'); var ReactDOM = require('react-dom'); var UserList = require('./working/UserList'); var ChatWebAPIUtils = require('./utils/ChatWebAPIUtils'); ChatWebAPIUtils.getAllUsers(); ReactDOM.render( <UserList/>, document.getElementById('react') );
//acquiring the express library const express = require("express"); //acquiring the functionality of express.Router const router = express.Router(); //acquiring the controller const homeController = require("../controllers/home_controller"); console.log("index Router is called"); router.use("/user", require("./user")); router.use("/posts", require("./post")); router.use("/comments", require("./comments")); router.use('/likes',require('./likes')); router.get("/", homeController.home); //telling the router about the api router.use('/api',require('./api')); //exporting the current module module.exports = router;
import React from 'react'; import { mount } from 'enzyme'; import PageLoader from '.'; describe('PageLoader', () => { const wrapper = mount(<PageLoader/>); it('should render the page loader class to provide the basic styling', () => { expect(wrapper.find('.page-loader')).toHaveLength(1); }) it('should render loading indicator text within the component', () => { expect(wrapper.find('h3').text()).toEqual('Finding the best results for you...'); }) });
/** * Exports ParseJS */ if(typeof module !== "undefined" && module.exports) { module.exports = Parse; } if(typeof define === 'function' && define.amd) { define("parse", [], function() { return Parse; }); } global.parse = Parse; }(typeof window !== "undefined" ? window : this));
import firebase from 'firebase/app'; import 'firebase/auth'; import 'firebase/database'; // Your web app's Firebase configuration // For Firebase JS SDK v7.20.0 and later, measurementId is optional const firebaseConfig = { apiKey: "AIzaSyDdEwHfjLCPaGBq8M_MfjYSYpwl_NkTGSg", authDomain: "tts-chat-app-39d7a.firebaseapp.com", databaseURL: "https://tts-chat-app-39d7a-default-rtdb.firebaseio.com", projectId: "tts-chat-app-39d7a", storageBucket: "tts-chat-app-39d7a.appspot.com", messagingSenderId: "386373851201", appId: "1:386373851201:web:dce701bba2a7f880934ec0", measurementId: "G-H4Q1DX6PJE" }; // Initialize Firebase firebase.initializeApp(firebaseConfig); // firebase.analytics(); // exports export const auth = firebase.auth; export const db = firebase.database();
 guidedModel =// @startlock { Rel_Quality_Group : { methods : {// @endlock Load_Choice_Arrays_for_Quality:function(Quality_ID) {// @lock var Rel_Quality_Group_Coll = ds.Rel_Quality_Group.query('Quality.ID = :1',Quality_ID); var resultArrays = Rel_Quality_Group_Coll.toArray('ID,TireGroup.Name,Size_List','TireGroup.Name'); // promote related arrays to base level for (var i = 0, len = resultArrays.length; i < len; i++) { resultArrays[i].Name = []; resultArrays[i].Name = resultArrays[i].TireGroup.Name; delete resultArrays[i].TireGroup; }; // end for return resultArrays; }// @startlock } }, TireGroup : { events : { onSave:function() {// @endlock include ('scripts/Rel_Quality_Group.js'); Rel_Quality_Group_Entities_List_Make_for_TireGroup (this); // make tire sizes entities for TireGroup entity },// @startlock onRemove:function() {// @endlock this.Rel_Quality_GroupCollection.remove(); }// @startlock } }, TireRange : { Name : { onGet:function() {// @endlock include ('scripts/TireRange_Functions.js'); return TireRange_Name_OnGet(this); }// @startlock } }, Quality : { events : { onSave:function() {// @endlock include ('scripts/Rel_Quality_Group.js'); Rel_Quality_Group_Entities_Make_for_Quality (this); // make tire sizes entities for Quality entity },// @startlock onRemove:function() {// @endlock this.Rel_Quality_Group_Collection.remove(); }// @startlock }, methods : {// @endlock Load_Choice_Arrays:function() {// @lock return ds.Quality.all().toArray('ID,Name,Default_Quality','Name'); }// @startlock } }, Rel_Inquiry_Tire : { Percentage_Calculation : { onGet:function() {// @endlock var result = null; if (this.Selected) { // Selected by User result = this.Percentage_Frequency; if ((this.Percentage_Limit > 0 && this.Percentage_Limit <= this.Percentage_Frequency)) result = this.Percentage_Limit; }; // end if Selected by User return result; }// @startlock }, methods : {// @endlock TireInquiry_Save_Arrays:function(attributeArrays) {// @lock // delete calculated and read-only attributes for (var i = 0, len = attributeArrays.length; i < len; i++) { var Rel_Inquiry_Tire_Entity = ds.Rel_Inquiry_Tire.find('ID = :1',attributeArrays[i].ID); if (Rel_Inquiry_Tire_Entity) { // entity defined Rel_Inquiry_Tire_Entity.Selected = attributeArrays[i].Selected; Rel_Inquiry_Tire_Entity.Percentage_Limit = attributeArrays[i].Percentage_Limit; Rel_Inquiry_Tire_Entity.save(); }; // end if entity defined }; // end for },// @lock Built_Collection_TireInquiry:function(TireInquiry_ID,return_Arrays_Flag) {// @lock var OK_Flag = !!TireInquiry_ID; if (OK_Flag) { include ('scripts/Rel_Inquiry_Tire_Functions.js'); Rel_Inq_Tire_Create_Entities(TireInquiry_ID); // create related entities TireInquiry - Tire var result = ds.Rel_Inquiry_Tire.query('TireInquiry.ID = :1',TireInquiry_ID); if (!return_Arrays_Flag) { // version return entities return result; } // end if version return entities else { // version return arrays //var resultArrays = result.toArray('ID,Tire.Diameter_mm,Tire.Displaystring,Tire.Frequency.Name,Tire.Inch,Selected,Percentage_Frequency,Percentage_Limit,Percentage_Calculation,Tire.Series','Tire.Inch,Tire.Width_mm,Tire.Series,Tire.Cargo_LT,Tire.Offroad_4x4'); var resultArrays = result.toArray('ID,Tire.Diameter_mm,Tire.Displaystring,Tire.Frequency.Name,Tire.Inch,Selected,Percentage_Frequency,Percentage_Limit,Percentage_Calculation,Tire.Width_mm,Tire.Series,Tire.Cargo_LT,Tire.Offroad_4x4'); // promote related arrays to base level for (var i = 0, len = resultArrays.length; i < len; i++) { resultArrays[i].Tire_Displaystring = []; resultArrays[i].Tire_Displaystring = resultArrays[i].Tire.Displaystring; resultArrays[i].Tire_Diameter_mm = []; resultArrays[i].Tire_Diameter_mm = resultArrays[i].Tire.Diameter_mm; resultArrays[i].Tire_Frequency_Name = []; resultArrays[i].Tire_Frequency_Name = resultArrays[i].Tire.Frequency.Name; resultArrays[i].Tire_Inch = []; resultArrays[i].Tire_Inch = resultArrays[i].Tire.Inch; resultArrays[i].Tire_Width_mm = []; resultArrays[i].Tire_Width_mm = resultArrays[i].Tire.Width_mm; resultArrays[i].Tire_Series = []; resultArrays[i].Tire_Series = resultArrays[i].Tire.Series; resultArrays[i].Tire_Cargo_LT = []; resultArrays[i].Tire_Cargo_LT = resultArrays[i].Tire.Cargo_LT; resultArrays[i].Tire_Offroad_4x4 = []; resultArrays[i].Tire_Offroad_4x4 = resultArrays[i].Tire.Offroad_4x4; delete resultArrays[i].Tire; }; // end for return resultArrays; }; // end else version return arrays }; // end if OK_Flag }// @startlock } }, TireInquiry : { Name : { events : { onValidate:function(attributeName) {// @endlock if (!this.Name) this.Name = 'Inquiry'; }// @startlock } }, Price_Unit_Displaystring : { onGet:function() {// @endlock var result = ''; var quality_Base_Price_Defined = false; if (this.Quality) quality_Base_Price_Defined = !!this.Quality.Base_Price; if (quality_Base_Price_Defined) { // Base price defined in Quality if (this.Choosen_Tires_Percentage >= 99.98) { result = (this.Quality.Base_Price * 0.9).toFixed(2) + ' 10% discounted'; } else { if ((this.Choosen_Tires_Percentage >= 80) && (this.Choosen_Tires_Percentage < 100)) { result = this.Quality.Base_Price.toFixed(2) + ' base price'; } else { var min_Perc_reached = true; if (this.Quality.Minimum_Percentage > 0) { // Minimum percentage defined in Quality min_Perc_reached = (this.Choosen_Tires_Percentage >= this.Quality.Minimum_Percentage); }; // end if Minimum percentage defined in Quality if (min_Perc_reached) { result = this.Quality.Base_Price / this.Choosen_Tires_Percentage; result = (result * 100).toFixed(2); } else { result = this.Quality.Minimum_Percentage + '% not reached'; }; }; }; } else { // no base price defined in Quality result = 'No price defined'; }; // end if Base price defined in Quality return result; }// @startlock }, Choosen_Displaystring : { onGet:function() {// @endlock var result = ''; var Tire_Coll = ds.Tire.query('rel_Inquiry_TireCollection.TireInquiry.ID = :1 & rel_Inquiry_TireCollection.Selected = :2 order by Inch asc Width asc Series asc Cargo_LT asc Offroad_4x4 asc',this.ID,true); for (var Tire_Entity = Tire_Coll.first(); Tire_Entity != null; Tire_Entity = Tire_Entity.next()) { if (result) result += ', '; result += Tire_Entity.Displaystring; }; // end for return result; }// @startlock }, Choosen_Tires_Percentage : { onGet:function() {// @endlock return this.rel_Inquiry_TireCollection.query('Selected = true').sum('Percentage_Calculation'); }// @startlock }, methods : {// @endlock Remove_Entity_ID:function(ID_to_remove) {// @lock var entity_to_remove = ds.TireInquiry.find('ID = :1',ID_to_remove); if (entity_to_remove) entity_to_remove.remove(); },// @lock Webuser_Related_Save:function(attributeArrays) {// @lock for (var i = 0, len = attributeArrays.length; i < len; i++) { var tireInq_Entity = ds.TireInquiry.find('ID = :1',attributeArrays[i].ID); if (!tireInq_Entity && attributeArrays[i].Name) { // ID does not exist and Name defined: create new entity var Session_Stored_Webuser_ID = sessionStorage.getItem("Webuser_Logged_In_ID"); tireInq_Entity = ds.TireInquiry.createEntity(); tireInq_Entity.Webuser = Session_Stored_Webuser_ID; }; // end if ID does not exist and Name defined: create new entity if (tireInq_Entity) { // entity defined tireInq_Entity.Name = attributeArrays[i].Name; tireInq_Entity.Quality = attributeArrays[i].Quality.ID; tireInq_Entity.Tire_Quantity = attributeArrays[i].Tire_Quantity; tireInq_Entity.Modified_by_User = attributeArrays[i].Modified_by_User; tireInq_Entity.save(); }; // end if entity defined }; // end for },// @lock Load_Webuser_Related:function(Webuser_ID) {// @lock // Find default Quality var default_Quality_Entity = ds.Quality.find('Default_Quality = :1',true); var tireInq_Coll = ds.TireInquiry.query('Webuser.ID = :1',Webuser_ID); if (tireInq_Coll.length == 0) { // No TireInquiry exists for Webuser tireInq_New_Entity = ds.TireInquiry.createEntity(); tireInq_New_Entity.Name = 'Inquiry 1'; tireInq_New_Entity.Tire_Quantity = 1000; tireInq_New_Entity.Webuser = Webuser_ID; tireInq_New_Entity.Quality = default_Quality_Entity; tireInq_New_Entity.Created_automatically = true; tireInq_New_Entity.save(); tireInq_Coll.add(tireInq_New_Entity); include ('scripts/Rel_Inquiry_Tire_Functions.js'); Rel_Inq_Tire_Create_Entities(tireInq_New_Entity.ID); // create related entities TireInquiry - Tire }; // end if // No TireInquiry exists for Webuser var resultArrays = tireInq_Coll.toArray('ID,Name,Tire_Quantity,Quality.ID,Quality.Name,Choosen_Tires_Percentage,Choosen_Displaystring,Price_Unit_Displaystring,Modified_by_User','Name','withKey'); // flaten Quality.ID and Quality.Name for use in jqx grid for (var i = 0, len = resultArrays.length; i < len; i++) { resultArrays[i].Quality_ID = []; resultArrays[i].Quality_Name = []; if (resultArrays[i].Quality) { // Quality defined resultArrays[i].Quality_ID = resultArrays[i].Quality.ID; resultArrays[i].Quality_Name = resultArrays[i].Quality.Name; } // end if Quality defined else { // Quality undefined resultArrays[i].Quality_ID = default_Quality_Entity.ID; resultArrays[i].Quality_Name = 'Quality undefined on server'; }; // end else Quality undefined }; // end for return resultArrays; }// @startlock }, events : { onRemove:function() {// @endlock this.rel_Inquiry_TireCollection.remove(); },// @startlock onValidate:function() {// @endlock if (!this.Webuser) { // No Webuser related var Session_Stored_Webuser_ID = sessionStorage.getItem("Webuser_Logged_In_ID"); this.Webuser = Session_Stored_Webuser_ID // relate current Webuser }; }// @startlock } }, Tire : { events : { onValidate:function() {// @endlock var ok_Flag = (this.Inch > 0 && this.Series > 0 && this.Width_mm > 0); if(!ok_Flag) return {error: 1, errorMessage: 'Tire specifications not complete.'}; if(ok_Flag) { var queryString = 'Width_mm = :1 & Series = :2 & Inch = :3 & Cargo_LT = :4 & Offroad_4x4 = :5'; var result = ds.Tire.find(queryString,this.Width_mm,this.Series,this.Inch,this.Cargo_LT,this.Offroad_4x4); if(result) { // an entity with this specifications already exists if(result.ID != this.ID) { // another entity with same specifications return {error: 2, errorMessage: 'A tire ' + this.Displaystring + ' already exists.'}; }; }; }; }// @startlock }, Displaystring : { onGet:function() {// @endlock var result = ''; if (this.Width_mm && this.Series && this.Inch) { var result = this.Width_mm + '/' + this.Series + '/' + this.Inch; if (this.Series == 80) { result += ' (' + this.Width_mm +'R' + this.Inch + ')'; }; if (this.Cargo_LT) { result += ' C'; }; if (this.Offroad_4x4) { result += ' OR'; }; }; return result; }// @startlock } }, Webuser : { events : { onInit:function() {// @endlock this.Tire_Selection_incl_C_Tires = true; this.Tire_Selection_incl_OR_Tires = true; }// @startlock }, entityMethods : {// @endlock Get_Webuser_TireInquiry_Coll:function() {// @lock if (this.tireInquiryCollection.length == 0) { // no TireInquiry still exists for Webuser // Create a a first default TireInquiry new_TireInquiry = ds.TireInquiry.createEntity(); new_TireInquiry.Name = 'First inquiry'; new_TireInquiry.Tire_Quantity = 1000; new_TireInquiry.Quality = 1; new_TireInquiry.Webuser = this; new_TireInquiry.save(); this.refresh(); }; return this.tireInquiryCollection; }// @startlock }, methods : {// @endlock Create_Temp_Webuser:function() {// @lock new_Webuser = ds.Webuser.createEntity(); new_Webuser.Temporary_User = true; new_Webuser.Name = 'Temporary user ' + new_Webuser.ID; new_Webuser.Email = 'Temporary user ' + new_Webuser.ID; new_Webuser.Password = 'Temporary user ' + new_Webuser.ID; new_Webuser.save(); ds.Webuser.Save_Current_Webuser_ID(new_Webuser.ID); // save Webuser ID in SessionStorage return new_Webuser; },// @lock Save_Current_Webuser_ID:function(login_Webuser_ID) {// @lock // Webuser: Save logged in Webuser in sessionStorage sessionStorage.setItem ("Webuser_Logged_In_ID",login_Webuser_ID); // save Webuser ID in SessionStorage },// @lock Register_New_Webuser:function(login_name,login_email,login_password) {// @lock // Register new Webuser // return of result object with entity and error text to client does not work var result = { // result object returned to client entity: null, // new added entity error_text: '' // error text if new Webuser could not be created }; var new_Webuser = null // new Webuser entity to return. Version with object and error text does not work var ok_Flag = true; ok_Flag = !!(login_name); if(!ok_Flag) { result.error_text = 'No name passed.'; }; if(ok_Flag) { var existing_Webuser = ds.Webuser.find('Name = :1',login_name); if(existing_Webuser) { ok_Flag = false; result.error_text = 'A User with name ' + login_name + ' already exists.'; }; }; if(ok_Flag) { ok_Flag = !!(login_email); if(!ok_Flag) { result.error_text = 'No email passed.'; }; }; if(ok_Flag) { var existing_Webuser = ds.Webuser.find('Email = :1',login_email); if(existing_Webuser) { ok_Flag = false; result.error_text = 'A User with email ' + login_email + ' already exists.'; }; }; if(ok_Flag) { ok_Flag = !!(login_password); if(!ok_Flag) { result.error_text = 'No password passed.'; }; }; if(ok_Flag) { // Create new Webuser new_Webuser = ds.Webuser.createEntity(); new_Webuser.Name = login_name; new_Webuser.Email = login_email; new_Webuser.Password = login_password; new_Webuser.save(); // Webuser dataclass functions generic to all projects include ('scripts/gWebuser_Functions.js'); Webuser_Logged_In_Take_Over_Temp_User(new_Webuser.ID); // Take over relations of prior temporary Webuser ds.Webuser.Save_Current_Webuser_ID(new_Webuser.ID); // save Webuser ID in SessionStorage return new_Webuser; } else { return result; }; },// @lock Logout:function() {// @lock // Logout current Webuser sessionStorage.removeItem ("Webuser_Logged_In_ID") ; // remove Webuser ID in SessionStorage },// @lock Login_Session_Restore_Webuser:function() {// @lock // Restore Webuser for current session var login_Webuser = null; // Webuser entity to return to client var Session_Stored_Webuser_ID = sessionStorage.getItem("Webuser_Logged_In_ID"); if(Session_Stored_Webuser_ID) {// Webuser stored login_Webuser = ds.Webuser.find('ID = :1',Session_Stored_Webuser_ID); }; return login_Webuser; },// @lock Login_Name_PW:function(login_name,login_password) {// @lock var login_Webuser = ds.Webuser.find('Name = :1 & Password = :2',login_name,login_password); if(!login_Webuser) { // No Webuser with passed name and password login_Webuser = ds.Webuser.find('Email = :1 & Password = :2',login_name,login_password); // try email and password }; if(!!login_Webuser) { // Webuser exists include ('scripts/gWebuser_Functions.js'); Webuser_Logged_In_Take_Over_Temp_User(login_Webuser.ID); // Take over relations of prior temporary Webuser ds.Webuser.Save_Current_Webuser_ID(login_Webuser.ID); // save Webuser ID in SessionStorage return login_Webuser; } else { // Webuser does not exist return null; }; // end if Webuser exists }// @startlock } } };// @endlock
const http = require('http'); const url = require('url'); const zlib = require('zlib'); // utils const isJSON = require('./util').isJSON; const extend = require('./util').extend; const nklient = {}; const keepAliveAgent = new http.Agent({ keepAlive: true }); // TODO: move this to seperate file (much like handler - inject params) let client = (params, resolve, reject) => { let reqURI = url.parse(params.uri); var settings = { host: reqURI.hostname, port: reqURI.port || 80, path: params.newPath || reqURI.pathname, headers: params.headers || {}, method: params.method || 'GET' }; if (params.postData){ settings.params = params.postData; settings.headers['Content-Length'] = params.postData.length; }; let req = http.request(settings); if (settings.params) { req.write(settings.params); } if (params.timeout) { req.setTimeout(params.timeout, () => { let err = new Error('ETIMEDOUT'); err.code = 'ETIMEDOUT'; reject(err); }); } req.on('response', function(res){ if (res.statusCode >= 300 && res.statusCode < 400 && 'location' in res.headers) { let newPath = res.headers.location; params.newPath = newPath; return client(params, resolve, reject); } let chunks = []; // concat chunks res.on('data', (chunk) => { chunks.push(chunk); }); // when the response has finished res.on('end', () => { res.body = Buffer.concat(chunks); let encoding = res.headers['content-encoding']; if (encoding === 'gzip') { zlib.gunzip(res.body, (err, decoded) => { if (err) { reject(err); } res.body = decoded && isJSON(decoded) ? JSON.parse(decoded.toString()) : decoded.toString(); resolve(res) }); } else if (encoding === 'deflate') { zlib.inflate(res.body, (err, decoded) => (err, decoded) => { if (err) { reject(err); } res.body = decoded && isJSON(decoded) ? JSON.parse(decoded.toString()) : decoded.toString(); resolve(res) }); } else { res.body = res.body.toString(); res.body = isJSON(res.body) ? JSON.parse(res.body) : res.body; resolve(res); } }); }); // when err'd out req.on('error', (e) => reject(e)); // end the request req.end(); } let initParams = (uri, options) => { let params = {}; if (typeof options === 'object') { options.uri = uri; return extend(params, options); } else if (typeof uri === 'string') { return extend(params, {uri: uri}); } return extend(params, uri); } let verbFunc = (verb) => { let method = verb.toUpperCase(); return (uri, options) => { nklient.options = extend(initParams(uri, options), {method}); return nklient; } } nklient.get = verbFunc('get'); nklient.head = verbFunc('head'); nklient.post = verbFunc('post'); nklient.put = verbFunc('put'); nklient.patch = verbFunc('patch'); nklient.del = verbFunc('delete'); nklient.headers = (key, val) => { let headers = nklient.options.headers || {}; headers[key] = val; extend(nklient.options, {headers}); return nklient; }; nklient.postBody = (body, encoding) => { if (typeof body === 'string' || body instanceof String) { extend(nklient.options, { postData: body, encoding: encoding || 'utf-8' }) } else { extend(nklient.options, { postData: JSON.stringify(body), encoding: encoding || 'utf-8' }) } return nklient; } nklient.timeout = (timeout) => { extend(nklient.options, {timeout}); return nklient; } nklient.exec = () => new Promise((resolve, reject) => client(nklient.options, resolve, reject)); module.exports = nklient;
export const selectAllPhotos = state => { return Object.keys(state).reverse().map(key => state[key]); }; export const selectPhoto = (id, userId, state) => { let selectedPhoto; state.user[userId].photos.forEach(photo =>{ if (photo.id === id){ selectedPhoto = photo; } }); return selectedPhoto; };
import React from 'react'; import { whyDidYouUpdate } from 'why-did-you-update'; const localStorage = window.localStorage; if (localStorage && localStorage.getItem('nekoboard:wdyu') === 'true') { whyDidYouUpdate(React); }
const { App, Wobj } = require('models'); const _ = require('lodash'); /** * Return hashtags of specified app * List of hashtags saved in App.supported_hashtags * @param appName {String} * @param skip {number} * @param limit {number} * @returns {Promise<{error: any}|{appError: *}|{wobjects: any, hasMore: any}>} */ module.exports = async ({ name, skip, limit }) => { const { app, error: appError } = await App.getOne({ name }); if (appError) return { appError }; const { wObjectsData, hasMore, error } = await Wobj.getAll({ author_permlinks: _.get(app, 'supported_hashtags', []), skip, limit, }); if (error) return { error }; return { wobjects: wObjectsData, hasMore }; };
/*============================================================================= # # Copyright (C) 2016 All rights reserved. # # Author: Larry Wang # # Created: 2016-07-04 15:16 # # Description: # =============================================================================*/ import { combineReducers } from 'redux'; import ui from './ui'; import data from './data'; export default combineReducers({ui, data});
import React from 'react'; import { BrowserRouter, Switch, Route, Redirect } from 'react-router-dom'; import ApolloClient from 'apollo-boost'; import { ApolloProvider } from 'react-apollo'; import Rollbar from 'rollbar'; import moment from 'moment'; import 'moment/min/locales'; //all locales equals 14% of bundle size, revisit import browserLocale from 'browser-locale'; import styled from 'styled-components'; import CssBaseline from '@material-ui/core/CssBaseline'; import { MuiThemeProvider, createMuiTheme } from '@material-ui/core/styles'; import lightBlue from '@material-ui/core/colors/lightBlue'; import orange from '@material-ui/core/colors/orange'; import { QueryProgressProvider } from './QueryProgressContext'; import { UserProvider } from './UserContext'; import WaitTime from '../waittime/WaitTime'; import Admin from '../admin/Admin'; import NotFound from './NotFound'; import Locations from './Locations'; import ErrorPage from './Error'; import ErrorBoundary from '../common/ErrorBoundary'; import BackgroundImage from '../assets/resort-carousel-bg.jpg'; let client; try { Rollbar.init({ accessToken: '77405bf881c942f5a153ceb6b8be9081', captureUncaught: true, captureUnhandledRejections: true, payload: { environment: process.env.NODE_ENV, }, }); //window.addEventListener('error', function (event) { // let { error } = event; // console.log(error.stack); // // Ignore errors that will be processed by componentDidCatch: https://github.com/facebook/react/issues/10474 // if (error.stack && error.stack.indexOf('invokeGuardedCallbackDev') >= 0) { // return true; // } // Rollbar.error(error); // ReactDOM.render(<Error />, document.getElementById('root')); //}); moment.locale(browserLocale()); client = new ApolloClient({ clientState: { resolvers: { Mutation: { selectTimePeriod: (_, { waitTimeDateID, timestamp }, { cache, getCacheKey }) => { const id = getCacheKey({ __typename: 'WaitTimeDate', id: waitTimeDateID }); const data = { __typename: 'WaitTimeDate', selectedTimestamp: timestamp, }; cache.writeData({ id, data }); return null; }, }, WaitTimeDate: { selectedTimestamp: waitTimeDate => { if (!waitTimeDate.timePeriods || !waitTimeDate.timePeriods.length) { return null; } // default to middle time period const middleIndex = Math.round(waitTimeDate.timePeriods.length / 2); return waitTimeDate.timePeriods[middleIndex].timestamp; }, }, }, }, onError: ({ graphQLErrors, networkError, operation, response, forward }) => { const logError = (error, type) => { Rollbar.error(error, { type, operation, }); }; if (graphQLErrors) { graphQLErrors.forEach(error => logError(error, 'GraphQL Error')); } if (networkError) { logError(networkError, 'Network Error'); } }, }); } catch (error) { Rollbar.error(error); } const theme = createMuiTheme({ palette: { type: 'dark', primary: lightBlue, secondary: orange, background: { paper: '#343434', default: '#282828', }, divider: 'rgba(230, 230, 230, 0.12)', }, }); const Background = styled.div` background-image: url(${BackgroundImage}); background-position: center; background-size: cover; background-repeat: no-repeat; background-attachment: fixed; `; class App extends React.Component { render() { return ( <ApolloProvider client={client} > <CssBaseline> <MuiThemeProvider theme={theme}> <Background> <ErrorBoundary component={ErrorPage}> <BrowserRouter> <UserProvider> <QueryProgressProvider> <Switch> {Locations.WaitTime.toRoute({ component: WaitTime, invalid: NotFound }, true)} <Redirect from='/' to={Locations.Resort.toUrl({id: 13})} exact /> <Route path='/' component={Admin} /> <Route component={NotFound} /> </Switch> </QueryProgressProvider> </UserProvider> </BrowserRouter> </ErrorBoundary> </Background> </MuiThemeProvider> </CssBaseline> </ApolloProvider> ); } } export default App;
(function() { 'use strict'; var Geolocator = function(targetElement) { this.targetElement = targetElement; }; Geolocator.prototype.determineUsersLocation = function(successCallback, errorCallback) { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(successCallback, function() { errorCallback(true); }); } else { // Browser doesn't support Geolocation errorCallback(false); } }; window.Geolocator = Geolocator; })();
/* eslint-disable no-underscore-dangle */ import { createStore } from 'redux' import { isDevelopment } from 'services/utils/environment' import reducers from './ducks' const store = createStore(reducers, isDevelopment() && window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()) export default store
import React from 'react' import { compose } from 'recompose' import every from 'lodash/every' import { formData } from '../../HOCs/form' import { tableState } from '../../HOCs/tableState' import { arrangeTableData, changeSort, changeQuery, columnFilter } from '../../util/arrangeTableData' import Form from './Form' import Table from './Table' import Checkboxes from './Checkboxes' const ConfigurableTable = ({ form, tabState, handleCheckCol, handleChange, handleShowTable, handleUpdateQuery, handleHeaderClick, handleToggleChecks, }) => <div id="table-container" className="flex-between"> <Form headers={form.headers} data={form.data} onChange={handleChange} onClick={handleShowTable} query={tabState.query} showTable={tabState.showTable} showColsHidden={tabState.showColsHidden} handleUpdateQuery={handleUpdateQuery} colsHidden={tabState.colsHidden} handleCheckCol={handleCheckCol} handleToggleChecks={handleToggleChecks} /> { (form.headers && tabState.showColsHidden) ? <Checkboxes onChange={handleCheckCol} colsHidden={tabState.colsHidden} showColsHidden={tabState.showColsHidden} headers={form.headers} /> : <div /> } { every([tabState.showTable, form.headers, form.data], x => !!x) && tabState.showTable ? <Table handleHeaderClick={handleHeaderClick} sortedBy={tabState.sortedBy} order={tabState.order} tableData={ changeSort(changeQuery(columnFilter(arrangeTableData(form.headers, form.data), tabState.colsHidden), tabState.query), tabState.sortedBy, tabState.order) } /> : <div /> } </div> export default compose( formData({ headers: '', data: '' }), tableState({ showTable: false, query: '', order: 'asc', sortedBy: '', showColsHidden: false, colsHidden: [], }), )(ConfigurableTable)
// @flow import * as React from 'react'; import { Image } from 'react-native'; type CardType = | 'MASTERCARD' | 'VISA' | 'MAESTRO' | 'AMERICAN_EXPRESS' | 'DISCOVER' | 'DINERS_CLUB' | 'MIR' | 'UNKNOWN'; type Props = {| +cardType: CardType, |}; const CardImage = ({ cardType }: Props) => { let source; switch (cardType) { case 'MASTERCARD': { source = require('./images/MasterCardLogo.imageset/mastercard.png'); break; } case 'VISA': { source = require('./images/VisaLogo.imageset/visa.png'); break; } case 'MAESTRO': { source = require('./images/MaestroLogo.imageset/maestro.png'); break; } case 'AMERICAN_EXPRESS': { source = require('./images/AmexLogo.imageset/amex.png'); break; } case 'DISCOVER': { source = require('./images/DiscoverLogo.imageset/discover.png'); break; } case 'DINERS_CLUB': { source = require('./images/DinersLogo.imageset/diners.png'); break; } case 'MIR': { source = require('./images/MirLogo.imageset/mir.png'); break; } case 'UNKNOWN': default: { source = require('./images/all_cards.imageset/all_cards.png'); break; } } return <Image source={source} mode="contain" />; }; export default CardImage;
var Left = x => this._value = x Left.of = x => new Left(x) Left.prototype.map = function(f) { return this } Left.prototype.join = function() { return this._value } Left.prototype.ap = function(m) { return m.map(this._value) } module.exports = Left
/** * @license * Copyright (C) 2011 Zimin A.V. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview * Registers a language handler for the Nemerle language. * http://nemerle.org * @author Zimin A.V. */ (function () { // http://nemerle.org/wiki/index.php?title=Base_keywords var keywords = 'abstract|and|as|base|catch|class|def|delegate|enum|event|extern|false|finally|' + 'fun|implements|interface|internal|is|macro|match|matches|module|mutable|namespace|new|' + 'null|out|override|params|partial|private|protected|public|ref|sealed|static|struct|' + 'syntax|this|throw|true|try|type|typeof|using|variant|virtual|volatile|when|where|with|' + 'assert|assert2|async|break|checked|continue|do|else|ensures|for|foreach|if|late|lock|new|nolate|' + 'otherwise|regexp|repeat|requires|return|surroundwith|unchecked|unless|using|while|yield'; PR['registerLangHandler'](PR['createSimpleLexer']( // shortcutStylePatterns [ [PR['PR_STRING'], /^(?:\'(?:[^\\\'\r\n]|\\.)*\'|\"(?:[^\\\"\r\n]|\\.)*(?:\"|$))/, null, '"'], [PR['PR_COMMENT'], /^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\r\n]*)/, null, '#'], [PR['PR_PLAIN'], /^\s+/, null, ' \r\n\t\xA0'] ], // fallthroughStylePatterns [ [PR['PR_STRING'], /^@\"(?:[^\"]|\"\")*(?:\"|$)/, null], [PR['PR_STRING'], /^<#(?:[^#>])*(?:#>|$)/, null], [PR['PR_STRING'], /^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/, null], [PR['PR_COMMENT'], /^\/\/[^\r\n]*/, null], [PR['PR_COMMENT'], /^\/\*[\s\S]*?(?:\*\/|$)/, null], [PR['PR_KEYWORD'], new RegExp('^(?:' + keywords + ')\\b'), null], [PR['PR_TYPE'], /^(?:array|bool|byte|char|decimal|double|float|int|list|long|object|sbyte|short|string|ulong|uint|ufloat|ulong|ushort|void)\b/, null], [PR['PR_LITERAL'], /^@[a-z_$][a-z_$@0-9]*/i, null], [PR['PR_TYPE'], /^@[A-Z]+[a-z][A-Za-z_$@0-9]*/, null], [PR['PR_PLAIN'], /^'?[A-Za-z_$][a-z_$@0-9]*/i, null], [PR['PR_LITERAL'], new RegExp( '^(?:' // A hex number + '0x[a-f0-9]+' // or an octal or decimal number, + '|(?:\\d(?:_\\d+)*\\d*(?:\\.\\d*)?|\\.\\d\\+)' // possibly in scientific notation + '(?:e[+\\-]?\\d+)?' + ')' // with an optional modifier like UL for unsigned long + '[a-z]*', 'i'), null, '0123456789'], [PR['PR_PUNCTUATION'], /^.[^\s\w\.$@\'\"\`\/\#]*/, null] ]), ['n', 'nemerle']); })();
(function(global){ function Roulette(paper,length,labelStoppers) { var self = this; self.angle = 0; self.width = length; self.height = length; self.radius = length * 0.8 /2; var sizes = { r : self.radius, r1_2 : self.radius/2, r1_3 : self.radius/3, r2_3 : self.radius*2/3, r1_4 : self.radius*1/4, r3_4 : self.radius*3/4, r1_5 : self.radius*1/5, r1_6 : self.radius*1/6, r1_10 : self.radius*1/10, r1_12 : self.radius*1/12, r1_24 : self.radius*1/24, }; sizes.fontsize = sizes.r1_12; self.sizes = sizes; self.x = self.width/2; self.y = self.height/2; self.group = paper.group(); self.labelStoppers = labelStoppers; var lines = []; var angles = []; var PI = Math.PI; //LabelStopperに対応する図形を描く.{pie,text}という形式で帰ってくる //とっておく必要あるかな・・・? var pathes = self.labelStoppers.map(function(labelStopper, index){ var ang = labelStopper.getAngle(); var nextang = labelStopper.next.getAngle(); var diffAng = nextang.calcDiff(ang); var middleAng = ang.getAdd(diffAng.get()/2); var pie = paper.pie( 0, 0, sizes.r, ang.get() * 180 / Math.PI, nextang.get() * 180 / Math.PI ).remove() //色を設定 .attr({ fill : Snap.hsb(ang.get()/(2*Math.PI) + Math.PI/6, 0.5,0.9), stroke : "#000", strokeWidth: sizes.r1_24 }); var text = paper.text(0, 0, labelStopper.getLabel()).remove() .transform( "rotate("+ (-middleAng.get() * 180 / Math.PI) + ") "+ "translate("+ (sizes.r*0.75 - sizes.fontsize/2) +",0) "+ //; "rotate(90) ") .attr({ fill : Snap.hsb(0, 0, 0), "text-anchor": "middle", "font-size" : self.sizes.fontsize, //サイズは半径に依存しなければならない }); self.group.append(pie); self.group.append(text); var res = {pie: pie, text:text}; return res; }) //中央固定要素 var centerObj = paper.group().remove() .transform("translate("+ self.x +","+self.y+")"); var borderWidth = sizes.r1_24; //上の三角▲ this.triAngle = PI/24; this.triangle = centerObj.path( "M"+ 0 +","+ -sizes.r1_10 + "L"+sizes.r1_10 +","+(sizes.r1_12)+ "L"+(-sizes.r1_10) +","+(sizes.r1_12)+"z") .attr({ fill:Snap.rgb(255,255,255), stroke:Snap.rgb(0,0,0,1), strokeWidth:borderWidth }) .transform("translate("+ 0 +","+ -sizes.r1_2 +") "+ "rotate("+ this.fure * 180/10 +")" ); //真ん中の円 var circle = centerObj.circle(0, 0, self.radius *(1/2)) .attr({ fill:Snap.rgb(255,255,255), stroke:Snap.rgb(0,0,0,1), strokeWidth:borderWidth }); //真ん中の文字列 this.centerText = centerObj.text(0,0, "asdfasdfasdflakjsdaf") .attr({ fill : Snap.hsb(0,0,0), "text-anchor": "middle", "font-size":sizes.fontsize, }); //self.group.append(circle); paper.append(centerObj); //透明な窓 var eventRect = paper.rect(0, 0, self.width, self.height).attr({ opacity:0 }); this.render(); } //requestAnimationFrameにより呼ばれる Roulette.prototype.render = function() { this.group.transform("translate("+this.x+","+this.y+") rotate("+ this.angle/Math.PI*180+")"); var stateText = ("angle is " + this.angle.toFixed(2)); this.centerText.attr({ "text": this.text || stateText }); this.triangle .transform("translate("+ 0 +","+ -this.sizes.r1_2 +") "+ "rotate("+ this.fure * 180/10 +")" ); //this.text = null; //1回表示したら消すようにしてみる } Roulette.prototype.setAngle = function(angle_rad) { this.angle = angle_rad; }; Roulette.prototype.setFure= function(fure) { this.fure= fure; }; Roulette.prototype.setText = function(text) { this.text = text; }; global.Roulette = Roulette; }(window));
'use strict' /** * @fileoverview creates index of .mj files */ var fs = require("fs"); var path = require("path"); /** * @param {string} src is a relative directory path to .mj files * @returns {meta_data} is an array; contains information of * all tracked .mj files */ module.exports = function(src){ var location = path.join(".", src); var files = fs.readdirSync(location); var meta_data = []; var index_data = []; for(var i = 0; i < files.length; i++){ if(files[i].slice(-3, files[i].length) == ".mj"){ var file_path = path.join(location, files[i]); var file_content = fs.readFileSync(file_path, { encoding: 'utf8' }); var re_title = /title:(.*?);/i; var re_date = /date:(.*?);/i; var re_time = /time:(.*?);/i; var re_keywords = /keywords:(.*?);/i; var re_content = /(---)([\s\S]*)(---)/mi; var title = file_content.match(re_title, "$1")[1].replace(/^\s+|\s+$/g, ""); var date = file_content.match(re_date, "$1")[1].replace(/^\s+|\s+$/g, ""); var time = file_content.match(re_time, "$1")[1].replace(/^\s+|\s+$/g, ""); var content = file_content.match(re_content)[2].replace(/^\s+|\s+$/g, ""); var keywords = file_content.match(re_keywords, "$1")[1].split(","); keywords = keywords.map(function(item){ return item.replace(/^\s+|\s+$/g, ""); }); var data = { file: files[i], title: title, date: date, time: time, keywords: keywords, } index_data.push(data); data = JSON.parse(JSON.stringify(data)); data.content = content; meta_data.push(data); } } fs.writeFile(path.join(location, "index.mj.json"), JSON.stringify(index_data), function(err){ if(err){ return console.log(err); } console.log("index.mj.json is successfully created."); }); return meta_data; }
import React from 'react' import {FaTwitter, SocialIcon, FaGithub, FaLinkedIn, FaFacebook} from '../../component/Atoms/SocialIcon' import { SubHeading } from '../../component/Atoms/SubHeading'; import { Subtitle } from '../../component/Atoms/Subtitle'; import { Section } from '../../component/Atoms/Section'; import {Container} from '../../component/Atoms/ContainerElements' import {SectionTitle} from '../../component/Atoms/SectionTitle' const About = ({firstName, lastName, address, email, titleDetail}) => { return ( <Container> <Section id='about'> <SectionTitle style={{marginBottom: '12px'}}>{firstName} <span className="primary">{lastName}</span></SectionTitle> <SubHeading style={{marginBottom: '40px'}}>{address}<span className="primary">{email}</span></SubHeading> <Subtitle> {titleDetail} </Subtitle> <div style={{marginTop:'50px'}}> <SocialIcon> <FaGithub /> </SocialIcon> <SocialIcon> <FaLinkedIn /> </SocialIcon> <SocialIcon> <FaTwitter /> </SocialIcon> <SocialIcon> <FaFacebook/> </SocialIcon> </div> </Section> </Container> ) } export default About;
var express = require('express'); var router = express.Router(); var Bank = require('../models/Bank'); router.get('/:userid?', function(req, res, next) { if (req.params.userid){ Bank.getBankByUserId(req.params.userid, function(err, rows){ if (err){ res.json(err); }else{ res.json(rows); } }) } else{ Bank.getAllBanks(function(err, rows){ if (err){ res.json(err); }else{ res.json(rows); } }) } }); router.post('/',function(req,res,next){ Bank.addBank(req.body,function(err,count){ //console.log(req.body); if(err) { res.json(err); } else{ res.json(req.body);//or return count for 1 & 0 } }); }); router.delete('/:id',function(req,res,next){ Bank.deleteBank(req.params.id,function(err,count){ if(err) { res.json(err); } else { res.json(count); } }); }); router.put('/:id',function(req,res,next){ Bank.updateBank(req.params.id,req.body,function(err,rows){ if(err) { res.json(err); } else { res.json(rows); } }); }); module.exports = router;
// Modules import { render } from './render.js' // Utils import { parseHash } from '../utils/parseHash.js' // Pages import Index from '../pages/Index.js' import Error404 from '../pages/Error404.js' // Routes const routes = { '': Index } async function handleRoutes() { // Get the path and optional query parameters from the URL hash const { path, params } = parseHash() // Render the page based on the path const page = routes[path] ? routes[path] : Error404 render({ page, params }) } export { handleRoutes }
module.exports={ "db":"localhost:27017/mychannel", "secretkey":"secret" }