text
stringlengths
7
3.69M
import { router } from "./router"; export const AuthManager = { getAuth(details = 0) { return router.app .$axios({ method: "get", url: router.app.$master.api("/oauth/check"), params: { details: details } }) .then(response => { const auth = Boolean(response.data.auth); router.app.$store.dispatch("auth/setAuthStatus", auth); if (auth) { router.app.$store.dispatch( "auth/setUserInfo", response.data.data ); } router.app.$store.dispatch("auth/reloadAuthStatus"); }) .catch(error => { router.app.$store.dispatch("auth/setAuthStatus", false); router.app.$store.dispatch("auth/reloadAuthStatus"); throw error.code; }); }, forceAuth(to, from, next) { this.getAuth(1) .then(r => { if (router.app.$store.state.auth.auth) { next(); } else { router.app.$q.notify({ message: "请您先登录。", type: "warning" }); next({ name: "public.index" }); } }) .catch(e => { router.app.$q.notify({ message: "请您先登录。", type: "warning" }); next({ name: "public.index" }); }); }, optionalAuth(to, from, next) { this.getAuth(1) .then(r => { next(); }) .catch(e => { next(); }); } };
jQuery(document).ready(function ($) { _.templateSettings = { interpolate: /\{\{(.+?)\}\}/g }; //Variables del template se ingresarán así: {{nombre_Variable}} moment.locale("es"); //Se settea el formato de fecha de la librería moment var record_id = 0; $(document).children('.lazy').Lazy(); $(document).on('click', '[data-toggle="lightbox"]', function(event) { event.preventDefault(); $(this).ekkoLightbox({ alwaysShowClose: true, onHide: () => { $("#detail-modal").css({ 'overflow-y': 'scroll' }); } }); }); if($.fn.DataTable) { window.tabla_registros = $("#records-table").DataTable({ 'oLanguage': { 'sLengthMenu': 'Mostrando _MENU_ filas', 'sSearch': '', 'sProcessing': 'Procesando...', 'sLengthMenu': 'Mostrar _MENU_ registros', 'sZeroRecords': 'No se encontraron resultados', 'sEmptyTable': 'Ningún dato disponible en esta tabla', 'sInfo': 'Mostrando registros del _START_ al _END_ de un total de _TOTAL_ registros', 'sInfoEmpty': 'Mostrando registros del 0 al 0 de un total de 0 registros', 'sInfoFiltered': '(filtrado de un total de _MAX_ registros)', 'sInfoPostFix': '', 'sSearch': 'Buscar:', 'sUrl': '', 'sInfoThousands': '', 'sLoadingRecords': 'Cargando...', 'oPaginate': { 'sFirst': 'Primero', 'sLast': 'Último', 'sNext': 'Siguiente', 'sPrevious': 'Anterior' } } }); loadTable(); } else { $.when( $.getScript('js/jquery.dataTables.js'), $.Deferred(function (deferred) { $(deferred.resolve); }) ).done(()=>{ window.tabla_registros = jQuery("#records-table").DataTable({ 'oLanguage': { 'sLengthMenu': 'Mostrando _MENU_ filas', 'sSearch': '', 'sProcessing': 'Procesando...', 'sLengthMenu': 'Mostrar _MENU_ registros', 'sZeroRecords': 'No se encontraron resultados', 'sEmptyTable': 'Ningún dato disponible en esta tabla', 'sInfo': 'Mostrando registros del _START_ al _END_ de un total de _TOTAL_ registros', 'sInfoEmpty': 'Mostrando registros del 0 al 0 de un total de 0 registros', 'sInfoFiltered': '(filtrado de un total de _MAX_ registros)', 'sInfoPostFix': '', 'sSearch': 'Buscar:', 'sUrl': '', 'sInfoThousands': '', 'sLoadingRecords': 'Cargando...', 'oPaginate': { 'sFirst': 'Primero', 'sLast': 'Último', 'sNext': 'Siguiente', 'sPrevious': 'Anterior' } } }); loadTable(); }); } $('#records-table').on('click', 'a.btn-detail', showRecord); $('#btn-aprobar').on('click', send_request); $('#btn-rechazar').on('click', send_request); $('#btn-trasladar').on('click', send_request); $("#carta-preliminar").on('hidden.bs.modal', ()=>{ window.location.reload(true); }); function loadTable() { $('#loader').show(); $.ajax({ type: 'GET', url: 'ws/medidas/solicitudes', dataType: 'json' }).done(function (response) { //Se agregó este try/catch como la solución más rápida para corregir un error en la línea 90, en la cual por alguna extraña razón, muy pero muy esporádicamente falla al intentar borrar la tabla window.tabla_registros.clear() y no se cierra el loader try { window.tabla_registros.clear().draw(false); var records = response.records.map(record=>{ //Filtrar que no hayan campos nulos if(!record.empleado){ record.empleado = { EMPID: "", UEN: "", DEPTO: "", PUESTO: "" } } return record; }); $.each(records, function (index, value) { no_empleado = value.empleado.EMPID; nombre_empleado = value.empleado.NOMBRE; fecha = value.fecha; uen = value.empleado.UEN; departamento = value.empleado.DEPTO; puesto = value.empleado.PUESTO; sancion = value.especifica.descripcion; acciones = "<a href='#' class='btn btn-xs btn-primary btn-detail' data-amonestacion='"+ JSON.stringify(value.falta_amonestacion) +"' data-toggle='modal' data-id='"+value.id+"'>Detalle</a>"; window.tabla_registros.row.add([++index, no_empleado, nombre_empleado, fecha, uen, departamento, puesto, sancion, acciones]).draw(false); }); } catch(e) { $('#loader').fadeOut(); } }).fail(function (response) { toastr['error'](response.message, 'Error'); }).always(function () { $('#loader').fadeOut(); }); } function showRecord (e) { e.preventDefault(); record_id = $(this).data('id'); const falta_amonestacion = $(this).data('amonestacion'); $("#attachment-files").empty(); $.ajax({ type: 'GET', url: 'ws/medidas/solicitudes/'+record_id, dataType: 'json' }).done(function (response) { $('#falta_general').val(response.records.general.descripcion); $('#falta_especifica').val(response.records.especifica.descripcion); $('#fecha').val(moment(response.records.fecha).format('DD[-]MM[-]YYYY')); //$("#sancion").val(falta_amonestacion.amonestacion.descripcion); html = ''; json = JSON.parse(response.records.detalle); const showAttachmentFiles = (title, fields, tag, container) => { const prefix = `<div><h5 style='font-weight: 900;'>${title}</h5></div>`, sufix = "</div>", fields_html = []; if (fields.forEach) { fields.forEach( (field, index) => { if (tag.toLowerCase() == 'img') { fields_html.push(`<a href='${field}' data-toggle="lightbox" data-max-width="900"> <img src='${field}' class='lazy' style='width: 140px;margin-right: 10px;' /> </a>`) return; } if (tag.toLowerCase() == 'video') { fields_html.push(`<p><a href='${field}' data-toggle='lightbox' >Ver vídeo ${(index + 1)}</a></p>`) return; } if (tag.toLowerCase() == 'audio') { fields_html.push(`<p><a href='${field}' data-toggle='lightbox' >Ver audio ${(index + 1)}</a></p>`) return; } if (tag.toLowerCase() == 'document') { fields_html.push(`<a href='${field}' target='_blank'> Documento ${(index + 1)}</a>`); } if (tag.toLowerCase() == 'email') { fields_html.push(`<a href='${field}' target='_blank'> Correo ${(index + 1)}</a>`); } //fields_html.push(`<a href='${field}' target='_blank'> <${tag}>Documento ${(index + 1)}</${tag}></a>`); }); $(container).append(prefix + fields_html + sufix); } }; if (response.records.imagen.length > 0) { const images = response.records.imagen.split(", ") showAttachmentFiles("Imágenes", images, 'img', '#attachment-files'); } if (response.records.video.length > 0) { const videos = response.records.video.split(", "); showAttachmentFiles("Videos", videos, "video", "#attachment-files") } if (response.records.audio.length > 0) { const audios = response.records.audio.split(", "); showAttachmentFiles("Audios", audios, "audio", "#attachment-files"); } if (response.records.documento.length > 0) { const documentos = response.records.documento.split(", "); showAttachmentFiles("Documentos", documentos, "document", "#attachment-files"); } if (response.records.email.length > 0) { const emails = response.records.email.split(", "); showAttachmentFiles('Correos', emails, 'email', "#attachment-files"); } $.each(json, function(index, value){ if(value.type == 'checkbox-group') { html += '<div class="col-sm-12">'; html += '<div class="form-group">'; html += '<label>'+value.label+'</label>'; $.each(value.values, function(a, b){ checked = b.selected ? 'checked' : ''; html += '<div class="checkbox">'; html += '<label>'; html += '<input type="checkbox" '+checked+' disabled>'; html += b.label; html += '</label>'; html += '</div>'; }); html += '</div>'; html += '</div>'; } else if(value.type == 'date') { html += '<div class="col-sm-6">'; html += '<div class="form-group">'; html += '<label>'+value.label+'</label>'; html += '<input type="text" name="'+ value.label +'" class="form-control" value="'+ moment(value.value).format('DD[-]MM[-]YYYY') +'" readonly>'; html += '</div>'; html += '</div>'; } else if(value.type == 'number') { html += '<div class="col-sm-6">'; html += '<div class="form-group">'; html += '<label>'+value.label+'</label>'; html += '<input type="text" name="'+ value.label +'" class="form-control" value="'+value.value+'" readonly>'; html += '</div>'; html += '</div>'; } else if(value.type == 'radio-group') { html += '<div class="col-sm-12">'; html += '<div class="form-group">'; html += '<label>'+value.label+'</label>'; $.each(value.values, function(a, b){ checked = b.selected ? 'checked' : ''; html += '<div class="radio">'; html += '<label>'; html += '<input type="radio" '+checked+' disabled>'; html += b.label; html += '</label>'; html += '</div>'; }); html += '</div>'; html += '</div>'; } else if(value.type == 'select') { html += '<div class="col-sm-6">'; html += '<div class="form-group">'; html += '<label>'+value.label+'</label>'; $.each(value.values, function(a, b){ if(b.selected) { html += '<input type="text" class="form-control" value="'+b.label+'" readonly />'; } }); html += '</div>'; html += '</div>'; } else if(value.type == 'text') { html += '<div class="col-sm-6">'; html += '<div class="form-group">'; html += '<label>'+value.label+'</label>'; html += '<input type="text" class="form-control" name="'+ value.label +'" value="'+value.value+'" readonly>'; html += '</div>'; html += '</div>'; } else if(value.type == 'textarea') { html += '<div class="col-sm-12">'; html += '<div class="form-group">'; html += '<label>'+value.label+'</label>'; html += '<textarea class="form-control" name="'+ value.label +'" readonly>'+value.value+'</textarea>'; html += '</div>'; html += '</div>'; } }); $('#informacion').html(html); if( $("#carta_preliminar").hasClass('hidden') == false ) { $("#carta_preliminar").addClass('hidden'); $("#description").removeClass('hidden'); } $("#detail-modal").attr({ "data-id": record_id, "data-amonestacion": JSON.stringify(falta_amonestacion), "data-info": JSON.stringify(response.records) }).modal(); }).fail(function (response) { toastr['error'](response.message, 'Error'); }).always(function () { }); } function send_request(e) { e.preventDefault(); estado = $(this).data('reg'); const id = $("#detail-modal").data("id"); /*if($(this).hasClass('aprobar_carta')) {$(this).removeClass('aprobar_carta'); return; }*/ if(estado == 1) { const {amonestacion, info} = $("#detail-modal").data(); $("#loader .spinner .text h4").text("Generando y Enviando Carta"); $('#loader').show(); var xhr = $.ajax({ url: 'ws/medidas/solicitudes/' + id, type: 'PUT', dataType: 'json', cache: false, data: { estado: estado, uid_aprobo: localStorage.USUARIO.toUpperCase(), fecha_aprobacion: moment().format("YYYY[-]MM[-]DD"), sendMail: 'false' } }); xhr .done((carta)=>{ if(carta.result) { var $carta = $(carta.records.carta); var clone_carta = carta.records.carta; const empleado = carta.records.empleado; const jefe = carta.records.jefe; $carta.find(".field-to-replace").each((index, field)=>{ clone_carta = clone_carta.replace(field.outerHTML, "<span>{{"+ $(field).attr("data-name") +"}}</span>"); }); $carta.find("p[contenteditable]").each((index, p)=>{ clone_carta = clone_carta.replace(p.outerHTML, "<span>"+ p.innerText +"</span>"); }); //<p style='margin-bottom: 1.5em;'>Atentamente, </p><div><hr style='width: 200px;display: inline-block;border-width: 1px;border-color: #333;margin: 0;' /><p style='margin: 0;'>"+ localStorage.NOMBRE_USUARIO +"</p> clone_carta = clone_carta + `<div style="text-align: left;margin-top: 4em;"> <p style="margin:0;border-top: 1px solid;display: inline-block;padding-right: 1.5em;padding-top: 0.5em;">${jefe.NOMBRE}</p> <p>Florida Bebidas, S.A.</p> </div>`; var compiled = _.template(clone_carta); var _compiled_carta = compiled({ fecha_impresion: moment().format("DD [de] MMMM [de] YYYY"), nombre: info.empleado.NOMBRE, puesto: info.empleado.PUESTO, numero_empleado: info.empleado.UEN, fecha_falta: moment(info.fecha).format("DD [de] MMMM"), falta_general: info.general.descripcion, falta_especifica: info.especifica.descripcion }); var sendMail = $.ajax({ url: 'ws/medidas/solicitudes/' + id, type: 'PUT', dataType: 'JSON', cache: false, data: { carta: _compiled_carta, estado: 1, jefe: jefe.CORREO, sendMail: true } }); sendMail .done((response)=>{ if (response.result) { loadTable(); toastr['success']('Registro aprobado correctamente', "Éxito"); $("#loader .spinner .text h4").text(""); $('#loader').fadeOut(); $("#carta-preliminar #content").html(_compiled_carta); //$("#carta-preliminar .modal-header").html("<h3>"+ carta.records.falta_amonestacion.amonestacion.descripcion +"</h3>") $("#detail-modal").modal("hide"); $("#carta-preliminar").modal(); } else { toastr.error('No se pudo guardar la carta correctamente'); } $('#loader').fadeOut(); }) .fail(error=>{ console.log(error); toastr.error(error.message, 'Error'); $('#loader').fadeOut(); }); } else { toastr.warning(carta.message, "Error"); $('#loader').fadeOut(); } }) .fail((error)=>{ toastr.error(error.message, 'Error'); $('#loader').fadeOut(); }); } else if(estado == 2) { var xhr = $.ajax({ url: 'ws/medidas/solicitudes/' + id, type: 'PUT', dataType: 'json', data: { estado: estado } }); xhr .done((response)=>{ if(response.result) { loadTable(); toastr.success(response.message, "Solicitud rechazada"); $("#detail-modal").modal("hide"); window.location.reload(true); } else { toastr.warning(response.message, "Solicitud no rechazada"); } }) .fail((error)=>{ toastr.error(error.message, 'Ocurrió un error'); $('#loader').fadeOut(); }); } else { //TRASLADO LEGAL var usuario = localStorage.USUARIO; var form_falta = $("#form-solicitud").serializeJSON(); var form_info_adicional_falta = $("#form-info-adicional").serializeJSON(); form_falta.fecha = transformDate(form_falta.fecha); $("#loader .spinner .text h4").text("Enviando Carta a Gerente Legal"); $('#loader').show(); var xhr = $.ajax({ url: 'ws/medidas/solicitudes/' + id, type: 'PUT', dataType: 'json', data: { estado: estado, usuario: usuario.toUpperCase(), solicitud: { falta: form_falta, adicional: form_info_adicional_falta } } }); xhr .done((data)=>{ if(data.result) { toastr.success(data.message, 'Correo Enviado'); loadTable(); $("#detail-modal").modal("hide"); window.location.reload(true); } else { toastr.warning(data.message, 'Correo no enviado'); } $('#loader').fadeOut(); }) .fail((response)=>{ toastr.error(response.message, 'Ocurrió un error'); $('#loader').fadeOut(); }); } } function transformDate(date) { var _date_split = date.split("-"); var _date = `${_date_split[2]}-${_date_split[1]}-${_date_split[0]}`; return _date; } });
const { User } = require('../models/index').db; const bcrypt = require('bcrypt'); const jwt = require('jsonwebtoken'); module.exports = { register: async (req, res) => { try { const { email, firstName, lastName, password } = req.body; const validator = req.validator.build({ email, firstName, lastName, password },{ email: 'required|string|email', firstName: 'required|string', lastName: 'required|string', password: 'required|min:6' }); const validationResult = await validator.validate(); if (validationResult.status === 'error') { return res.status(422).json(validationResult.data); } let passwordHash = ''; bcrypt.hash(password, 10, function(err, hash) { if (err) { console.log(err); } passwordHash = hash; User.create({ email, firstName, lastName, password: passwordHash }); res.status(200).json({ status: 'success', message: 'Register successfully!' }); }); } catch (e) { req.app.locals.handleError(res, e); } }, login: async (req, res) => { try { const { email, password } = req.body; const user = await User.findOne({ where: { email: email } }); if (!user) { return res.status(400).json({ status: 'login failed', message: 'Cannot find user with that email, please try again' }); } const checkHash = await bcrypt.compare(password, user.password); if (!checkHash) { return res.status(400).json({ status: 'login failed', message: 'Password incorrect, please try again' }); } res.status(200).json({ status: 'login success', token: jwt.sign({ id: user.id, firstName: user.firstName, lastName: user.lastName, email: user.email }, process.env.JWT_SECRET || '123456', { expiresIn: '2h' }), user: { id: user.id, firstName: user.firstName, lastName: user.lastName, email: user.email } }); } catch(e) { req.app.locals.handleError(res, e); } } }
// mixins const abouts = { data () { return { modalsInsert: true, navbar: true, cart: [], allMenu: false, nameproduk: null, price: null, image: null, id_category: null } }, // costume directives di login navbar directives: { backgroundColour: { bind: (elemen, binding) => { elemen.style.backgroundColor = binding.value } } } // custom directives } export default abouts
import './css/style.css'; import './css/animate.css' import {addLesson} from "./js/addLesson.js"; addLesson();
"use strict"; function _instanceof(left, right) { if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { return !!right[Symbol.hasInstance](left); } else { return left instanceof right; } } function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!_instanceof(instance, Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var StreamElement = /*#__PURE__*/ function (_GameObject) { _inherits(StreamElement, _GameObject); function StreamElement(canvas, player) { var _this; _classCallCheck(this, StreamElement); _this = _possibleConstructorReturn(this, _getPrototypeOf(StreamElement).call(this, canvas)); _this.radius = Math.floor(Math.random() * 9); _this.radius *= renderSizeKoef; _this.width = _this.radius; _this.height = _this.radius; _this.direction = Math.floor(Math.random() * 47) - 23; _this.posX = player.posX + (player.width - _this.width) / 2; _this.posY = player.posY + player.height * 0.7; _this.startSpeed = 5; _this.speedX = _this.startSpeed * Math.sin(_this.direction * Math.PI / 180); _this.speedY = _this.startSpeed * Math.cos(_this.direction * Math.PI / 180); _this.friction = 0.97; _this.transparency = 0.5; _this.done = false; if (!exclusiveColor) { _this.redColor = colorOfSteam[0]; _this.greenColor = colorOfSteam[1]; _this.blueColor = colorOfSteam[2]; } else { _this.redColor = Math.floor(Math.random() * 256); _this.greenColor = Math.floor(Math.random() * 256); _this.blueColor = Math.floor(Math.random() * 256); } return _this; } _createClass(StreamElement, [{ key: "update", value: function update() { this.transparency -= 0.005; if (this.transparency <= 0) this.done = true; this.speedX *= this.friction; this.speedY *= this.friction; this.posX += this.speedX; this.posY += this.speedY; } }, { key: "isDone", value: function isDone() { return this.done; } }, { key: "render", value: function render() { //this.ctx.save(); this.ctx.beginPath(); this.ctx.arc(this.posX + this.width / 2, this.posY + this.height / 2, this.radius, 0, Math.PI * 2); if (!exclusiveColor) { this.redColor = Math.floor(this.redColor * 0.91); this.greenColor = Math.floor(this.greenColor * 0.91); this.blueColor = Math.floor(this.blueColor * 0.91); } this.ctx.fillStyle = "rgba(" + this.redColor + "," + this.greenColor + "," + this.blueColor + "," + this.transparency + ")"; this.ctx.fill(); // this.ctx.restore(); } }]); return StreamElement; }(GameObject);
import React from "react"; import styled from "styled-components"; import LoginForm from "../../components/admin/LoginForm"; const StyledLogin = styled.div` width: 100vw; height: 100vh; background-image: url("images/banner.jpg"); background-size: cover; filter: grayscale(0.5); background-repeat: no-repeat; background-color: #f2f2f2; background-position: center top; margin: 0; display: flex; justify-content: center; align-items: center; `; const LoginContainer = styled.div` width: 40%; height: 50%; background-color: white; margin: 0; display: flex; border-radius: 15px; justify-content: center; align-items: center; flex-direction: column; box-shadow: 0 8px 9px -1px hsl(0deg 2% 48% / 60%); h1 { height: 20%; font-weight: 300; margin: 0; } `; const Admin = () => { return ( <StyledLogin> <LoginContainer> <h1>PROPER 360</h1> <LoginForm /> </LoginContainer> </StyledLogin> ); }; export default Admin;
import React from 'react'; import ReactDOM from 'react-dom' import styles from './index.less'; import locationIco from './img/location.svg'; import downIco from './img/down.svg'; import searchIco from './img/search.png'; import QueueAnim from 'rc-queue-anim'; class Header extends React.Component { constructor(props) { super(props); this.state = { searchFloat: false, showSelectLoc:false, } } componentWillMount() { window.addEventListener('scroll', this.onScroll.bind(this), false) } componentWillUnmount() { window.removeEventListener('scroll', this.onScroll.bind(this), false) } onScroll() { if (window.scrollY <= 48 && this.state.searchFloat) { this.setState({ searchFloat: false, }) } if (window.scrollY > 48 && !this.state.searchFloat) { this.setState({ searchFloat: true, }) } console.log(window.scrollY); } showSelectLoc = ()=>{ this.setState({ showSelectLoc:true }) } hideSelectLoc = ()=>{ this.setState({ showSelectLoc:false, }) } render() { const { address } = this.props; const searchFloatCom = ( <div className={styles.searchWrapFloat}> <div className={styles.search} > <img src={searchIco} className={styles.searchIco} /> <span className={styles.searchText}>搜索商家、商品名称</span> </div> </div> ) return ( <div className={styles.header}> <div className={styles.address} onClick={this.showSelectLoc}> <img src={locationIco} className={styles.locationIco} /> <div className={styles.locationText}>{address}</div> <img src={downIco} className={styles.downIco} /> </div> <div className={styles.searchWrap}> <div className={styles.search} > <img src={searchIco} className={styles.searchIco} /> <span className={styles.searchText}>搜索商家、商品名称</span> </div> </div> {this.state.searchFloat && searchFloatCom} {/* <QueueAnim animConfig={[ { translateX: [0, 750] }, ]} > {this.state.showSelectLoc ? <SelectLocation key='1' onBackClick={this.hideSelectLoc}/> : null} </QueueAnim> */} </div> ) } } export default Header;
const pseudoName = document.getElementById("pseudoName"); const email = document.getElementById("email"); const password = document.getElementById("password"); const confirmPass = document.getElementById("confirmPass"); const confirmPassDanger = document.getElementById("confirmPassDanger"); const confirmPassWarn = document.getElementById("confirmPassWarn"); const confirmPassSucces = document.getElementById("confirmPassSucces"); const valuePseudo = (check) => { check; }; let valueEmail = ""; let valuePass = ""; let valueConfirm = ""; pseudo.addEventListener("input", (e) => { if (e.target.value.length < 3 || e.target.value.length > 17) { pseudoName.innerHTML = "Pseudo doit contenir entre 3 et 17 caractères"; // valuePseudo = ""; } else if (e.target.value.match(/^[a-zA-Z]{3,17}[0-9]{0,3}$/)) { pseudoName.innerHTML = ""; valuePseudo(e.target.value); } else { pseudoName.innerHTML = "Pseudo ne doit pas contenir de caractère spécial"; // valuePseudo = ""; } }); mail.addEventListener("input", (e) => { if (e.target.value.match(/^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/)) { email.innerHTML = ""; } else { email.innerHTML = "Email incorrect ex : marty@hotmail.fr"; } }); pass.addEventListener("input", (e) => { if ( e.target.value.match(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[a-zA-Z]).{8,}$/) ) { password.innerHTML = ""; confirmPassDanger.classList.add("display-none"); confirmPassWarn.classList.remove("display-none"); confirmPassSucces.classList.add("display-none"); } if ( e.target.value.match(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&]).{8,}$/) ) { password.innerHTML = ""; confirmPassDanger.classList.add("display-none"); confirmPassWarn.classList.add("display-none"); confirmPassSucces.classList.remove("display-none"); } if ( !e.target.value.match( /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/, ) && !e.target.value.match(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[a-zA-Z]).{8,}$/) ) { confirmPassDanger.classList.remove("display-none"); confirmPassWarn.classList.add("display-none"); confirmPassSucces.classList.add("display-none"); password.innerHTML = "Faible 1 minuscule 1 majuscule et 1 chiffre min 8 Lts."; } if (e.target.value.length == 0) { console.log("rien"); confirmPassDanger.classList.add("display-none"); confirmPassWarn.classList.add("display-none"); confirmPassSucces.classList.add("display-none"); password.innerHTML = ""; } }); console.log(valuePseudo);
/************************ des: 站点全局模块 date: 2016/11/28 auth: mike ************************/ let ngApp = angular.module("ngApp", ['ui.router']); //import {apiConfig} from '../components/config'; //配置阶段 注入全局路由服务 routerproviderProvider ngApp.config(['$httpProvider','routerproviderProvider',function($httpProvider,routerproviderProvider) { //$httpProvider.interceptors.push('requestInterceptorfactory'); //注入全局请求拦截器 //注入X-Requested-With属性 $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'; //$httpProvider.defaults.headers.common['Content-Security-Policy'] = "script-src 'self'; object-src 'none'" }]); //运行阶段 ngApp.run(['$rootScope','$location','rolefactory',function($rootScope,$location,rolefactory) { //监听路由事件 $rootScope.$on('$stateChangeStart',function(event, toState, toParams, fromState, fromParams) { //if(toState.name == 'login') return;// 如果是进入登录界面则允许 }); //获得用户菜单 rolefactory.getUserMenu(); //获取用户信息,并保存至$rootScope rolefactory.getUserRoles(); }]); export default ngApp;
import React, { Component } from 'react'; import './App.css'; import mina1 from './data/mina1' class App extends Component { constructor(props) { super(props); this.state = { lesson: 1, words: mina1['l1'], index: 0, showVnese: false } this.onChangeLesson = this.onChangeLesson.bind(this); this.getRamdomWord = this.getRamdomWord.bind(this); this.showVnese = this.showVnese.bind(this); } onChangeLesson(lesson) { this.setState({lesson, words: mina1['l' + lesson], showVnese: false}); } getRamdomWord() { let words = this.state.words; let index = Math.floor(Math.random() * words.length); return this.setState({ index, showVnese: false }); } showVnese() { this.setState({ showVnese: true }); } renderNav() { let lessons = []; let keys = Object.keys(mina1); for (let i = 0; i < keys.length; i++) { lessons.push( <li key={i} className={`item ${i + 1 === this.state.lesson ? 'active' : ''}`} onClick={this.onChangeLesson.bind(null, i + 1)} > Lesson {i + 1} </li> ); } return ( <nav className="App-nav" id="nav"> <ul> <li> <span>Home</span> </li> <li> <span>Lesson {this.state.lesson}</span> <ul className="sub-menu">{lessons}</ul> </li> </ul> </nav> ) } renderBody() { let word = this.state.words[this.state.index]; return ( <div className="App-body"> <div className="kanji">{word[0] || word[1]}</div> <div className="hira">{word[1] || ''}</div> <div className="vnese">{this.state.showVnese ? word[2] : ''}</div> <div className="hint"> <span className="btn animated-button gibson-one" onClick={this.showVnese}>Vietnamese</span> <span className="btn animated-button victoria-two" onClick={this.getRamdomWord}>Next</span> </div> </div> ); } render() { return ( <div className="App" id="mina"> {this.renderNav()} {this.renderBody()} </div> ); } } export default App;
ROOT = process.cwd(); HELPERS = require(ROOT + '/helpers/general.js'); log = HELPERS.log; var config = require(ROOT + '/config.json'); var fs = require('fs'); var gm = require('gm').subClass({ imageMagick: true }); var sizeOf = require('image-size'); var path = require('path'); var formidable = require('formidable'); var util = require('util'); var fileExists = require('file-exists'); var users = require(ROOT + '/models/userModel.js'); var clubs = require(ROOT + '/models/clubModel.js'); var httpResponsesModule = require(ROOT + '/httpResponses/httpResponses.js'); var httpResponses = httpResponsesModule('user'); var hasAsFriend = function(friendlist, friendname){ for(i in friendlist){ if(friendlist[i] == friendname){ return true; } } return false; } linkProfilePicture = function(username, pictureLink){ log("Adding link: " + username + " -> " + pictureLink); users.findOne({username: username}, function(err, user){ if(user){ user.profilePicture = pictureLink; user.save(); } }); return; } module.exports = function () { return { getUser: function(username, res){ users.findOne({username: username}, function(err, user){ if (user){ log('found user!'); httpResponses.respondObject(res, user); }else{ httpResponses.sendFail(res, "No users found."); } }); return ; }, getUsers: function(req, res) { users.find(function(err, userz){ if(userz.length>0){ log('found users: ' + userz.length); httpResponses.respondObjects(res, userz); } }); return ; }, updateRating: function(username, newrating) { users.findOne({username: username}, function(err, user){ if(user){ if(newrating>user.maxRating){ user.maxRating = newrating; } user.rating = newrating; user.save(); log('User: ' + username + ", new rating: " + newrating); } }); return; }, updateUserLastSeen: function(username){ users.findOne({username: username}, function(err, user){ if(user){ user.lastSeen = Date.now; user.save(); log('User: ' + username + " - last seen: " + user.lastSeen); } }); return; }, addGame: function(username, gameid){ users.findOne({username: username}, function(err, user){ if(user){ user.games.push(gameis); for(i in user.friends){ addGameFromFriend(user.friends[i], gameid); } user.save(); log('User: ' + username + ' was part of a game!'); } }) return ; }, addGameFromFriend: function(username, gameid){ users.findOne({username: username}, function(err, user){ if(user){ var isInList = false; for(i in user.friendsTimeline){ if(gameid == user.friendsTimeline[i]){ isInList = true; } } if(!isInList){ user.friendsTimeline.push(gameid); user.save(); Log('Added game: ' + gameid + ", to user: " + username + " friends' timeline.") } } }); return; }, getGamesForUser: function(username, number, req, res){ users.findOne({username: username}, function(err, user){ if(err){ httpResponses.sendError(res, err); return; } var gamez = []; for(i in user.games){ gamez.unshift(user.games[i]); //now it's sorted } if(gamez.length()>number){ gamez = gamez.splice(number,(gamez.length-number)); } httpResponses.sendObjects(res, gamez); }); return; }, getGamesTimeline: function(username, number, req, res){ users.findOne({username: username}, function(err, user){ if(err) httpResponses.sendError(res, err); return; if(user){ var games = []; for(i in user.friendsTimeline){ games.unshift(user.friendsTimeline[i]); } if(games.length()>number){ games = gamez.splice(number,(gamez.length-number)); } httpResponses.sendObjects(res, gamez); } }); return; }, addFriend: function(username, friendname, firstfunction, req, res){ users.findOne({username: username}, function(err, user){ users.findOne({username: friendname}, function(err, friend){ if(!hasAsFriend(user.friends, friendname)){ user.friends.push(friendname); user.save(); if(firstfunction){ addFriend(friendname, username, false); httpResponses.sendOK(res, "friend added - " + friendname); return; } } }); }); if(req!=undefined && res!=undefined){ httpResponses.sendFail("friend adding fail - " + friendname); } }, getUsernames: function(req, res){ users.find({}) .sort({username: 1}) .select({username : 1, _id : 0}) .exec(function(err, userz){ if(err){ httpResponses.sendError(res, err); return; } response = []; for(i in userz) response.push(userz[i].username); log(response); httpResponses.respondPureString(res, response); return; }); }, uploadProfilePicture: function(req, res){ var form = new formidable.IncomingForm(); form.parse(req, function(err, fields, files){ req.files = files; log(util.inspect({fields: fields, files: files})); var dir = ROOT + '/uploads/profile/' + req.user.username + '/'; var fullpath = dir + req.files.image.name; var respath = path.resolve(fullpath); log(respath); if(!fs.existsSync(dir)){ fs.mkdirSync(dir); } fs.rename(files.image.path, respath, function(err){ if(err){ httpResponses.sendError(res, err); return; } else { linkProfilePicture(req.user.username, files.image.name); httpResponses.sendOK(res, "upload complete"); } }); return; }); }, getProfilePicture: function(req, res){ users.findOne({username: req.params.username}, function(err, user){ if(user){ if(user.profilePicture){ var imgLink = ROOT + '/uploads/profile/' + user.username + '/' + user.profilePicture; if(fs.existsSync(imgLink)){ var img = fs.readFileSync(imgLink); httpResponses.sendImage(res, img); return; } }else{ httpResponses.sendFail(res, "no profile picture"); return; } } else { httpResponses.sendError(res, "could not find user"); return; } }); }, getProfileIcon: function(req, res){ users.findOne({username: req.params.username}, function(err, user){ if(user){ if(user.profilePicture){ var iconLink = ROOT + '/uploads/profile/' + user.username + '/icon.jpg' if(fileExists(iconLink)){ img = fs.readFileSync(iconLink) httpResponses.sendImage(res, img); return; }else{ var imgLink = ROOT + '/uploads/profile/' + user.username + '/' + user.profilePicture; log(imgLink); var width = sizeOf(imgLink).width; var height = sizeOf(imgLink).height; var x_start = (width * 15 / 70).toFixed(); var x_total = (width * 40 / 70).toFixed(); gm(imgLink) .crop(x_total, height, x_start, 0) .resize(40,40) .write(iconLink, function (err){ if(err){ httpResponses.sendError(res, err); return; } log('File writing done!'); var img = fs.readFileSync(iconLink); if(img) httpResponses.sendImage(res, img); return; }); } } else { httpResponses.sendError(res, "could not find profilePicture"); return; } } else { httpResponses.sendError(res, "could not find user"); return; } }); }, postUser: function(req, res){ users.findOneAndUpdate( { username: req.user.username}, { firstName: req.body.firstName, lastName: req.body.lastName, about: req.body.about }, function(err, user){ if(err){ httpResponses.sendError(res, err); return; } if(user){ httpResponses.sendUsername(res, user.username); return; }else{ httpResponses.sendFail(res, "updating user fail"); return; } }); } } }
import styled from '@kuba/styled' export default styled` .button { align-items: center; border-radius: var(--border-radius-pill); font-family: var(--font-family-base); font-size: var(--font-size-xxs); font-weight: var(--font-weight-medium); display: flex; gap: var(--spacing_inset-nano); height: 40px; justify-content: center; line-height: var(--line-height-default); padding: var(--spacing_inset-nano) var(--spacing_inset-xs); } .primary { background-color: var(--color-master-dark); border: var(--border-width-hairline) solid var(--color-master-dark); color: var(--color-pure-white); } .secondary { background-color: var(--color-pure-white); border: var(--border-width-hairline) solid var(--color-master-dark); color: var(--color-master-dark); } `
import * as authTypes from "../ActionTypes/loginTypes"; import axios from "axios"; /** * Confirm if user is logged in. */ export const confirmLogin = () => async (dispatch) => { dispatch({ type: authTypes.CONFIRM_IF_LOGGED_IN, }); }; /** * Confirm if user is logged out. */ export const confirmLogout = () => async (dispatch) => { dispatch({ type: authTypes.CONFIRM_IF_LOGGED_OUT, }); }; /** Logs out the authenticated user. */ export const logout = () => async (dispatch) => { try { dispatch({ type: authTypes.LOGIN_OUT_REQUEST, }); await axios({ url: "/logout", method: "POST", }); // Reset localStorage localStorage.clear(); dispatch({ type: authTypes.LOGGED_OUT, }); } catch (err) { console.log(err); } };
import React, { Component } from 'react' // <img src={this.props.game.thumb_url.replace('https://s3-us-west-1.amazonaws.com/5cc.images/games/uploaded/','https://d2k4q26owzy373.cloudfront.net/150x150/games/uploaded/')} /> export class GameItem extends Component { render() { // console.log(this.props.favorites.findIndex(el => el.external_id === this.props.game.id)) return ( <tr> <td className={this.props.favorites.findIndex(el => el.external_id === this.props.game.id) !== -1 ? 'fav' : ''} onClick={() => this.props.handleFavorite(this.props.game, this.props.favorites.findIndex(el => el.external_id === this.props.game.id))}>❤</td> <td>{this.props.game.name}</td> <td>{this.props.game.year_published}</td> <td>{this.props.game.min_players}-{this.props.game.max_players}</td> <td>{this.props.game.min_playtime}-{this.props.game.max_playtime}</td> <td>{this.props.game.id}</td> </tr> ) } }
// pages/login/login.js const request = require("../../utils/request.js"); const dateUtil = require("../../utils/dateUtil.js"); const util = require("../../utils/util.js"); const app = getApp(); Page({ /** * 页面的初始数据 */ data: { canLogin: false, //mobileNo:"13701627785", mobileNo: "", smsCode: "", smsCodeGetStr: "获取验证码", unauthorized:false }, mobileNoInput(e) { this.data.mobileNo = e.detail.value; }, smsCodeInut(e) { this.data.smsCode = e.detail.value; }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { var pages = getCurrentPages(); var currPage = pages[pages.length - 1]; //当前页面 var prevPage = pages[pages.length - 2]; console.log(pages); }, smsCodeGetStrChange: function () { var that = this var smsCodeGetStr = this.data.smsCodeGetStr; var second = parseInt(this.data.smsCodeGetStr.substr(0, 2)) - 1; if (second > 0) { this.data.smsCodeGetStr = second + "秒"; if (second < 10) { this.data.smsCodeGetStr = "0" + this.data.smsCodeGetStr; } this.setData({ smsCodeGetStr: this.data.smsCodeGetStr }) setTimeout(function () { that.smsCodeGetStrChange() }, 1000); } else { this.data.smsCodeGetStr = "获取验证码"; this.setData({ smsCodeGetStr: this.data.smsCodeGetStr }) } }, //获取验证码 getCheckCode: function () { if (this.data.smsCodeGetStr != "获取验证码") { return; } var that = this; if (util.isBank(this.data.mobileNo)) { this.showErroeToast("请输入手机号码"); return; } if (!(/^1[34578]\d{9}$/.test(this.data.mobileNo))) { this.showErroeToast("手机号码不正确"); return; } var paramData = { req: { mobileNo: this.data.mobileNo } } request.request("","smallProgramApi", "sendLoginSmsCode", paramData, function (resp) { console.log(resp); if (resp.data.resp.resultData.status == "0000") { that.showErroeToast("发送成功"); that.data.canLogin = true; //60秒倒计时 that.data.smsCodeGetStr = "60秒"; that.setData({ smsCodeGetStr: that.data.smsCodeGetStr }) setTimeout(function () { that.smsCodeGetStrChange() }, 1000); } else { that.showErroeToast(resp.data.msg); } }, null) }, apiLogin:function(){ if (!app.globalData.isLogin) { wx.login({ success: function (res) { if (res.code) { var data = { apiWxLoginReq: { loginCode: res.code, // mobileNo: "120", needMobileNo: false } } request.request("", "smallProgramApi", "handleApiWxLogin", data, function (resp) { console.log(resp) if (resp.data.resp.resultData.status == app.globalData.successCode) { app.globalData.isLogin = true; let loginResp = resp.data.resp.resultData.data.loginResp; wx.setStorageSync("token", loginResp.token); wx.setStorageSync("expireTime", loginResp.expireTime); wx.setStorageSync("user", loginResp.user); app.globalData.user = loginResp.user; wx.setStorageSync("dept", loginResp.dept) wx.setStorageSync("roleList", loginResp.roleList); //进入首页 // wx.switchTab({ // url: '../index/index' // }) wx.navigateBack({ delta: 1 }) } else { console.error(resp.data.resp.resultData.msg); } }, function (resp) { }); } else { console.log('获取用户登录态失败!' + res.errMsg) } } }); } }, //登录接口 login: function () { var that = this; //todo:暂时注销 if(util.isBank(this.data.mobileNo)){ this.showErroeToast("请输入手机号码"); return; } if(util.isBank(this.data.smsCode)){ this.showErroeToast("请输入验证码"); return; } wx.login({ success: function (res) { if (res.code) { var paramData = { apiLoginReq: { mobileNo: that.data.mobileNo, smsCode: that.data.smsCode, loginCode: res.code, initUser: false, userInfo: JSON.stringify(app.globalData.userInfo) } } request.request("","smallProgramApi", "handleApiLogin", paramData, function (loginSuccessResp) { if(loginSuccessResp.data.resp.resultData.status !="0000"){ that.showErroeToast(loginSuccessResp.data.resp.resultData.msg); return ; } app.globalData.isLogin = true; console.log(loginSuccessResp); let loginResp = loginSuccessResp.data.resp.resultData.data.loginResp; //存储相关信息 wx.setStorageSync("token", loginResp.token); wx.setStorageSync("expireTime", loginResp.expireTime); wx.setStorageSync("user", loginResp.user); app.globalData.user = loginResp.user; wx.setStorageSync("dept", loginResp.dept) wx.setStorageSync("roleList", loginResp.roleList); //进入首页 wx.switchTab({ url: '../index/index' }) }, null) } else { console.log('获取用户登录态失败!' + res.errMsg) } } }) }, showErroeToast: function (msg) { wx.showToast({ title: msg, icon: 'none', duration: 2000 }) }, showSuccessToast: function (msg) { wx.showToast({ title: msg, icon: 'success', duration: 3000 }) }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { }, /** * 生命周期函数--监听页面显示 */ onShow: function () { console.log(app.globalData); let that = this; if (!app.globalData.userInfo) { this.getUserInfo(function(e){ that.apiLogin(); }); return; } console.log(app.globalData.isLogin,"show"); }, bindGetUserInfo: function (userResult) { let that = this; if (userResult.detail.errMsg == "getUserInfo:ok") { app.globalData.userInfo = userResult.detail.userInfo that.setData({ unauthorized: false }) that.apiLogin(); } }, getUserInfo: function (cb) { var that = this; if (app.globalData.userInfo) { typeof cb == "function" && cb(app.globalData.userInfo) } else { //调用登录接口 wx.getUserInfo({ withCredentials: false, success: function (res) { console.log(res); that.setData({ unauthorized: false }) app.globalData.userInfo = res.userInfo typeof cb == "function" && cb(app.globalData.userInfo) }, fail: function (userError) { if (userError.errMsg == 'getUserInfo:fail scope unauthorized' || userError.errMsg == 'getUserInfo:fail auth deny' || userError.errMsg == 'getUserInfo:fail:scope unauthorized' || userError.errMsg == 'getUserInfo:fail:auth deny') { that.setData({ unauthorized:true }) } } }) } }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { console.log("hide"); }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { var pages = getCurrentPages(); var currPage = pages[pages.length - 1]; //当前页面 var prevPage = pages[pages.length - 2]; //如果登录失败且上一个页面为bar 则点击返回就跳转到首页 if (!app.globalData.isLogin && prevPage.data.isBar){ wx.reLaunch({ url: '../index/index', }) return; } }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { } })
import createCanvas, { reset as resetMockCanvas, instances as mockCanvasInstances, } from 'utils/canvas'; import { loadAsImage, loadAsVideo, } from './contextProviders'; import gearUrl from '../../../image/icon/gear.png'; jest.mock('utils/canvas'); jest.mock('service/image'); jest.mock('utils/video'); describe('contextProvider', () => { afterEach(resetMockCanvas); describe('loadAsImage', () => { it('uses a canvasFactory', () => { const canvas = createCanvas(); const canvasFactory = jest.fn().mockReturnValue(canvas); const provider = loadAsImage({ canvasFactory, }); expect(provider.context).toEqual(canvas); expect(canvasFactory).toHaveBeenCalled(); }); it('uses a canvasInit', async () => { const canvasInit = jest.fn(); const provider = loadAsImage({ canvasInit, }); await provider.promise; expect(canvasInit).toHaveBeenCalledWith(expect.objectContaining({ canvas: mockCanvasInstances[0], })); }); it('can render with a renderer', async () => { const renderer = jest.fn(); const provider = loadAsImage({ renderer, }); const canvas = createCanvas(); provider.render(canvas); expect(renderer).toHaveBeenCalledWith(expect.objectContaining({ dstContext: canvas, srcContext: mockCanvasInstances[1], })); }); it('copies other fields', () => { const provider = loadAsImage({ foo: 'bar', }); expect(provider.foo).toEqual('bar'); }); }); describe('loadAsVideo', () => { it('uses a canvasFactory', () => { const canvas = createCanvas(); const canvasFactory = jest.fn().mockReturnValue(canvas); const provider = loadAsVideo({ canvasFactory, }); expect(provider.context).toEqual(canvas); expect(canvasFactory).toHaveBeenCalled(); }); it('uses a canvasInit', async () => { const canvasInit = jest.fn(); const provider = loadAsVideo({ canvasInit, }); await provider.promise; expect(canvasInit).toHaveBeenCalledWith(expect.objectContaining({ canvas: mockCanvasInstances[1], })); }); it('can render with a renderer', async () => { const renderer = jest.fn(); const provider = loadAsVideo({ renderer, }); const canvas = createCanvas(); provider.render(canvas); expect(renderer).toHaveBeenCalledWith(expect.objectContaining({ dstContext: canvas, srcContext: expect.any(Object), })); }); it('copies other fields', () => { const provider = loadAsVideo({ foo: 'bar', }); expect(provider.foo).toEqual('bar'); }); }); });
window.onload = function() { document.getElementById("calcular").onclick = function () { var valor = parseFloat(document.getElementById("valor").value); var desconto = parseFloat(document.getElementById("desconto").value); var valorAPagar = 0; if(document.getElementById("descontar").checked === true){ valorAPagar = valor - (valor * (desconto/100)); document.getElementById("resultado").innerHTML = "Valor a pagar: R$ " + valorAPagar; }else{ valorAPagar = valor + (valor * (desconto/100)); document.getElementById("resultado").innerHTML = "Valor a pagar: R$ " + valorAPagar; } console.log(valor); console.log(desconto); }; };
import { Bar } from "react-chartjs-2"; import API from "../utils/API"; import React, { useState, useEffect } from "react"; const Chart = () => { const [projInProgressJs, setProjInProgressJs] = useState([]); const [projCompleteJs, setProjCompleteJs] = useState(""); const [projInProgressReact, setProjInProgressReact] = useState([]); const [projCompleteReact, setProjCompleteReact] = useState(""); const [projInProgressAlg, setProjInProgressAlg] = useState([]); const [projCompleteAlg, setProjCompleteAlg] = useState(""); useEffect(() => { loadUserProjects(); }, []); const loadUserProjects = () => { API.getUser().then((res) => { console.log(res.data[0].projectsInProgress); console.log("comp", res.data[0].projectsComplete); var projInProgressArray = res.data[0].projectsInProgress; var projCompleteArray = res.data[0].projectsComplete; console.log(projInProgressArray); console.log(projCompleteArray); if (!projInProgressArray && !projCompleteArray) { alert("Please visit the project pages to add projects in progress."); } else { setProjInProgressJs( projInProgressArray.filter( (jsProjInProgress) => jsProjInProgress.language === "Javascript" ) ); setProjInProgressReact( projInProgressArray.filter( (reactProjInProgress) => reactProjInProgress.language === "React" ) ); setProjInProgressAlg( projInProgressArray.filter( (algProjInProgress) => algProjInProgress.language === "Algorithm" ) ); setProjCompleteJs( projCompleteArray.filter( (jsProjComplete) => jsProjComplete.language === "Javascript" ) ); setProjCompleteReact (projCompleteArray.filter( (reactProjComplete) => reactProjComplete.language === "React" ) ); setProjCompleteAlg( projCompleteArray.filter( (algProjComplete) => algProjComplete.language === "Algorithm" ) ); } }); }; const data = { labels: ["JavaScript", "Algorithms", "React"], datasets: [ { label: "In-progress", data: [ projInProgressJs.length, projInProgressAlg.length, projInProgressReact.length, ], backgroundColor: "rgb(255, 99, 132)", }, { label: "Completed", data: [ projCompleteJs.length, projCompleteAlg.length, projCompleteReact.length, ], backgroundColor: "rgb(54, 162, 235)", }, ], }; return ( <div className="container chart"> <h5 className="pageTitle text-center pt-5">My progress</h5> <Bar data={data} /> </div> ); }; export default Chart;
describe("csvToArray", function () { var output = csvToArray(csvData); describe("Output type", function () { it("should be an array", function () { expect(output).toEqual(jasmine.any(Array)); }); it("should be an array of arrays", function () { expect(output).toContain(jasmine.any(Array)); }); }); describe("Data", function () { it("should have 2 data lines", function () { expect(output.length).toEqual(2); }); it("first value of datarow should be a date", function () { expect(output[0][0]).toEqual(jasmine.any(Date)); }); it("second value of datarow should be a number", function () { expect(output[0][1]).toEqual(jasmine.any(Number)); }); it("first percentage should be 70", function () { expect(output[0][1]).toEqual(70); }); it("second percentage should be 60", function () { expect(output[1][1]).toEqual(60); }); }); });
const RandomNumber = () => { return Math.floor(Math.random() * (7 - 1) + 1); } export default RandomNumber
import clsx from 'clsx'; import path from 'path'; import { NavLink, useLocation } from 'react-router-dom'; import { getConfigKey, removeTrailingSlash } from '../utils'; import PropTypes from 'prop-types'; const Item = ({ label, path, root }) => { const labelClassName = clsx(root && "font-bold"); const activeClassName = clsx(!root && ["text-gray-800", "font-medium"]); return ( <> <span className={labelClassName}> <NavLink to={path} className="hover:text-light-blue-600 hover:underline" activeClassName={activeClassName} exact > {label} </NavLink> </span> <span className="text-gray-800 font-light">/</span> </> ); }; Item.propTypes = { label: PropTypes.string.isRequired, path: PropTypes.string.isRequired, root: PropTypes.bool, }; const Breadcrumb = (props) => { const location = useLocation(); const route = removeTrailingSlash(location.pathname.substring(1)); const items = route.length > 0 ? route.split("/") : []; const title = getConfigKey("name"); const containerClassName = clsx( props.className && props.className, "text-light-blue-600 space-x-2 text-sm md:text-lg", "overflow-x-auto whitespace-nowrap pretty-scrollbar" ); props = { ...props, className: containerClassName }; return ( <div {...props}> <Item label={title} path="/" root /> {items.map((value, index) => { const pathname = path.join("/", items.slice(0, index + 1).join("/"), "/"); return ( <Item key={index} label={value} path={pathname} /> ); })} </div> ); }; Breadcrumb.propTypes = { className: PropTypes.string }; export default Breadcrumb;
var defines________2____8js__8js_8js = [ [ "defines____2__8js_8js", "defines________2____8js__8js_8js.html#ae7cf347a70d4439059aadb4febb0fce0", null ] ];
const {resolve} = require('path'); const cmd = require('commander'); const convert = require('../convert'); const archives = require('../archives'); const pkg = require('../package.json'); cmd.version(pkg.version). option('--use-config', 'Use Config.'). option('--custom-highlight', 'Enable custom highlight.'). option('-s, --source [path]', 'Source dir.'). option('-d, --dist [path]', 'dist dir.'). usage(`--use-config true`). parse(process.argv); if (!cmd.args.length || cmd.args.length > 4 || !(cmd.source || cmd.useConfig)) { cmd.help(); process.exit(1); } if (cmd.useConfig) { const baseDir = resolve(__dirname, '..'); const config = require('../config.json'); config.jobs.forEach((job) => { if (job.source && job.dist) { const source = resolve(baseDir, job.source); const dist = resolve(baseDir, job.dist); const hl = Boolean(job.hl); convert(source, dist, hl); archives(source, dist); } }); } else { convert(cmd.source, cmd.dist, cmd.customHighlight); archives(cmd.source, cmd.dist); }
import React, { Component, PropTypes } from 'react'; class NavItem extends Component { constructor(props) { super(props); this.state = { active: this.props.active } this.handlerClick = this.handlerClick.bind(this); } handlerClick() { this.props.selectItem(this); } render() { var selected = this.props.isSelected; return ( <li onClick={this.handlerClick} role="presentation" className={selected == true ? "active" : ""}> <a href='javascript:void(0);"'> {this.props.label} </a> </li> ); } } NavItem.propTypes = { label: PropTypes.string.isRequired, href: PropTypes.string, isSelected: PropTypes.bool, key: PropTypes.number, selectItem: PropTypes.func, i: PropTypes.number } NavItem.defaultProps = { active: false, href: "/", isSelected: false } export default NavItem;
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Link } from 'react-router-dom'; import FormComponent from '../components/formComponent'; import data from '../../JSON/mockProducts.json'; import CouponsData from 'javascripts/components/couponsData'; import firebase from '../../../Firebase'; import Loading from 'javascripts/components/loading'; class ApplyCoupons extends Component { constructor(props) { super(props); this.ref = firebase.firestore().collection('coupon'); this.state = { coupon: [], loading: true, key: '', }; } onCollectionUpdate = (querySnapshot) => { const coupon = []; querySnapshot.forEach((doc) => { const { nameCoupon, descount, date } = doc.data(); coupon.push({ key: doc.id, doc, // DocumentSnapshot nameCoupon, descount, }); }); this.setState({ coupon, loading: false }); } componentDidMount() { this.unsubscribe = this.ref.onSnapshot(this.onCollectionUpdate); } render() { const { loading } = this.state; return ( <section id="apply" className={'apply'} ref="apply"> <div className="apply-block"> <div className="apply-limit limit-grid"> <h2 className="title"> Aplicar Cupons </h2> <p className="text"> Aplique descontos nos pedidos da sua loja. </p> <div className="apply-content"> <ul className="apply-coupon"> { data.Products.map((product) => { return ( <li className="apply-coupons-items"> <div className="apply-coupons-items-image"> <img className="apply-coupons-items-image--user" src="/src/images/user-apply.png" alt="user" /> {product.titleProduct} </div> <div className="apply-coupons-items-price"> {product.priceProduct} </div> <div className="apply-coupons-items-coupon"> <FormComponent placeholder="Cupom" type='text' name='coupon' className="input-group" /> <button className="input-icon"> <img className="input-icon-add" src="/src/images/icon-add.png" alt="add" /> </button> </div> </li> ); }) } </ul> <div className="apply-available"> <div className="apply-available--text"> <h3 className="apply-available-text">Cupons Disponíveis</h3> <h4 className="apply-available-link"><Link to="/gerenciar-cupons"> Editar Cupons </Link></h4> </div> <ul className="apply-available-items"> {this.state.coupon.map(item => ( <CouponsData path={item.key} code={item.nameCoupon} descount={`-${item.descount}%`} /> ))} </ul> </div> </div> </div> </div> </section> ); } } const mapStateToProps = state => { return { user: state.user }; }; export default connect(mapStateToProps)(ApplyCoupons);
const crypto = require('crypto'); var generateRandomString = function (length) { var text = ''; var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; for (var i = 0; i < length; i++) { text += possible.charAt(Math.floor(Math.random() * possible.length)); } return text; }; function sha512(password, salt) { var hash = crypto.createHmac('sha512', salt); /** Hashing algorithm sha512 */ hash.update(password); var value = hash.digest('hex'); return { salt: salt, passwordHash: value }; }; function getRandom(arr, n) { var result = new Array(n), len = arr.length, taken = new Array(len); if (n > len) throw new RangeError("getRandom: more elements taken than available"); while (n--) { var x = Math.floor(Math.random() * len); result[n] = arr[x in taken ? taken[x] : x]; taken[x] = --len in taken ? taken[len] : len; } return result; } module.exports = { sha512, generateRandomString, getRandom };
const frontendURL = 'https://samahan.addu.edu.ph'; const backendURL = 'https://samahan-api.addu.edu.ph'; const cdnURL = 'https://samahan.stdcdn.com'; module.exports = { frontendURL, backendURL, cdnURL };
const { questoes } = require("./questoes"); async function apagar(pesquisaId) { try { await questoes.findOneAndDelete({ _id: pesquisaId }); return "feito"; } catch (error) { return "error" } } exports.apagar = apagar;
document.write('\ </ul>\ </div>\ </div>\ </nav>\ </div>\ </header>\ ');
"use strict"; // const url = "https://api.cederdorff.com/wp-json/wp/v2/posts"; const url = "https://api.cederdorff.com/wp-json/wp/v2/posts?_embed"; fetch(url) .then(function(response) { return response.json(); }) .then(function(posts) { console.log(posts); appendPosts(posts); }); // append wp posts to the DOM function appendPosts(posts) { let htmlTemplate = ""; for (let post of posts) { console.log(post); htmlTemplate += ` <article> <img src="${getFeaturedImageUrl(post)}"> <h3>${post.title.rendered}</h3> <p>${post.content.rendered}</p> </article> `; } document.querySelector('#content').innerHTML = htmlTemplate; } // get the featured image url function getFeaturedImageUrl(post) { let imageUrl = ""; if (post._embedded['wp:featuredmedia']) { imageUrl = post._embedded['wp:featuredmedia'][0].source_url; } return imageUrl; }
export const NOT_OCCUPIED = 'NOT_OCCUPIED'; export const OCCUPIED_WHITE ='OCCUPIED_WHITE'; export const OCCUPIED_BLACK ='OCCUPIED_BLACK';
var db = require('../db'); module.exports = { messages: { get: function (req, res) { db.connect.query('SELECT * FROM messages', function(err,result){ if(err) throw err; res.send(JSON.stringify(result)); }); }, // a function which produces all the messages post: function (req, res) { db.connect.query('INSERT INTO messages SET ?', req.body, function(err){ if(err) throw err; }); } // a function which can be used to insert a message into the database }, users: { // Ditto as above. get: function (req, res) { console.log('inside the get require') db.connect.query('SELECT * FROM users', function(err,result){ if(err) throw err; res.send(JSON.stringify(result)); }); }, post: function (req, res) { console.log('inside on models post for users') db.connect.query('INSERT INTO users SET ?', req.body, function(err){ if(err) throw err; }); } } };
/* Author: Pradeep Khodke URL: http://www.codingcage.com/ */ $('document').ready(function() { /* validation */ // valid email pattern $("#admin-form").validate({ errorElement: 'div', errorClass: 'help-block', focusInvalid: true, ignore: "", rules: { token: { required: true, maxlength: 100, minlength: 50 }, }, messages: { token:{ required: "Masukkan Token Akses Admin!", maxlength: "Maximal Hanya 100 Karakter!", minlength: "Minimal 50 Karakter!" }, }, errorPlacement : function(error, element) { $(element).closest('.form-group').find('.help-block').html(error.html()); }, highlight : function(element) { $(element).closest('.form-group').removeClass('has-success').addClass('has-error'); }, unhighlight: function(element, errorClass, validClass) { $(element).closest('.form-group').removeClass('has-error'); $(element).closest('.form-group').find('.help-block').html(''); }, submitHandler: submitForm }); /* validation */ /* post submit */ function submitForm() { var data = $("#admin-form").serialize(); $.ajax({ type : 'POST', url : 'ajax/admin_process.php', data : data, beforeSend: function() { $("#error").fadeOut(); $("#btn-admin").html('<span class="fa fa-exchange fa-pulse fa-fw"></span> Mohon tunggu ...'); }, success : function(response) { if(response=="Akses Admin Diterima!"){ $("#btn-admin").html('<i class="fa fa-spinner fa-pulse fa-fw"></i> Mengecek ...').prop('disabled', true); $("#error").fadeIn(1000, function(){ toastr.success(''+response+'', {timeOut: 5000}); $("#btn-admin").html('<span class="fa fa-check"></span> Akses Admin Diterima!').prop('disabled', true); setTimeout('window.location.replace("https://ayoklarifikasi.com/home.html")', 1000); }); } else { $("#error").fadeIn(1000, function(){ toastr.error(''+response+'', {timeOut: 5000}); $("#btn-admin").html('<span class="fa fa-pencil"></span> Submit'); }); } } }); return false; } /* post submit */ });
const express = require("express") const router = express.Router() const controller = require("../controller/posts") const auth = require("../controller/auth") // API router.get("/likes/:id", controller.like) // 공감 개수 조회 router.post("/likes/:id", controller.updateLike) // 공감 개수 수정 router.post("/like/:id", controller.isLike) // 공감 여부 확인 router.get("/write", auth.authenticateUser, controller.writePost) // REST API router.options("/", controller.options) router.get("/ranking", controller.ranking) router.get("/", controller.list) // 목록조회 router.get("/:id", controller.detail) // 상세조회 router.post("/", controller.create) // 등록 router.post("/:id", controller.createError) // 등록 에러 router.put("/:id", controller.update) // 전체 수정 router.patch("/:id", controller.patch) // 일부 수정 router.delete("/", controller.erase) // 전체 삭제, 개발자 남용 금지 router.delete("/:id", controller.remove) // 선택 삭제 module.exports = router
import { Mongo } from 'meteor/mongo'; import SimpleSchema from 'simpl-schema'; import { Tracker } from 'meteor/tracker'; /** Create a Meteor collection. */ const Data = new Mongo.Collection('Data'); /** Create a schema to constrain the structure of documents associated with this collection. */ const BagSchema = new SimpleSchema({ type: String, category: String, weight: Number, volume: Number, notes: String, }); const DataSchema = new SimpleSchema({ campus: String, building: String, date: String, timeStart: String, timeEnd: String, bagTare: { type: Number, optional: true, }, notes: String, bags: [BagSchema], // removeEmptyStrings: false allows empty strings to count as values }, { clean: { removeEmptyStrings: false }, tracker: Tracker }); /** Attach this schema to the collection. */ Data.attachSchema(DataSchema); /** Make the collection and schema available to other code. */ export { Data, DataSchema };
jQuery(document).on("ready", iniciar); function hacerLogin( e ) { e.preventDefault(); var datos = jQuery(this).serialize(); // jQuery.ajax // ({ // type: "GET", // url: "ws/login_office", // dataType: "json", // data: datos, // success: function ( result ) // { // if( result.result ) // { // //toastr["success"](result.message, 'Éxito'); // setTimeout( "window.location.href = '../public/'" , 1000 ); // } // else // console.log(result); // }, // error: function ( err ) // { // console.log(err); // } // }); } function iniciar( e ) { jQuery("#form-login").on("submit", hacerLogin); }
var ADD_DELAY = 1000; var list = document.querySelectorAll(".audio_row"); console.log(`Total songs: ${list.length}`); function add(el, audio_obj) { setTimeout(function(){ console.log(`${audio_obj.title} added`); AudioUtils.addAudio(el, audio_obj); }, ADD_DELAY); } list.forEach(function(el, num) { let audio_obj = AudioUtils.asObject(AudioUtils.getAudioFromEl(el)); add(el, audio_obj); });
/* 订单详情 内在灵魂,沉稳坚毅 生成时间:Fri Nov 11 2016 破门狂人R2-D2为您服务! */ define('DriverCenter', [ 'avalon', 'text!../../package/DriverCenter/DriverCenter.html', 'css!../../package/DriverCenter/DriverCenter.css', 'dic', '../../obj/bridge/Drivers.js', '../../lib/hey/hey' ], function (avalon, html, css, dic, Drivers) { //构建基础字段 var base = {} avalon.mix(base, dic) base.info = Drivers.obj var vm = avalon.define(avalon.mix({ $id: "DriverCenter", // 传入的i为用户编号UID!! ready: function (i) { var obj = '' if (obj != "") { require(['../../obj/Management/' + obj + '.js'], function () { start() }) } else { start() } function start() { if(i==0){ i=cache.go('UID'); } vm.reset(); index.html = html; //以及其他方法 //传入的i为用户编号UID!! vm.UID = i; vm.getDriverInfo(i); vm.$watch('tab_which', function (a, b) { setTimeout(function () { avalon.mix(vm, { list: [], P: 1, N: 6, T: 0 }); vm.getDriverOrder(1) }, 300) }) } }, reset: function () { avalon.mix(vm, { tab_which: "left", info: { User: { Company: {} } } }) }, tab_which: "left", RS: false, //由于数据渲染刷新采用的是刷新list数组,因此,添加一个responseStatus作为中间状态。 orderList: function () { vm.tab_which = 'left'; vm.RS = false; }, orderChase: function () { vm.tab_which = 'right'; vm.RS = false; }, //获取司机信息 UID: "", getDriverInfo: function (UID) { //require(['../../obj/bridge/User'], function (obj) { // obj.get(UID, function (res) { // vm.info=res // }) //}) require(['../../obj/bridge/Drivers'], function (obj) { obj.search({ P: 1, N: 9999999999999999, W: { UID: vm.UID, } }, function (res) { //var info=res.L[0] // //ForEach(info, function (el, key) { // if(typeof el=='object'){ // // ForEach(el, function (al,al_kay) { // vm.info[key][al_kay]=al // }) // return // } // vm.info[key]=el //}) if(res.L.length==0){ //当前用户不是司机,跳转客户中心 goto('#!/CusCenter/0') return } vm.info = res.L[0]; vm.getDriverOrder(1) }) }) }, //获取订单 list: [], P: 1, N: 6, T: 0, getDriverOrder: function (P) { var data = { P: P, N: vm.N, W: {} } switch (vm.tab_which) { case 'left': //获取司机的订单 data.W = { AssignDriverID: ['EQ', vm.info.DriverID], SnapDriverID: ['EQ', vm.info.DriverID], _logic: 'or' }; break; case 'right': //获取抢单列表 data.W.Status = 3;//已经发起了抢单才可以抢 break } vm.RS = true; require(['../../obj/bridge/Order'], function (obj) { obj.search(data, function (res) { avalon.mix(vm, { P: res.P, T: res.T }); vm.list = []; // vm.list = res.L; vm.list = vm.list.concat(res.L); vm.list.forEach(function (el) { //遍历数组,填充路径 vm.getAddress(el); }); }); }); }, getAddress: function (el) { //根据类型判断获取路径点的函数 el.beginAddress = el.endAddress = el.otherAddress = " "; //新增的本地变量,当路径为空,为渲染时不将表达式渲染出来 el.Routers.forEach(function (al) { if (al.TypeID == 1 && al.Address) { el.beginAddress += al.Address; } else if (al.TypeID == 2 && al.Address) { el.otherAddress += " " + al.Address + " " } else if (al.TypeID == 3 && al.Address) { el.endAddress += al.Address } }) }, //详情 MyOrdersInfo: function (OrderID) { goto("#!/OrderInfo/" + OrderID + "&&driver/"); }, //抢单 $opthey: { id: "hey", tipType: 'both_double', //仅当参数为both时,显示为确定和取消 titleColor: "#ff0000", btn1Color: "#777777", btn2Color: "#000066", }, snap: function (id) { require(['../../obj/bridge/Order'], function (obj) { obj.snap(id, vm.info.DriverID, function (res) { hey.confirmLR("提示", "恭喜您抢单成功,正在进行抢单审核!", "查看", function () { // console.info("这里是左侧的回调函数"); vm.MyOrdersInfo(id); hey.close(); }, "确认", function () { // console.info("这里是右侧的回调函数"); hey.close(); }); }, function (err) { tip.on("抢单失败", 0, 3000); console.error(err); } ) }) } }, base)); window.setInterval(function () { vm.getDriverOrder(); },2000); return window[vm.$id] = vm })
import createDays from './calculator'; export const calc = (jobId, date, weekOffset, location) => { const days = createDays(date, weekOffset, location); return { jobId, days }; };
let buttonColours = ["red", "blue", "green", "yellow"]; let gamePattern = []; let userClickedPattern = []; var level = 0; var started = false; function HeaderText(){ $("#level-title").text("Your Level is " + level); } function nextSequence(){ userClickedPattern = []; var randomNumber = Math.round(Math.random() * 3); //generate random number var randomChosenColour = buttonColours[randomNumber]; // use random # to find color at // that index & store in var gamePattern.push(randomChosenColour); //store that color in array $("#" + randomChosenColour).fadeOut(80).fadeIn(80).fadeOut(80).fadeIn(80); //flash button playSound(randomChosenColour); //play sound assoc with random button } function increaseLevel(){ level++; //change the level HeaderText(); //display the new level } function playSound(name){ var newAudio = "sounds/" + name + ".mp3"; $( "#audio" ).attr( "src", newAudio ); $('audio#audio')[0].play(); // var audio = new Audio("sounds/" + name + ".mp3"); // audio.play(); } function animatePress(currentColour){ $("#" + currentColour).addClass("pressed"); //adds pressed class!! setTimeout(function(){ // removes press class after 50ms $("#" + currentColour).removeClass("pressed"); },100); } function checkAnswer(currentLevel, userColour){ if (userClickedPattern[currentLevel] === gamePattern[currentLevel] ){ if (userClickedPattern.length === gamePattern.length){ setTimeout(function() { nextSequence(); increaseLevel(); },1000); } } else { console.log("wrong"); playSound("wrong"); $("body").addClass("game-over"); setTimeout(function(){ $("body").removeClass("game-over"); }, 200); $("h1").text("Game Over, Press Any Key To Restart") startOver(); } } function startOver() { level = 0; gamePattern = []; started = false; } $(document).on("keypress", function(){ if (!started){ level++; nextSequence(); HeaderText(); started = true; } else { alert("You already pressed a key") } }) $(document).on('click', '.btn', function(){ var userChosenColour = $(this).attr('id'); //id of button clicked userClickedPattern.push(userChosenColour); // store button click in array var indexOfLastClick = userClickedPattern.lastIndexOf(userChosenColour); playSound(userChosenColour); //play sound of button color animatePress(userChosenColour); //animate button pressed checkAnswer(indexOfLastClick, userChosenColour); console.log("id = " + userChosenColour); console.log("Clicked pattern: " + userClickedPattern); console.log("game pattern: "+ gamePattern); console.log("index is: " + indexOfLastClick); });
const expect = require('chai').expect; const handler = require('../../src/exports/handler'); const settings = require('../../src/exports/settings'); const jsl = require('../../src/adapters/json.like'); describe('JSON Like - Object - Equal Properties', () => { it('object equals - empty', () => { const actual = {}; const expected = {}; expect(jsl.validate(actual, expected)).equals(''); }); it('object equals - different types of properties', () => { const actual = { id: 1, name: 'bob', minor: true, any: null, age: 8 }; const expected = { id: 1, name: 'bob', minor: true, any: null, age: /\d+/ }; expect(jsl.validate(actual, expected)).equals(''); }); it('object not equals - one property - number', () => { const actual = { id: 1 }; const expected = { id: 2 }; expect(jsl.validate(actual, expected)).equals(`Json doesn't have value '2' at '$.id' but found '1'`); }); it('object not equals - one property - different types', () => { const actual = { id: 1 }; const expected = { id: '1' }; expect(jsl.validate(actual, expected)).equals(`Json doesn't have type 'string' at '$.id' but found 'number'`); }); it('object not equals - different types - actual array', () => { const actual = [{ id: 1 }]; const expected = { id: '1' }; expect(jsl.validate(actual, expected)).equals(`Json doesn't have type 'object' at '$' but found 'array'`); }); it('object not equals - different types - expected array', () => { const expected = [{ id: 1 }]; const actual = { id: '1' }; expect(jsl.validate(actual, expected)).equals(`Json doesn't have type 'array' at '$' but found 'object'`); }); it('object not equals - one property - string', () => { const actual = { id: "1" }; const expected = { id: "2" }; expect(jsl.validate(actual, expected)).equals(`Json doesn't have value '2' at '$.id' but found '1'`); }); it('object not equals - one property - boolean', () => { const actual = { id: false }; const expected = { id: true }; expect(jsl.validate(actual, expected)).equals(`Json doesn't have value 'true' at '$.id' but found 'false'`); }); it('object not equals - one property - null', () => { const actual = { id: {} }; const expected = { id: null }; expect(jsl.validate(actual, expected)).contains(`Json doesn't have value 'null' at '$.id' but found`); }); it('object not equals - one property - RegEx', () => { const actual = { id: 1 }; const expected = { id: /\W+/ }; expect(jsl.validate(actual, expected)).equals(`Json doesn't match with '/\\W+/' at '$.id' but found '1'`); }); it('object not equals - multiple properties', () => { const actual = { id: 1, name: 'hunt' }; const expected = { id: 1, name: 'bent' }; expect(jsl.validate(actual, expected)).equals(`Json doesn't have value 'bent' at '$.name' but found 'hunt'`); }); it('nested objects equals - multiple properties', () => { const actual = { id: 1, name: 'hunt', scores: { maths: 90, social: 80, sciences: { physics: 40, chemistry: 45 } } }; const expected = { id: 1, name: 'hunt', scores: { maths: 90, social: 80, sciences: { physics: 40, chemistry: 45 } } }; expect(jsl.validate(actual, expected)).equals(''); }); it('nested objects not equals - multiple properties', () => { const actual = { id: 1, name: 'hunt', scores: { maths: 90, social: 80, sciences: { physics: 40, chemistry: 45 } } }; const expected = { id: 1, name: 'hunt', scores: { maths: 90, social: 80, sciences: { physics: 50, chemistry: 45 } } }; expect(jsl.validate(actual, expected)).equals(`Json doesn't have value '50' at '$.scores.sciences.physics' but found '40'`); }); }); describe('JSON Like - Object - Extra Properties', () => { it('object not equals - one property', () => { const actual = { id: "1" }; const expected = { name: "2" }; expect(jsl.validate(actual, expected)).equals(`Json doesn't have property 'name' at '$'`); }); it('object equals - multiple properties', () => { const actual = { id: 1, name: 'hunt' }; const expected = { id: 1 }; expect(jsl.validate(actual, expected)).equals(''); }); it('object not equals - multiple properties', () => { const actual = { id: 1, name: 'hunt' }; const expected = { id: 1, age: 26 }; expect(jsl.validate(actual, expected)).equals(`Json doesn't have property 'age' at '$'`); }); it('nested object equals - multiple properties', () => { const actual = { id: 1, name: 'hunt', scores: { maths: 90, social: 80 } }; const expected = { name: 'hunt', scores: { social: 80, } }; expect(jsl.validate(actual, expected)).equals(''); }); it('nested object not equals - multiple properties', () => { const actual = { id: 1, name: 'hunt', scores: { maths: 90, social: 80 } }; const expected = { id: 1, name: 'hunt', scores: { maths: 90, social: 80, art: 12 } }; expect(jsl.validate(actual, expected)).equals(`Json doesn't have property 'art' at '$.scores'`); }); it('nested objects equals - multiple properties', () => { const actual = { id: 1, name: 'hunt', scores: { maths: 90, social: 80, sciences: { physics: 40, chemistry: 45 } } }; const expected = { name: 'hunt', scores: { social: 80, sciences: { physics: 40 } } }; expect(jsl.validate(actual, expected)).equals(''); }); it('nested objects not equals - multiple properties', () => { const actual = { id: 1, name: 'hunt', scores: { maths: 90, social: 80, sciences: { physics: 40, chemistry: 45 } } }; const expected = { id: 1, name: 'hunt', scores: { maths: 90, social: 80, sciences: { physics: 40, chemistry: 45, biology: 21 } } }; expect(jsl.validate(actual, expected)).equals(`Json doesn't have property 'biology' at '$.scores.sciences'`); }); }); describe('JSON Like - Array', () => { it('array equals - empty', () => { const actual = []; const expected = []; expect(jsl.validate(actual, expected)).equals(''); }); it('array equals - one item - number', () => { const actual = [1]; const expected = [1]; expect(jsl.validate(actual, expected)).equals(''); }); it('array not equals - one item - number', () => { const actual = [1]; const expected = [2]; expect(jsl.validate(actual, expected)).equals(`Json doesn't have value '2' at '$[0]' but found '1'`); }); it('array equals - multiple items - number', () => { const actual = [1, 2, 3]; const expected = [1, 2, 3]; expect(jsl.validate(actual, expected)).equals(''); }); it('array equals - multiple items (reverse order) - number', () => { const actual = [1, 2, 3]; const expected = [3, 2, 1]; expect(jsl.validate(actual, expected)).equals(''); }); it('array not equals - multiple expected items', () => { const actual = [1]; const expected = [2, 3]; expect(jsl.validate(actual, expected)).equals(`Json doesn't have 'array' with length '2' at '$' but found 'array' with length '1'`); }); it('array not equals - multiple actual items', () => { const actual = [1, 4]; const expected = [2, 3]; expect(jsl.validate(actual, expected)).equals(`Json doesn't have value '2' at '$[0]' but found '1'`); }); it('array not equals - multiple actual items - last item doesn\'t match', () => { const actual = [1, 4]; const expected = [1, 3]; expect(jsl.validate(actual, expected)).equals(`Json doesn't have value '3' at '$[1]' but found '4'`); }); it('nested array equals - multiple items - number', () => { const actual = [[1, 2], [2, 4]]; const expected = [[1, 2], [2, 4]]; expect(jsl.validate(actual, expected)).equals(''); }); it('nested array equals - multiple items (reverse) - number', () => { const actual = [[1, 2], [2, 4]]; const expected = [[2, 4], [1, 2]]; expect(jsl.validate(actual, expected)).equals(''); }); it('nested array not equals - multiple items - number', () => { const actual = [[1, 2], [2, 4]]; const expected = [[1, 2], [3, 5]]; expect(jsl.validate(actual, expected)).equals(`Json doesn't have value '3' at '$[1][0]' but found '2'`); }); it('nested array not equals - multiple actual items - number', () => { const actual = [[1, 2], [2, 4], [3, 4]]; const expected = [[1, 2], [3, 5]]; expect(jsl.validate(actual, expected)).equals(`Json doesn't have value '3' at '$[1][0]' but found '2'`); }); it('array equals - multiple expected items - number', () => { const actual = [1, 2, 3, 2]; const expected = [2, 2]; expect(jsl.validate(actual, expected)).equals(''); }); it('array not equals - multiple expected items - number', () => { const actual = [1, 2, 3]; const expected = [2, 2]; expect(jsl.validate(actual, expected)).equals(`Json doesn't have expected value at '$[1]'`); }); }); describe('JSON Like Array of Objects', () => { it('equals - empty arrays', () => { const actual = [{}]; const expected = [{}]; expect(jsl.validate(actual, expected)).equals(''); }); it('equals - empty expected array', () => { const actual = [{ id: 1 }]; const expected = [{}]; expect(jsl.validate(actual, expected)).equals(''); }); it('equals - array of one object with one property', () => { const actual = [{ id: 1 }]; const expected = [{ id: 1 }]; expect(jsl.validate(actual, expected)).equals(''); }); it('not equals - array of one object with one property', () => { const actual = [{ id: 1 }]; const expected = [{ id: 2 }]; expect(jsl.validate(actual, expected)).equals(`Json doesn't have value '2' at '$[0].id' but found '1'`); }); it('equals - array of one object with multiple properties', () => { const actual = [{ id: 1, name: 'hunt' }]; const expected = [{ id: 1, name: 'hunt' }]; expect(jsl.validate(actual, expected)).equals(''); }); it('not equals - array of one object with multiple properties', () => { const actual = [{ id: 1, name: 'hunt' }]; const expected = [{ id: 1, name: 'bent' }]; expect(jsl.validate(actual, expected)).equals(`Json doesn't have value 'bent' at '$[0].name' but found 'hunt'`); }); it('equals - array of one nested object', () => { const actual = [{ id: 1, name: 'hunt', scores: { maths: 90, social: 80 } }]; const expected = [{ id: 1, name: 'hunt', scores: { maths: 90, social: 80 } }]; expect(jsl.validate(actual, expected)).equals(''); }); it('not equals - array of one nested object', () => { const actual = [{ id: 1, name: 'hunt', scores: { maths: 90, social: 80 } }]; const expected = [{ id: 1, name: 'hunt', scores: { maths: 90, social: 70 } }]; expect(jsl.validate(actual, expected)).equals(`Json doesn't have value '70' at '$[0].scores.social' but found '80'`); }); it('equals - array of one with nested objects', () => { const actual = [{ id: 1, name: 'hunt', scores: { maths: 90, social: 80, sciences: { physics: 40, chemistry: 45 } } }]; const expected = [{ id: 1, name: 'hunt', scores: { maths: 90, social: 80, sciences: { physics: 40, chemistry: 45 } } }]; expect(jsl.validate(actual, expected)).equals(''); }); it('not equals - array of one with nested objects', () => { const actual = [{ id: 1, name: 'hunt', scores: { maths: 90, social: 80, sciences: { physics: 40, chemistry: 45 } } }]; const expected = [{ id: 1, name: 'hunt', scores: { maths: 90, social: 80, sciences: { physics: 30, chemistry: 45 } } }]; expect(jsl.validate(actual, expected)).equals(`Json doesn't have value '30' at '$[0].scores.sciences.physics' but found '40'`); }); it('equals - array of one with nested objects & array of numbers', () => { const actual = [{ id: 1, name: 'hunt', scores: { maths: 90, social: 80, sciences: { physics: 40, chemistry: 45 }, languages: [21, 22] } }]; const expected = [{ id: 1, name: 'hunt', scores: { maths: 90, social: 80, sciences: { physics: 40, chemistry: 45 }, languages: [21, 22] } }]; expect(jsl.validate(actual, expected)).equals(''); }); it('not equals - array of one with nested objects & array of numbers', () => { const actual = [{ id: 1, name: 'hunt', scores: { maths: 90, social: 80, sciences: { physics: 40, chemistry: 45 }, languages: [21, 22] } }]; const expected = [{ id: 1, name: 'hunt', scores: { maths: 90, social: 80, sciences: { physics: 40, chemistry: 45 }, languages: [20, 22] } }]; expect(jsl.validate(actual, expected)).equals(`Json doesn't have value '20' at '$[0].scores.languages[0]' but found '21'`); }); it('equals - array of one with nested objects & array of objects', () => { const actual = [{ id: 1, name: 'hunt', scores: { maths: 90, social: 80, sciences: { physics: 40, chemistry: 45 }, languages: [ { english: 44, telugu: 49 }, { english: 42, telugu: 50 } ] } }]; const expected = [{ id: 1, name: 'hunt', scores: { maths: 90, social: 80, sciences: { physics: 40, chemistry: 45 }, languages: [ { english: 44, telugu: 49 }, { english: 42, telugu: 50 } ] } }]; expect(jsl.validate(actual, expected)).equals(''); }); it('not equals - array of one with nested objects & array of objects', () => { const actual = [{ id: 1, name: 'hunt', scores: { maths: 90, social: 80, sciences: { physics: 40, chemistry: 45 }, languages: [ { english: 44, telugu: 49 }, { english: 42, telugu: 50 } ] } }]; const expected = [{ id: 1, name: 'hunt', scores: { maths: 90, social: 80, sciences: { physics: 40, chemistry: 45 }, languages: [ { english: 44, telugu: 49 }, { english: 41, telugu: 50 } ] } }]; expect(jsl.validate(actual, expected)).equals(`Json doesn't have value '41' at '$[0].scores.languages[1].english' but found '42'`); }); it('equals - array of multiple with nested objects & array of objects', () => { const actual = [ { id: 1, name: 'hunt', scores: { maths: 90, social: 80, sciences: { physics: 40, chemistry: 45 }, languages: [ { english: 44, telugu: 49 }, { english: 42, telugu: 50 } ] } }, { id: 2, name: 'bent', scores: { maths: 99, social: 60, sciences: { physics: 49, chemistry: 46 }, languages: [ { english: 43, telugu: 42 }, { english: 41, telugu: 40 } ] } } ]; const expected = [{ id: 1, name: 'hunt', scores: { maths: 90, social: 80, sciences: { physics: 40, chemistry: 45 }, languages: [ { english: 44, telugu: 49 }, { english: 42, telugu: 50 } ] } }]; expect(jsl.validate(actual, expected)).equals(''); }); it('equals - array of multiple with nested objects & array of objects - trimmed expected', () => { const actual = [ { id: 1, name: 'hunt', scores: { maths: 90, social: 80, sciences: { physics: 40, chemistry: 45 }, languages: [ { english: 44, telugu: 49 }, { english: 42, telugu: 50 } ] } }, { id: 2, name: 'bent', scores: { maths: 99, social: 60, sciences: { physics: 49, chemistry: 46 }, languages: [ { english: 43, telugu: 42 }, { english: 41, telugu: 40 } ] } } ]; const expected = [ { id: 1, name: 'hunt', scores: { maths: 90, social: 80, sciences: { physics: 40, chemistry: 45 }, languages: [ { english: 44, telugu: 49 }, { english: 42, telugu: 50 } ] } }, { id: 2, name: 'bent', scores: { social: 60, sciences: { chemistry: 46 }, languages: [ { english: 43, }, { telugu: 40 } ] } } ]; expect(jsl.validate(actual, expected)).equals(''); }); it('not equals - array of multiple with nested objects & array of objects - trimmed expected', () => { const actual = [ { id: 1, name: 'hunt', scores: { maths: 90, social: 80, sciences: { physics: 40, chemistry: 45 }, languages: [ { english: 44, telugu: 49 }, { english: 42, telugu: 50 } ] } }, { id: 2, name: 'bent', scores: { maths: 99, social: 60, sciences: { physics: 49, chemistry: 46 }, languages: [ { english: 43, telugu: 42 }, { english: 41, telugu: 40 } ] } } ]; const expected = [ { id: 1, name: 'hunt', scores: { maths: 90, social: 80, sciences: { physics: 40, chemistry: 45 }, languages: [ { english: 44, telugu: 49 }, { english: 42, telugu: 50 } ] } }, { id: 2, name: 'bent', scores: { social: 60, sciences: { chemistry: 46 }, languages: [ { english: 42, }, { telugu: 40 } ] } } ]; expect(jsl.validate(actual, expected)).equals(`Json doesn't have value '42' at '$[1].scores.languages[0].english' but found '43'`); }); it('equals - different order', () => { const actual = [ { id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }, { id: 6 } ]; const expected = [ { id: 4 }, { id: 3 }, { id: 5 }, { id: 6 }, { id: 2 }, { id: 1 } ]; expect(jsl.validate(actual, expected)).equals(''); }); it('not equals - different order', () => { const actual = [ { id: 1 }, { id: 2 }, { id: 3 }, { id: 4 } ]; const expected = [ { id: 4 }, { id: 3 }, { id: 1 }, { id: 1 } ]; expect(jsl.validate(actual, expected)).equals(`Json doesn't have expected value at '$[3]'`); }); }); describe('JSON Like - Assert Expressions', () => { it('object fulfil simple expression', () => { const actual = { id: 1 }; const expected = { id: '$V === 1'}; expect(jsl.validate(actual, expected)).equals(''); }); it('object does not fulfil simple expression', () => { const actual = { id: 1 }; const expected = { id: '$V > 1'}; expect(jsl.validate(actual, expected)).equals(`Json doesn't fulfil expression '$.id > 1'`); }); it('array fulfil simple expression', () => { const actual = [{ id: 1 }]; const expected = '$V.length === 1'; expect(jsl.validate(actual, expected)).equals(''); }); it('array does not fulfil simple expression', () => { const actual = [{ id: 1 }]; const expected = '$V.length > 1'; expect(jsl.validate(actual, expected)).equals(`Json doesn't fulfil expression '$.length > 1'`); }); it('object fulfil complex expression', () => { const actual = { id: 1, marks: { maths: 70 } }; const expected = { id: 1, marks: { maths: '$V > 50' } }; expect(jsl.validate(actual, expected)).equals(''); }); it('object does not fulfil complex expression', () => { const actual = { id: 1, marks: { maths: 70 } }; const expected = { id: 1, marks: { maths: '$V > 80' } }; expect(jsl.validate(actual, expected)).equals(`Json doesn't fulfil expression '$.marks.maths > 80'`); }); it('object fulfil simple custom includes expression', () => { settings.setAssertExpressionStrategy({ includes: '$' }); const actual = { id: 1 }; const expected = { id: '$ === 1'}; expect(jsl.validate(actual, expected)).equals(''); }); afterEach(() => { settings.setAssertExpressionStrategy({ includes: '$V' }); }); }); describe('JSON Like - Assert Handlers', () => { before(() => { handler.addAssertHandler('number', (ctx) => { return typeof ctx.data === 'number'; }); handler.addAssertHandler('type', (ctx) => { return typeof ctx.data === ctx.args[0]; }); }); it('object fulfil simple assert', () => { const actual = { id: 1 }; const expected = { id: '#number'}; expect(jsl.validate(actual, expected)).equals(''); }); it('object does not fulfil simple assert', () => { const actual = { id: '1' }; const expected = { id: '#number'}; expect(jsl.validate(actual, expected)).equals(`Json doesn't fulfil assertion '#number' at '$.id'`); }); it('object fulfil simple assert with args', () => { const actual = { id: 1 }; const expected = { id: '#type:number'}; expect(jsl.validate(actual, expected)).equals(''); }); it('simple assert does not exist', () => { const actual = { id: '1' }; const expected = { id: '#number py'}; expect(jsl.validate(actual, expected)).equals(`Json doesn't have value '#number py' at '$.id' but found '1'`); }); it('object fulfil simple custom starts with assert', () => { settings.setAssertHandlerStrategy({ starts: '#$' }); const actual = { id: 1 }; const expected = { id: '#$number'}; expect(jsl.validate(actual, expected)).equals(''); }); it('object fulfil simple custom ends with assert', () => { settings.setAssertHandlerStrategy({ ends: '#$' }); const actual = { id: 1 }; const expected = { id: 'number#$'}; expect(jsl.validate(actual, expected)).equals(''); }); it('object fulfil simple custom starts & ends with assert', () => { settings.setAssertHandlerStrategy({ starts: '#$', ends: '$#' }); const actual = { id: 1 }; const expected = { id: '#$number$#'}; expect(jsl.validate(actual, expected)).equals(''); }); it('simple assert satisfies only one strategy', () => { settings.setAssertHandlerStrategy({ starts: '#', ends: '$#' }); const actual = { id: '1' }; const expected = { id: '#number'}; expect(jsl.validate(actual, expected)).equals(`Json doesn't have value '#number' at '$.id' but found '1'`); }); afterEach(() => { settings.setAssertHandlerStrategy({ starts: '#' }); }); });
import * as types from './types'; export function updateUserScore(score) { return { type: types.UPDATE_USER_SCORE, score, }; } export function updateMachineScore(score) { return { type: types.UPDATE_MACHINE_SCORE, score, }; } export function updateDrawScore(score) { return { type: types.UPDATE_MACHINE_SCORE, score, }; };
/** * File: activities collection * Author: Filip Jarno * Date: 27.11.2014 */ define([ 'backbone', 'models/activity' ], function (Backbone, Activity) { 'use strict'; app.collections.Activities = Backbone.Collection.extend({ initialize: function (data, options) { this.temporaryModels = []; this.on('add remove', function () { if (this.length > options.maxLength) { this.temporaryModels.push(this.pop()); } if (this.length < options.maxLength && this.temporaryModels.length) { this.add(this.temporaryModels.pop()); } }, this); }, temporaryModels: null, comparator: function (activity) { return -activity.get('date'); }, model: Activity }); return app.collections.Activities; });
import React from 'react'; import { StyleSheet, Text, View } from 'react-native'; import SmoothPinCodeInput from 'react-native-smooth-pincode-input'; export default class App extends React.Component { state = { code: '', password: '', }; pinInput = React.createRef(); _checkCode = (code) => { if (code != '1234') { this.pinInput.current.shake() .then(() => this.setState({ code: '' })); } } render() { const { code, password } = this.state; return ( <View style={styles.container}> {/* default */} <View style={styles.section}> <Text style={styles.title}>Default</Text> <SmoothPinCodeInput ref={this.pinInput} value={code} onTextChange={code => this.setState({ code })} onFulfill={this._checkCode} onBackspace={() => console.log('No more back.')} /> </View> {/* password */} <View style={styles.section}> <Text style={styles.title}>Password</Text> <SmoothPinCodeInput password mask="﹡" cellSize={36} codeLength={8} value={password} onTextChange={password => this.setState({ password })}/> </View> {/* underline */} <View style={styles.section}> <Text style={styles.title}>Underline</Text> <SmoothPinCodeInput cellStyle={{ borderBottomWidth: 2, borderColor: 'gray', }} cellStyleFocused={{ borderColor: 'black', }} value={code} onTextChange={code => this.setState({ code })} /> </View> {/* customized */} <View style={styles.section}> <Text style={styles.title}>Customized</Text> <SmoothPinCodeInput placeholder="⭑" cellStyle={{ borderWidth: 2, borderRadius: 24, borderColor: 'orange', backgroundColor: 'gold', }} cellStyleFocused={{ borderColor: 'darkorange', backgroundColor: 'orange', }} textStyle={{ fontSize: 24, color: 'salmon' }} textStyleFocused={{ color: 'crimson' }} value={code} onTextChange={code => this.setState({ code })} /> </View> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', alignItems: 'center', justifyContent: 'center', }, section: { alignItems: 'center', margin: 16, }, title: { fontSize: 16, fontWeight: 'bold', marginBottom: 8, }, });
import { setParam, getParam } from "../HelperFunctions/HelperFunctions.js"; export function receiveLobbyData(data) { setParam("redPlayerCount", data.redPlayerCount); setParam("bluePlayerCount", data.bluePlayerCount); } export function receivePlayerList(list) { setParam("playerList", list); console.log("Received player list: ", list); }
class Contact{ constructor(id, name, email, lastName ){ this.id = id this.name = name this.email = email this.lastName = lastName } get name(){return this.name} get email(){return this.email} get lastName(){return this.lastName} toJson = function (){ return ("{" + "\"id\":\"" + this.id + "\"," + "\"name\":\"" + this.name + "\"," + "\"email\":\"" + this.email + "\"," + "\"lastName\":" + this.lastName + "}"); } }
import React from 'react'; import Welcome from './welcome'; import Clock from './Clock'; import Toggle from './Toggle'; import LoginControl from './Greeting'; import Mailbox from './Mailbox'; import WarningBanner from './WarningBanner'; import List from './List'; import ListItem from './ListItem'; import Blog from './Blog'; import NameForm from './NameForm'; import EssayForm from './Form/EssayForm'; import FlavorForm from './Form/FlavorForm'; import ReservationForm from './Form/Reservation'; // import Calculator from './Calculator'; import { Calculator } from './liftStateUp' const messages = ['React', 'Re: React', 'Re:Re React']; const numbers = [1,2,3,4,5]; const posts = [ {id: 1, title: 'Hello world', content: 'Welcome to learning React!'}, {id: 2, title: 'Installation', content: 'You can install React from npm.'} ]; import Forwaring from '../advanced/useButton'; import ContextTheme from '../advanced/contextApi'; import ThemeButton from '../advanced/theme-app'; export default function App(props) { return ( <div> <ThemeButton /> {/* <ContextTheme /> */} {/* <Forwaring /> */} {/* <Calculator /> */} {/* <ReservationForm /> <FlavorForm /> <NameForm /> <EssayForm /> */} {/* <Clock /> <Toggle /> <LoginControl isLoggedIn={false} /> <Mailbox unreadMessages={messages} /> <WarningBanner /> <List numbers={numbers}></List> <ListItem numbers={numbers}></ListItem> <Blog posts={posts} /> */} </div> ); }
var shell = require('shell'); var bootbox = require('bootbox'); var Q = require('q'); var os = require('os'); /*************************************************************** Global items for access from all modules / files ***************************************************************/ require('./class.GenericSettings'); require('./class.OpenAppHackSettings'); require('./class.OpenAppHackPlugin'); // container for openapphack data window.openapphack = {}; // settings data that will be written to settings.json; the only exception is // window.openapphack.settings.plugins.##.instance, which is meant for temporary // plugin-related data, and gets auto-removed by storage during save operation window.openapphack.settings = function () {}; // the nav click callback will set this to the plugin responsible for the // clicked nav item window.active_plugin = false; /** * Helper to load custom modules. Alleviates the need to provide a * relative filepath when loading a custom module from somewhere other than * a file in /app/ * * @param {[type]} src [description] * @return {[type]} [description] */ window.load_mod = function (src) { return require('./' + src + '.js'); } // shortcut reference var settings = window.openapphack.settings; var qc = load_mod('tools/qchain'); var nav = load_mod('components/nav'); var openapphackenv_running = false; var OpenAppHackENV_START = "start"; var OpenAppHackENV_STOP = "stop"; var OpenAppHackENV_PROVISION = "provision"; var OpenAppHackENV_RELOAD = "reload"; // groups of startup operations; these will be performed sequentially; // each operation will only execute if the previous one completed successfully; // these are separated into sub-groups so that a grouped subset of these // operations can be re-executed at a later time (ex. running plugins and nav ops // again when the "manage plugins" form is updated) window.openapphack_operations = { boot: [], plugins: [], nav: [] }; window.reloadCurrentView = function (callback) { nav.reloadCurrentView(callback); }; /** * Runs operations in specified groups. * * @param {[type]} groups [description] * @param {[type]} args [description] * @param {[type]} success [description] * @param {[type]} error [description] * @param {[type]} step [description] * @return {[type]} [description] */ window.runOps = function (groups, args, success, error, step) { // default to all groups groups = groups || Object.keys(window.openapphack_operations); // default callbacks var success = success || function () {}; var error = error || function () {}; var step = step || function () {}; // default arguments passed to each op var args = args || []; // build a flat array of operations from the desired groups var ops = []; for (var i in groups) { if (window.openapphack_operations.hasOwnProperty(groups[i])) { for (var j in window.openapphack_operations[groups[i]]) { ops.push(window.openapphack_operations[groups[i]][j]); } } } // build a chain of promises from the operations var chain = Q.fcall(function (){}); var op_count = 0; ops.forEach(function (item) { var link = function () { var deferred = Q.defer(); item.apply(item, args).then(function (result) { op_count++; step(op_count, ops.length); deferred.resolve(result); }, function (error) { deferred.reject(error); }); return deferred.promise; }; chain = chain.then(link); }); chain.then(success, error); }; $(document).ready(function () { // build and run startup operations var boot = load_mod('internal/boot'); var dialog = load_mod('components/dialog').create('Reading configuration...'); var ops = window.openapphack_operations; // boot group ops.boot.push(boot.loadSettings); ops.boot.push(boot.checkPluginsDir); // plugins group ops.plugins.push(boot.checkPlugins); ops.plugins.push(boot.bootPlugins); // navigation group ops.nav.push(boot.buildNavigation); // promise chain success callback var success = function (result) { dialog.hide(); nav.loadFile(window.openapphack.public_path + '/views/dashboard/dashboard.html', function (error) { if (error) { console.log('Error: ' + error); } // save the dialog's content for use in dashboard.js window.openapphack.settings.views.dashboard.boot_log = encodeURI(dialog.getContent()); }); }; // promise chain error callback var error = function (error) { dialog.append(error, 'error'); }; // promise chain step callback var step = function (count, total) { dialog.setProgress(count / total * 100); }; runOps(null, [dialog], success, error, step); }); // ------ Event Hookups ------ // $("#provisionLink").click(function () { if(openapphackenv_running) { controlENV(OpenAppHackENV_PROVISION); } else { controlENV(OpenAppHackENV_START); } }); $("#openapphackenv_start").click(function () { controlENV(OpenAppHackENV_START); }); $("#openapphackenv_stop").click(function () { controlENV(OpenAppHackENV_STOP); }); $("#openapphackenv_provision").click(function () { if(openapphackenv_running) { controlENV(OpenAppHackENV_PROVISION); } else { controlENV(OpenAppHackENV_START); } }); function openapphackENVProcessing(modalTitle) { var contents = "<div class='progress'>"; contents+= "<div class='progress-bar progress-bar-striped active' role=progressbar' aria-valuenow='100' aria-valuemin='0' aria-valuemax='100' style='width: 100%''>"; contents+= "<span class='sr-only'>100% Complete</span>"; contents+= "</div>"; contents+= "</div>"; contents+= "Details"; contents+= "<div id='processingLog'>"; contents+= "<pre></pre>"; contents+= "</div>"; var dialog = bootbox.dialog({ title: modalTitle, message: contents }); } function controlENV(action) { var title = ''; var cmd = ''; switch(action) { case OpenAppHackENV_START: cmd = 'up' title = 'Starting ENV'; break; case OpenAppHackENV_STOP: cmd = 'halt'; title = 'Stopping ENV'; break; case OpenAppHackENV_PROVISION: cmd = 'provision'; title = 'Re-provisioning ENV'; break; case OpenAppHackENV_RELOAD: cmd = 'reload'; title = 'Reloading ENV'; break; } var spawn = require('child_process').spawn; var child = spawn('vagrant', [cmd, settings.ENV.id]); var dialog = load_mod('components/dialog').create(title); dialog.logProcess(child); child.on('exit', function (exitCode) { switch(action) { case OpenAppHackENV_START: if (!window.openapphack.ENV.needs_reprovision) { updateENVStatus(dialog); return; } controlENV(OpenAppHackENV_PROVISION); break; case OpenAppHackENV_STOP: case OpenAppHackENV_RELOAD: updateENVStatus(dialog); break; case OpenAppHackENV_PROVISION: hide_reprovision_notice(); updateENVStatus(dialog); break; } }); }
var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); var port = process.env.PORT || 3000; app.get('/', function (req, res) { var ip = req.connection.remoteAddress; res.send('<h1>Signal Server Running on ' + ip + ':' + port + '</h1>'); // res.sendFile(__dirname + '/index.html'); }); /** default namespace / This namespace is identified by io.sockets or simply io var nsp = io.of('/my-namespace'); nsp.on('connection', function(socket){ console.log('someone connected'); }); nsp.emit('hi', 'everyone!'); --------------- var socket = io('/my-namespace'); =============== io.to('some room').emit('some event'); io.in('some room').emit('some event'); Each Socket in Socket.IO is identified by a random, unguessable, unique identifier Socket#id. For your convenience, each socket automatically joins a room identified by this id io.to(id).emit('my message', msg); socket.broadcast.to(id).emit('my message', msg); */ /*io.on('connection', function (socket) { console.log('a user connected'); socket.on('disconnect', function () { console.log('user disconnected'); }); socket.on('chat message', function (msg) { console.log('message: ' + msg); }); });*/ //map key-value var userMap = {}; // var jsonList = []; //为了防止误解 client 替代 socket io.on('connection', function (client) { client.removeAllListeners(); console.log('-- ' + client.id + ' connection --'); // client.on('doLogin', function (options, callback) { console.log('-- ' + client.id + ' doLogin ' + options + ' --'); if (callback) { //返回socketId callback(client.id); } //赋值 var js = JSON.parse(options); js.socketId = client.id; options = JSON.stringify(js); userMap[client.id] = options; client.broadcast.emit('onLogin', options); io.emit('onUserChange', userMap); console.log('-- userMap json ' + JSON.stringify(userMap) + ' --'); }); client.on('doLogout', function (options) { console.log('-- ' + client.id + ' doLogout ' + options + ' --'); delete userMap[client.id]; client.broadcast.emit('onLogout', options); io.emit('onUserChange', userMap); console.log('-- userMap json ' + JSON.stringify(userMap) + ' --'); }); // client.on('disconnect', function () { console.log('-- ' + client.id + ' disconnect --'); //附加一步 移除断线客户端的用户信息 处理部分设备未正常退出 delete userMap[client.id]; io.emit('onUserChange', userMap); console.log('-- userMap json ' + JSON.stringify(userMap) + ' --'); }); //转发 client.on('message', function (options) { // var otherClient = io.sockets.connected[details.to]; io.emit('message', options); }); //请求呼叫 client.on('doVideoChat', function (options) { console.log('-- ' + client.id + ' doVideoChat --'); //对方 socketId var to_socketId = JSON.parse(options.too).socketId; if (to_socketId === client.id) { return } /* if (io.sockets.connected[to_socketId]) { io.sockets.connected[to_socketId].emit("onVideoChat", options); console.log('-- ' + client.id + ' emit onVideoChat ' + to_socketId + ' --'); }*/ io.to(to_socketId).emit('onVideoChat', options); console.log('-- ' + client.id + ' emit onVideoChat ' + to_socketId + ' --'); }); client.on('doVideoChatAgree', function (options) { console.log('-- ' + client.id + ' doVideoChatAgree --'); //对方 socketId //同意 呼叫发起方还是 from //所以是告诉 from !!! var from_socketId = JSON.parse(options.from).socketId; if (from_socketId === client.id) { return } /*if (io.sockets.connected[to_socketId]) { io.sockets.connected[to_socketId].emit("onVideoChatAgree", options); console.log('-- ' + client.id + ' emit onVideoChatAgree ' + to_socketId + ' --'); }*/ //所以是告诉 from !!! io.to(from_socketId).emit('onVideoChatAgree', options); console.log('-- ' + client.id + ' emit onVideoChatAgree ' + from_socketId + ' --'); }); // client.on('doCreateOffer', function (options) { console.log('-- ' + client.id + ' doCreateOffer ' + options + ' --'); //对方 socketId var to_socketId = options.to_socketId; if (to_socketId === client.id) { return } /*if (io.sockets.connected[to_socketId]) { io.sockets.connected[to_socketId].emit("onCreateOffer", options); console.log('-- ' + client.id + ' emit onCreateOffer ' + to_socketId + ' --'); }*/ io.to(to_socketId).emit("onCreateOffer", options); console.log('-- ' + client.id + ' emit onCreateOffer ' + to_socketId + ' --'); }); // client.on('doCreateAnswer', function (options) { console.log('-- ' + client.id + ' doCreateAnswer ' + options + ' --'); //对方 socketId //应答 呼叫发起方还是 from //所以是告诉 from !!! var from_socketId = options.from_socketId; if (from_socketId === client.id) { return } //所以是告诉 from !!! /* if (io.sockets.connected[from_socketId]) { io.sockets.connected[from_socketId].emit("onCreateAnswer", options); console.log('-- ' + client.id + ' emit onCreateAnswer ' + from_socketId + ' --'); }*/ io.to(from_socketId).emit("onCreateAnswer", options); console.log('-- ' + client.id + ' emit onCreateAnswer ' + from_socketId + ' --'); }); // client.on('doCandidate', function (options) { console.log('-- ' + client.id + ' doCandidate ' + options + ' --'); //对方 socketId var to_socketId = options.to_socketId; if (to_socketId === client.id) { return } /* if (io.sockets.connected[to_socketId]) { io.sockets.connected[to_socketId].emit("onCandidate", options); console.log('-- ' + client.id + ' onCandidate ' + options + ' --'); }*/ io.to(to_socketId).emit("onCandidate", options); console.log('-- ' + client.id + ' emit onCandidate ' + to_socketId + ' --'); }); client.on('doCallEnd', function (options) { console.log('-- ' + client.id + ' doCallEnd --'); //暂时不区分是谁挂断的 var from_socketId = options.from_socketId; /* if (io.sockets.connected[from_socketId]) { io.sockets.connected[from_socketId].emit("onCallEnd", options); console.log('-- ' + client.id + ' onCallEnd ' + from_socketId + ' --'); }*/ io.to(from_socketId).emit("onCallEnd", options); console.log('-- ' + client.id + ' emit onCallEnd ' + from_socketId + ' --'); var to_socketId = options.to_socketId; /* if (io.sockets.connected[to_socketId]) { io.sockets.connected[to_socketId].emit("onCallEnd", options); console.log('-- ' + client.id + ' onCallEnd ' + to_socketId + ' --'); }*/ io.to(to_socketId).emit("onCallEnd", options); console.log('-- ' + client.id + ' emit onCallEnd ' + to_socketId + ' --'); }); client.on('videoChatReject', function (options) { console.log('-- ' + client.id + ' videoChatReject ' + options + ' --'); var from_socketId = JSON.parse(options.from).socketId; io.to(from_socketId).emit('videoChatReject', options); }); client.on('isBeBusy', function (options) { console.log('-- ' + client.id + ' isBeBusy ' + options + ' --'); //对方 socketId var from_socketId = JSON.parse(options.from).socketId; io.to(from_socketId).emit('isBeBusy', options); }); /* client.on('message', function (options) { var otherClient = io.sockets.connected[details.to]; io.sockets.emit('message', userMap); });*/ /* if (streams.getStreams().length > 0) { client.emit('id2', streams.getOtherStream(client.id)); client.emit('callMe', client.id); } else { client.emit('id', client.id); } */ /* client.on('login', function (options) { console.log('-- ' + client.id + ' ' + options + ' is login --'); idList.push(client.id); nameList.push(options); io.sockets.emit('idList', idList); io.sockets.emit('nameList', nameList); });*/ /* client.on('message', function (details) { var otherClient = io.sockets.connected[details.to]; if (!otherClient) { return; } delete details.to; details.from = client.id; otherClient.emit('message', details); });*/ /*client.on('readyToStream', function (options) { console.log('-- ' + client.id + ' ' + options + ' is ready to stream --'); streams.addStream(client.id, options.name); });*/ // console.log('--getStreams ' + streams.getStreams()) /*client.on('update', function (options) { streams.update(client.id, options.name); });*/ /* function leave() { console.log('-- ' + client.id + ' left --'); streams.removeStream(client.id); //leave leave leave idList.removeByValue(client.id); io.sockets.emit('idList', idList); }*/ /*client.on('logout', function (options) { console.log('-- ' + client.id + ' ' + options + ' left --'); nameList.removeByValue(options); io.sockets.emit('nameList', nameList); });*/ /* client.on('disconnect', function (client) { console.log('-- ' + client.id + ' disconnect --'); });*/ // client.on('leave', leave); // /* client.on('EVENT_USER_LOGIN', function (options) { console.log('== ' + client.id + ' ' + options + ' user_login --'); io.sockets.emit('EVENT_USER_LOGIN', options); jsonList.push(options); io.sockets.emit('EVENT_USER_CHANGE', jsonList); }); client.on('EVENT_USER_LOGOUT', function (options) { console.log('== ' + client.id + ' ' + options + ' user_logout --'); io.sockets.emit('EVENT_USER_LOGOUT', options); for (var i = 0; i < jsonList.length; i++) { if (jsonList[i].key_userId == options.key_userId) { jsonList.splice(i, 1);//deleteCount 1 break; } } io.sockets.emit('EVENT_USER_CHANGE', jsonList); }); client.on('EVENT_USER_MESSAGE', function (options) { console.log('== ' + client.id + ' ' + options + ' user_message --'); io.sockets.emit('EVENT_USER_MESSAGE', options); });*/ }); //不指定 hostname req.connection.remoteAddress 获取到 ::ffff:192.168.0.111 /*http.listen(port, function () { console.log('listening on ' + port); });*/ //指定 hostname req.connection.remoteAddress 获取到 192.168.0.111 http.listen(port, '0.0.0.0', function () { console.log('listening on ' + port); });
import {combineReducers} from 'redux-immutable' // local libs import errorMessageReducer from 'src/generic/ErrorMessage/reducers' export default combineReducers({ errorMessage: errorMessageReducer })
import { useEffect, useState } from "react"; import sportFacade from "../facades/sportFacade"; import { Modal } from "react-bootstrap"; export default function SportTeams({roles}) { const [player, setPlayer] = useState({}); const [coach, setCoach] = useState({}); const [allSportTeams, setAllSportTeams] = useState([]); const [allSports, setAllSports] = useState([]); const [isOpen, setIsOpen] = useState(false); const [isEdit, setIsEdit] = useState(false); const [msg, setMsg] = useState(""); const [error, setError] = useState(""); let initialState = {sportId: 0, teamName: "", description: "", pricePerYear: "", minAge: "", maxAge: "", players: [], coaches: []} const [sportTeam, setSportTeam] = useState(initialState); useEffect(() => { sportFacade.getAllSportTeams() .then(sportTeams => setAllSportTeams([...sportTeams])); sportFacade.getAllSports() .then(sports => setAllSports([...sports])); if (roles.includes("player")) { sportFacade.getPlayerByUsername(localStorage.getItem("user")) .then(playerFromDb => setPlayer({...playerFromDb})); } else if (roles.includes("coach")) { sportFacade.getCoachByUsername(localStorage.getItem("user")) .then(coachFromDb => setCoach({...coachFromDb})); } }, [msg]) const handleChange = (e) => { setSportTeam({ ...sportTeam, [e.target.id]: e.target.value }); } const handleSubmit = (e) => { e.preventDefault(); let team = {...sportTeam}; delete team.sportId; team["sport"] = {id: parseInt(sportTeam.sportId)}; team.pricePerYear = parseFloat(team.pricePerYear); if (!isEdit) { sportFacade.addSportTeam(team) .then(addedSportTeam => { setMsg(addedSportTeam.teamName + " has been added to the database.") setError(""); }) .catch((promise) => { if (promise.fullError) { printError(promise, setError); } else { setError("No response from API.") } }) } else { if (typeof sportTeam.sportId === "undefined") { team.sport.id = sportTeam.sport.id; } else { team.sport.id = parseInt(sportTeam.sportId); } sportFacade.editSportTeam(team, parseInt(team.id)) .then(editedTeam => { setMsg(editedTeam.teamName + " has been edited.") setError(""); }) .catch((promise) => { if (promise.fullError) { printError(promise, setError); } else { setError("No response from API.") } }) } } const toggleModal = (e) => { setError(""); setMsg("") setIsOpen(!isOpen); if (typeof e !== "undefined" && e.target.id === "add") { setIsEdit(false); setSportTeam({...initialState}); } } const deleteTeam = (e) => { e.preventDefault(); sportFacade.deleteSportTeam(parseInt(e.target.id)) .then(deletedTeam => setMsg(`${deletedTeam.teamName} has been deleted.`)) .catch((promise) => { if (promise.fullError) { printError(promise, setError); } else { setError("No response from API.") } }) setTimeout(() => { setMsg(""); }, 8000); } const editTeam = (e) => { setIsEdit(true); toggleModal(); sportFacade.getSportTeamById(parseInt(e.target.id)) .then(team => setSportTeam({...team})) } const signUpAsPlayer = (e) => { sportFacade.addPlayerToTeam(player, parseInt(e.target.id)) .then(playerFromDb => setMsg(`Congratulations, ${playerFromDb.name}! You've joined ${e.target.name}!`)) .catch((promise) => { if (promise.fullError) { printError(promise, setError); setMsg(""); } else { setError("No response from API.") } }) } const signUpAsCoach = (e) => { sportFacade.addCoachToTeam(coach, parseInt(e.target.id)) .then(coachFromDb => setMsg(`Congratulations, ${coachFromDb.name}! You've joined ${e.target.name}!`)) .catch((promise) => { if (promise.fullError) { printError(promise, setError); setMsg(""); } else { setError("No response from API.") } }) } return ( <div> <br /> <h1>Sport Teams</h1> <br /> {roles.includes("admin") && ( <div> <button className="btn btn-danger" id="add" onClick={toggleModal}> Add sport team </button> <br /><br /> </div> )} <p style={{color: "green"}}>{msg}</p> <p style={{color: "red"}}>{error}</p> <div className="container" style={{backgroundColor: "white"}}> <table className="table table-bordered"> <thead className="thead thead-dark"> <tr> <th>Sport</th> <th>Team name</th> <th>Description</th> <th>Price per year</th> <th>Minimum age</th> <th>Maximum age</th> <th>Number of players</th> <th>Number of coaches</th> <th></th> <th></th> </tr> </thead> <tbody> {allSportTeams.map(sportTeam => { return ( <tr key={sportTeam.id}> <td>{sportTeam.sport.name}</td> <td>{sportTeam.teamName}</td> <td>{sportTeam.description}</td> <td>{sportTeam.pricePerYear} DKK</td> <td>{sportTeam.minAge}</td> <td>{sportTeam.maxAge}</td> <td>{sportTeam.players.length}</td> <td>{sportTeam.coaches.length}</td> <td>{roles.includes("admin") ? (<button className="btn btn-danger" onClick={deleteTeam} id={sportTeam.id}>Delete</button>) : roles.includes("player") ? <button className="btn btn-danger" onClick={signUpAsPlayer} id={sportTeam.id} name={sportTeam.teamName}>Join as player</button> : ""} </td> <td>{roles.includes("admin") ? (<button className="btn btn-danger" onClick={editTeam} id={sportTeam.id}>Edit</button>) : roles.includes("coach") ? <button className="btn btn-danger" onClick={signUpAsCoach} id={sportTeam.id} name={sportTeam.teamName}>Join as coach</button> : ""} </td> </tr> ) })} </tbody> </table> </div> <Modal show={isOpen} onHide={toggleModal}> <Modal.Header closeButton> <Modal.Title>{isEdit ? "Edit a sport team" : "Add a sport"}</Modal.Title> </Modal.Header> <Modal.Body> <div style={{textAlign: "center"}}> <form onSubmit={handleSubmit}> <label>{isEdit ? `Select a sport (current: )` : "Select a sport"} </label><br /> <select onChange={handleChange} id="sportId" className="form-control" style={{width: "210px", marginLeft: "130px"}}> {allSports.map(sport => { return ( <option key={sport.id} value={sport.id} > {sport.name} </option> ) })} </select> <br /> <label>Team name</label><br /> <input id="teamName" value={sportTeam.teamName} onChange={handleChange} /> <br /> <label>Description</label><br /> <input id="description" value={sportTeam.description} onChange={handleChange} /> <br /> <label>Price per year</label><br /> <input id="pricePerYear" value={sportTeam.pricePerYear} onChange={handleChange} /> <br /> <label>Minimum age</label><br /> <input id="minAge" value={sportTeam.minAge} onChange={handleChange} /> <br /> <label>Maximum age</label><br /> <input id="maxAge" value={sportTeam.maxAge} onChange={handleChange} /> <br /> <br /> <input type="submit" value={isEdit ? "Edit" : "Add"} className="btn btn-danger"> </input> </form> <br /> <p style={{color : "green"}}>{msg}</p> <p style={{color: "red"}}>{error}</p> </div> </Modal.Body> </Modal> </div> ) } const printError = (promise, setError) => { promise.fullError.then(function (status) { setError(`${status.message}`); }); };
import React, { Link ,props} from 'react'; export default Secu;
import React,{Component} from 'react' import AvatarEditor from 'react-avatar-editor' export default class ImageEditor extends Component { constructor(props) { super(props) this.imgChangeHandle = this.imgChangeHandle.bind(this) this.setEditorRef = this.setEditorRef.bind(this) this.saveImgHandle = this.saveImgHandle.bind(this) this.scaleHandle = this.scaleHandle.bind(this) this.smallHandle = this.smallHandle.bind(this) this.bigHandle = this.bigHandle.bind(this) this.state={ scale: 1 } } saveImgHandle(){ if (this.editor) { // This returns a HTMLCanvasElement, it can be made into a data URL or a blob, // drawn on another canvas, or added to the DOM. // console.log(typeof (this.editor.getImage())); const canvas = this.editor.getImage().toDataURL("image/png") // If you want the image resized to the canvas size (also a HTMLCanvasElement) const canvasScaled = this.editor.getImageScaledToCanvas().toDataURL("image/png") this.props.getImage(canvasScaled) } } setEditorRef(editor){ this.editor = editor } scaleHandle(e){ e.stopPropagation() e.preventDefault() this.setState({ scale: parseFloat(e.target.value/10).toFixed(1) }) this.saveImgHandle() } smallHandle(e){ e.stopPropagation() e.preventDefault() if(this.state.scale>0){ this.setState({ scale: (this.state.scale*10-1)/10 }) this.saveImgHandle() } } bigHandle(e){ e.stopPropagation() e.preventDefault() if(this.state.scale<2){ this.setState({ scale: (this.state.scale*10+1)/10 }) this.saveImgHandle() } } imgChangeHandle(){ this.setState({ scale: 1 }) this.saveImgHandle() } render () { const {scale} = this.state const {url,width,height,borderRadius} = this.props return ( <div className="imgEditBox unselect"> <div className="range"> <div className="smaller icon-set" onClick={this.smallHandle}></div> <div className="rangeBar"> <div className="circle" style={{left:70*scale/2+'px'}}></div> </div> <input type="range" value={scale*10} min='0' max='20' step='1' onChange={this.scaleHandle}/> <div className="bigger icon-set" onClick={this.bigHandle}></div> </div> <AvatarEditor ref={this.setEditorRef} crossOrigin={'anonymous'} image={url} width={120} height={120} borderRadius={60} scale={scale} onPositionChange={this.saveImgHandle} onLoadSuccess={this.imgChangeHandle} /> </div> ) } }
var images = {}; module.exports = images; var path = require('path'); var db = require(path.join(__dirname, '..', 'db')); var helper = require(path.join(__dirname, '..', 'helper')); /* Image Expiration */ images.addImageExpiration = function(url, expiration) { var q = 'INSERT INTO image_expirations (image_url, expiration) VALUES ($1, $2)'; return db.sqlQuery(q, [url, expiration]); }; images.clearImageExpiration = function(url) { var q = 'DELETE FROM image_expirations WHERE image_url = $1'; return db.sqlQuery(q, [url]); }; images.getExpiredImages = function() { var q = 'SELECT image_url FROM image_expirations WHERE expiration < now()'; return db.sqlQuery(q); }; /* Post Images */ images.addPostImage = function(postId, url) { postId = helper.deslugify(postId); var q = 'INSERT INTO images_posts (image_url, post_id) VALUES ($1, $2)'; return db.sqlQuery(q, [url, postId]); }; images.removePostImages = function(postId) { postId = helper.deslugify(postId); var q = 'UPDATE images_posts SET post_id = NULL WHERE post_id = $1'; return db.sqlQuery(q, [postId]); }; images.getDeletedPostImages = function() { var q = 'SELECT id, image_url FROM images_posts WHERE post_id IS NULL'; return db.sqlQuery(q).then(helper.slugify); }; images.getImageReferences = function(url) { var q = 'SELECT post_id FROM images_posts WHERE image_url = $1'; return db.sqlQuery(q, [url]).then(helper.slugify); }; images.deleteImageReference = function(id) { id = helper.deslugify(id); var q = 'DELETE FROM images_posts WHERE id = $1'; return db.sqlQuery(q, [id]); };
module.exports=[ "https://img01.sogoucdn.com/app/a/100520093/fa2b533c5b547227-2a308818cdc38979-048fae8314b834dfca5cde51065d669c.jpg", "https://i01piccdn.sogoucdn.com/69d50986592a3357" , 'https://img04.sogoucdn.com/app/a/100520093/ed109a49daa0fd71-b1ae24d77db1302b-b5f2316c120c2100e323a4022e7b60b1.jpg', ]
import React, {Component} from 'react'; import Celula from './Celula'; import 'bootstrap-css-only/css/bootstrap.min.css'; export default class Cellsgroup extends Component{ render(){ let cells= []; for(let j=0; j< this.props.cols; j++){ let id_= this.props.calcIndexSec( this.props.row , j); cells.push( <Celula key={ id_ } isAlive={ this.props.sobrevivir( this.props.row, j)} /> ) ; } return ( <div className="row"> {cells} </div>); } }
/** * Created by wcq on 2018/12/26. */ import React from 'react'; import View from '@View'; class PageChild extends View { render() { return <div> 子页面1 </div> } } export default PageChild;
import React, { useState, useEffect } from "react"; import { Table } from "reactstrap"; import { Button } from "reactstrap"; import { firebaseApp } from "./Firebase"; import "../css/TableOfLecture.css"; const getShow = (number) => { var isShow = null; firebaseApp .database() .ref("Lecture/Inform/Lecture" + number + "/isShow") .on("value", function (snapshot) { if (snapshot.exists) { isShow = snapshot.val(); } }); if (isShow === true) return "Hiện"; else if (isShow === false) return "Ẩn"; else return "Hiện"; }; const TableOfLecture = (props) => { const [L1, setL1] = useState(getShow(1)); const [L2, setL2] = useState(getShow(2)); const [L3, setL3] = useState(getShow(3)); const [L4, setL4] = useState(getShow(4)); const [L5, setL5] = useState(getShow(5)); const [L6, setL6] = useState(getShow(6)); const [L7, setL7] = useState(getShow(7)); const [L8, setL8] = useState(getShow(8)); const [L9, setL9] = useState(getShow(9)); const [L10, setL10] = useState(getShow(10)); const setShow = (number, isShow) => { if (number === 1 && isShow === true) setL1("Hiện"); if (number === 1 && isShow === false) setL1("Ẩn"); if (number === 1) { if (isShow === true) setL1("Hiện"); else setL1("Ẩn"); } else if (number === 2) { if (isShow === true) setL2("Hiện"); else setL2("Ẩn"); } else if (number === 3) { if (isShow === true) setL3("Hiện"); else setL3("Ẩn"); } else if (number === 4) { if (isShow === true) setL4("Hiện"); else setL4("Ẩn"); } else if (number === 5) { if (isShow === true) setL5("Hiện"); else setL5("Ẩn"); } else if (number === 6) { if (isShow === true) setL6("Hiện"); else setL6("Ẩn"); } else if (number === 7) { if (isShow === true) setL7("Hiện"); else setL7("Ẩn"); } else if (number === 8) { if (isShow === true) setL8("Hiện"); else setL8("Ẩn"); } else if (number === 9) { if (isShow === true) setL9("Hiện"); else setL9("Ẩn"); } else if (number === 10) { if (isShow === true) setL10("Hiện"); else setL10("Ẩn"); } firebaseApp .database() .ref("Lecture/Inform/Lecture" + number) .set({ isShow: isShow, }); }; return ( <div className="tableOfLecture"> <Table hover> <thead> <tr> <th>Môn học</th> <th>Chương</th> <th>Tên chương</th> <th>Trạng thái</th> <th>Ẩn/Hiện</th> </tr> </thead> <tbody> <tr> <td>Kỹ thuật lập trình C</td> <td>1</td> <td>Giới thiệu</td> <td>{L1}</td> <td> <Button id="hide" color="info" onClick={() => setShow(1, true)}> Hiện </Button> <Button id="show" color="danger" onClick={() => setShow(1, false)} > Ẩn </Button> </td> </tr> </tbody> <tbody> <tr> <td>Kỹ thuật lập trình C</td> <td>2</td> <td>Kiểu dữ liệu cơ sở và các phép toán</td> <td>{L2}</td> <td> <Button id="hide" color="info" onClick={() => setShow(2, true)}> Hiện </Button> <Button id="show" color="danger" onClick={() => setShow(2, false)} > Ẩn </Button> </td> </tr> </tbody> <tbody> <tr> <td>Kỹ thuật lập trình C</td> <td>3</td> <td>Cấu trúc điều khiển</td> <td>{L3}</td> <td> <Button id="hide" color="info" onClick={() => setShow(3, true)}> Hiện </Button> <Button id="show" color="danger" onClick={() => setShow(3, false)} > Ẩn </Button> </td> </tr> </tbody> <tbody> <tr> <td>Kỹ thuật lập trình C</td> <td>4</td> <td>Con trỏ và hàm</td> <td>{L4}</td> <td> <Button id="hide" color="info" onClick={() => setShow(4, true)}> Hiện </Button> <Button id="show" color="danger" onClick={() => setShow(4, false)} > Ẩn </Button> </td> </tr> </tbody> <tbody> <tr> <td>Kỹ thuật lập trình C</td> <td>5</td> <td>Mảng dữ liệu</td> <td>{L5}</td> <td> <Button id="hide" color="info" onClick={() => setShow(5, true)}> Hiện </Button> <Button id="show" color="danger" onClick={() => setShow(5, false)} > Ẩn </Button> </td> </tr> </tbody> <tbody> <tr> <td>Kỹ thuật lập trình C</td> <td>6</td> <td>Chuỗi</td> <td>{L6}</td> <td> <Button id="hide" color="info" onClick={() => setShow(6, true)}> Hiện </Button> <Button id="show" color="danger" onClick={() => setShow(6, false)} > Ẩn </Button> </td> </tr> </tbody> <tbody> <tr> <td>Kỹ thuật lập trình C</td> <td>7</td> <td>Kiểu dữ liệu cấu trúc</td> <td>{L7}</td> <td> <Button id="hide" color="info" onClick={() => setShow(7, true)}> Hiện </Button> <Button id="show" color="danger" onClick={() => setShow(7, false)} > Ẩn </Button> </td> </tr> </tbody> <tbody> <tr> <td>Kỹ thuật lập trình C</td> <td>8</td> <td>Kiểu tập tin</td> <td>{L8}</td> <td> <Button id="hide" color="info" onClick={() => setShow(8, true)}> Hiện </Button> <Button id="show" color="danger" onClick={() => setShow(8, false)} > Ẩn </Button> </td> </tr> </tbody> <tbody> <tr> <td>Kỹ thuật lập trình C</td> <td>9</td> <td>Kỹ thuật duyệt mảng sử dụng con trỏ</td> <td>{L9}</td> <td> <Button id="hide" color="info" onClick={() => setShow(9, true)}> Hiện </Button> <Button id="show" color="danger" onClick={() => setShow(9, false)} > Ẩn </Button> </td> </tr> </tbody> <tbody> <tr> <td>Kỹ thuật lập trình C</td> <td>10</td> <td>Bộ nhớ động và ứng dụng trong DSLK</td> <td>{L10}</td> <td> <Button id="hide" color="info" onClick={() => setShow(10, true)}> Hiện </Button> <Button id="show" color="danger" onClick={() => setShow(10, false)} > Ẩn </Button> </td> </tr> </tbody> </Table> </div> ); }; export default TableOfLecture;
console.log("bidsController"); app.controller('bidsController', ['$scope','usersFactory','bidsFactory','$location', '$cookies','$routeParams', function($scope, usersFactory, bidsFactory, $location, $cookies,routeParams) { $scope.new = {}; console.log($cookies.get('name')); if($cookies.getAll() === undefined){ console.log('++++undefined+++'); $location.url('index'); } var cookies = $cookies.getAll(); user = function(){ console.log("bids======="); usersFactory.user($scope.user, function(data){ if (data.data.errors){ $scope.errors = data.data.errors; } else { $scope.users = data.data; $scope.currentUser = $cookies.get('name'); } }); } var get_bid = function(){ bidsFactory.get_bid(function(data){ console.log("=======inside get_bid=======", data.data); // $scope.show_bids = data.data; if (data.data.errors){ $scope.errors = data.data.errors; console.log($scope.errors); } else { $scope.show_bids = data.data; console.log("$scope.show_bids===", data.data); // $location.url('bids'); } }); } $scope.bid = function(id){ console.log("|||====inside bid======||||", $scope.new); $scope.new._user = $cookies.get('id'); $scope.new.user_name = $cookies.get('name'); $scope.new.product_id = id; console.log($scope.new.bid,"---bid----"); get_bid(); var largest = 0; for (var i = 0; i< $scope.show_bids.length;i++) { if($scope.show_bids[i].product_id == id){ if($scope.show_bids[i].bid > largest){ largest = $scope.show_bids[i].bid; } } } if(!$scope.new.bid){ $scope.message = "Must be entered a bid!!!"; }else if($scope.new.bid[id] <= largest){ $scope.message = "Must be larger than current bid"; }else{ $scope.new.bid = $scope.new.bid[id]; bidsFactory.bid($scope.new, function(data){ console.log("====inside++++++ bid======", data); if (data.data.errors){ $scope.errors = data.data.errors; } else { $scope.new = {}; $location.url('bids'); } }); get_bid(); } } $scope.end = function(){ console.log("inside end------"); get_bid(); var p1 = false; var p2 = false; var p3 = false; console.log($scope.show_bids.length); for (var i =0; i < $scope.show_bids.length; i++) { if($scope.show_bids[i].product_id == 1 && $scope.show_bids[i].user_name == $cookies.get('name')){ p1 =true; } if($scope.show_bids[i].product_id == 2 && $scope.show_bids[i].user_name == $cookies.get('name')){ p2 =true; } if($scope.show_bids[i].product_id == 3 && $scope.show_bids[i].user_name == $cookies.get('name')){ p3 =true; } } // alert(p1, p2 , p3); if(p1 && p2 && p3){ console.log("All have bids"); $location.url('result'); }else{ alert("Cannot end the bid. One Product does not have any bid yet!!"); $location.url('bids'); } } $scope.logout = function(){ console.log("inside logout"); usersFactory.logout($scope.user, function(data){ $cookies.remove('name'); $location.url('index'); }); } user(); get_bid(); }]);
app.config(function($stateProvider) { $stateProvider.state('addDream', { url: '/add-dream', templateUrl: 'js/add-dream/add-dream.html', controller: 'AddDreamCtrl', data: { authenticate: true } }) }) app.controller('AddDreamCtrl', function($scope, $rootScope, DreamFactory, Session, $state, TagFactory, SpeechFactory) { TagFactory.getTags() .then(function(tags) { $scope.tags = tags.map(function(tag) { return tag.tagName; }) }) .then(null, console.error.bind(console)); $scope.dream = {}; $scope.dream.user = Session.user._id; $scope.dream.content = ''; $rootScope.$on('dreamSpoken', function(newValue, oldValue) { console.log('watch worked!!!!!') if(newValue !== oldValue) { $scope.dream.content += " " + SpeechFactory.getDreamText(); $scope.$apply(); } }); $scope.addDream = function() { console.log('addDream invoked') DreamFactory.addDream($scope.dream) .then(function() { $state.go('browseDreams') }) .then(null, console.error.bind(console)); } });
// JavaScript Document //A开发 define(function(require,exports,module){ var autoSlt = require('./autoSelect.js'); autoSlt.autoSelect( { disabled:true, id : '#select', setStyleClass :'b1', requestName : ['id', 'name'], zIndex : 2, dataUrl : '../../../static/js/test2.json' } ); autoSlt.autoSelect( { disabled:false, id : '#select1', setStyleClass :'b1', requestName : ['id', 'name'], zIndex : 3, dataUrl : '../../../static/js/test2.json' } ); autoSlt.autoSelect( { disabled:false, id : '#select2', setStyleClass :'b1', requestName : ['id', 'name'], zIndex : 4, dataUrl : '../../../static/js/test2.json' } ); });
"use strict"; /* * @Author: Marte * @Date: 2019-04-01 17:06:30 * @Last Modified by: Marte * @Last Modified time: 2019-04-02 08:55:18 */ (function ($) { $.fn.lunbo = function (opt) { var _this = this; var defaults = { width: "1200", height: "471", imgurl: [], type: "horizontal", idx: 0 }; var newopt = Object.assign({}, defaults, opt); var len = newopt.imgurl.length; var timer; var $ul; var init = function init() { $ul = $("<ul></ul>"); $ul.appendTo($(_this).addClass('lunbo')); $page = $('<div></div>'); $page.addClass('page').appendTo($(_this)); for (var i = 0; i < len; i++) { $('<img src="' + newopt.imgurl[i] + '"/>').width(newopt.width).height(newopt.height).appendTo($('<li></li>').appendTo($ul)); $('<span>' + (i + 1) + '</span>').appendTo($page); } $page.children().filter(":eq(" + newopt.idx + ")").addClass('active'); $($ul.children()[0]).clone(true).appendTo($ul); $(_this).width(newopt.width).height(newopt.height); if (newopt.type == "horizontal") { $ul.width(newopt.width * (len + 1)).addClass('horizontal'); } else if (newopt.type == "visible") { $ul.height(newopt.height * (len + 1)); } else if (newopt.type = "faded") { $ul.height(newopt.height).width(newopt.width).addClass('faded'); } dianji(); move(); ustop(); }; var move = function move() { timer = setInterval(function () { newopt.idx++; if (newopt.idx > len) { $ul.css({ "left": 0, "top": 0 }); newopt.idx = 1; } yidong(); gaoliang(newopt.idx); }, 2000); }; var gaoliang = function gaoliang(idx) { if (idx == len) { idx = 0; } $page.children().not(":eq(" + idx + ")").removeClass('active'); $page.children().filter(":eq(" + idx + ")").addClass('active'); }; var dianji = function dianji() { $page.on("click", "span", function () { newopt.idx = $(this).text() - 1; yidong(); gaoliang(newopt.idx); }); }; var ustop = function ustop() { $(_this).hover(function () { clearInterval(timer); }, function () { move(); }); }; var yidong = function yidong() { if (newopt.type == "horizontal") { $ul.stop(true).animate({ left: -newopt.idx * newopt.width }, 1000); } else if (newopt.type == "visible") { $ul.stop(true).animate({ top: -newopt.idx * newopt.height }, 1000); } else if (newopt.type = "faded") { $ul.stop(true).children().not(":eq(" + newopt.idx + ")").fadeOut(1000); $ul.stop(true).children().filter(":eq(" + newopt.idx + ")").fadeIn(1000); } }; init(); }; })(jQuery);
import "./style.css"; const About = () => { return ( <div className="about"> <h2>About Component</h2> </div> ); }; export default About;
/** * S3 Deploy: A class to help deploy vue_dsl to AWS S3. * @name s3 * @module s3 **/ import base_deploy from './base_deploy' export default class s3 extends base_deploy { constructor({ context={} }={}) { super({ context, name:'AWS S3' }); } async logo() { let cfonts = require('cfonts'); cfonts.say(this.name, {...{ font:'3d', colors:['red','#333'] }}); } async modifyPackageJSON(config) { //little sass errors hack fix 13jun21 let ci = require('ci-info'); if (ci.isCI==false) { //config.devDependencies['sass-migrator']='*'; //config.scripts.hackfix = 'sass-migrator division node_modules/vuetify/**/*.sass && sass-migrator division node_modules/vuetify/**/*.scss'; //config.scripts.dev = 'npm run hackfix && '+config.scripts.dev; //config.scripts.build = 'npm run hackfix && '+config.scripts.build; } return config; } async modifyNuxtConfig(config) { if (this.context.x_state.config_node.axios && this.context.x_state.config_node.axios.deploy) { let ax_config = config.axios; ax_config.baseURL = this.context.x_state.config_node.axios.deploy; ax_config.browserBaseURL = this.context.x_state.config_node.axios.deploy; delete ax_config.deploy; config.axios = ax_config; } this.context.x_state.central_config.static=true; //force static mode return config; } async deploy() { let build={}; this.context.x_console.title({ title:'Deploying to Amazon AWS S3', color:'green' }); await this.logo(); // builds the app build.try_build = await this.base_build(); if (build.try_build.length>0) { this.context.x_console.outT({ message:`There was an error building the project.`, color:'red' }); return false; } // deploys to aws build.deploy_aws_s3 = await this.run(); //test if results.length>0 (meaning there was an error) if (build.deploy_aws_s3.length>0) { this.context.x_console.outT({ message:`There was an error deploying to Amazon AWS.`, color:'red', data:build.deploy_aws_s3.toString()}); return false; } return true; } async run() { let spawn = require('await-spawn'); let path = require('path'); let errors = [], results={}; let bucket = this.context.x_state.central_config.deploy.replaceAll('s3:','').trim(); let aliases = []; let ci = require('ci-info'); let spa_opt = { cwd:this.context.x_state.dirs.base }; let profile = ['--profile','default']; if (ci.isCI==true) { //spa_opt.stdio = 'inherit'; profile = []; } if (this.context.x_state.central_config.dominio) { bucket = this.context.x_state.central_config.dominio.trim(); } //support for domain aliases if (bucket.includes('<-')==true) { let extract = require('extractjs'); aliases = bucket.split('<-').pop().split(','); bucket = bucket.split('<-')[0].replaceAll('s3:','').trim(); } // let region = 'us-east-1'; if (this.context.x_state.config_node.aws.region) region = this.context.x_state.config_node.aws.region; let dist_folder = path.join(this.context.x_state.dirs.compile_folder,'dist/'); //AWS S3 deploy this.context.debug('AWS S3 deploy'); //MAIN //create bucket policy let spinner = this.context.x_console.spinner({ message:`Creating policy for bucket:${bucket}` }); let policy = { Version: '2012-10-17', Statement: [ { Sid: 'PublicReadGetObject', Effect: 'Allow', Principal: '*', Action: 's3:GetObject', Resource: `arn:aws:s3:::${bucket}/*` } ] }; let policyFile = path.join(this.context.x_state.dirs.base,'policy.json'); try { await this.context.writeFile(policyFile,JSON.stringify(policy)); spinner.succeed('Bucket policy created'); } catch(x1) { spinner.fail('Bucket policy creation failed'); errors.push(x1); } //create bucket spinner.start('Creating bucket'); try { results.create_bucket = await spawn('aws',['s3api','create-bucket','--bucket',bucket,'--region',region,...profile],spa_opt); //, stdio:'inherit' spinner.succeed(`Bucket created in ${region}`); } catch(x2) { spinner.fail('Bucket creation failed'); errors.push(x2); } //add bucket policy //aws s3api put-bucket-policy --bucket www.happy-bunny.xyz --policy file:///tmp/bucket_policy.json --profile equivalent spinner.start('Adding bucket policy'); try { results.adding_policy = await spawn('aws',['s3api','put-bucket-policy','--bucket',bucket,'--policy','file://'+policyFile,...profile],spa_opt); //, stdio:'inherit' spinner.succeed(`Bucket policy added correctly`); } catch(x3) { spinner.fail('Adding bucket policy failed'); errors.push(x3); } //upload website files to bucket //aws s3 sync /tmp/SOURCE_FOLDER s3://www.happy-bunny.xyz/ --profile equivalent spinner.start('Uploading website files to bucket'); try { results.website_upload = await spawn('aws',['s3','sync',dist_folder,'s3://'+bucket+'/',...profile],spa_opt); //, stdio:'inherit' spinner.succeed(`Website uploaded successfully`); } catch(x4) { spinner.fail('Failed uploading website files'); errors.push(x4); } //set s3 bucket as website, set index.html and error page //aws s3 website s3://www.happy-bunny.xyz/ --index-document index.html --error-document error.html --profile equivalent spinner.start('Setting S3 bucket as type website'); try { results.set_as_website = await spawn('aws', [ 's3','website', 's3://'+bucket+'/', '--index-document','index.html', '--error-document','200.html', ...profile], spa_opt); spinner.succeed(`Bucket configured as website successfully`); } catch(x5) { spinner.fail('Failed configuring bucket as website'); errors.push(x5); } //ALIASES let fs = require('fs').promises; if (aliases.length>0) { for (let alias of aliases) { let spinner = this.context.x_console.spinner({ message:`Creating policy for bucket alias:${alias}` }); let policy = { RedirectAllRequestsTo: { HostName: bucket } }; let policyFile = path.join(this.context.x_state.dirs.base,'policy_alias.json'); try { await this.context.writeFile(policyFile,JSON.stringify(policy)); spinner.succeed(`Bucket alias '${alias}' policy created`); } catch(x1) { spinner.fail(`Bucket alias '${alias}' policy creation failed`); errors.push(x1); } //create bucket spinner.start(`Creating bucket alias '${alias}'`); try { results.create_bucket = await spawn('aws',['s3api','create-bucket','--bucket',alias,'--region',region,...profile],spa_opt); //, stdio:'inherit' spinner.succeed(`Bucket alias '${alias}' created in ${region}`); } catch(x2) { spinner.fail(`Bucket alias '${alias}' creation failed`); errors.push(x2); } //add bucket policy spinner.start(`Adding bucket alias '${alias}' policy`); try { results.adding_policy = await spawn('aws',['s3api','put-bucket-website','--bucket',alias,'--website-configuration','file://policy_alias.json',...profile],spa_opt); //, stdio:'inherit' spinner.succeed(`Bucket alias '${alias}' policy added correctly`); } catch(x2) { spinner.fail(`Adding bucket alias '${alias}' policy failed`); errors.push(x2); } //erase policy_alias.json file try { await fs.unlink(policyFile); } catch(err_erasepolicy_alias) { } } } if (errors.length==0) { this.context.x_console.out({ message:`Website ready at http://${bucket}.s3-website-${region}.amazonaws.com/`, color:'brightCyan'}); } //erase policy.json file try { await fs.unlink(policyFile); } catch(err_erasepolicy) { } //ready return errors; } //**************************** // onPrepare and onEnd steps //**************************** async post() { let ci = require('ci-info'); //restores aws credentials if modified by onPrepare after deployment if (!this.context.x_state.central_config.componente && this.context.x_state.central_config.deploy && this.context.x_state.central_config.deploy.indexOf('s3:') != -1 && this.context.x_state.config_node.aws && ci.isCI==false) { // @TODO add this block to deploys/s3 'post' method and onPrepare to 'pre' 20-br-21 // only execute after deploy and if user requested specific aws credentials on map let path = require('path'), copy = require('recursive-copy'), os = require('os'); let fs = require('fs'); let aws_bak = path.join(this.context.x_state.dirs.base, 'aws_backup.ini'); let aws_file = path.join(os.homedir(), '/.aws/') + 'credentials'; // try to copy aws_bak over aws_ini_file (if bak exists) let exists = s => new Promise(r=>fs.access(s, fs.constants.F_OK, e => r(!e))); if ((await this.context.exists(aws_bak))) { await copy(aws_bak,aws_file,{ overwrite:true, dot:true, debug:false }); // remove aws_bak file await fs.promises.unlink(aws_bak); } } } async pre() { let ci = require('ci-info'); if (!this.context.x_state.central_config.componente && this.context.x_state.central_config.deploy && this.context.x_state.central_config.deploy.indexOf('s3:') != -1 && ci.isCI==false) { // if deploying to AWS s3:x, then recover/backup AWS credentials from local system let ini = require('ini'), path = require('path'), fs = require('fs').promises; // read existing AWS credentials if they exist let os = require('os'); let aws_ini = ''; let aws_ini_file = path.join(os.homedir(), '/.aws/') + 'credentials'; try { //this.debug('trying to read AWS credentials:',aws_ini_file); aws_ini = await fs.readFile(aws_ini_file, 'utf-8'); this.context.debug('AWS credentials:',aws_ini); } catch (err_reading) {} // if (this.context.x_state.config_node.aws) { // if DSL defines temporal AWS credentials for this app .. // create backup of aws credentials, if existing previously if (aws_ini != '') { let aws_bak = path.join(this.context.x_state.dirs.base, 'aws_backup.ini'); this.context.x_console.outT({ message: `config:aws:creating .aws/credentials backup`, color: 'yellow' }); await fs.writeFile(aws_bak, aws_ini, 'utf-8'); } // debug this.context.x_console.outT({ message: `config:aws:access ->${this.context.x_state.config_node.aws.access}` }); this.context.x_console.outT({ message: `config:aws:secret ->${this.context.x_state.config_node.aws.secret}` }); if (this.context.x_state.config_node.aws.region) { this.context.x_console.outT({ message: `config:aws:region ->${this.context.x_state.config_node.aws.region}` }); } // transform config_node.aws keys into ini let to_aws = { aws_access_key_id: this.context.x_state.config_node.aws.access, aws_secret_access_key: this.context.x_state.config_node.aws.secret }; if (this.context.x_state.config_node.aws.region) { to_aws.region = this.context.x_state.config_node.aws.region; } let to_ini = ini.stringify(to_aws, { section: 'default' }); this.context.debug('Setting .aws/credentials from config node'); // save as .aws/credentials (ini file) await fs.writeFile(aws_ini_file, to_ini, 'utf-8'); } else if (aws_ini != '') { // if DSL doesnt define AWS credentials, use the ones defined within the local system. let parsed = ini.parse(aws_ini); if (parsed.default) this.context.debug('Using local system AWS credentials', parsed.default); this.context.x_state.config_node.aws = { access: '', secret: '' }; if (parsed.default.aws_access_key_id) this.context.x_state.config_node.aws.access = parsed.default.aws_access_key_id; if (parsed.default.aws_secret_access_key) this.context.x_state.config_node.aws.secret = parsed.default.aws_secret_access_key; if (parsed.default.region) this.context.x_state.config_node.aws.region = parsed.default.region; } } } }
"use strict"; var express = require("express"); var router = express.Router(); var userMaster = require('../models/UserMaster'); var async = require('async'); var LocalStrategy = require('passport-local').Strategy; module.exports = function(passport) { // demo test api link router.get('/demo', function(req, res) { // var response = { // "error": false, // "message": "you connected to server rest api successfully !!" // }; var response; userMaster.useHello("hello",function(err,data) { console.log("____________"+JSON.stringify(data)); response=data; }); res.send(response); }); //fetching all the records router.get('/user', function(req, res) { userMaster.getUser(function(err,response) {if(response) {res.send(response); } else { res.send(response); } }); }); // creating user router.post("/user",function(req, res) { userMaster.createUser(req.body,function(err,response) {if(response) {res.send(response); } else {res.send(err); } }); }); // setting user password router.post("/userSetPass",function(req, res) { userMaster.setPassword(req.body,function(err,response) {if(response) {res.send(response); } else {res.send(err); } }); }); }; // passport.serializeUser(function(user, done) { // done(null, user); // }) // // passport.deserializeUser(function(user, done) { // done(null, user); // }) // // passport.use(new LocalStrategy(function(email, password, callback) { // process.nextTick(function() { // // // userMaster.getUserByEmail(req.body, function(err, user) { // if (err) { // return callback(err); // } // // if (!user) { // return callback(null, false); // } // // if (user.password != password) { // return callback(null, false); // } // // return callback(null, user); // }); // // // }); // })); // // //login // // process the login form // router.route("/login").post(passport.authenticate('local-login', { // successRedirect : '/profile', // redirect to the secure profile section // failureRedirect : '/login', // redirect back to the signup page if there is an error // failureFlash : true // allow flash messages // }), // function(req, res) { // console.log("hello"); // // if (req.body.remember) { // req.session.cookie.maxAge = 1000 * 60 * 3; // } else { // req.session.cookie.expires = false; // } // res.redirect('/'); // }); // // // router.get('/loginFailure', function(req, res, next) { // res.render('failed'); // }) // // router.get('/loginSuccessAdmin', function(req, res, next) { // res.render('admin'); // }) // router.get('/loginSuccessUsers', function(req, res, next) { // res.render('users'); // }) // // // //module.exports = router;
import React from 'react'; import Helmet from 'react-helmet'; const Article2 = () => { return ( <> <Helmet> <title>Blog article 2 page</title> <meta name="description" content="Blog article 2 page" /> <meta name="robots" content="INDEX,FOLLOW" /> </Helmet> <h2>Blog article 2 page</h2> </> ) } export default Article2;
const Express = require("express"); const router = Express.Router(); const mongoUser = require("../../controller/mongoUser"); const { searchSong } = require("../../controller/mongoSong"); const checkers = require("../../controller/checkers"); const isLoggedIn = require("../../middlewares/isLoggedIn"); router.post("/", isLoggedIn, async (req, res) => { const data = { message: "", code: "", navbar: true }; try { const { spotify_id, name, album } = req.body; const songID = await searchSong(spotify_id, name, album); const deleteSong = await mongoUser.deleteFavoriteSong( req.session.currentUser, songID ); res.status(200).json({ message: deleteSong }); } catch (error) { data.code = 422; data.message = error; res.render("error", data); } }); module.exports = router;
(function ($) { /** * Behaviour for the RND15 Site Media Wall * * Author: J.Pitt * Contributors: - * * Last update: 4th February 2015 * * Description & additional notes: * Simply adds negative bottom to captions based on paragraph height * */ Drupal.behaviors.rnd15siteMediaWall = { defaults : { baseClass : '.media-wall', captionElementClass: '.pane-media-wall__caption-content', paragraphElementClass: '.pane-media-wall__paragraph:visible', linkElementClass: '.pane-media-wall--link', $captions: null }, attach: function (context, settings) { var _base = Drupal.behaviors.rnd15siteMediaWall; // Setup the panes media wall, passing in the relevant context $(_base.defaults.baseClass, context).once('rnd15siteMediaWall', function() { // Extend the current behaviour with default values Drupal.settings.rnd15siteMediaWall = $.extend({}, Drupal.settings.rnd15siteMediaWall, _base.defaults); // Setup the menu _base.setupPanesMediaWall(context); }); }, /** * Sets up the media wall panes */ setupPanesMediaWall : function(context) { var _base = Drupal.behaviors.rnd15siteMediaWall; var _settings = Drupal.settings.rnd15siteMediaWall; // Skip lower than ie9 browsers _base.isLtIe9 = $('html', context).hasClass('lt-ie9'); if(_base.isLtIe9) return; /** * Cache JS & jQuery Objects we require */ _settings.$paragraphs = $(_settings.paragraphElementClass, context); _settings.$captions = $(_settings.captionElementClass, context); // Let's run the responsive captions which will take care of stuff for us _base.responsiveCaptions(); // Setup Touch Captions _base.touchCaptions(); }, /* * Responsive Captions * Uses enquire js to trigger the responsive captions */ responsiveCaptions : function() { var _base = Drupal.behaviors.rnd15siteMediaWall; var _settings = Drupal.settings.rnd15siteMediaWall; // We use the exception handler in case enquire.js is not available try { // Attach enquire JS events enquire .register(Drupal.settings.crl2.breakpoints.sm, { // Remove positions in case we go from SM to XS unmatch : _base.removeCaptionPositions, match : _base.updateCaptions }) .register(Drupal.settings.crl2.breakpoints.md, { unmatch : _base.updateCaptions, match : _base.updateCaptions }, true) .register(Drupal.settings.crl2.breakpoints.lg, { unmatch : _base.updateCaptions, match : _base.updateCaptions }); } catch(err) { // Output the error if (window.console) { console.log(err); } } }, /* * Touch Captions * Uses the rnd15_site_menu isTouchDevice check */ touchCaptions : function() { var _base = Drupal.behaviors.rnd15siteMediaWall; var _settings = Drupal.settings.rnd15siteMediaWall; // If on touch, add a special click handler that shows the caption first if(typeof Drupal.settings.rnd15touchMenu !== 'undefined' && Drupal.settings.rnd15touchMenu.isTouchDevice) { // Skip if we are on the XS breakpoint if(typeof Drupal.settings.crl2.breakpointActive !== 'undefined' && Drupal.settings.crl2.breakpointActive === 'xs') return; _settings.$paragraphs .parents(_settings.linkElementClass) .once('touchCaptions') .on('click', _base.touchOnPane); } }, /** * Click event handler for panes * Simply skips the first click :) */ touchOnPane : function(e) { if(typeof this.clicked == 'undefined') { this.clicked = 1; e.preventDefault(); } }, /** * Loop through each caption and paragraph */ updateCaptions : function() { var _settings = Drupal.settings.rnd15siteMediaWall; var _base = Drupal.behaviors.rnd15siteMediaWall; $.each(_settings.$paragraphs, _base.setCaptionPosition); }, /** * Set each caption bottom negative to the paragraph height */ setCaptionPosition : function(index, value) { var _settings = Drupal.settings.rnd15siteMediaWall; var paragraphHeight = this.offsetHeight; if(typeof paragraphHeight !== 'undefined') { this.parentNode.style.bottom = -paragraphHeight.toString() + 'px'; } }, /** * Loop through each caption and paragraph */ removeCaptionPositions : function() { var _settings = Drupal.settings.rnd15siteMediaWall; var _base = Drupal.behaviors.rnd15siteMediaWall; $.each(_settings.$captions, _base.resetCaptionPosition); }, /** * Set each caption bottom negative to the paragraph height */ resetCaptionPosition : function(index, value) { this.style.bottom = '0px'; } }; })(jQuery);
var template = ` <h1> Internal compay Directory</h1> <div class = "container" > ` for (var i = 0; i < customers.results.length; i++) { template += ` <div class = "customer-info"> <img src="${customers.results[i].picture.large}"> <div class = "name"> ${customers.results[i].name.first} ${customers.results[i].name.last} </div> <div class = "email"> <a href="">${customers.results[i].email}</a> </div> <div class = "street"> ${customers.results[i].location.street} </div> <div class = "city"> ${customers.results[i].location.city + ", " + customers.results[i].location.state + ", " + customers.results[i].location.postcode} </div> <div class = "phone"> ${"555-555-5555"} </div> <div class = "blurred-SSN"> ${customers.results[i].id.value} </div> </div> ` } template += `</div>`; document.querySelector('body').innerHTML = template console.log(customers); // note on PHONE Number - the mockpng has 555-555-5555 pull actual number by using ${customers.results[i].phone}
var canvas = document.querySelector('canvas'); // Selecting the element <canvas> canvas.width = window.innerWidth; // Grabbing the windows inner-width canvas.height = window.innerHeight; var c = canvas.getContext('2d'); for (i = 0; i < canvas.width + 1; i = i + 15){ c.moveTo(i, 0); c.lineTo(i, canvas.height); c.stroke(); } for (i = 0; i < canvas.height; i = i + 15){ c.moveTo(0, i); c.lineTo(canvas.width + 100, i); c.lineWidth = 1; c.strokeStyle="#ebebeb"; c.stroke(); } var pen_button = document.querySelector('.pen_button'); var box_button = document.querySelector('.box_button'); var input_button = document.querySelector('.input_button'); var lorem_button = document.querySelector('.lorem_button'); var customText_button = document.querySelector('.customText_button'); var button = document.querySelectorAll('.button'); var penCanvas = document.querySelector('.penCanvas'); var boxDrawLayer = document.querySelector('#boxDrawLayer'); var body = document.querySelector('body'); ////////// Button Toggler ////////// for (i = 0; i < button.length; i++){ button[i].addEventListener('click', function(){ var active = this.classList.contains('active'); $('.active').removeClass('active'); if (!active){ this.classList.add('active'); } }); } ////////// Brush Function Toggler ////////// pen_button.addEventListener('click', function(){ $('.penCanvasNone').toggleClass('penCanvasNone'); var active = this.classList.contains('active'); if (active){ penActivate(); boxDrawLayer.classList.add('boxCanvasNone'); inputDrawLayer.classList.add('inputCanvasNone'); loremDrawLayer.classList.add('loremCanvasNone'); customTextDrawLayer.classList.add('customTextCanvasNone'); } if (!active){ penCanvas.classList.add('penCanvasNone'); } }); ////////// Box Function Toggler ////////// box_button.addEventListener('click', function(){ $('.boxCanvasNone').toggleClass('boxCanvasNone'); var active = this.classList.contains('active'); if (active){ boxDrawActivate(); penCanvas.classList.add('penCanvasNone'); inputDrawLayer.classList.add('inputCanvasNone'); loremDrawLayer.classList.add('loremCanvasNone'); customTextDrawLayer.classList.add('customTextCanvasNone'); } if (!active){ boxDrawLayer.classList.add('boxCanvasNone'); } }); ////////// Input Function Toggler ////////// input_button.addEventListener('click', function(){ $('.inputCanvasNone').toggleClass('inputCanvasNone'); var active = this.classList.contains('active'); if (active){ inputDrawActivate(); boxDrawLayer.classList.add('boxCanvasNone'); penCanvas.classList.add('penCanvasNone'); loremDrawLayer.classList.add('loremCanvasNone'); customTextDrawLayer.classList.add('customTextCanvasNone'); } if (!active){ inputDrawLayer.classList.add('inputCanvasNone'); } }); ////////// Lorem Function Toggler ////////// lorem_button.addEventListener('click', function(){ $('.loremCanvasNone').toggleClass('loremCanvasNone'); var active = this.classList.contains('active'); if(active){ loremDrawActivate(); boxDrawLayer.classList.add('boxCanvasNone'); penCanvas.classList.add('penCanvasNone'); inputDrawLayer.classList.add('inputCanvasNone'); customTextDrawLayer.classList.add('customTextCanvasNone'); } if (!active){ loremDrawLayer.classList.add('loremCanvasNone'); } }); ////////// Custom Text Function Toggler ////////// customText_button.addEventListener('click', function(){ $('.customTextCanvasNone').toggleClass('customTextCanvasNone'); var active = this.classList.contains('active'); if(active){ customTextDrawActivate(); boxDrawLayer.classList.add('boxCanvasNone'); penCanvas.classList.add('penCanvasNone'); inputDrawLayer.classList.add('inputCanvasNone'); loremDrawLayer.classList.add('loremCanvasNone'); } if (!active){ customTextDrawLayer.classList.add('customTextCanvasNone'); } }); ////////// Mouse Positioning's ////////// var box = null; var input = null; var lorem = null; var customText = null; var mouse = { MouseX: 0, MouseY: 0, // sMouseX: 0, // sMouseY: 0, mouseStartX: 0, mouseStartY: 0, xPositionBrush: undefined, yPositionBrush: undefined }; ////////// Brush Active ////////// function penActivate(){ canvas.addEventListener('mousemove', function(e) { mouse.MouseX = e.pageX - this.offsetLeft; mouse.MouseY = e.pageY - this.offsetTop; }); canvas.addEventListener('mousedown', function(e) { c.beginPath(); canvas.addEventListener('mousemove', painter); }); canvas.addEventListener('mouseup', function() { canvas.removeEventListener('mousemove', painter); c.strokeStyle = '#000000'; }); function painter() { c.lineTo(mouse.MouseX, mouse.MouseY); c.stroke(); }; canvas.addEventListener('mousemove', function(event){ mouse.xPositionBrush = event.x; mouse.yPositionBrush = event.y; console.log(event); }) } ////////// Box Active ////////// function boxDrawActivate() { initiatorBoxDraw(document.getElementById('boxDrawLayer')); function initiatorBoxDraw(canvas) { canvas.style.cursor = "crosshair"; function setMousePosition(e) { if (e.pageX) { //Moz // Always going to be true mouse.MouseX = e.pageX + window.pageXOffset; mouse.MouseY = e.pageY + window.pageYOffset; } }; canvas.addEventListener('mousedown', function(e) { if (box != null) { box = null; // boxBorderSlider.addEventListener('input', boxBorderWidth); // boxRadiusSlider.addEventListener('input', boxRadius); // boxSliderBorderOutput.classList.remove('disabledBoxBorder'); // boxSilderRadiusOutput.classList.remove('disabledBoxBorder'); // for (i = 0; i < placeHolderBoxText.length; i++){ // placeHolderBoxText[i].classList.add('disabledBoxBorder'); // } } else { mouse.mouseStartX = mouse.MouseX; mouse.mouseStartY = mouse.MouseY; box = document.createElement('div'); box.className = 'rectangle'; // box.style.left = mouse.MouseX; // box.style.top = mouse.MouseY; box.style.height == mouse.MouseX; box.style.width == mouse.MouseY; canvas.appendChild(box) } }); canvas.addEventListener('mouseup', function(e){ box = null; }); canvas.addEventListener('mousemove', function(e) { setMousePosition(e); if (box !== null) { box.style.width = Math.abs(mouse.MouseX - mouse.mouseStartX) + 'px'; // Set box width to absolute number of mouse position - mouse's starting position (Removes distance from edge of box to the mouse, would be the same distance between starting position and canvas wall) box.style.height = Math.abs(mouse.MouseY - mouse.mouseStartY) + 'px'; box.style.left = (mouse.MouseX - mouse.mouseStartX < 0) ? mouse.MouseX + 'px' : mouse.mouseStartX + 'px'; // If previous statements (mouse.x - mouse.startX) is less than 0 (in other words, goes into negative axis), add mouse.x as pixels (determines what happens when it goes into the negatives of the x and y axis) box.style.top = (mouse.MouseY - mouse.mouseStartY < 0) ? mouse.MouseY + 'px' : mouse.mouseStartY + 'px'; // Determines how much change there should be when switching from negative and positive axis } }); } }; ////////// Input Active ////////// function inputDrawActivate() { initiatorInputDraw(document.getElementById('inputDrawLayer')); function initiatorInputDraw(body) { body.style.cursor = "crosshair"; function setMousePosition(e) { if (e.pageX) { //Moz // Always going to be true mouse.MouseX = e.pageX + window.pageXOffset; mouse.MouseY = e.pageY + window.pageYOffset; } }; body.addEventListener('mousedown', function(e) { if (input != null) { input = null; // boxBorderSlider.addEventListener('input', boxBorderWidth); // boxRadiusSlider.addEventListener('input', boxRadius); // boxSliderBorderOutput.classList.remove('disabledBoxBorder'); // boxSilderRadiusOutput.classList.remove('disabledBoxBorder'); // for (i = 0; i < placeHolderBoxText.length; i++){ // placeHolderBoxText[i].classList.add('disabledBoxBorder'); // } } else { mouse.mouseStartX = mouse.MouseX; mouse.mouseStartY = mouse.MouseY; input = document.createElement('input'); input.className = 'input'; input.autofocus = 'true'; input.placeholder = 'Please enter your name...'; // box.style.left = mouse.MouseX; // box.style.top = mouse.MouseY; input.style.height == mouse.MouseX; input.style.width == mouse.MouseY; body.appendChild(input); } }); body.addEventListener('mouseup', function(e){ input = null; }); body.addEventListener('mousemove', function(e) { setMousePosition(e); if (input !== null) { input.style.width = Math.abs(mouse.MouseX - mouse.mouseStartX) + 'px'; // Set box width to absolute number of mouse position - mouse's starting position (Removes distance from edge of box to the mouse, would be the same distance between starting position and canvas wall) input.style.height = Math.abs(mouse.MouseY - mouse.mouseStartY) + 'px'; input.style.left = (mouse.MouseX - mouse.mouseStartX < 0) ? mouse.MouseX + 'px' : mouse.mouseStartX + 'px'; // If previous statements (mouse.x - mouse.startX) is less than 0 (in other words, goes into negative axis), add mouse.x as pixels (determines what happens when it goes into the negatives of the x and y axis) input.style.top = (mouse.MouseY - mouse.mouseStartY < 0) ? mouse.MouseY + 'px' : mouse.mouseStartY + 'px'; // Determines how much change there should be when switching from negative and positive axis } }); } }; ////////// Lorem Active ////////// function loremDrawActivate() { initiatorLoremDraw(document.getElementById('loremDrawLayer')); function initiatorLoremDraw(body) { body.style.cursor = "crosshair"; function setMousePosition(e) { if (e.pageX) { //Moz // Always going to be true mouse.MouseX = e.pageX + window.pageXOffset; mouse.MouseY = e.pageY + window.pageYOffset; } }; body.addEventListener('mousedown', function(e) { if (lorem != null) { lorem = null; // boxBorderSlider.addEventListener('input', boxBorderWidth); // boxRadiusSlider.addEventListener('input', boxRadius); // boxSliderBorderOutput.classList.remove('disabledBoxBorder'); // boxSilderRadiusOutput.classList.remove('disabledBoxBorder'); // for (i = 0; i < placeHolderBoxText.length; i++){ // placeHolderBoxText[i].classList.add('disabledBoxBorder'); // } } else { mouse.mouseStartX = mouse.MouseX; mouse.mouseStartY = mouse.MouseY; lorem = document.createElement('div'); lorem.className = 'lorem'; lorem.innerHTML = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'; // box.style.left = mouse.MouseX; // box.style.top = mouse.MouseY; lorem.style.height == mouse.MouseX; lorem.style.width == mouse.MouseY; body.appendChild(lorem); } }); body.addEventListener('mouseup', function(e){ lorem = null; }); body.addEventListener('mousemove', function(e) { setMousePosition(e); if (lorem !== null) { lorem.style.width = Math.abs(mouse.MouseX - mouse.mouseStartX) + 'px'; // Set box width to absolute number of mouse position - mouse's starting position (Removes distance from edge of box to the mouse, would be the same distance between starting position and canvas wall) lorem.style.height = Math.abs(mouse.MouseY - mouse.mouseStartY) + 'px'; lorem.style.left = (mouse.MouseX - mouse.mouseStartX < 0) ? mouse.MouseX + 'px' : mouse.mouseStartX + 'px'; // If previous statements (mouse.x - mouse.startX) is less than 0 (in other words, goes into negative axis), add mouse.x as pixels (determines what happens when it goes into the negatives of the x and y axis) lorem.style.top = (mouse.MouseY - mouse.mouseStartY < 0) ? mouse.MouseY + 'px' : mouse.mouseStartY + 'px'; // Determines how much change there should be when switching from negative and positive axis } }); } }; ////////// Custom Text Active ////////// function customTextDrawActivate() { initiatorCustomTextDraw(document.getElementById('customTextDrawLayer')); function initiatorCustomTextDraw(body) { body.style.cursor = "crosshair"; function setMousePosition(e) { if (e.pageX) { //Moz // Always going to be true mouse.MouseX = e.pageX + window.pageXOffset; mouse.MouseY = e.pageY + window.pageYOffset; } }; body.addEventListener('mousedown', function(e) { if (customText != null) { customText = null; // boxBorderSlider.addEventListener('input', boxBorderWidth); // boxRadiusSlider.addEventListener('input', boxRadius); // boxSliderBorderOutput.classList.remove('disabledBoxBorder'); // boxSilderRadiusOutput.classList.remove('disabledBoxBorder'); // for (i = 0; i < placeHolderBoxText.length; i++){ // placeHolderBoxText[i].classList.add('disabledBoxBorder'); // } } else { mouse.mouseStartX = mouse.MouseX; mouse.mouseStartY = mouse.MouseY; customText = document.createElement('textarea'); customText.className = 'customText'; customText.placeholder = 'Enter custom text here...'; // box.style.left = mouse.MouseX; // box.style.top = mouse.MouseY; customText.style.height == mouse.MouseX; customText.style.width == mouse.MouseY; body.appendChild(customText); } }); body.addEventListener('mouseup', function(e){ customText = null; customText.style.border = 'none'; }); body.addEventListener('mousemove', function(e) { setMousePosition(e); if (customText !== null) { customText.style.width = Math.abs(mouse.MouseX - mouse.mouseStartX) + 'px'; // Set box width to absolute number of mouse position - mouse's starting position (Removes distance from edge of box to the mouse, would be the same distance between starting position and canvas wall) customText.style.height = Math.abs(mouse.MouseY - mouse.mouseStartY) + 'px'; customText.style.left = (mouse.MouseX - mouse.mouseStartX < 0) ? mouse.MouseX + 'px' : mouse.mouseStartX + 'px'; // If previous statements (mouse.x - mouse.startX) is less than 0 (in other words, goes into negative axis), add mouse.x as pixels (determines what happens when it goes into the negatives of the x and y axis) customText.style.top = (mouse.MouseY - mouse.mouseStartY < 0) ? mouse.MouseY + 'px' : mouse.mouseStartY + 'px'; // Determines how much change there should be when switching from negative and positive axis } }); } };
var Pi = require('./src/Pi.class.js'); //Pi.getInstance().press(Pi.PRESS_START_PIN); Pi.getInstance().watch(Pi.RED_VICTORY_PIN);
$("form").submit(function(event) { event.preventDefault(); postData($( this ).serialize()); document.getElementById("loader").style.display = "block"; }); function clearform() { document.myform.REACT1.value = ""; document.myform.REACT2.value = ""; document.myform.REACT3.value = ""; document.myform.REACT4.value = ""; document.myform.react1n.value = ""; document.myform.react2n.value = ""; document.myform.react3n.value = ""; document.myform.react4n.value = ""; } function default_values() { document.myform.TMIN.value = "1000"; document.myform.T_units.selectedIndex = 0; document.myform.MASS.selectedIndex = 0; document.myform.P_value.value = "1"; document.myform.PRESSURE.selectedIndex = 0; document.myform.CUT.selectedIndex = 0; document.myform.format.selectedIndex = 1; document.myform.DIST.selectedIndex = 0; document.myform.REACT1.value = "Si"; document.myform.REACT2.value = "O2"; document.myform.REACT3.value = ""; document.myform.react1n.value = ""; document.myform.react2n.value = "1.5"; document.myform.react3n.value = ""; } function postData(form) { fetch("http://localhost:8080", { method: 'POST', body: form }) // À noter, la fonction .json() provoquait une SyntaxError // Cette erreur semblait être causée par l'absence de guillemets autour des éléments de data-output.json. // Nous avons donc pris la liberté de modifier le fichier en ajoutant des guillemets, faute d'avoir // une autre solution évidente sous la main. .then((res) => res.json()) .then(data => { console.log(data); console.log(data['output1'][3]['libelle']); formatData(data); }) .catch(function(error) { console.log(error); }) } function formatData(data) { document.getElementById("output1").style.display = "table"; document.getElementById("output2").style.display = "table"; document.getElementById("loader").style.display = "none"; var x = document.querySelectorAll("#output1 td"); for (let i = 0; i < data['output1'].length; i++){ x[i*2].innerHTML = data['output1'][i]['libelle']; x[i*2 + 1].innerHTML = data['output1'][i]['concentration']; } var y = document.querySelectorAll("#output2 td"); for (let i = 0; i < data['output2'].length; i++){ y[i*3].innerHTML = data['output2'][i]['libelle']; y[i*3+1].innerHTML = data['output2'][i]['unite']; y[i*3+2].innerHTML = data['output2'][i]['valeur']; } } /* fetch("data-output.json") .then(response => { response.json(); }).then(data => { console.log(data); }) */ /* (event) => { event.preventDefault(); event.form; } fetch(localhost8080, //url, option //retourne promesse { method: //http verbs methods body: form: //? } ) .then(function(data)) //après asyncrone finie, roule la fonction dans then .catch(function()) //pour erreur .then((response) => response.json()) //arrow fonction .then((data)=>cquon fait avec le data methode generator) */
(function ($) { var loginURL = window.location.origin + "/oauth2/token"; var LoginModule = function (form, url) { var self = this, $divLoginForm = form, $inputLogin = $divLoginForm.querySelector("input[name='login']"), $inputPassword = $divLoginForm.querySelector("input[name='password']"), $inputSubmit = $divLoginForm.querySelector("input[name='submit']"); self.init = function () { $inputSubmit.addEventListener("click", function (e) { authorizeUser(); e.preventDefault(); }); } function showError() { alert("Login Error"); } function authorizeUser() { var login = $inputLogin.value, password = $inputPassword.value, expires = new Date(); return fetch(url, { method: 'POST', cache: 'no-cache', body: "username=" + login + "&password=" + password + "&grant_type=password", headers: { 'content-type': 'application/x-www-form-urlencoded', 'accept': 'application/json', 'accept-language': 'en-gb', 'audience': 'Any' } }).then(res => { if (res.status === 200) { document.cookie = "login=" + login; document.cookie = "password=" + password; document.cookie = "logedIn=true"; var url = getCookie("previousUrl"); if(url!="") window.location.replace(url); } else { showError(); } }); } function getCookie(cname) { var name = cname + "="; var decodedCookie = decodeURIComponent(document.cookie); var ca = decodedCookie.split(';'); for (var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1); } if (c.indexOf(name) == 0) { return c.substring(name.length, c.length); } } return ""; } } $(document).ready(function () { var loginObject = new LoginModule(document.querySelector('.formLogin'), loginURL); loginObject.init(); }); })(jQuery);
import { combineReducers } from 'redux'; import homeReducer from './home_reducer'; import adsReducer from './ads_reducer'; import authReducer from './auth_reducer'; import { reducer as formReducer } from 'redux-form'; const rootReducer = combineReducers({ authReducer, home: homeReducer, ads: adsReducer, form: formReducer, }); export default rootReducer;
import React from 'react' import { View, Text, Image, Button, onPress, StyleSheet, TouchableOpacity } from 'react-native' import { connect } from 'react-redux' import Firebase from '../../config/FireBase.js' class Profile extends React.Component { handleSignout = () => { Firebase.auth().signOut() this.props.navigation.navigate('Login') } render() { const {container, content, emailText, textLogout, logout, tabBar, buttCalendar} = styles; return ( <View style={container}> <View style={content}> <Text style={emailText}>{this.props.user.typeUser}</Text> <Text style={emailText}>{this.props.user.name}</Text> <TouchableOpacity onPress={this.handleSignout} style={logout}> <Text style={textLogout}>LOGOUT</Text> </TouchableOpacity> </View> </View> ) } } const styles = StyleSheet.create({ container: { width: '100%', height: '100%', backgroundColor: '#021425' }, content: { height: '100%', alignItems: 'center', justifyContent: 'center' }, emailText: { fontSize: 22, color: '#fff', }, logout: { width: 250, height: 50, alignItems: 'center', borderRadius: 22, justifyContent: 'center', backgroundColor: '#fff', }, textLogout: { fontSize: 18, color: '#000000', fontWeight: 'bold' }, tabBar: { height: '100%', width: '100%', alignItems: 'flex-end', position: 'absolute', justifyContent: 'center', flexDirection: 'row', }, buttCalendar: { padding: '6%' } }); const mapStateToProps = state => { return { user: state.user } } export default connect(mapStateToProps)(Profile)
import React, { Component } from 'react'; export default class extends Component { constructor(props) { super(props); } handleChange = (e) => { const { onChange } = this.props; onChange && onChange(e.target.value); } render() { const { value, describe } = this.props; return ( <select onChange={this.handleChange} value={value}> {describe.data && describe.data.map(d => ( <option key={d.key} value={d.key}>{d.name}</option> ))} </select> ) } }
import React, { Component } from 'react'; import background from '../../images/background-header.jpg'; import SearchForm from '../forms/SearchForm'; import Eyecatcher from '../Eyecatcher'; class Header extends Component { constructor(props){ super(props); } render() { return ( <section className="header"> <div className="headerBackground"> <img src={background} alt="header background"/> </div> <div className="headerWrapper"> <div className="headerContent"> <Eyecatcher hasReadMore={true}/> <div className="searchBlockWrapper"> <SearchForm /> </div> </div> </div> </section> ); } } export default Header;
const models = require('../models'); const MINIMUM_YEAR = 2015; const sendError = (err, res) => { res.status(500).send(`Error while doing operation: ${err.name}, ${err.message}`); }; exports.findAll = function findAll(req, res) { const { searchYear, project } = req.query; const smwgType = req.query.smwgType ? parseInt(req.query.smwgType, 10) : 1; const limit = req.query.pageSize ? parseInt(req.query.pageSize, 10) : 10; const currentPage = req.query.currentPage ? parseInt(req.query.currentPage, 10) : 1; const offset = (currentPage - 1) * limit; const projectWhere = {}; if (project) { projectWhere.id = project; } models.Smwg.findAndCountAll({ where: { smwgType, year: searchYear || MINIMUM_YEAR, }, include: [ { model: models.Project, required: true, where: projectWhere, }, ], order: ['year', 'month'], limit, offset, }) .then((smwgs) => { res.json(smwgs); }) .catch((err) => { sendError(err, res); }); }; exports.findByYear = function findByYear(req, res) { const { year } = req.query; models.Smwg.findAll({ where: { year: year || MINIMUM_YEAR, }, order: ['year', 'month'], }) .then((smwgs) => { res.json(smwgs); }) .catch((err) => { sendError(err, res); }); }; exports.findOne = function findOne(req, res) { models.Smwg.findOne({ where: { id: req.params.smwgId }, include: [ { model: models.Project }, ], }) .then((smwg) => { res.json(smwg); }) .catch((err) => { sendError(err, res); }); }; const insertSmwgItem = (smwgId, code, name, bobot, itemType, smwgSequence) => ( new Promise((resolve, reject) => { models.SmwgItem.create({ SmwgId: smwgId, code, name, bobot, itemType, smwgSequence, }) .then((smwgItem) => { resolve(smwgItem.id); }) .catch((err) => { console.error(err); reject(err); }); }) ); exports.create = function create(req, res) { const smwgForm = req.body; const projectId = smwgForm.project; const { smwgType } = smwgForm; smwgForm.ProjectId = projectId; models.Smwg.create(smwgForm) .then((smwg) => { models.SmwgTemplate.findAll({ where: { smwgType, }, }) .then((templates) => { const promises = []; for (let i = 0; i < templates.length; i += 1) { const template = templates[i]; const { code, name, bobot, itemType, smwgSequence } = template; promises.push(insertSmwgItem(smwg.id, code, name, bobot, itemType, smwgSequence)); } Promise.all(promises) .then(() => { res.json(smwg); }); }); }) .catch((err) => { sendError(err, res); }); }; exports.update = function update(req, res) { const smwgForm = req.body; const projectId = smwgForm.project; smwgForm.ProjectId = projectId; models.Smwg.update( smwgForm, { where: { id: req.params.smwgId }, }) .then((result) => { res.json(result); }) .catch((err) => { sendError(err, res); }); }; exports.destroy = function destroy(req, res) { models.Smwg.destroy( { where: { id: req.params.smwgId }, }) .then((result) => { res.json(result); }) .catch((err) => { sendError(err, res); }); };
import React, { useCallback } from 'react'; import clsx from 'clsx'; import Drawer from '@material-ui/core/Drawer'; import Divider from '@material-ui/core/Divider'; import IconButton from '@material-ui/core/IconButton'; import ChevronLeftIcon from '@material-ui/icons/ChevronLeft'; import theme from "../../Theme/index.js"; import { useSelector, useDispatch } from 'react-redux'; import history from '../AppRouter/createHistory.js'; import ListItem from '@material-ui/core/ListItem'; import ListItemIcon from '@material-ui/core/ListItemIcon'; import ListItemText from '@material-ui/core/ListItemText'; import DashboardIcon from '@material-ui/icons/Dashboard'; import PeopleIcon from '@material-ui/icons/People'; import {TOGGLE_DRAWER} from '../../redux/actions/uiActions/uiActionTypes' const useStyles = theme; export const NavDrawer = () => { const dispatch = useDispatch(); const classes = useStyles(); const isOpen = useSelector(state => state.UI.drawerIsOpen); const toggleDrawer = useCallback(() => dispatch({ type: TOGGLE_DRAWER }), [dispatch]) const Navigate = (arg) => () =>{ toggleDrawer(); return history.push(arg); } return ( <Drawer variant="persistent" classes={{ paper: clsx(classes.drawerPaper, !isOpen && classes.drawerPaperClose) }} open={isOpen} > <div className={classes.toolbarIcon}> <IconButton onClick={toggleDrawer}> <ChevronLeftIcon /> </IconButton> </div> <Divider /> <ListItem button onClick={Navigate('/')}> <ListItemIcon> <DashboardIcon /> </ListItemIcon> <ListItemText primary="Dashboard" /> </ListItem> <ListItem button onClick={Navigate('/season/add')}> <ListItemIcon> <PeopleIcon /> </ListItemIcon> <ListItemText primary="Add a Season" /> </ListItem> <ListItem button onClick={Navigate('/seasons')}> <ListItemIcon> <PeopleIcon /> </ListItemIcon> <ListItemText primary="Seasons" /> </ListItem> </Drawer> ) }; export default NavDrawer;
import {onDeleteEvent} from '../framework/actions' export const DeleteCalendarEvent = (dispatch) => async( calendarId, eventId ) => { const event = {id: eventId, calendarId: calendarId} const response = await fetch(`http://localhost:8000/calendar/${event.calendarId}/events/${event.id}`, { method: 'DELETE', headers: { 'Content-Type': 'application/json' }, }) let calendarEvents = await response.json() let adjustedEvents = [] calendarEvents.forEach((item) => { let fixed = { id: item.id, title: item.title, description: item.description, start: new Date(item.start), end: new Date(item.end), createdAt: item.createdAt, updatedAt: item.updatedAt, } adjustedEvents.push(fixed) }) console.log(adjustedEvents) return dispatch(onDeleteEvent(adjustedEvents)) } export default DeleteCalendarEvent
class Action { constructor() {} execute(gameState) {} } module.exports = { Action };
import React, { useState } from "react"; import { Link, Redirect } from "react-router-dom"; import { connect } from "react-redux"; import FormInput from "../form-input/form-input.component"; import CustomButton from "../custom-button/custom-button.component"; import { login } from "../../redux/user/user.actions"; import "./sign-in.styles.scss"; const SignIn = ({ login, isAuthenticated, error }) => { const [userCredential, setUserCredentials] = useState({ username: "", password: "" }); const { username, password } = userCredential; const handleSubmit = event => { event.preventDefault(); login(username, password); }; const handleChange = event => { const { value, name } = event.target; setUserCredentials({ ...userCredential, [name]: value }); }; let authRedirect = null; if (isAuthenticated) { authRedirect = <Redirect to="/feed" />; } return ( <div className="login-form"> {authRedirect} <h2 className="login-brand">Photograph</h2> {error?<span style={{color:"red"}}>{error}</span>:null} <form onSubmit={handleSubmit}> <FormInput type="text" name="username" value={username} handleChange={handleChange} label="Username" required /> <FormInput type="password" name="password" value={password} handleChange={handleChange} label="Password" required /> <div className="login-button"> <CustomButton type="submit">SIGN IN</CustomButton> </div> </form> <span>Create an account </span> <Link className="signup-link" to="/auth/signup"> Sign up </Link> </div> ); }; const mapStateToProps = state => { return { loading: state.user.loading, error: state.user.error, isAuthenticated: state.user.token !== null, authRedirectPath: state.user.authRedirectPath }; }; const mapDispatchToProps = dispatch => { return { login: (username, password) => dispatch(login(username, password)) }; }; export default connect(mapStateToProps, mapDispatchToProps)(SignIn);
(function() { "use strict"; // # ToArray var converter = new ArrayBuffer(8); var converterFloat = new Float64Array(converter); var converterBytes = new Uint8Array(converter); // ## toBon function pushVB(buf, pos, n) { // ### var pos0 = pos; buf[pos] = n & 127; if(n > 127) { do { n = n >> 7; buf[++pos] = 128 | n; } while(n > 127); var pos1 = pos; while(pos0 < pos1) { var t = buf[pos0]; buf[pos0] = buf[pos1]; buf[pos1] = t; ++pos0; --pos1; } } return ++pos; } function pushNVB(buf, pos, n) { // ### var pos0 = pos; buf[pos] = ~(n & 127); if(n > 127) { do { n = n >> 7; buf[++pos] = ~(128 | n); } while(n > 127); var pos1 = pos; while(pos0 < pos1) { var t = buf[pos0]; buf[pos0] = buf[pos1]; buf[pos1] = t; ++pos0; --pos1; } } return ++pos; } var any2arr = function(buf, pos, o) { // ### // types: // 1. string // 2. negative integer // 3. positive integer // 4. double // 5. array/list // 6. object/map // ... keyword, buffer, true, false, null ... if(typeof o === 'string') { // ### buf[pos++] = 1; for(var i = 0; i < o.length; ++i) { var c = o.charCodeAt(i) + 1; if(c < 128) { buf[pos++] = c; } else { pos = pushVB(buf, pos, c); } } buf[pos++] = 0; } else if(typeof o === 'number') { // ### if((o | 0) === o) { if(o < 0) { buf[pos++] = 2; pos = pushNVB(buf, pos, -o); } else { buf[pos++] = 3; pos = pushVB(buf, pos, o); } } else { buf[pos++] = 4; converterFloat[0] = o; for(var i = 0; i < 8; ++i) { buf[pos++] = converterBytes[i]; } } } else if(Array.isArray(o)) { // ### buf[pos++] = 5; for(var i = 0; i < o.length; ++i) { pos = any2arr(buf, pos, o[i]); } buf[pos++] = 0; } else if(o.constructor === Object) { // ### buf[pos++] = 6; for(var key in o) { pos = any2arr(buf, pos, key); pos = any2arr(buf, pos, o[key]); } buf[pos++] = 0; } else { // ### throw {"unserialisable type": o}; } return pos; } var str2arr = function(buf, s) { // ### var pos = any2arr(buf, 0, s); while(!buf[--pos]) {}; return ++pos; } function toBon(o) { // ### var a = []; any2arr(a, 0, o); return a; } // ## fromBon function popAny(buf) { // ### switch(buf.arr[buf.pos++]) { case 0: return popAny(buf); case 1: return popStr(buf); case 2: return popNeg(buf); case 3: return popPos(buf); case 4: return popDouble(buf); case 5: return popArr(buf); case 6: return popObj(buf); } } function popStr(buf) { // ### var c, s = ""; while(c = popPos(buf)) { s += String.fromCharCode(c - 1); } return s; } function popNeg(buf) { // ### var res = 0; do { var c = ~ buf.arr[buf.pos++]; res = (res << 7) | (c & 127); } while(c & 128); return -res; } function popPos(buf) { // ### var res = 0; do { var c = buf.arr[buf.pos++]; res = (res << 7) | (c & 127); } while(c & 128); return res; } function popDouble(buf) { // ### for(var i = 0; i < 8; ++i) { converterBytes[i] = buf.arr[buf.pos++]; } return converterFloat[0]; } function popArr(buf) { // ### var result = []; while(buf.arr[buf.pos]) { result.push(popAny(buf)); } buf.pos++; return result; } function popObj(buf) { // ### var result = {}; while(buf.arr[buf.pos]) { var key = popAny(buf); result[key] = popAny(buf); } buf.pos++; return result; } function fromBon(arr) { // ### return popAny({arr:arr, pos:0}); } // ## bench function arrToStr(arr) { var str = ""; for(var i = 0; i < arr.length; ++i) { str += String.fromCharCode(arr[i]); } return str } exports.any2arr = any2arr; exports.str2arr = str2arr; exports.toBon = toBon; exports.fromBon = fromBon; if(require.main === module) { var o = [3, "hello", -1, 0, 100.1, [0.1,{"hi": ["hello", ["wo", "r", ["l", "d"],{a: 1, c: {b:-3}}, 1,-2,3, "!"]]}]]; //o = [123, 100.1]; var n = 100000; var timings = []; var s; var t0 = Date.now(); for(var i = 0; i < n; ++i) { var json = JSON.stringify(o); } timings.push(Date.now() - t0); t0 = Date.now(); for(var i = 0; i < n; ++i) { JSON.parse(json); } timings.push(Date.now() - t0); t0 = Date.now(); timings.push(json.length); for(var i = 0; i < n; ++i) { var binary = toBon(o); } timings.push(Date.now() - t0); t0 = Date.now(); console.log(JSON.stringify(arrToStr(binary))); console.log(JSON.stringify(fromBon(binary))); for(var i = 0; i < n; ++i) { fromBon(binary); } timings.push(Date.now() - t0); t0 = Date.now(); timings.push(binary.length); console.log(timings, JSON.stringify(o) === JSON.stringify(fromBon(binary))); } })();
(function() { // Prefer camera resolution nearest to 1280x720. var constraints = { audio: true, video: { width: 1280, height: 720 } }; navigator.mediaDevices.getUserMedia(constraints) .then(function(mediaStream) { var video = document.querySelector('video'); video.srcObject = mediaStream; video.onloadedmetadata = function(e) { video.play(); }; }) .catch(function(err) { console.log(err.name + ": " + err.message); }); // always check for errors at the end. var startButton = document.getElementById('startbutton'); startButton.addEventListener('click', function(event) { var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); context.drawImage(video, 0, 0, 1280, 720); var data = canvas.toDataUrl('image/png'); photo.setAttribute('src', data); event.preventDefault(); }, false); })();
import React from "react" import Layout from "../components/layout" import SEO from "../components/seo" import MainNav from "../components/MainNav" import MobileNav from "../components/MobileNav" import BtnAddToRequest from "../components/BtnAddToRequest" import Footer from "../components/Footer" import PageTitle from "../components/PageTitle" import GeneralNames from "../components/GeneralNames" import EnvelopeParam from "../components/EnvelopeParam" import { css } from "@emotion/core" import { useTranslation } from "react-i18next" import rtgData from "../data/rtg" import rtg from "../../static/products/rtg.jpg" export default props => { const T = useTranslation() if (T.i18n.language !== props.pageContext.langKey) { T.i18n.changeLanguage(props.pageContext.langKey) } const t = key => (typeof key === "string" ? T.t(key) : key[T.i18n.language]) return ( <Layout> <SEO title={t("seoRTG")} /> <MainNav {...props} /> <MobileNav {...props} /> <PageTitle title={t("seoRTG")} /> <div css={css` width: 90vw; background: #ffffff; background-position: left; background-repeat: no-repeat; background-size: 40% 80%; margin: 9px auto 50px auto; padding: 30px 70px 90px 70px; color: #000000; display: flex; justify-content: space-between; @media screen and (max-width: 768px) { flex-direction: column; } `} > <div css={css` width: 35%; @media screen and (max-width: 768px) { width: 100%; } `} > <img src={rtg} alt="envelope RTG" /> </div> <div css={css` width: 60%; @media screen and (max-width: 768px) { width: 100%; } `} > <div css={css` font-weight: 500; font-size: 18px; line-height: 27px; width: 100%; a { text-decoration: none; color: black; :hover { text-decoration: underline; } `} dangerouslySetInnerHTML={{ __html: t("rtgText") }} /> <div css={css` font-weight: 500; font-size: 24px; line-height: 27px; padding: 49px 0 0 0; `} > {t("whereUse")} <ul css={css` display: flex; justify-content: start; flex-wrap: wrap; list-style: none; padding: 0; `} > <li css={css` font-weight: 500; font-size: 16px; line-height: 36px; padding-right: 40px; :before { content: "-"; padding-right: 5px; } `} > {t("hospital")} </li> <li css={css` font-weight: 500; font-size: 16px; line-height: 36px; padding-right: 40px; :before { content: "-"; padding-right: 5px; } `} > {t("laboratories")} </li> </ul> </div> </div> </div> <h4 css={css` font-weight: 500; font-size: 28px; line-height: 33px; text-align: center; margin: 54px 0 23px 0; `} > {t("chooseDesiredProduct")} </h4> <div> {rtgData.map(({ code, size, color, boxSize }) => ( <div key={code} css={css` background: #ffffff; box-shadow: 0px 4px 4px rgba(0, 0, 0, 0.25); border-radius: 3px; width: 90vw; margin: 20px auto 54px auto; padding: 30px; display: flex; justify-content: space-around; align-items: center; @media screen and (max-width: 570px) { flex-direction: column; } `} > <div css={css` display: flex; justify-content: space-around; flex: 1; @media screen and (max-width: 1024px) { display: grid; grid-template-columns: repeat(auto-fill, 150px); } `} > <GeneralNames> {t("code")} <EnvelopeParam>{code}</EnvelopeParam> </GeneralNames> <GeneralNames> {t("size")}, {t("mm")} <EnvelopeParam>{size}</EnvelopeParam> </GeneralNames> <GeneralNames> {t("color")} <EnvelopeParam>{t(color)}</EnvelopeParam> </GeneralNames> <GeneralNames> {t("quantityBox")}, {t("pcs")} <EnvelopeParam>{boxSize}</EnvelopeParam> </GeneralNames> </div> <BtnAddToRequest boxQuantity={boxSize} code={code} /> </div> ))} </div> <Footer /> </Layout> ) }
import React, {Component} from 'react'; import SineUpForm from "./SineUpForm"; import PropTypes from 'prop-types' const initValues = { fullName: '', fatherName: '', motherName: '', gender: '', birthDay: '', address: '', password: '' } class SineUp extends Component { // State Declaration state = { values: initValues, agreement: false, errors: {} } // HandleChange Function/Method Declaration handleChange = e =>{ this.setState({ values:{ ...this.state.values, [e.target.name]:e.target.value } }) } // Agreement Change Function/Method Declaration agreementChange = e => { this.setState({ agreement: e.target.checked }) } // Submit Handle Function/Methods Declaration submitHandle = e =>{ e.preventDefault() const {isValid, errors} = this.validate() if(isValid){ this.props.createUsers(this.state.values) console.log(this.state.values) e.target.reset() this.setState({ values: initValues, agreement:false }) }else{ this.setState({ errors }) } } validate = () => { const errors = {} const {values: {fullName, fatherName, motherName, address, birthDay, gender, password}} = this.state //Validation Condition Apply if(!fullName){ errors.fullName = 'Please enter your name' } else if(fullName.length >= 10){ errors.fullName = 'Please type your name within 10 latter' } if(!fatherName){ errors.fatherName = 'Please enter your father name' }else if(fatherName.length > 5){ errors.fatherName = 'Please type father name within five latter' } if(!motherName){ errors.motherName = 'Please enter your mother name' }else if(motherName.length > 5){ errors.motherName = 'Please type mother name within five latter' } if(!address){ errors.address = 'Please enter your address name' }else if(address.length >= 20){ errors.address = 'Please type address within 20 latter' } if(!birthDay){ errors.birthDay = 'Please select your Birthday' } if(!gender){ errors.gender = 'Please select your gender' } if(!password){ errors.password = 'Please enter your password' }else if(password.length >= 8){ errors.password = 'Please type password within eight latter' } // Return Value return { errors, isValid: Object.keys(errors).length ===0 } } render() { return ( <div className='col-md-auto'> <div className='card-header mb-5'> <h2 className='text-danger'>Sine Up Now</h2> </div> <div className='form-row'> <SineUpForm submitHandle={this.submitHandle} handleChange={this.handleChange} data={this.state.values} btnText = 'SineUp Now' errors= {this.state.errors} agreement = {this.state.agreement} agreementHandle={this.agreementChange} /> </div> </div> ); } } SineUp.propTypes = { createUsers: PropTypes.func.isRequired }; export default SineUp;
var unirest = require('unirest'); var changeCase = require('change-case') const facts = require('../tokens/facts.json'); exports.run = function(client, message, args) { let argscmd = message.content.split(" ").slice(1); let month = argscmd[0]; // yes, start at 0, not 1. I hate that too. let day = argscmd[1]; if (!month) return message.reply("Please give me month\nExample:\n!facts 5 1"); if (!day) return message.reply("Please give me day\nExample:\n!facts 5 1"); unirest.get("https://numbersapi.p.mashape.com/" + month + "/" + day + "/date?fragment=true&json=true") .header("X-Mashape-Key", facts.token) .header("Accept", "text/plain") .end(function(result) { // For debug Only //console.log(result.status, result.headers, result.body); console.log("Running command for Facts | Params: Day: " + day + " " + "Month: " + month); var text = changeCase.upperCaseFirst(result.body["text"]) message.channel.send(text + "." + "\n\nDate: " + month + "/" + day + "/" + result.body["year"]); }); }
for (i = 1; i <= 5; i++) { console.log(i * 100); } var j = 1; for (i = 1; i <= 7; i++) { console.log(j); j *= 2; } for (i = 1; i <= 3; i++) { for (j = 1; j <= 3; j++) { console.log(i); } } j = 0; for (i = 1; i <= 6; i++) { console.log(j); j += 2; } j = 0; for (i = 1; i <= 5; i++) { j += 3; console.log(j); } for (i = 9; i >= 0; i--) { console.log(i); } for (i = 0; i < 3; i++) { for (j = 0; j <=3; j++) { console.log(j); } }
import React, { useState, useEffect } from 'react'; import { useDispatch } from 'react-redux'; import { Aside, InputBlock, InputGroup } from './styles'; import { addDevRequest } from '../../store/modules/dev/actions'; export default function Side() { const [loading, setLoading] = useState(false); const [github_username, setGitHubUserName] = useState(''); const [techs, setTechs] = useState(''); const [latitude, setLatitude] = useState(''); const [longitude, setLongitude] = useState(''); const dispatch = useDispatch(); useEffect(() => { navigator.geolocation.getCurrentPosition( position => { setLatitude(position.coords.latitude); setLongitude(position.coords.longitude); }, err => { console.log(err); }, { timeout: 30000, } ); }, []); async function handleSubmit(e) { e.preventDefault(); setLoading(true); dispatch(addDevRequest({ github_username, techs, latitude, longitude })); setLoading(false); } return ( <Aside> <strong>Cadastrar</strong> <form onSubmit={handleSubmit}> <InputBlock> <label htmlFor="github_username">Usuário Github</label> <input type="text" value={github_username} onChange={e => setGitHubUserName(e.target.value)} name="github_username" id="github_username" required /> </InputBlock> <InputBlock> <label htmlFor="techs">Tecnologias</label> <input type="text" name="techs" id="techs" value={techs} onChange={e => setTechs(e.target.value)} required /> </InputBlock> <InputGroup> <InputBlock> <label htmlFor="latitude">Latitude</label> <input type="number" name="latitude" id="latitude" onChange={e => setLatitude(e.target.value)} value={latitude} required /> </InputBlock> <InputBlock> <label htmlFor="longitude">Longitude</label> <input type="number" name="longitude" id="longitude" onChange={e => setLongitude(e.target.value)} value={longitude} required /> </InputBlock> </InputGroup> <button disabled={loading} type="submit"> {loading ? 'Enviando...' : 'Enviar'} </button> </form> </Aside> ); }
$(document).ready(function(){ (function(){ var max_submissions = 3, index = 0, word_of = ['zero', 'one', 'two', 'three']; $('form.new_submission').on('click', '.add_fields', function(e){ e.preventDefault(); index += 1; if(index === 1){ $(this).text('Add Another'); } if(index === max_submissions){ $(this).addClass('inactive'); } if(index > max_submissions) { return; } var time = new Date().getTime(), regexp = new RegExp($(this).data('id'), 'g'), container = $(this).data('container'), $new_form = $($(this).data('fields').replace(regexp, time)); $new_form .addClass(word_of[index]) .find('.submission-label') .html('Piece ' + word_of[index]); if(container !== ''){ $(container).append($new_form.hide().fadeIn()); }else{ $(this).before($new_form).hide().fadeIn(); } }); }()); });
/* Copyright 2012 - $Date $ by PeopleWare n.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. */ define(["dojo/_base/declare", "ppwcode-util-oddsAndEnds/ui/MultiLangFormatOutput"], function(declare, MultiLangFormatOutput) { return declare([MultiLangFormatOutput], { // summary: // This widget is a superclass for widgets that show (not-editable) the value of // a Value in an i18n-ed way, and who can change the representation language. // `lang` is the locale, which can change. `value` is the Value. // Setting these re-renders. // description: // Rendering is done using value.constructor.format. This means the formatter used is dynamic. // The lang of this instance // is injected as the locale in the options to that call, if no locale is set in formatOptions. // value: Value value: null, format: function(/*Value*/ value, /*Object*/ options) { return value.constructor.format(value, options); } }); } );
// general utilities export function uniqueId(prefix) { return (prefix+Math.random().toString(36).substring(2, 10) + Math.random().toString(36).substring(2, 10)) }
/*globals redraw, $*/ "use strict"; exports.pagingControl = function (pager, eventListener) { var _control, _parentControl, _totalItemsCount, that, setPreviousPageCell = function (pageNumber) { var previousCellText = pageNumber === 1 ? '' : 'Previous', previousPageCell = _control.find('.previousPage'), previousNumber = previousCellText ? pageNumber - 1 : ''; previousPageCell.unbind('click'); previousPageCell.text(previousCellText); if (previousNumber) { previousPageCell.attr('id', previousNumber); previousPageCell.bind('click', redraw); } }, setNextCell = function (pageNumber, pageCount) { var nextCellText = pageNumber === pageCount ? '' : 'Next', nextPageCell = _control.find('.nextPage'), nextNumber = nextCellText ? pageNumber + 1 : ''; nextPageCell.unbind('click'); nextPageCell.text(nextCellText); if (nextNumber) { nextPageCell.attr('id', nextNumber); nextPageCell.bind('click', redraw); } }, redraw = function () { var id = $(this).closest('table').attr('id'), pageNumber = Number($(this).attr("id")), pageCount = pager.getPageCount(_totalItemsCount), pageNumbers = pager.getPages(_totalItemsCount, pageNumber), cells = _control.find('.pageNumber'); setPreviousPageCell(pageNumber); setNextCell(pageNumber, pageCount); cells.each(function (index) { var text, cell = $(this); text = pageNumbers[index] || ''; cell.removeClass('currentPageNumber'); cell.unbind('click'); cell.text(text); cell.attr('id', text); if (pageNumbers[index]) { cell.bind('click', redraw); if (pageNumbers[index] === pageNumber) { cell.addClass('currentPageNumber'); } } }); eventListener.fire('page', [id, pageNumber]); }, constructControl = function (documentId, totalLineCount, pageSize, pageNumber) { var row, cell, pageNumbers, control; control = $('<table>').addClass('pagingControl').attr("id", documentId); row = $('<tr>'); cell = $('<td>').text('').addClass("previousPage"); row.append(cell); pageNumbers = pager.getPages(totalLineCount, pageNumber); pageNumbers.forEach(function (pageNumber) { cell = $('<td>').text(pageNumber).addClass("pageNumber"); cell.attr('id', pageNumber); cell.bind('click', redraw); row.append(cell); }); cell = $('<td>').text("Next").addClass("nextPage"); row.append(cell); control.append(row); return control; }; that = { initialize : function (parentControl) { _parentControl = parentControl; }, hide: function () { _parentControl.hide(); }, create : function (documentId, totalLineCount, pageSize, pageNumber) { var pageCount, pageNumbers, cells; if (totalLineCount === 0 || totalLineCount < (pageSize + 1)) { return; } _totalItemsCount = totalLineCount; _control = constructControl(documentId, totalLineCount, pageSize, pageNumber); pageCount = pager.getPageCount(totalLineCount); pageNumbers = pager.getPages(totalLineCount, pageNumber); _parentControl.empty(); cells = _control.find('.pageNumber'); setPreviousPageCell(pageNumber); setNextCell(pageNumber, pageCount); cells.each(function (index) { var text, cell = $(this); text = pageNumbers[index] || ''; cell.removeClass('currentPageNumber'); cell.unbind('click'); cell.text(text); cell.attr('id', text); if (pageNumbers[index]) { cell.bind('click', redraw); if (pageNumbers[index] === pageNumber) { cell.addClass('currentPageNumber'); } } }); _parentControl.append(_control); _parentControl.show(); eventListener.fire('page', [documentId, pageNumber]); } }; return that; };
export const SEARCH = "SEARCH"; export const GET_COMPANY_PROFILE = "GET_COMPANY_PROFILE";
const { ObjectId } = require('mongodb'); const convertIdInDocument = (document) => { const newDocument = { ...document }; newDocument._id = document._id.toString(); return newDocument; }; const checkValidStrings = (stringObject) => { for (const key of Object.keys(stringObject)) { const value = stringObject[key]; if (!value || typeof value !== 'string' || !value.trim()) throw `${key} must be a non-empty string.`; } }; const checkValidArrayOfStrings = (array, name = 'array') => { if ( !array || array.constructor !== Array || array.length === 0 || array.filter((item) => item && !!item.trim()).length === 0 || array.filter((item, ind) => array.indexOf(item) !== ind).length !== 0 ) throw `${name} must be a non-empty array with no duplicates.`; }; const checkValidArray = (array, name = 'array') => { if (!array || array.constructor !== Array) throw `${name} must be an array.`; }; const checkValidObject = (object, name = 'object') => { if (!object || typeof object !== 'object' || object === null) throw `${name} must be an object.`; }; const checkDate = (dateString) => { const date = new Date(dateString); if (date.getTime() !== date.getTime()) throw 'invalid date'; }; const parseId = (id) => { checkValidStrings({ id }); return ObjectId(id.trim()); }; function checkReviewsFields(fields) { const validFields = { title: (title) => checkValidStrings({ title }), reviewer: (reviewer) => checkValidStrings({ reviewer }), bookBeingReviewed: (id) => parseId(id), rating: (rating) => checkValidRating(rating), dateOfReview: (date) => checkDate(date), review: (review) => checkValidStrings({ review }), }; for (const field of Object.keys(fields)) { if (!validFields[field]) throw `invalid field ${field} passed in!`; validFields[field](fields[field]); } } function checkBooksFields(fields) { const validFields = { title: (title) => checkValidStrings({ title }), author: (author) => { checkValidObject(author); try { checkValidStrings({ firstName: author.authorFirstName, }); } catch (error) { try { checkValidStrings({ lastName: author.authorLastName }); } catch (error) { throw 'missing fields'; } } }, genre: (genre) => checkValidArrayOfStrings(genre), datePublished: (date) => checkDate(date), summary: (summary) => checkValidStrings({ summary }), reviews: (reviews) => checkValidArray(reviews), }; for (const field of Object.keys(fields)) { if (!validFields[field]) throw `invalid field ${field} passed in!`; validFields[field](fields[field]); } } const checkValidRating = (number) => { const convert = Number(number); if ( isNaN(convert) || convert < 1 || convert > 5 || !Number.isInteger(number) ) throw 'rating must be an integer between 1 and 5'; }; module.exports = { checkBooksFields, parseId, checkDate, checkValidArrayOfStrings, checkValidObject, checkValidStrings, checkValidRating, convertIdInDocument, checkReviewsFields, checkValidArray, };
export const preProcessCountryData = data => { const keys = Object.keys(data || {}); keys.sort().reverse(); const today = data[keys[0]] || []; const yesterday = data[keys[1]] || []; const dayBeforeYesterday = data[keys[2]] || []; const todaysInitData = getDaysData(today); const yesterdaysInitData = getDaysData(yesterday); const dayBeforeYesterdayInitData = getDaysData(dayBeforeYesterday); const todaysData = addNewCases(todaysInitData, yesterdaysInitData); const yesterdaysData = addNewCases(yesterdaysInitData, dayBeforeYesterdayInitData) const indiaTotal = getTodaysGrandTotal(todaysData, yesterdaysData); return { indiaTotal, todaysData, yesterdaysData }; }; const addNewCases = (todaysInitData, yesterdaysData) => { return todaysInitData.map(state => { const yesterdaysStateData = yesterdaysData.find(yState => yState.name === state.name) || {}; return { ...state, newActive: state.total - (yesterdaysStateData.total || 0), newRecovered: state.recovered - (yesterdaysStateData.recovered || 0), newDeaths: state.death - (yesterdaysStateData.death || 0) }; }); }; const getDaysData = day => (day || []).map(state => { const total = Number.parseInt(state.totalIndians || 0) + Number.parseInt(state.totalForeign || 0); return { ...state, total: total, active: total - Number.parseInt(state.recovered || 0) - Number.parseInt(state.death || 0) }; }); const getTodaysGrandTotal = (today, yesterday) => { const totalYesterday = yesterday.reduce( (acc, state) => acc + Number.parseInt(state.total || 0), 0 ); const grandTotal = today.reduce( (acc, state) => ({ totalCases: (acc.totalCases || 0) + Number.parseInt(state.total || 0), totalRecovered: (acc.totalRecovered || 0) + Number.parseInt(state.recovered || 0), totalDeath: (acc.totalDeath || 0) + Number.parseInt(state.death || 0) }), {} ); grandTotal.newCases = grandTotal.totalCases - totalYesterday; return grandTotal; };
import Route from '@ember/routing/route'; import { inject as service } from '@ember/service'; import { isEmpty } from '@ember/utils'; export default Route.extend({ kredits: service(), redirect () { this._super(...arguments); let accessToken; try { accessToken = window.location.hash.match(/access_token=(.+)/)[1]; } catch (error) { /* ignore */ } if (isEmpty(accessToken) || accessToken === 'undefined') { console.error('No GitHub access token found.'); this.transitionTo('signup'); return; } this.kredits.set('githubAccessToken', accessToken); this.transitionTo('signup.account'); } });
var gazou= prompt("パズルを選択してください。1:数字パズル、2:花火、3:ローマ数字、4:夕日 数値を入力 : ","1"); if(gazou == 1){ gazou = 'img/15puzzle.png' }else if(gazou == 2){ gazou = 'img/hanabi.jpg' }else if(gazou == 3){ gazou = 'img/ro-masuuji.jpg' }else if(gazou == 4){ gazou = 'img/yuuhi.jpg' }else{ document.write("正しい数値を入力してください。") } var Difficulty = prompt("難易度を設定します。数値が大きいほど難易度は高くなります。整数を入力 : ","30"); (() => { class Puzzle { constructor(canvas, level) { //canvasを受け取る  this.canvas = canvas; //puzzleクラスにプロパティとしてcanvasをセット this.level = level; this.ctx = this.canvas.getContext('2d'); //canvasに描画するためのコンテキストを取得しctxに格納 引数を2dにすることで2Dグラフィックに this.TILE_SIZE = 70; //一つのタイルのサイズ this.tiles = [ //行ごとの配列の配列を作成 [0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15], ]; this.isCompleted = false; this.img = document.createElement('img'); //画像をプロパティとして保持 this.img.src = gazou; //画像を読み込む this.img.addEventListener('load', () => { //画像を読み終えたときに次の処理 this.render(); //renderメソッドを呼び出す }); this.canvas.addEventListener('click', e => {  //クリックしたときの処理 クリックしたところの座標を取得 if (this.isCompleted === true) { //ゲームをクリアしたらクリックイベントを起こさない return; } const rect = this.canvas.getBoundingClientRect(); //getBoundingClientRectで位置やサイズのオブジェクトを取得 const col = Math.floor((e.clientX - rect.left) / this.TILE_SIZE); //クリックされた座標が何列目かを計算 左端を原点にしたいので上で取得したオブジェクトを引く const row = Math.floor((e.clientY - rect.top) / this.TILE_SIZE); //クリックされた座標が何行目かを計算 this.swapTiles(col, row); //タイルを入れ替えるメソッドに列と行をセット this.render(); //タイルを入れ替えた後に再描画 if (this.isComplete() === true) {        //すべてを並び終えたらrenderGameClearを呼ぶ this.isCompleted = true; this.renderGameClear(); } }); do { //シャッフルしたときに最初から完成していたらやり直し this.shuffle(this.level); //shuffleに渡す引数を設定 } while (this.isComplete() === true); } shuffle(n) { let blankCol = 3; //空白の初期位置を右下に let blankRow = 3; for (let i = 0; i < n; i++) { //n回文シャッフルするためのループ let destCol; //空白を動かす先の列と行を変数で宣言 let destRow; do { //範囲外の時にやりなおす const dir = Math.floor(Math.random() * 4); //動かす先をランダムにするために0から3までのランダムな整数値を作成 switch (dir) { //dirの値に応じで上下左右で列と行の計算 case 0: // up destCol = blankCol; destRow = blankRow - 1; break; case 1: // down destCol = blankCol; destRow = blankRow + 1; break; case 2: // left destCol = blankCol - 1; destRow = blankRow; break; case 3: // right destCol = blankCol + 1; destRow = blankRow; break; } } while ( //範囲外になる条件 destCol < 0 || destCol > 3 || destRow < 0 || destRow > 3 ); [ //分割代入を使って入れ替える this.tiles[blankRow][blankCol], this.tiles[destRow][destCol], ] = [ this.tiles[destRow][destCol], this.tiles[blankRow][blankCol], ]; [blankCol, blankRow] = [destCol, destRow]; //空白のタイルが動いたら更新 } } swapTiles(col, row) { if (this.tiles[row][col] === 15) { //クリックしたタイルが15だったら何もしない return; } for (let i = 0; i < 4; i++) { //クリックしたタイルの上下左右が空白かどうかを調べるループ let destCol; //調べたいタイルの列 let destRow; //調べたいタイルの行 switch (i) { //switchで上下左右、4回分 case 0: //0だった場合は上を調べる destCol = col; //列はそのまま destRow = row - 1; //一つ上の行なのでrowから1をひく break; case 1: //1だった場合は下を調べる destCol = col; destRow = row + 1; //一つ下の行なのでrowに1を足す break; case 2: //2だった場合は左を調べる destCol = col - 1; //1つ左の列なのでcol-1 destRow = row; break; case 3: //3だった場合は右を調べる destCol = col + 1; //1つ右の列なのでcol+1 destRow = row; break; } if ( //this.tilesの範囲を超えるとエラーになるのでチェック destCol < 0 || destCol > 3 || destRow < 0 || destRow > 3 ) { continue; } if (this.tiles[destRow][destCol] === 15) { //中身が15、空白だったら入れ替える [ this.tiles[row][col], this.tiles[destRow][destCol], ] = [ this.tiles[destRow][destCol], this.tiles[row][col], ]; break; } } } isComplete() { //ゲームクリアの判定 let i = 0; for (let row = 0; row < 4; row++) { for (let col = 0; col < 4; col++) { if (this.tiles[row][col] !== i++) { return false; } } } return true; } renderGameClear() { //ゲームクリアしたときに呼び出される処理 this.ctx.fillStyle = 'rgba(0, 0, 0, 0.4)'; //半透明の黒色の四角 this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height); //を上にかぶせる this.ctx.font = '28px Arial'; //フォントの設定 this.ctx.fillStyle = '#fff'; //文字を白色に this.ctx.fillText('GAME CLEAR!!', 40, 150); //表示される文字と位置 } render() { //描画するメソッドを作成、すべての値を描画したいので2重ループを作成 for (let row = 0; row < 4; row++) { //行数分のループ for (let col = 0; col < 4; col++) { //列数分のループ this.renderTile(this.tiles[row][col], col, row); //row,colのあたいのタイルを切り出してcol列目、row列目に描画 } } } renderTile(n, col, row) { //メソッドの定義、引数を設定 if (n === 15) { //空白の時に見やすくグレーに表示させる this.ctx.fillStyle = '#eeeeee'; this.ctx.fillRect(col * this.TILE_SIZE, row * this.TILE_SIZE, this.TILE_SIZE, this.TILE_SIZE); } else { this.ctx.drawImage( //画像の一部を切り出す this.img, (n % 4) * this.TILE_SIZE, Math.floor(n / 4) * this.TILE_SIZE, this.TILE_SIZE, this.TILE_SIZE, //タイルのサイズである幅70高さ70の領域を切り出す    //sxの座標は0、1、2、3と繰り返され、syはnが1増えるごとに4づつ増えるので上記の記述に col * this.TILE_SIZE, row * this.TILE_SIZE, this.TILE_SIZE, this.TILE_SIZE //canvasのdx,dy座標の同じ大きさの領域に描画 //dxはcolが1増えるごとに70増えdyはrowが1増えるごとに70増える。 ); } } } const canvas = document.querySelector('canvas'); //canvas要素を取得 if (typeof canvas.getContext === 'undefined') { //canvasが取得できなかった時 return; //returnを使用するために全体に即時関数を適用 } new Puzzle(canvas, Difficulty); //インスタンスを作成して引数にcanvasをセット、シャッフル回数をセット })();
const worker = require('./worker'); /* * A queue to decouple API server from the outgoing requests * done by `workers`. * * Currently, we utilize the internal queue of node.js. It is * possible that this will be replaced by a proper standalone * message queue in the future. */ class Queue { enqueue (notification) { // The processing is not awaited to simulate the behavior of // a "proper" queue and not delay the caller. worker.process(notification); } } let _Q; function get () { if (!_Q) { _Q = new Queue(); } return _Q; } module.exports = { get: get, };