text
stringlengths
7
3.69M
import React from "react"; import Menu from "./Menu"; import ProfileInfo from "./ProfileInfo"; import Security from "./Security"; import "./Settings.css"; function SettingPage({ currentTab, authUser, setAuthValue }) { return ( <div className="settings-wrapper"> <div className="settings-container"> <Menu currentTab={currentTab} /> <div className="settings-tab-container"> {currentTab === "Profile" && ( <ProfileInfo authUser={authUser} setAuthValue={setAuthValue} /> )} {currentTab === "Security" && <Security />} </div> </div> </div> ); } export default SettingPage;
import tw from 'tailwind-styled-components' /** */ export const StyledNameItemLabel= tw.div` text-xl `
import React from 'react'; import Question from './components/Question'; function App() { return ( <div className="container"> <header className="container"> <h1>Weekly spending</h1> <Question /> </header> </div> ); } export default App;
import React, { Component } from 'react'; export default class Notes extends Component { render() { return ( <div id="headerWrapper" className="indigoBackground"> <div className="container"> <div id="logo"></div> <h1>EelcoBosklopper.com</h1> <ul id="navigation"> <li><a href="/">Home</a></li> <li><a href="#">Portfolio</a></li> <li><a href="#">Skills</a></li> <li><a href="#">Contact</a></li> </ul> </div> </div> ); } }
var requirejs = require('requirejs'); var Backbone = require('backbone'); var PageConfig = requirejs('page_config'); var Controller = requirejs('extensions/controllers/controller'); var PrototypesView = require('../views/prototypes'); var PrototypesController = Controller.extend({ viewClass: PrototypesView }); module.exports = function (req, res) { var model = new Backbone.Model(); model.set(PageConfig.commonConfig(req)); var prototypesController = new PrototypesController({ model: model, raw: req.query.raw, url: req.originalUrl }); prototypesController.render(); res.send(prototypesController.html); };
var myapp = angular.module( 'appDoctorado' , [ "ui.router" ]) myapp.config(function( $stateProvider , $urlRouterProvider ){ // For any unmatched url, send to /route1 $urlRouterProvider.otherwise( "/views/route1" ) $stateProvider .state( 'route1' , { url: "/ruta 1", //nombre que aparecera en la url templateUrl: "views/route1.html" //Direccion del archivo que sera llamado }) .state( 'route1.list' , { url: "/views/list", templateUrl: "views/route1.list.html", controller: function($scope){ $scope.items = ["A", "List", "Of", "Items"]; } }) .state('route2', { url: "/views/route2", templateUrl: "views/route2.html" }) .state('route2.list', { url: "/views/list", templateUrl: "views/route2.list.html", controller: function($scope){ $scope.things = ["A", "Set", "Of", "Things"]; } }) .state('1', { url: "/views/route2", templateUrl: "views/route2.html" }) .state('1.list', { url: "/views/list", templateUrl: "views/route2.list.html", controller: function($scope){ $scope.things = ["A", "Set", "Of", "Things"]; } }) })
(function() { 'use strict'; angular .module('template.AboutUs') .controller("AboutUsController", function(){ var self = this; self.name = "Nevendra's About Us Page"; self.hey = 'hey there' }); })();
// // ScriptWidget // https://scriptwidget.app // // Usage for component capsule // $render( <vstack frame="max"> <capsule frame="50,30" color="blue"></capsule> </vstack> );
/** * Class for Stage. * @author htanjo */ define([ 'three' ], function () { /** * Create a stage. * @class Stage * @augments THREE.Object3D */ var Stage = function (mapOffset, mapSize, blockMap) { var chipSize = 100, groundTexture = 'img/ground_00_top.jpg', blockTextures = [ 'img/block_00_side.jpg', 'img/block_00_side.jpg', 'img/block_00_top.jpg', 'img/block_00_top.jpg', 'img/block_00_side.jpg', 'img/block_00_side.jpg' ]; this.setGround(blockMap, mapOffset, mapSize, chipSize, groundTexture); this.setMapChips(blockMap, chipSize, blockTextures); }; Stage.prototype = new THREE.Object3D(); Stage.prototype.constructor = Stage; /** * Set map-chips in array. * @param {Array} map Arrangement map of 2x2 array. * @param {Number} chipSize Size of map chip. * @param {Array} textures Array of texture file path. */ Stage.prototype.setMapChips = function (map, chipSize, textures) { var blocks = [], block = {}, materials = [], i, j; for (i = 0; i < textures.length; i++) { materials.push(new THREE.MeshPhongMaterial({ map: THREE.ImageUtils.loadTexture(textures[i]), ambient: 0x030303, specular: 0xcccc66, shininess: 15 })); } block.size = new THREE.Vector3(chipSize, chipSize * 2, chipSize); block.geometry = new THREE.CubeGeometry(block.size.x, block.size.y, block.size.z, 1, 1, 1, materials); block.material = new THREE.MeshFaceMaterial(); for (i = 0; i < map.length; i++) { blocks[i] = []; for (j = 0; j < map[i].length; j++) { if (map[i][j] !== 0) { blocks[i][j] = {}; blocks[i][j].mesh = new THREE.Mesh(block.geometry, block.material); blocks[i][j].mesh.position.x = block.size.x / 2 + block.size.x * j; blocks[i][j].mesh.position.y = block.size.y / 2; blocks[i][j].mesh.position.z = block.size.z / 2 + block.size.z * i; this.add(blocks[i][j].mesh); } } } }; /** * Set ground. * @param {THREE.Vector2} offset Offset position of ground. * @param {THREE.Vector2} size Size of ground. * @param {Number} chipSize Size of map chip. * @param {Array} texture Array of texture file path. */ Stage.prototype.setGround = function (map, offset, size, chipSize, texture) { var self = this; var ground = {}, fullSize = new THREE.Vector2(size.x + chipSize * 2, size.y + chipSize * 2), i, j; ground.canvas = document.createElement('canvas'); ground.canvas.width = fullSize.x; ground.canvas.height = fullSize.y; ground.ctx = ground.canvas.getContext('2d'); ground.image = new Image(); ground.image.src = texture; ground.image.onload = function () { for (i = 0; i < fullSize.x / chipSize; i++) { for (j = 0; j < fullSize.y / chipSize; j++) { ground.ctx.drawImage(ground.image, 0, 0, chipSize, chipSize, i * chipSize, j * chipSize, chipSize, chipSize) } } for (i = 0; i < fullSize.x / chipSize; i++) { for (j = 0; j < fullSize.y / chipSize; j++) { if (map[j][i] !== 0) { ground.ctx.rect(i * chipSize, j * chipSize, chipSize, chipSize); ground.ctx.fillStyle = '#000000'; } } } ground.ctx.shadowColor = '#000000'; ground.ctx.shadowBlur = 80; ground.ctx.fill(); ground.ctx.fill(); ground.texture = new THREE.Texture(ground.canvas); ground.texture.needsUpdate = true; ground.geometry = new THREE.PlaneGeometry(fullSize.x, fullSize.y, fullSize.x / chipSize, fullSize.y / chipSize); ground.material = new THREE.MeshLambertMaterial({ map: ground.texture, ambient: 0x030303 }); ground.mesh = new THREE.Mesh(ground.geometry, ground.material); ground.mesh.position.set(size.x / 2 + offset.x, 0, size.y / 2 + offset.y); ground.mesh.rotation.x = -90 / 180 * Math.PI; var walls = { nx: {}, px: {}, nz: {}, pz: {} }; walls.nx.geometry = new THREE.CubeGeometry(size.x, 1000, 20, size.x / chipSize, 1000 / chipSize, 1); walls.px.geometry = new THREE.CubeGeometry(size.x, 1000, 20, size.x / chipSize, 1000 / chipSize, 1); walls.nz.geometry = new THREE.CubeGeometry(20, 1000, size.y, 1, 1000 / chipSize, size.y / chipSize); walls.pz.geometry = new THREE.CubeGeometry(20, 1000, size.y, 1, 1000 / chipSize, size.y / chipSize); walls.nx.material = new THREE.MeshLambertMaterial({ map: THREE.ImageUtils.loadTexture('img/wall_00_side.jpg'), ambient: 0x030303 }); walls.nx.mesh = new THREE.Mesh(walls.nx.geometry, walls.nx.material); walls.px.mesh = new THREE.Mesh(walls.px.geometry, walls.nx.material); walls.nz.mesh = new THREE.Mesh(walls.nz.geometry, walls.nx.material); walls.pz.mesh = new THREE.Mesh(walls.pz.geometry, walls.nx.material); walls.nx.mesh.position.set(size.x / 2 + offset.x, 1000 / 2, offset.y - 20 / 2); walls.px.mesh.position.set(size.x / 2 + offset.x, 1000 / 2, size.y + offset.y + 20 / 2); walls.nz.mesh.position.set(offset.x - 20 / 2, 1000 / 2, size.y / 2 + offset.y); walls.pz.mesh.position.set(size.x + offset.x + 20 / 2, 1000 / 2, size.y / 2 + offset.y); self.add(ground.mesh); self.add(walls.nx.mesh); self.add(walls.px.mesh); self.add(walls.nz.mesh); self.add(walls.pz.mesh); }; }; return Stage; });
// Task A02 // Design a suitable, single SQL ‘CREATE TABLE’ instruction that results // in the creation (IF NOT EXISTS) of the ‘Messages’ table as illustrated in the AdaBoard schema; // don’t forget to include the Primary Key and Foreign Key constraint - ensure your FK cascades any user table deletes. // Repeat the setup for “CURRENT_TIMESTAMP” as outlined in the previous requirement. const createMessages = ` ` module.exports = { createMessages };
import React from 'react'; import styles from "./Header.module.css"; import Columns from "../../Utility/Columns/Columns" function Header({ nav, left, right }) { return ( <header> {nav} <div className={styles.header_lower_row} > <Columns left={left} right={right} /> </div> </header> ) } export default Header;
import React from "react"; import {useDispatch, useSelector} from "react-redux"; import ProfileImg from "./ProfileImg"; import moment from "moment"; const ContactsItem = ({contact, isVisible, toggleIsVisible}) => { const dispatch = useDispatch(); const messagesHistory = useSelector(state => state.messages.messagesHistory); const activeContact = useSelector(state => state.contacts.activeContact); const getLastMessage = (contactId) => { return contact.id in messagesHistory ? messagesHistory[contactId][messagesHistory[contactId].length - 1] : ''; } const handleClickContact = () => { dispatch({type: 'SET_ACTIVE', payload: contact}); toggleIsVisible(!isVisible); } return ( <li className={activeContact.id === contact.id? 'contacts__item contacts__item--active' : 'contacts__item'} key={contact.id} onClick={handleClickContact}> <ProfileImg contact={contact}/> <div className="contacts__content"> <p className="contacts__name">{contact.name}</p> {getLastMessage(contact.id) ? <> <p className="contacts__date">{moment(getLastMessage(contact.id).date).format('MMM D , YYYY')}</p> <p className="contacts__message">{getLastMessage(contact.id).value}</p> </> : ''} </div> </li> ); }; export default ContactsItem;
/* eslint-disable no-console */ const parseArgs = require("minimist")(process.argv.slice(2)); const logCli = require("./build-utils/log-cli"); const spawn = require("child_process").spawn; const chokidar = require("chokidar"); require("dotenv").config(); let spawnedProcess = ""; let { theme, tenant } = process.env; if (!theme || !theme.length) { theme = ""; } if (!tenant || !tenant.length) { tenant = ""; } let watcher = null; const watch = () => { watcher = chokidar.watch(["./themes/"], { ignoreInitial: true, }); let serve = executeServe(); watcher .on("add", () => { queueWatch(serve); }) .on("unlink", () => { queueWatch(serve); }); }; let watchTimer = null; function queueWatch(serve) { console.log("queue watcher"); spawnedProcess.kill(); if (watchTimer) { clearTimeout(watchTimer); } watchTimer = setTimeout(() => { logCli("rebuilding"); serve = executeServe(); }, 2000); } function executeServe() { const cmd = `vue-cli-service`; spawnedProcess = spawn(cmd, ["serve"], { env: { ...process.env, VUE_APP_CONTEXT: "watch", NODE_ENV: "development", VUE_APP_THEME: theme, VUE_APP_TENANT: tenant, NODE_TLS_REJECT_UNAUTHORIZED: 0, }, stdio: "inherit", detached: true, }); return spawnedProcess; } function exitHandler(options) { if (watchTimer) { clearTimeout(watchTimer); } if (watcher) { watcher.close(); } if (options.exit) { spawnedProcess.kill(); process.exit(); } } watch(); process.on("exit", exitHandler.bind(null, { cleanup: true })); process.on("SIGINT", exitHandler.bind(null, { exit: true })); process.on("SIGUSR1", exitHandler.bind(null, { exit: true })); process.on("SIGUSR2", exitHandler.bind(null, { exit: true })); process.once("SIGTERM", exitHandler.bind(null, { exit: true })); process.on("uncaughtException", function(err) { console.error(new Date().toUTCString() + " uncaughtException:", err.message); console.error(err.stack); process.exit(1); });
// listen to TCP (transmission control protocol) connections on stdin port (argv 1) // print 24hr date time to stdout // networking module const net = require("net"); // format Date object to %Y-%m-%d %H:%M function formatDateTime() { return (new Date()).toISOString().replace(/T/, " ").replace(/\:(?!\d{2}\:).*$/, ""); } // set up simple server const server = net.createServer((socket) => { // socket object contains connection meta data and can be read from, written to // write formatted datetime to socket and close socket.end(formatDateTime() + "\n"); }); // connect to stdin port server.listen(parseInt(process.argv[2]));
var SkipAds = require('./skip_ads'); describe('SkipAds', function() { var skipAds, player; beforeEach(function(done) { var video = document.createElement('video'); video.id = 'video'; video.className = 'video-js'; document.body.appendChild(video); player = videojs('video'); player.ready(function() { done(); }); }); afterEach(function() { player.dispose(); }); describe('options', function() { describe('defaults', function() { beforeEach(function() { skipAds = new SkipAds(player, {}); }); it('allows preroll skip after 5 seconds', function() { expect(skipAds.settings.delayInSeconds).to.equal(5); }); it('allows preroll skip by default', function() { expect(skipAds.settings.skip).to.be.true; }); }); describe('can override preroll skip', function() { it('allows preroll skip to be configured', function() { skipAds = new SkipAds(player, { delayInSeconds: 10 }); expect(skipAds.settings.delayInSeconds).to.equal(10); }); it('allows skippability to be configured', function() { skipAds = new SkipAds(player, { skip: false }); expect(skipAds.settings.skip).to.be.false; }); }); }); describe('new SkipAds', function() { it('calls #init on new', function() { stub(SkipAds.prototype, 'init'); skipAds = new SkipAds(player, {}); expect(SkipAds.prototype.init.called).to.be.true; }); }); describe('#init', function() { beforeEach(function() { stub(SkipAds.prototype, 'createButton'); stub(SkipAds.prototype, 'setupEventHandlers'); skipAds = new SkipAds(player, {}); }); it('calls createButton', function() { expect(SkipAds.prototype.createButton.called).to.be.true; }); it('calls setupEventHandlers', function() { expect(SkipAds.prototype.setupEventHandlers.called).to.be.true; }); }); describe('#createButton', function() { beforeEach(function() { skipAds = new SkipAds(player, {}); }); it('appends a div at the bottom of the videojs div', function() { expect($('#video .videojs-ads-info').length).to.equal(1); }); it('sets a reference to adsInfo on the object', function() { expect(skipAds.adsInfo).to.equal($('.videojs-ads-info')[0]); }); it('sets a reference to skip button on the object', function() { expect(skipAds.skipButton).to.equal($('.videojs-ads-info a')[0]); }); it('sets a reference to the time left span on the object', function() { expect(skipAds.timeLeftInfo).to.equal($('.videojs-ads-info span')[0]); }); }); describe('#skipButtonClicked', function() { beforeEach(function() { skipAds.player.vpApi = { skipAd: function(){} }; stub(skipAds.player.vpApi, 'skipAd'); skipAds.skipButtonClicked(); }); it('skips the ad', function() { expect(skipAds.player.vpApi.skipAd.called).to.be.true; }); }); describe('#timeUpdate', function() { describe('not ad state playback', function() { beforeEach(function() { skipAds = new SkipAds(player, {}); skipAds.timeLeft = undefined; skipAds.player.ads = { state: null }; skipAds.timeUpdate(); }); it('does not do anything', function() { expect(skipAds.timeLeft).to.be.undefined; }); }); describe('ad state playback', function() { beforeEach(function() { skipAds = new SkipAds(player, {}); skipAds.timeLeft = undefined; skipAds.player.ads = { state: 'ad-playback' }; stub(skipAds.player, 'currentTime', 5); stub(skipAds.player, 'duration', 30); skipAds.timeUpdate(); }); it('adds enabled class to info div', function() { expect($(skipAds.adsInfo).hasClass('enabled')).to.be.true; }); it('sets timeLeft and updates the user info', function() { expect(skipAds.timeLeft).to.equal(25); expect(skipAds.timeLeftInfo.innerHTML).to.equal('Your video will resume in 25 seconds'); }); }); describe('skip disabled, but past setting', function() { beforeEach(function() { skipAds = new SkipAds(player, { skip: false }); skipAds.timeLeft = undefined; skipAds.player.ads = { state: 'ad-playback' }; stub(skipAds.player, 'currentTime', 15); stub(skipAds.player, 'duration', 30); skipAds.timeUpdate(); }); it('will not add class to skipButton', function() { expect($(skipAds.skipButton).hasClass('enabled')).to.be.false; }); }); describe('skip enabled but not past delay', function() { beforeEach(function() { skipAds = new SkipAds(player, {}); skipAds.timeLeft = undefined; skipAds.player.ads = { state: 'ad-playback' }; stub(skipAds.player, 'currentTime', 4); stub(skipAds.player, 'duration', 30); skipAds.timeUpdate(); }); it('will not add class to skipButton', function() { expect($(skipAds.skipButton).hasClass('enabled')).to.be.false; }); }); describe('skip enabled and past delay', function() { beforeEach(function() { skipAds = new SkipAds(player, {}); skipAds.timeLeft = undefined; skipAds.player.ads = { state: 'ad-playback' }; stub(skipAds.player, 'currentTime', 15); stub(skipAds.player, 'duration', 30); skipAds.timeUpdate(); }); it('will add class to skipButton', function() { expect($(skipAds.skipButton).hasClass('enabled')).to.be.true; }); }); }); describe('#adEnd', function() { beforeEach(function() { skipAds = new SkipAds(player, {}); skipAds.addClass(skipAds.adsInfo, 'enabled'); skipAds.adEnd(); }); it('remove "enabled" class to adsInfo', function() { expect($(skipAds.adsInfo).hasClass('enabled')).to.be.false; }); }); describe('#setupEventHandlers', function() { it('calls adEnd on adend event', function() { stub(SkipAds.prototype, 'adEnd'); skipAds = new SkipAds(player, {}); skipAds.player.trigger('adend'); expect(SkipAds.prototype.adEnd.called).to.be.true; }); it('calls timeUpdate on timeupdate event', function() { stub(SkipAds.prototype, 'timeUpdate'); skipAds = new SkipAds(player, {}); skipAds.player.trigger('adtimeupdate'); expect(SkipAds.prototype.timeUpdate.called).to.be.true; }); }); });
export default { id: '9', title: 'Dérivation des motifs', date: '07/09/2020', tags: [ 'patterns', 'dev', 'abs' ], content: ` ## Mise en garde sur l'utilisation des motifs "La carte n'est pas le territoire" Et, je rajouterais, Ce n'est pas forcément le territoire de la carte ... Il est tentant de prendre pour un motif Un individu Mais les motifs, se combinant à l'infini, Engendre un nombre exponentiellement croissant vers l'infini De manifestations Transitivement, les manifestations et les motifs, Se composent les uns les autres, De façon dynamique, Assurant la poursuite du ré-engendrement permanent. Ainsi, dire qu'une chose est ce qu'elle est C'est balbutier avec de la compote dans la bouche. C'est rater le mouvement et l'inter-relation, L'absence de frontières et la composition-décomposition permanente. **Merci donc de garder en tête l'idée suivante : <br>Sachez voir la spécificité derrière chacun de vos motifs, <br>Et, humblement, acceptez de les faire évoluer avec vos a priori\*.** *\*C'est la dérivation des motifs.* ## Dans le monde de l'informatique Heureusement, les mondes des humains sont Autrement plus simples Ce sont des mondes remplis de motifs dérivés à partir Du un-éternel, Au lieu de la nature infinie et mouvante du chaos. La philosophie des anciens grecs, Des anciens chinois, des anciens indiens Ainsi que toutes les sociétés historiques Et les tribus Ils ont tous dérivé leurs concepts de l'Un Car en fait leur capacité d'attention était limitée ... Et qu'il leur était plus doux et plaisant de l'avoir fixé sur le tout-un Pour traduire l'apparente et infinie complexité du monde, Leurs motifs ont fini par prendre la même apparence de chaos Bien qu'initialement le premier motif eût été : Stimuli / pas stimuli, Maintenant les motifs forment une jungle dense dans laquelle L'informaticien doit avec justesse retrouver le chemin de la résorbtion. ## Nommer, le premier pouvoir Nommer c'est amener à l'existence Nommer c'est le lien entre un motif Et les idées qui vont être générées autour De ses instances au nombre variable Souvent le nom fait un noeud entre Un motif et un contexte, C'est-à-dire un autre motif. De toutes façons, On ne peut rien faire d'autre qu'associer des motifs Nos mots, notre langue, notre inconscient, Ils parlent tous en motifs S'ils pouvaient s'aligner entre eux Et sur la réalité "une" de toute chose, Grande serait notre joie Et encore plus douce nous serait la vie. ## Concrètement pour le code Selon le principe du DRY, Le générique doit être extrait du code Pour faire du nombre un seul et même motif ... Auquel on peut désormais associer de façon intéropérable Les mêmes processeurs. Je commence par le premier motif qui m'intéresse : **Le motif "motif"** **Ensuite, de la façon la plus naïve au monde,** Je déploie les motifs les uns après les autres À mesure que je développe ma codebase Et rencontre des mécanismes qui se répètent et se combinent La dérivation des motifs est simplement L'action de **trouver une règle plus générale <br>Qui, en même temps, allège les règles des individus qu'elle décrit.** En fait, on peut commencer méthodiquement, en V, Descendre les problématiques du projet dans l'ordre : glossaire, modélisation, développement, test On devrait surtout créer immédiatement Une structure souple et sémantique Pour l'adaptabilité et la rapidité à comptre les motifs sous-jacents Ainsi voyant un nouveau motif apparaître, Le refactoring doit me paraître le plus ergonomique possible ## Conclusion Cherchez la grande image En cherchant comment ne pas être limité par vos croyances Dérivez vos motifs de l'expérience Et non l'inverse Sinon vous vivez dans un monde imaginaire Et votre prise sur la réalité diminue en même temps que votre compétitivité. ` }
import React from 'react' import { useState } from 'react/cjs/react.development' import APISERVICE from './APISERVICE'; function Form(props) { const [title, setTitle] = useState(props.article.title) const [body, setBody] = useState(props.article.body) const UpdateArticle = () => { APISERVICE.UpdateArticle(props.article.id, { title, body }) .then(resp => props.updatedData(resp)) .then(error => console.log(error)) } const InsertArticle=()=>{ APISERVICE.InsertArticle({title,body}) .then(resp=>props.InsertedArticle(resp)) .catch(error=>console.log(error)) } return ( <div> {props.article ? ( <div className="mb-3"> <label htmlFor="title" className="form-label">Title</label> <input type="text" className="form-control" placeholder="Please enter Title" value={title} onChange={(e) => setTitle(e.target.value)} /> <label htmlFor="body" className="form-label">Description</label> <textarea rows="5" value={body} onChange={(e) => setBody(e.target.value)} className="form-control" placeholder="Enter your body" /> { props.article.id ? <button onClick={UpdateArticle} className="btn btn-success mt-3" >Update</button> : <button onClick={InsertArticle} className="btn btn-outline-warning mt-3" >Insert</button> } </div> ) : null } </div> ) } export default Form
/** * Write a function that returns and array of * strings that present the product name and * price for all in stock items. In this case: * ['Soap dispenser ($12.45)', 'Chainsaw blade ($41.45)'] */ let products = [ { name: 'Soap Dispenser', price: 12.45, inStock: true }, { name: 'Chainsaw Blade', price: 41.45, inStock: true }, { name: 'Bath Towel Warmer', price: 87.14, inStock: false }, ]; function stockCheck(productArray) { if (productArray.inStock === true) { return true; } else { return false; } } function nameAndPrice(item) { return item.name + ": " + item.price; } let stocked = products.filter(stockCheck).map(nameAndPrice); console.log(stocked);
// Get Current Date let today = new Date(); // new Date object // now concatenate formatted output let date = (today.getMonth()+1) + " / " + today.getDate() + " / " + today.getFullYear(); document.getElementById('currentdate').innerHTML = date; // Defining Table // INPUT: Get principal, annual rate, number of years, and periods per year from the user. // PROCESSING: The second function (computeFutureValue) computes and returns the future value of an investment. // OUTPUT: Display the future value. function doFV() { let p = document.getElementById('principal').value; let r = document.getElementById('rate').value; let y = document.getElementById('years').value; let per = document.getElementById('periods').value; let futureValue = computeFutureValue(p, r, y, per); document.getElementById('output').innerHTML = "Anticipated future value: $" + futureValue.toFixed(2); } function computeFutureValue (principal, annualRate, years, periodsPerYear) { let r = annualRate/periodsPerYear; let n = years*periodsPerYear; let fV = principal * Math.pow((1 + r),n) return fV; }
import { useInputValue } from '..'; describe('useInputValue', () => { it('is truthy', () => { expect(useInputValue).toBeTruthy(); }); });
"use strict"; const positive = { [Symbol.hasInstance](value) { return Number.isFinite(value); } }; module.exports = positive;
/* * productDetailAuditModalController.js * * Copyright (c) 2016 HEB * All rights reserved. * * This software is the confidential and proprietary information * of HEB. */ /** * Modal controller to support the Modal Controller. * * @author l730832 * @since 2.6.0 */ 'use strict'; (function () { 'use strict'; var app = angular.module('productMaintenanceUiApp'); app.controller('ProductDetailAuditModalController', ProductDetailAuditModalController); ProductDetailAuditModalController.$inject = ['ngTableParams', 'callback', 'parameters', 'title', '$uibModalInstance', '$scope']; function ProductDetailAuditModalController(ngTableParams, callback, parameters, title, $uibModalInstance, $scope) { var self = this; self.callback = callback; self.parameters = parameters; self.hasUpc = false; self.isWaiting = true; /** * Constant order by asc. * * @type {String} */ const ORDER_BY_ASC = "asc"; /** * Constant order by desc. * * @type {String} */ const ORDER_BY_DESC = "desc"; $uibModalInstance.rendered.then(function() { self.data = self.callback(self.parameters, self.loadData, self.fetchError); self.title = title + ": Change Log"; }); self.init = function () { self.isWaiting = true; }; /** * Closes the Audit Modal */ self.close = function () { self.isWaiting = false; if($uibModalInstance) { $uibModalInstance.close(); $uibModalInstance = null; } }; /** * Loads the data into an ngTable. * @param results */ self.loadData = function (results) { // Check if the first record contains a variable 'upc'. If the first record does contain this variable, // all of them should contain this variable, so only the first one needs to be checked. Set hasUpc = true so // the audit table shows the 'UPC' column. if (results !== null && results.length > 0 && results[0].key !== null && results[0].upc) { self.hasUpc = true; } // Else set hasUpc = false to not show the 'UPC' column else { self.hasUpc = false; } // Check for optional product ID if (results !== null && results.length > 0 && results[0].key !== null && results[0].prodId) { self.hasProdId = true; } // Else set hasProdId = false to not show the 'Product Id' column else { self.hasProdId = false; } // Check for optional warehouse ID if (results !== null && results.length > 0 && results[0].key !== null && results[0].warehouseId) { self.hasWarehouseId = true; } // Else set hasWarehouseId = false to not show the 'Warehouse Id' column else { self.hasWarehouseId = false; } $scope.filter = { attributeName: '', }; $scope.sorting = { changedOn: ORDER_BY_DESC }; // Loads the table data. self.tableParams = new ngTableParams( { page: 1, count: 10, filter: $scope.filter, sorting: $scope.sorting }, { counts: [], data: results } ) self.isWaiting = false; }; /** * Change sort. */ self.changeSort = function (){ if($scope.sorting.changedOn === ORDER_BY_DESC){ $scope.sorting.changedOn = ORDER_BY_ASC; }else { $scope.sorting.changedOn = ORDER_BY_DESC; } } /** * If an error has occured set the error. * @param error */ self.fetchError = function (error) { self.isWaiting = false; if (error && error.data) { if (error.data.message) { self.setError(error.data.message); } else { self.setError(error.data.error); } } else { self.setError("An unknown error occurred."); } }; /** * Sets the error * @param error */ self.setError = function (error) { self.error = error; }; } })();
import Order from '../resolvers/Order.js'; import Customer from '../resolvers/Customer.js'; import Product from '../resolvers/Product.js'; import User from '../resolvers/User.js'; export {Product,Order,Customer,User};
// Copyright (c) Dolittle. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. const TerserPlugin = require('terser-webpack-plugin'); module.exports = { minimizer: [ new TerserPlugin({ terserOptions: { sourceMap: false, // We want the class names and function names to be there for the IoC to work its magic keep_classnames: true, keep_fnames: true } }) ], runtimeChunk: true, moduleIds: 'deterministic', splitChunks: { chunks: 'initial', // sizes are compared against source before minification maxSize: 200000, // splits chunks if bigger than 200k, adjust as required (maxSize added in webpack v4.15) cacheGroups: { default: false, // Disable the built-in groups default & vendors (vendors is redefined below) // This is the HTTP/1.1 optimised cacheGroup configuration vendors: { // picks up everything from node_modules as long as the sum of node modules is larger than minSize test: /[\\/]node_modules[\\/]/, name: 'vendors', priority: 19, enforce: true, // causes maxInitialRequests to be ignored, minSize still respected if specified in cacheGroup minSize: 30000 // use the default minSize }, vendorsAsync: { // vendors async chunk, remaining asynchronously used node modules as single chunk file test: /[\\/]node_modules[\\/]/, name: 'vendors.async', chunks: 'async', priority: 9, reuseExistingChunk: true, minSize: 10000 // use smaller minSize to avoid too much potential bundle bloat due to module duplication. }, commonsAsync: { // commons async chunk, remaining asynchronously used modules as single chunk file name: 'commons.async', minChunks: 2, // Minimum number of chunks that must share a module before splitting chunks: 'async', priority: 0, reuseExistingChunk: true, minSize: 10000 // use smaller minSize to avoid too much potential bundle bloat due to module duplication. } } } };
/* eslint-disable eqeqeq */ import React from 'react' import { connect } from 'react-redux' import { StyleSheet } from 'quantum' import { applySearch, removeSearch, setDefaultSearch } from '../actions/search' import { Modal, Header, Body } from 'bypass/ui/modal' import { CloseIcon, FavoriteIcon } from 'bypass/ui/icons' import { Text } from 'bypass/ui/text' const styles = StyleSheet.create({ self: { border: '2px solid #a1a1a1', borderRadius: '5px', padding: '3px', margin: '15px 15px 20px 15px', overflowY: 'auto', background: '#ffffff', display: 'block', maxHeight: '300px', '& div': { paddingLeft: '10px', lineHeight: '38px', fontSize: '16px', textAlign: 'left', cursor: 'pointer', display: 'flex', flexDirection: 'row', '& div:first-child': { flexGrow: 1, }, '& svg': { position: 'relative', top: '10px', right: '5px', }, '&:hover': { background: '#ececec', }, }, }, }) const Searches = ({ items = [], onSelect, onRemove, onSetDefault }) => ( <div className={styles()}> {items.map(search => ( <div key={search.search_id}> <div onClick={() => onSelect(search.search_id)}> {search.search_name} </div> <div onClick={() => onSetDefault(search.search_id)}> <FavoriteIcon width={16} checked={search.def == 1} fill={search.def == 1 ? '#fdd835' : null} /> </div> <div onClick={() => onRemove(search.search_id)}> <CloseIcon width={16} fill='#b71c1c' /> </div> </div> ))} </div> ) const SelectSearch = ({ searches = [], onSelect, onRemove, onSetDefault, onClose }) => ( <Modal onClose={onClose}> <Header> <Text size={19}> {__i18n('CHECK.LOAD_TPL_LABEL')} </Text> </Header> <Body alignCenter> <Searches items={searches} onSelect={onSelect} onRemove={onRemove} onSetDefault={onSetDefault} /> </Body> </Modal> ) export default connect( state => ({ searches: state.cards.search.getIn(['presearch', 'search']).toJS(), }), dispatch => ({ onSelect: searchId => { dispatch(applySearch(searchId)) }, onRemove: searchId => { dispatch(removeSearch(searchId)) }, onSetDefault: searchId => { dispatch(setDefaultSearch(searchId)) }, }), )(SelectSearch)
import { LitElement, html, property } from "@polymer/lit-element"; import bulmaStyles from "../../style/bulma-styles"; import "../my-icons/my-icons"; import '@polymer/iron-icon'; // import fontawesomeStyle from "../../style/fontawesome-style"; class MyInputDatalist extends LitElement { static get properties() { return { // element: Object, // disabled: Boolean classnylon: { type: String }, id: { type: String }, ariaLabelledBy: { type: String }, ariaDescribedBy: { type: String }, disablednylon: Boolean, title: { type: String }, value: { type: String }, invalid: { type: String }, preventInvalidInput: { type: String }, allowedPattern: { type: String }, validator: { type: String }, type: { type: String }, pattern: { type: String }, required: { type: Boolean }, autocomplete: { type: String }, autofocus: { type: String }, inputmode: { type: String }, minlength: { type: Number }, maxlength: { type: Number }, min: Number, max: Number, step: Number, name: { type: String }, placeholder: { type: String }, readonly: { type: Boolean }, list: { type: String }, size: { type: String }, autocapitalize: { type: String }, autocorrect: { type: String }, tabIndex: { type: String }, autosave: { type: String }, results: { type: String }, accept: { type: String }, multiple: { type: String }, items: { type: Array }, classActive: { type: Boolean }, selected: { type: String }, element: { type: Object }, }; } constructor() { super(); this._changeValue = this._changeValue.bind(this); this._popUp = this._popUp.bind(this); this._dropdown = this._dropdown.bind(this); // this._setValue = this._setValue.bind(this); this._filterItems = this._filterItems.bind(this); this.items = []; this.classActive = false; this.value = ""; this.selected = ""; this.element = {}; // this.addEventListener("click", async e => { // this.whales++; // this._popUp(0); // await this.updateComplete; // // this.dispatchEvent(new CustomEvent('whales', {detail: {whales: this.whales}})) // // console.log(this.shadowRoot.querySelector('.count').textContent); // console.log("this.whales", this.whales); // }); } // <!-- ${fontawesomeStyle(this)} --> render() { return html` ${bulmaStyles(this)} <!-- is-active --> <div class="dropdown ${this.classActive ? "is-active" : ""}"> <div class="dropdown-trigger control has-icons-right"> <input class="input ${this.classnylon}" id="${this.id}" aria-labelledby="${this.ariaLabelledBy}" aria-describedby="${this.ariaDescribedBy}" ?disabled="${this.disablednylon}" title="${this.title}" value="${this.value}" invalid="${this.invalid}" prevent-invalid-input="${this.preventInvalidInput}" allowed-pattern="${this.allowedPattern}" validator="${this.validator}" type="${this.type}" pattern="${this.pattern}" required="${this.required}" autocomplete="${this.autocomplete}" .autofocus="${this.autofocus}" inputmode="${this.inputmode}" minlength="${this.minlength}" maxlength="${this.maxlength}" min="${this.min}" max="${this.max}" step="${this.step}" name="${this.name}" placeholder="${this.placeholder}" .readonly="${this.readonly}" list="${this.list}" size="${this.size}" autocapitalize="${this.autocapitalize}" autocorrect="${this.autocorrect}" tabindex="${this.tabIndex}" autosave="${this.autosave}" results="${this.results}" accept="${this.accept}" multiple="${this.multiple}" @click="${this._popUp}" @input="${this._filterItems}" aria-haspopup="true" aria-controls="dropdown-menu" > <span class="icon is-small is-right is-small"> <iron-icon icon="my-icons:arrow-drop-down"></iron-icon> </span> </div> <div class="dropdown-menu" id="dropdown-menu" role="menu"> <div class="dropdown-content"> ${this.items.map(({ value, name, itemActive }) => { if (itemActive || itemActive === undefined) { return html` <a value="${value}" class="dropdown-item" @click="${ this._changeValue }"> ${name} </a> `; } })} </div> </div> </div> `; } // firstUpdated() { // // this._inner = this.shadowRoot.querySelector('x-inner'); // // console.log("firstUpdated"); // this.element = this.shadowRoot.querySelector("input"); // // console.log(this.shadowRoot.querySelector("input")); // } // on-focusout="${this._dropdown}" async _popUp(e) { this.classActive = true; // await this.updateComplete; // console.log(this.classActive); } async _dropdown(e) { this.classActive = false; // await this.updateComplete; // console.log(this.classActive); } // _setValue(e) { // let value = e.currentTarget.getAttribute("value"); // this._dropdown(); // this.value = value; // } async _filterItems(e) { let value = e.currentTarget.value; // console.log(value); // console.log(this.items); // if (value !== "") { this.items.forEach(item => { if ( item.name.search(value) != -1 || value === "" || value === undefined ) { item = Object.assign(item, { itemActive: true }); } else { item = Object.assign(item, { itemActive: false }); } }); this.items = this.items.slice(0); // await this.updateComplete; // } } async _changeValue(e) { let value = e.currentTarget.value || e.currentTarget.getAttribute("value"); // หาอาเรย์ที่ตรงที่เลือก let itemSeleted = JSON.parse( JSON.stringify(this.items.find(item => item.value === value)) ); delete itemSeleted.itemActive; // console.log('itemSeleted',itemSeleted); this._dropdown(); let control = this.shadowRoot.querySelector("input"); // console.log(control.value); control.value = itemSeleted.name; this.value = itemSeleted.name; this.selected = itemSeleted.value // console.log(value); // await this.updateComplete; // console.log(value); this.dispatchEvent( new CustomEvent("value-changed", { bubbles: true, composed: true, detail: { value: value } }) ); this.dispatchEvent( new CustomEvent("value-changed-object", { bubbles: true, composed: true, detail: { value: itemSeleted } }) ); } update(changedProps) { super.update(changedProps); // console.log('this',this) // console.log('selected',this.selected) // console.log("updated!", changedProps); const value = this.selected; let itemSeleted = this.items.find(item => item.value === value); // console.log('itemSeleted',itemSeleted) this.value = itemSeleted.name; this.selected = itemSeleted.value // console.log(this.shadowRoot.querySelector("input")); } // shouldUpdate(changedProperties) { // console.log("shouldUpdate", changedProperties); // console.log(this.shadowRoot.querySelector("input")); // return true; // } // shouldInvalidate(value, oldValue) { // console.log("shouldInvalidate", value, oldValue); // return true; // } // createRenderRoot(){ // console.log('createRenderRoot'); // } // update(){ // super.update() // console.log(1234) // const value = this.selected; // let itemSeleted = this.items.find(item => item.value === value); // this.value = itemSeleted.name; // // this.selected = itemSeleted.value // // ต้องแทนค่าแบบนี้แทนเนึองจากมีปัญหามรการแทนค่าลงตรงๆ // let element = this.shadowRoot.querySelector("input") // element.value = itemSeleted.name; // } // createRenderRoot(e) { // console.log("createRenderRoot", e); // } // invalidateProperty(name, oldValue) { // // console.log("this.selected", this.selected); // // if (this.selected) { // // const value = this.selected; // // let itemSeleted = this.items.find(item => item.value === value); // // // console.log(itemSeleted.name); // // // ต้องแทนค่าแบบนี้แทนเนึองจากมีปัญหามรการแทนค่าลงตรงๆ // // let element = this.shadowRoot.querySelector("input"); // // console.log(element); // // element.value = itemSeleted.name; // // this.value = itemSeleted.name; // // } // // console.log("invalidateProperty", name, oldValue); // if (this.selected !== "") { // switch (name) { // case "selected": // console.log("this.selected", this.selected); // let element = this.shadowRoot.querySelector("input"); // console.log("element", element); // break; // default: // break; // } // } // } // get updateComplete() { // return (async () => { // return (await super.updateComplete) && (await this._inner.updateComplete); // })(); // } // _didRender(props, changedProps, prevProps) { // console.log(props, changedProps, prevProps); // if ("selected" in changedProps) { // const value = this.selected; // let itemSeleted = this.items.find(item => item.value === value); // // console.log(itemSeleted.name); // // ต้องแทนค่าแบบนี้แทนเนึองจากมีปัญหามรการแทนค่าลงตรงๆ // let element = this.shadowRoot.querySelector("input"); // // console.log(element); // element.value = itemSeleted.name; // // this.value = itemSeleted.name; // } // return true; // } } customElements.define("my-input-datalist", MyInputDatalist);
define(function(require) { var invitation = Backbone.Model.extend({ urlRoot: '/accounts/' + this.accountId + '/invitation' }); return invitation; });
import React, { useCallback, useEffect } from 'react'; import styled from '@emotion/styled'; import { basicStyle, Modal } from '../../public/style'; import { useSelector, useDispatch } from 'react-redux'; import { useRouter } from 'next/router'; import { loadCategorysRequestAction } from '../../reducers/category'; const InitialLocationContainer = styled.div` width: 100%; height: 90%; display: flex; flex-direction: column; justify-content: center; align-items: center; text-align: center; font-family: 'Nanum Gothic', sans-serif; img { width: 90px; height: 85px; } h2 { width: 90%; font-weight: bold; } h6 { width: 90%; color: #868686; margin-bottom: 5%; } `; const Button = styled.button` ${basicStyle}; width: 90%; color: #f8faff; border: 1px solid #ebe7f8; border-radius: 17.5px; font-weight: bold; background-color: #6055cd; `; const SkipButton = styled.button` ${basicStyle}; width: 90%; margin-top: 1%; border: none; border-radius: 17.5px; font-size: 12px; background-color: rgba(0, 0, 0, 0); `; const InitialLocation = ({ setShowingModal }) => { const { me } = useSelector((state) => state.user); const dispatch = useDispatch(); const router = useRouter(); useEffect(() => { dispatch(loadCategorysRequestAction()); }, []); useEffect(() => { if (me.PreferLocations?.length && me.PreferCategories?.length) { router.push('/'); } }, [me]); const openSelection = useCallback((e) => { e.preventDefault(); setShowingModal((prev) => !prev); }, []); const closeSelection = useCallback((e) => { e.preventDefault(); router.push('/'); }, []); return ( <> <Modal> <InitialLocationContainer> <img src={`/images/logo.png`} alt='로고 이미지' /> <h2> 모두의 모임을 <br />더 쉽게 이용하는 방법 </h2> <h6> 관심있는 모임이 등록되면 <br /> 추천해드릴게요 </h6> <Button onClick={openSelection}> 활동 선호 지역과 관심 분야 설정하기 </Button> <SkipButton onClick={closeSelection}>다음에 할래요</SkipButton> </InitialLocationContainer> </Modal> </> ); }; export default InitialLocation;
import createDebug from 'debug'; import { onLoad } from './util'; const debug = createDebug('ms:comments'); onLoad(() => { $(document.body).on('click', '.new-comment', ev => { debug('.new-comment click'); ev.preventDefault(); $('.add-comment').show(); $(ev.target).remove(); }); $(document.body).on('click', '.comment-edit', async ev => { ev.preventDefault(); const $comment = $(ev.target).parents('.post-comment, .abuse-comment'); const $body = $comment.find('.panel-body'); const id = $comment.data('cid'); const uri = $comment.hasClass('post-comment') ? `/comments/${id}` : `/abuse/comments/${id}`; const resp = await fetch(uri, { credentials: 'include' }); const json = await resp.json(); const text = json.text; $body.html(`<form method="POST" action="${uri}/edit"> <div class="field"> <textarea name="text" rows="3" cols="100" placeholder="Useful information about this post that others might need..." class="form-control">${text}</textarea> </div><br/> <div class="actions"> <input type="submit" value="Update comment" class="btn btn-primary" /> </div>`); }); });
import React from 'react'; import Routes from '../routes'; export default function Body() { return ( <main style={{ gridArea: 'main' }}> <Routes /> </main> ); }
import React from "react"; import { Link } from "react-router-dom"; import Button from "@material-ui/core/Button"; import AddIcon from "@material-ui/icons/Add"; import Table from "../../components/Table"; import { history } from '../../app/store/store' import Compose from "../../utils/Compose"; import UserManageAction from "./UserManageAction"; import { hasRole } from "../../utils/Utils"; const columns = [ { Header: "№", accessor: "rownum", width: 80 }, { Header: "ИИН", accessor: "iin" }, { Header: "Фамилия", accessor: "surname" }, { Header: "Имя", accessor: "name" }, { Header: "Отчество", accessor: "middlename" }, { Header: "Дата рождения", accessor: "birthDate" }, { Header: "Должность", accessor: "position" }, { Header: "Подразделение", accessor: "division" }, { Header: "Группа", accessor: "group" }, { Header: "Телефон", accessor: "cellphone" } ]; class UserManage extends React.Component { componentDidMount() { const { list, reqList } = this.props; if (!hasRole("ADMIN", "RUKOVODSTVO")) { history.replace("/"); } if (list.length === 0) { reqList() } } render() { const { list, loading } = this.props; return ( <div className="full-width"> <Table columns={columns} data={list} loading={loading} onClickRow={row => history.push('/usermanage/user/view/' + row.original.iin)} buttons={( <Link to="/usermanage/user/create"> <Button variant="contained" color="primary"> <AddIcon className="mr-10" /> Добавить пользователя </Button> </Link> )} /> </div> ); } } const stateProp = state => ({ list: state.usermanage.list, loading: state.usermanage.loading, }); const dispatchProp = () => ({ reqList: UserManageAction.reqList }); export default Compose(stateProp, dispatchProp)(UserManage);
export default { apollo: { networkInterface: 'http://localhost:5000', }, };
import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Button from '@material-ui/core/Button'; const useStyles = makeStyles(theme => ({ button: { margin: theme.spacing(1), }, input: { display: 'none', }, wax: { margin: theme.spacing(1), backgroundColor: '#43a047', color: 'white', }, fillin: { margin: theme.spacing(1), backgroundColor: '#ef6c00', color: 'white', }, pw: { margin: theme.spacing(1), backgroundColor: '#f06292', color: 'white', }, })); export default function ServiceButton(service) { console.log(service) const classes = useStyles(); switch (service.props) { case "mani": return ( <Button id={service.id} position={service.position} value={15 * 60 * 1000} variant="contained" color="primary" className={classes.button} // https://stackoverflow.com/questions/29537299/react-how-do-i-update-state-item1-on-setstate-with-jsfiddle onClick={function() {console.log(15 + " minutes")}}> Manicure </Button > ); case "pedi": return ( <Button id={service.id} position={service.position} value={service.props} variant="contained" color="secondary" className={classes.button} onClick={function() {console.log(15 + " minutes")}}> Pedicure </Button > ); case "wax": return ( <Button id={service.id} position={service.position} value={service.props} variant="contained" className={classes.wax} onClick={function() {console.log(5 + " minutes")}} > Wax </Button > ); case "fill": return ( <Button id={service.id} position={service.position} value={service.props} variant="contained" className={classes.fillin} onClick={function() {console.log(20 + " minutes")}}> FillIn </Button > ); case "pw": return ( <Button id={service.id} position={service.position} value={service.props} variant="contained" className={classes.pw} onClick={function() {console.log(20 + " minutes")}}> Pink&White </Button > ); default: return ( <Button id={service.id} position={service.position} value={service.props} variant="contained" className={classes.button} > Unknown </Button> ); }; };
requirejs(['./config'], function() { requirejs(['app/rsvp', 'app/navbar'], function(rsvp, navbar) { navbar(); rsvp.bind(); }); });
import express from 'express'; import { userController } from '../controllers'; import { userValidation, authorization, authentication } from '../middlewares'; const router = express.Router(); const { createUser, getOneUser, getAllUsers, updateUserDetails, deleteUser, activateUserAccount, deactivateUserAccount, login, logout } = userController; const { authenticateUser, verifyLoginDetails } = authentication; const { authorizeAdmin, authorizeAccountOwner, userIsActive } = authorization; const { checkRequiredUserFields, checkEmptyUserFields, checkIfUserExists, validateUsername, validateEmail, checkIfIdentifierIsInUse, ensureUserParamIsValid, validatePassword, ensureFalseyValueForDeactivation, ensureTruthyValueForReactivation } = userValidation; router .route('/register') .post( checkRequiredUserFields, checkEmptyUserFields, validateUsername, validateEmail, checkIfIdentifierIsInUse, validatePassword, createUser ); router.route('/allUsers').get(authenticateUser, getAllUsers); router .route('/deactivate/:id') .patch( ensureUserParamIsValid, checkIfUserExists, authenticateUser, authorizeAccountOwner, ensureFalseyValueForDeactivation, deactivateUserAccount ); router .route('/activate/:id') .patch( ensureUserParamIsValid, checkIfUserExists, authenticateUser, authorizeAccountOwner, ensureTruthyValueForReactivation, activateUserAccount ); router.route('/login').post(verifyLoginDetails, login); router.route('/logout').delete(logout); router .route('/:id') .all(ensureUserParamIsValid, checkIfUserExists, authenticateUser) .get(getOneUser) .patch( userIsActive, authorizeAccountOwner, validateUsername, validateEmail, checkIfIdentifierIsInUse, updateUserDetails ) .delete(authorizeAdmin, authorizeAccountOwner, deleteUser); export default router;
import React, { useEffect, useState } from 'react'; export default (props) => { const [up, setUp] = useState(false); useEffect(() => { if (props.toggle) { props.toggle(up) } }, [up]); const toggle = () => { setUp(prev => !prev); } return ( <div className={`blinds-horizontal ${up ? 'up' : 'down'}`} onClick={toggle}> {[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24].map((i) => ( <div key={i}></div> ))} </div> ) }
import React from 'react' import ResultsContainer from '../containers/ResultsContainer' export const ResultsView = () => ( <div> <h4>Results!</h4> <ResultsContainer /> </div> ) export default ResultsView
var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var index = require('./routes/index'); var users = require('./routes/users'); var settings = require('./routes/settings'); var chats = require('./routes/chats'); var app = express(); // socket.io app.io = require('socket.io')(); exports.io = app.io; // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'pug'); // uncomment after placing your favicon in /public //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.use('/', index); app.use('/users', users); app.use('/settings', settings); app.use('/chats', chats); // // session // var session = require("express-session")({ // secret: "my-secret", // resave: true, // saveUninitialized: true // }); // var sharedsession = require("express-socket.io-session"); // app.use(session); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // error handler app.use(function(err, req, res, next) { // set locals, only providing error in development res.locals.message = err.message; res.locals.error = req.app.get('env') === 'development' ? err : {}; // render the error page res.status(err.status || 500); res.render('error'); }); var appConst = require('./const'); // 채팅 로직 var customer = require('./service/customer'); var service = require('./service/chat'); var schedule = require('./service/schedule'); var USER_TYPE_MANAGER = 1; var USER_TYPE_CUSTOMER = 2; var USER_TYPE_NORMAL = 3; var USER_TYPE_AUTO = 4; var USER_TYPE_AUTO_DELAY = 5; var MSG_TYPE_NORMAL = 1; var MSG_TYPE_CUSTOMER = 2; var MSG_TYPE_MANAGER = 3; var MSG_TYPE_NOTICE = 4; var MSG_TYPE_IMAGE = 5; var MSG_TYPE_CLOSE = 6; var MSG_TYPE_IVR = 7; var MSG_TYPE_MANAGER_ONLY = 8; var MSG_TYPE_MANAGER_ONLY_RED = 9; var MSG_TYPE_KEYWORD = 10; var MSG_TYPE_FILE = 11; var CONSULT_STATUS_NEW = 1; var CONSULT_STATUS_WAITING = 2; var CONSULT_STATUS_PROCEEDING = 3; var CONSULT_STATUS_COMPLETE = 4; var CONSULT_STATUS_REQ_CHANGE = 5; var CONSULT_STATUS_REQ_REVIEW = 6; var connCnt = 0; var roomCnt = 0; var tempMessages = {}; // 방이 배정되지 않은 고객이 보낸 메시지 // 접속중인 방 정보 var connRooms = new Map(); // 접속중인 상담사 정보 var connUsers = new Map(); // IVR 사용중인 방 정보 var ivrDB = require('./db/ivr'); var ivrRooms = new Map(); app.io.on('connection', function(socket) { // console.log('P-COOKIE', socket.request.cookies); // if (socket.request.cookies.chat_id == undefined) { // // } // if (socket.handshake.headers.cookie.chat_id == undefined) { // socket.handshake.headers.cookie.chat_id = socket.id; // } // // socket.handshake.session.userdata = socket.id; // socket.handshake.session.save(); // // console.log('COOKIE2', socket.request.session); connCnt++; console.log('[DBG] conn_cnt: ' + connCnt + ' room_cnt: ' + roomCnt); /** * 사용자 접속 * 1. 고객 접속 * 2. 상담사 접속 * 3. 일반 접속 */ socket.on('user-req', function(data) { var userType = data.user_type; // 고객 접속 if (userType == USER_TYPE_CUSTOMER) { var cookie = data.cookie || socket.id; // 고객 쿠키 (최초 접속한 socket id) var name = data.name || ''; // 고객 이름 (O) var phone = data.phone || ''; // 고객 연락처 (O) var itemNo = data.item_no || 0; // 상담 카테고리 no (O) var params = data.params || ''; // 파라미터 (O) // /** // * 서비스 체크 // */ // var result = schedule.checkService(); // console.log('[check service] result', result); // // // 상담 불가 // if (result.available == false) { // // // V2 메시지 // var userInfo = {type: USER_TYPE_AUTO, no: 0, name: '한샘톡'}; // service.sendTempMessage(socket, userInfo, MSG_TYPE_NOTICE, result.comment); // return; // } console.log(`user entrance: ${cookie}, ${name}, ${phone}, ${itemNo}, params: ${params}`); /** * 고객 확인 로직 * 1. 이름 + 전화번호 (익명일때 제외) * 2. COOKIE */ customer.initCustomer(cookie, name, phone, function(err, userNo) { console.log(`[find customer] userNo: ${userNo}`); /** * 고객이 현재 상담중인지 확인 * 1. 있으면 기존방 입장 * 2. 없으면 상담 새로 만듬 */ customer.findConsult(userNo, function(err, consultNo, consultStatus) { console.log(`[find consult] consultNo: ${consultNo} ${consultStatus}`); // 기존 상담 if (consultNo != 0) { customer.findRoom(consultNo, function(err, roomNo, roomTitle) { console.log(`[find room] roomNo: ${roomNo}`); // 방 입장 socket.join(roomNo); // TODO 읽음 처리 // 1. 메시지를 모두 읽음으로 처리 service.updateFlag(roomNo, function(err) { // 2. 사용자가 있으면 방에 읽음 메시지 전송 (자신 제외) var room = app.io.sockets.adapter.rooms[roomNo]; if (room) { if (room.length > 1) { socket.to(roomNo).emit('user-entrance', {}); // app.io.to(roomNo).emit('user-entrance', {}); } } }); if (consultStatus === 0) { // 응답 (채팅방 no) socket.emit('user-res', {user_no: userNo, consult_no: consultNo, room_no: roomNo, room_title: roomTitle, available: false}); } else { // 응답 (채팅방 no) socket.emit('user-res', {user_no: userNo, consult_no: consultNo, room_no: roomNo, room_title: roomTitle}); } }); } // 신규 상담 else { // 1. 상담 초기화 (고객DB, 상담DB 생성) service.initConsult(userNo, itemNo, function (err, consultNo) { console.log(`[make consult] consultNo: ${consultNo}`); // 2. 방 생성 service.makeRoom(consultNo, 0, itemNo, params, function(err, roomNo, title) { console.log(`[make room] roomNo: ${roomNo}`); /** * 상담 가능 시간인지 체크 * 스케쥴 + 휴일 * 가능 : 상담사 분배 * 불가 : 멘트 전송 (방까지만 만들고 분배 안함) */ var result = schedule.checkSchedule(); console.log('[check schedule] result', result); if (result.available == false) { // if (result.available == false) { // 상담 불가 // 사용자 응답 (고객 no, 상담 no) socket.emit('user-res', {user_no: userNo, consult_no: 0, available: false}); // 방 입장 socket.join(roomNo); // V2 메시지 var userInfo = {type: USER_TYPE_AUTO, no: 0, name: '한샘톡'}; // service.sendTempMessage(socket, userInfo, MSG_TYPE_NOTICE, result.comment); service.sendMessage(app.io, roomNo, userInfo, MSG_TYPE_NOTICE, result.comment, false, true); return; } // 3. 상담사 분배 service.distributeConsult(consultNo, itemNo, function(err, consultantNo, consultantName) { // 사용자 응답 (고객 no, 상담 no) socket.emit('user-res', {user_no: userNo, consult_no: consultNo}); // 상담사 알림 if (connUsers.has(consultantNo)) { console.log('send push'); var s = connUsers.get(consultantNo); s.emit('push', {msg: '상담이 분배되었습니다.'}); } /** * 상담량 과다 체크 */ service.checkOverConsult(consultantNo); // 방 입장 socket.join(roomNo); // 사용자 초대 (방 no) socket.emit('invite', {room_no: roomNo, room_title: title}); // 고객 메시지 만듬 var msg = global.consult_setting.consult_greeting; if (name != '') { msg = name + ' 고객님\n' + msg; } // 파라미터중에 payload 있는지 확인 if (params != '') { var lParams = JSON.parse(params); var lPayload = lParams['payload']; if (lPayload) { msg = lPayload; } } msg = msg.replace(/\[consultant_name\]/g, consultantName); // TODO ONLY TEST // msg += '\nTEST (consult_no:' + consultNo + ' consultant_no: ' + consultantNo + ' room_no: ' + roomNo + ' user_no: ' + userNo +')'; // V2 메시지 var userInfo = {type: USER_TYPE_AUTO, no: 0, name: '한샘톡'}; service.sendMessage(app.io, roomNo, userInfo, MSG_TYPE_NOTICE, msg, false, true); // TODO AUTO IVR // IVR 자동 설정이 ON 되어있으면 console.log('XXX', global.consult_setting); if (global.consult_setting.ivr == 1) { service.updateChannel(consultNo, appConst.CONSULT_CHANNEL_IVR, function(err) { var ivrNo = global.consult_setting.ivr_script; var ivrGreeting = global.consult_setting.ivr_greeting; console.log(`[IVR] auto start room_no: ${roomNo} ivr_no: ${ivrNo}`); setTimeout(() => { var userInfo = {type: USER_TYPE_AUTO, no: 0, name: 'IVR'}; service.sendMessage(app.io, roomNo, userInfo, MSG_TYPE_NOTICE, ivrGreeting, false, false); }, 1000); // IVR 질문 목록 가져옴 setTimeout(() => { ivrDB.select(ivrNo, function (err, questions) { ivrRooms.set(roomNo, {ivr_no: ivrNo, questions: questions}); var ivr = ivrRooms.get(roomNo); var question = ivr.questions.shift(); // 질문 목록 체크 if (question) { var msg = JSON.stringify(question); console.log(`[IVR] send first question: ${msg}`); var userInfo = {type: USER_TYPE_AUTO, no: 0, name: 'IVR'}; service.sendMessage(app.io, roomNo, userInfo, MSG_TYPE_IVR, msg, false, false); } }); }, 2000); }); } }); }); }); } }); }); } // 매니저 접속시 else if (userType == USER_TYPE_MANAGER) { var managerNo = data.manager_no; // 상담사 no (M) var consultNo = data.consult_no; // 상담 no (M) // var consultStatus = data.consult_status; // 상담 상태 -> 실제 상태를 가져오도록 수정 // 1. 상담 상태 확인 service.getConsultStatus(consultNo, function(err, status) { // 2. 방이름을 찾아서 들어감 service.getRoomName(consultNo, function(err, roomNo) { // 방 입장 socket.join(roomNo); // TODO 읽음 처리 // 1. 메시지를 모두 읽음으로 처리 service.updateFlag(roomNo, function(err) { // 2. 사용자가 있으면 방에 읽음 메시지 전송 (자신 제외) var room = app.io.sockets.adapter.rooms[roomNo]; if (room) { if (room.length > 1) { socket.to(roomNo).emit('user-entrance', {}); // app.io.to(roomNo).emit('user-entrance', {}); } } }); // 매니저 응답 (채팅방 no) socket.emit('user-res', {room_no: roomNo}); // 3. 신규방 이면 if (status == 1) { roomCnt++; // TODO 읽음 처리 // 방에 접속중인 사람 카운트 // 2명이상이면 읽음으로 표시 var readFlag = false; var room = app.io.sockets.adapter.rooms[data.room_no]; if (room) { if (room.length > 1) { readFlag = true; } } // 상담 상태 업데이트 service.matchConsult(consultNo, function (err) { var userInfo = {type: USER_TYPE_AUTO, no: 0, name: '한샘톡'}; var msg = '<i class="fa fa-info-circle"><i> 상담원이 연결되었습니다.'; // roomNo + ' 방에서\n service.sendMessage(app.io, roomNo, userInfo, MSG_TYPE_NOTICE, msg, false, readFlag); }); } else { } }); }); } // 일반 접속 (팀, 협력등 상담과 관계 업이 대화) else if (userType == USER_TYPE_NORMAL) { var userNo = data.user_no; // 사용자 no (M) var roomNo = data.room_no; // 방 no (M) // 방 입장 socket.join(roomNo); // 응답 (채팅방 no) socket.emit('user-res', {room_no: roomNo}); console.log('test normal enter', userNo, roomNo); } }); // 3. 방 입장 // 고객이 초대 메시지를 받고 응한 경우 socket.on('join', function(data) { var roomNo = data.room_no; // 방이름 socket.join(roomNo); // socket.c_room_name = roomNo; // var msg = roomNo + ' 방에서\n상담원이 연결되었습니다.'; // app.io.to(roomNo).emit('message', {id: data.id, user: '한샘톡', time: new Date(), text: msg, // user_type: 1, name: '한샘톡', content: msg, create_time: new Date()}); }); // 4. 방 퇴장 socket.on('leave', function(data) { var userNo = data.user_no; var consultNo = data.consult_no; var roomNo1 = data.room_no; // var roomName = data.roomName; // 방이름 // 상담no 가 있으면 if (consultNo) { service.getRoomName(consultNo, function (err, roomNo) { socket.leave(roomNo); delete socket.c_room_name; console.log('leave room (consultNo: ' + consultNo + ' roomNo: ' + roomNo + ')'); }); } else { socket.leave(roomNo1); delete socket.c_room_name; console.log('leave room1 (consultNo: ' + consultNo + ' roomNo: ' + roomNo1 + ')'); } }); // 5. 상담 종료 socket.on('end', function(data, fn) { var userType = data.user_type; // 1: 매니저, 2: 고객 var userNo = data.user_no; // 종료한 사용자 no var consultNo = data.consult_no; // 상담 no var itemNo = data.category_no || 0; var itemDetail = data.category_detail || null; service.endConsult(userType, consultNo, itemNo, itemDetail, function(err, roomNo) { var msg1 = global.ars_comment_setting['4']; var userInfo1 = {type: USER_TYPE_AUTO, no: 0, name: '한샘톡'}; service.sendMessage(app.io, roomNo, userInfo1, MSG_TYPE_NOTICE, msg1, false, true); setTimeout(() => { var msg = '상담이 종료되었습니다. (' + (userType == 1 ? '매니저' : '고객') + ' 종료)'; var userInfo = {type: USER_TYPE_AUTO, no: 0, name: '한샘톡'}; service.sendMessage(app.io, roomNo, userInfo, MSG_TYPE_CLOSE, msg, false, true); // socket.leave(roomNo); console.log('end room (consultNo: ' + consultNo + ' roomNo: ' + roomNo + ')'); // jjlim@20180308 매니저가 접속종료했을때 고객이 접속중이면 고객에게 알림 if (userType == 1) { var room = app.io.sockets.adapter.rooms[roomNo]; console.log('END MESSAGE', room, room.length, roomNo); if (room) { if (room.length > 1) { socket.to(roomNo).emit('user-res', {consult_no: consultNo, room_no: roomNo, chat_end: true}); } } } fn('close'); }, 500); }); }); socket.on('disconnect', function(data) { connCnt--; console.log('[DBG] conn_cnt: ' + connCnt + ' room_cnt: ' + roomCnt); // 4. 고객 종료시 if (socket.c_type == 'customer') { console.log('CLIENT OUT !!!'); var roomNo = socket.c_room_name; if (roomNo != undefined) { socket.leave(roomNo); roomCnt--; } service.endConsult(socket.c_consult_no, 0, null, function(err, no) { if (err) { // 정상적으로 나가지 못한 경우 } else { console.log('종료하였습니다'); } }); } }); // 메시지를 받은 경우 socket.on('add-message', function(data) { // console.log('[add-message]', data); // 밑에꺼 필요없고 새로 // V2 메시지 if (1) { // console.log('MY SOCKET', socket.id); // console.log('MY SOCKET', socket.rooms); // console.log('MY SOCKET', app.io); // console.log('MY SOCKET', app.io.sockets); // console.log('MY SOCKET', app.io.sockets.adapter.rooms); // TODO 읽음 처리 // 방에 접속중인 사람 카운트 // 2명이상이면 읽음으로 표시 var readFlag = false; var room = app.io.sockets.adapter.rooms[data.room_no]; if (room) { if (room.length > 1) { readFlag = true; } } // 방 타입 확인 service.getRoomType(data.room_no, function(err, type) { if (!err) { // 일반방 에서만 읽음 처리 if (type !== appConst.ROOM_TYPE_NORMAL) { readFlag = true; } var userInfo = {type: data.user_type, no: data.user_no, name: data.name}; // 파트너인 경우 user_no 없음 if (data.user_no == undefined) { userInfo.no = 0; } service.sendMessage(app.io, data.room_no, userInfo, data.type, data.content, true, readFlag); /** * TODO IVR 이 진행중인지 확인 */ var roomNo = data.room_no; var userType = data.user_type; // IVR이 진행중인 방에 고객이 메시지 를 보냄 if (ivrRooms.has(roomNo) && userType == USER_TYPE_CUSTOMER) { console.log(`[IVR] receive messge`) var ivr = ivrRooms.get(roomNo); var question = ivr.questions.shift(); // 질문 목록 체크 if (question) { var msg = JSON.stringify(question); console.log(`[IVR] send next question: ${msg}`); setTimeout(() => { var userInfo = {type: USER_TYPE_AUTO, no: 0, name: 'IVR'}; service.sendMessage(app.io, roomNo, userInfo, MSG_TYPE_IVR, msg, false, readFlag); }, 1000); } else { setTimeout(() => { var userInfo = {type: USER_TYPE_AUTO, no: 0, name: 'IVR'}; service.sendMessage(app.io, roomNo, userInfo, MSG_TYPE_NOTICE, '잘문이 종료되었습니다.', false, false); console.log(`[IVR] end`); ivrRooms.delete(roomNo); }, 1000); } } } }); } else { // 상담사 if (data.user_type == 1) { var roomNo = data.room_no; var userNo = data.user_no; var userType = data.user_type; var name = data.name + ' 상담원'; // 방에 들어가 있으면 방모두에게 전송 (DB에 남김) if (roomNo != undefined) { service.addChat(roomNo, userNo, userType, 1, data.content, function (err, no) { if (err) console.log(err.message); else { app.io.to(roomNo).emit('message', { id: data.id, no: no, type: data.type, room_no: roomNo, user_no: userNo, user_type: userType, name: name, content: data.content, create_time: new Date() }); } }); } } // 고객 else if (data.user_type == 2) { // 1. 상담원이 아직 배정되지 않은 경우 if (data.room_no == undefined) { var userNo = data.user_no; var userType = data.user_type; var name = data.name || '고객'; // 임시로 저장 tempMessages[socket.id].push(data); // 보낸사람에게만 다시 전송 socket.emit('message', { type: data.type, user_no: userNo, user_type: userType, name: name, content: data.content, create_time: new Date(), }); } // 2. 상담원이 배정되어서 방이 만들어진 경우 else { var roomNo = data.room_no; var userNo = data.user_no; var userType = data.user_type; var name = data.name || '고객'; // 방에 들어가 있으면 방모두에게 전송 (DB에 남김) if (roomNo != undefined) { service.addChat(roomNo, userNo, userType, 1, data.content, function (err, no) { if (err) console.log(err.message); else { app.io.to(roomNo).emit('message', { id: data.id, no: no, type: data.type, room_no: roomNo, user_no: userNo, user_type: userType, name: name, content: data.content, create_time: new Date() }); } }); } // 방에 들어가 있지 않으면 자기에게만 전송 else { console.log('add-message(' + roomNo + '): ' + data.text); socket.emit('message', { id: data.id, user: userName, time: new Date(), text: data.text, user_type: userType, name: userName, content: data.text, create_time: new Date() }); } } } } // TEMP }); // TODO IVR socket.on('ivr', function(data) { var roomNo = data.room_no; var ivrNo = data.ivr_no; if (ivrRooms.has(roomNo)) { console.log(`[IVR] already start room_no: ${roomNo} ivr_no: ${ivrNo}`); return; } console.log(`[IVR] start room_no: ${roomNo} ivr_no: ${ivrNo}`); // IVR 질문 목록 가져옴 ivrDB.select(ivrNo, function(err, questions) { // console.log('qiestion', questions); ivrRooms.set(roomNo, {ivr_no: ivrNo, questions: questions}); var ivr = ivrRooms.get(roomNo); var question = ivr.questions.shift(); // 질문 목록 체크 if (question) { var msg = JSON.stringify(question); console.log(`[IVR] send first question: ${msg}`); // TODO 읽음 처리 // 방에 접속중인 사람 카운트 // 2명이상이면 읽음으로 표시 var readFlag = false; var room = app.io.sockets.adapter.rooms[data.room_no]; if (room) { if (room.length > 1) { readFlag = true; } } var userInfo = {type: USER_TYPE_AUTO, no: 0, name: 'IVR'}; service.sendMessage(app.io, roomNo, userInfo, MSG_TYPE_IVR, msg, false, readFlag); } }); // } }); // 알림 등록 socket.on('reg-push', function(data) { var userNo = data.user_no; // if (connUsers.has(userNo) == false) { connUsers.set(userNo, socket); console.log('reg-push', userNo); // } }); // 알림 헤제 socket.on('unreg-push', function(data) { var userNo = data.user_no; if (connUsers.has(userNo)) { connUsers.delete(userNo); console.log('unreg-push', userNo); } }); }); var moment = require('moment'); var cron = require('node-schedule'); // 재분배 타이머 var distTimer; // 셋팅 초기 로드 var setting = require('./service/setting'); setting.serviceReload(function (err) { if (err) { console.log('service setting load failure'); } else { console.log('service setting load success'); } }); setting.consultReload(function (err) { if (err) { console.log('consult setting load failure'); } else { console.log('consult setting load success'); } }); setting.scheduleReload(function (err) { if (err) { console.log('schedule/holiday load failure'); } else { console.log('schedule/holiday load success'); // 상담 재분배 (초기) schedule.checkConsultOff(function(distDate) { console.log('check consult off', moment(distDate)); distTimer = cron.scheduleJob(distDate, function() { schedule.distributeConsultOff(); }); }); } }); // setting.holydayReload(function (err) { // if (err) { // console.log('holiday load failure'); // } else { // console.log('holiday load success'); // } // }); setting.arsCommentReload(function (err) { if (err) { console.log('ars comment setting load failure'); } else { console.log('ars comment setting load success'); } }); setting.distOffReload(function (err) { if (err) { console.log('dist off user list load failure'); } else { console.log('dist off user list load success'); } }); setting.slangReload(function (err) { if (err) { console.log('slang list load failure'); } else { console.log('slang list load success'); } }); // setTimeout(function() { // console.log(schedule.checkSchedule()); // }, 1000); // 주기적 실행 (크론) var cronService = require('./service/cron'); var statService = require('./service/stat'); // 매분 cron.scheduleJob('* * * * *', function(){ console.log('minute: ' + moment().toDate()); // 응답없는 고객 확인 cronService.checkDelayChat(app.io); // statService.stat_1h(); }); // 매시 cron.scheduleJob('5 0 * * * *', function(){ console.log('hour: ' + moment().toDate()); // 통계 생성 statService.stat_1h(); }); // 매일 cron.scheduleJob('10 0 0 * * *', function(){ console.log('day: ' + moment().toDate()); // 스케쥴 리로드 setting.scheduleReload(function(err) {}); // 상담 재분배 schedule.checkConsultOff(function(distDate) { console.log('check consult off', moment(distDate)); if (distTimer != null) { distTimer.cancel(); } distTimer = cron.scheduleJob(distDate, function() { schedule.distributeConsultOff(); }); }); }); module.exports = app;
'use strict'; const tzData = require('moment-timezone/data/packed/latest.json'); function getOlsonTZNames() { return tzData.zones.map(zone => zone.split('|')[0]); } module.exports = getOlsonTZNames;
import React from 'react' const UserOverview = (props) => { return ( <div> <div className="jumbotron jumbotron-fluid hero"> <h1>{props.user}</h1> <br /> <button className='btn btn-danger' onClick={props.backToOverview}>back</button> </div> <div className="container"> {props.repos.map((item, index) => { return( <div className="card" key={index}> <div className="card-header"> <h5>{item.name}</h5> </div> <div className="card-body"> <p className="card-text">ssh: {item.ssh}</p> <p className="card-text">created on: {item.createdAt.substring(0,10).split('-').reverse().join('-')}</p> <p className="card-text">updated on: {item.updatedAt.substring(0,10).split('-').reverse().join('-')}</p> <a href={item.url} rel="noopener noreferrer" target="_blank" className="btn btn-primary">Go to Repo</a> </div> </div> ) } )} </div> </div> ) } export default UserOverview
// via https://unpkg.com/browse/emojibase-data@6.0.0/meta/groups.json const allGroups = [ [-1, '✨', 'custom'], [0, '😀', 'smileys-emotion'], [1, '👋', 'people-body'], [3, '🐱', 'animals-nature'], [4, '🍎', 'food-drink'], [5, '🏠️', 'travel-places'], [6, '⚽', 'activities'], [7, '📝', 'objects'], [8, '⛔️', 'symbols'], [9, '🏁', 'flags'] ].map(([id, emoji, name]) => ({ id, emoji, name })) export const groups = allGroups.slice(1) export const customGroup = allGroups[0]
/* This is a: <link rel="import" href="editable-name-tag.html"> <link rel="import" href="https://polygit.org/components/polymer/polymer-element.html"> <link rel="import" href="https://polygit.org/components/iron-input/iron-input.html"> <dom-module id="editable-name-tag"> <template> <p>This is <b>[[owner]]</b>'s name-tag element.</p> <iron-input bind-value="{{owner}}"> <input is="iron-input" placeholder="Your name here..."> </iron-input> </template> <script> */ class EditableNameTag extends Polymer.Element { static get is() { return "editable-name-tag"; } static get properties() { return { owner: { type: String, value: 'Daniel' } }; } } customElements.define(EditableNameTag.is, EditableNameTag); /* </script> </dom-module> */
import React from "react"; import StartButton from "../StartButton"; // styles import styles from "../../styles/WelcomePage.module.css"; import { Link } from "react-router-dom"; const Navbar = () => { return ( <nav> <div className={styles.navbar}> <h2> <a href="/#">Blocs</a> </h2> <ul> <li> <a href="/#why">Why Blocs</a> </li> <li> <a href="/#how">How It Works</a> </li> <li> <a href="/#about">About Us</a> </li> <li> <Link to="/game">Sign Up</Link> </li> </ul> </div> </nav> ); }; export default Navbar;
const puppeteer = require('puppeteer') const expect = require('chai').expect describe('Payment Test',async ()=>{ let browser let page before(async function () { browser = await puppeteer.launch( {headless:false , slowMo:10, devtools:false, defaultViewport: null, args: ['--start-maximized'] }); page = await browser.newPage() await page.setDefaultTimeout('10000') await page.setDefaultNavigationTimeout('20000') await page.goto('http://zero.webappsecurity.com/login.html') await page.waitForSelector('#login_form') await page.type('#user_login','username') await page.type('#user_password','password') await page.click('#user_remember_me') await page.click('[value="Sign in"]') await page.waitForSelector('#settingsBox') }) after(async function () { await browser.close(); }) it('Display Payment Form',async function (){ await page.waitForSelector('.nav.nav-tabs') await page.click('#pay_bills_tab') await page.waitForSelector('.board') }) it('Make Payment',async ()=>{ await page.waitForSelector('#sp_payee') await page.select('#sp_payee','apple') await page.select('#sp_account','5') await page.type('#sp_amount','500') await page.type('#sp_date','2020-07-16') await page.keyboard.press('Enter') await page.type('#sp_description','Payment done from my end') await page.click('#pay_saved_payees') await page.waitForSelector('#alert_content') }) })
import React, { Component } from 'react'; import axios from 'axios'; import { StyleSheet, View, Image, Text, TouchableOpacity, Button } from 'react-native'; import { Constants } from 'expo'; export default class Game extends Component { state = { isDisabled1: false, isDisabled2: false, isDisabled3: false, penalty: this.props.navigation.state.params.penalty, } resolve(penalty){ return axios.patch('https://a08ae967.ngrok.io/players/'+this.props.navigation.state.params.groupname, { progress: 'Game6', penalty: penalty, }) .then(res => res.data); } render() { const { isDisabled1, isDisabled2, isDisabled3 } = this.state return ( <View style={styles.container}> <View style={styles.logoContainer}> <Image style={styles.logo} source={require('../Icons/rick5.png')} /> <Text style={styles.title}>{this.props.navigation.state.params.username} i forgot the chemical formula</Text> </View> <Text style={styles.text}> {this.props.navigation.state.params.username} you need to finde the chemical formula for sulfuric acids...{'\n'} I have some options that you can choose from!{'\n'}{'\n'} 25% chance... EASY!{'\n'} </Text> <View style={styles.row}> <TouchableOpacity style={isDisabled1 ? styles.disabled : styles.enable} disabled={isDisabled1} onPress={() => this.setState({ isDisabled1: !this.state.isDisabled1, penalty: this.state.penalty + 1 })}> <Text style={styles.title}>{isDisabled1 ? "Disabled" : "H2SO3"}</Text> </TouchableOpacity> <TouchableOpacity style={isDisabled2 ? styles.disabled : styles.enable} disabled={isDisabled2} onPress={() => this.setState({ isDisabled2: !this.state.isDisabled2, penalty: this.state.penalty + 1 })}> <Text style={styles.title}>{isDisabled2 ? "Disabled" : "H4SO6"}</Text> </TouchableOpacity> </View> <View style={styles.row}> <TouchableOpacity style={styles.enable} onPress={() => this.resolve(this.state.penalty) && this.props.navigation.navigate('Game6', { username: this.props.navigation.state.params.username, groupname: this.props.navigation.state.params.groupname, penalty: this.state.penalty })} > <Text style={styles.title}>H2SO4</Text> </TouchableOpacity> <TouchableOpacity style={isDisabled3 ? styles.disabled : styles.enable} disabled={isDisabled3} onPress={() => this.setState({ isDisabled3: !this.state.isDisabled3, penalty: this.state.penalty + 1 })}> <Text style={styles.title}>{isDisabled3 ? "Disabled" : "H4SO2"}</Text> </TouchableOpacity> </View> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: 'black', alignItems: 'center', }, row: { flexDirection: 'row', justifyContent: 'space-between', margin: 10, }, enable: { borderRadius: 20, height: 50, width: 150, alignItems: 'center', backgroundColor: 'lightblue' }, disabled: { borderRadius: 20, height: 50, width: 150, alignItems: 'center', backgroundColor: 'black' }, logoContainer: { marginTop: 50, alignItems: 'center' }, text: { textAlign: 'center', color: 'lightblue', fontSize: 20 }, logo: { width: 250, height: 200, }, title: { color: 'black', marginTop: 10, marginBottom: 15, textAlign: 'center', fontSize: 26 } });
/* * The MIT License (MIT) * Copyright (c) 2019. Wise Wild Web * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * @author : Nathanael Braun * @contact : n8tz.js@gmail.com */ import Input from '@material-ui/core/Input'; import Button from '@material-ui/core/Button'; import Actions from "App/store/actions"; import React from 'react'; import {connect} from 'react-redux' import {withI18n, usePopins} from "App/ui/spells/(*).js"; @withI18n() @usePopins() export default class ConfirmPopin extends React.Component { static propTypes = {}; state = {}; pass = React.createRef(); user = React.createRef(); componentDidUpdate( prevProps, prevState, snapshot ) { let { popPopin, scadaxia } = this.props; } onClickOut = ( e ) => { let { popPopin } = this.props; e.preventDefault(); popPopin(); } onConfirm = ( e ) => { let { popPopin, onConfirm } = this.props; e.preventDefault(); onConfirm && onConfirm(); popPopin(); } render() { let { dispatch, t, label, confirmLabel = t('OK'), cancelLabel = t('cancel') } = this.props, {} = this.state; return <div className={"ConfirmPopin"}> <div className={"label"}>{label}</div> <div className={"buttons"}> <Button className={"confirmBtn"} onClick={this.onConfirm}>{confirmLabel}</Button> <Button className={"cancelBtn"} onClick={this.onClickOut}>{cancelLabel}</Button> </div> </div> } }
const webpack = require('webpack'); const babel_config = { 'test': /\.js$/, 'exclude': /node_modules/, 'use': { 'loader': 'babel-loader', 'options': { 'presets': [ 'env', 'react' ], 'plugins': [ 'transform-object-rest-spread', 'transform-react-remove-prop-types' ] } } } module.exports = babel_config;
require('../connection') const User = require('../models/User') const deleteUser = async () => { const deletedUser = await User.deleteMany({"username":"pancho"}) console.log(deletedUser) } deleteUser();
self.__precacheManifest = (self.__precacheManifest || []).concat([ { "revision": "62ce3451dc123d0009951d5182635d3b", "url": "/index.html" }, { "revision": "9b4a4f2630e6b33c014d", "url": "/static/css/2.47e06e2e.chunk.css" }, { "revision": "ab449e9083839f25749e", "url": "/static/css/main.384ab97f.chunk.css" }, { "revision": "9b4a4f2630e6b33c014d", "url": "/static/js/2.6c9b85df.chunk.js" }, { "revision": "0117d6bfe178eaa3446727e0cf23470b", "url": "/static/js/2.6c9b85df.chunk.js.LICENSE.txt" }, { "revision": "ab449e9083839f25749e", "url": "/static/js/main.37b99c58.chunk.js" }, { "revision": "5d93c6b2d15332364552", "url": "/static/js/runtime-main.cea588d5.js" } ]);
import React from 'react'; // import { Container } from './styles'; const Footer = props => { return ( <div className="footer"> <div className="container"> <div className="row"> <div className="col-lg-4 col-md-4 col-sm-4"> <ul className="list-group lista-links"> <li className="list-group-item"><a href="/" title="mini">mini</a></li> <li className="list-group-item"><a href="/" title="pequeno porte">pequeno porte</a></li> <li className="list-group-item"><a href="/" title="médio porte">médio porte</a></li> <li className="list-group-item"><a href="/" title="grande porte">grande porte</a></li> </ul> </div> <div className="col-lg-4 col-md-4 col-sm-4"> <ul className="list-group lista-links"> <li className="list-group-item"><a href="/" title="até R$100">até R$100</a></li> <li className="list-group-item"><a href="/" title="de R$100 a R$300">de R$100 a R$300</a></li> <li className="list-group-item"><a href="/" title="de R$300 a R$500">de R$300 a R$500</a></li> <li className="list-group-item"><a href="/" title="acima de R$500">acima de R$500</a></li> </ul> </div> <div className="col-lg-4 col-md-4 col-sm-4 text-right"> <img src={require("../img/logo-rodape.png")} alt="Charlie & Dogs" /> <br /> <p className="telefone">11 0000.0000<br /> <a href="mailto:#" title="Entre em contato!">contato@charlieedog.com.br</a></p> </div> </div> </div> </div> ) } export default Footer;
import React, {Component} from 'react'; import PropTypes from 'prop-types'; import {Button, Icon} from 'antd'; import './index.less'; export function ToolItem(props) { const {items} = props; return items.map((item, index) => { if (!item) return null; const { key, type = 'primary', loading, icon, text, visible = true, disabled, onClick = () => void 0, component, ...others } = item; const itemKey = key || index; if (!visible) return null; if (typeof component === 'function') return <div key={itemKey}>{component()}</div>; if (component) return <div key={itemKey}>{component}</div>; return ( <Button key={itemKey} type={type} loading={loading} disabled={disabled} onClick={onClick} {...others} > {icon ? ( <Icon type={icon}/> ) : null} {text} </Button> ); }) } export default class ToolBar extends Component { static propTypes = { items: PropTypes.array, right: PropTypes.bool, }; static defaultProps = { items: [], right: false, }; render() { const {items, style = {}, right, children, ...others} = this.props; if (right && !style.justifyContent) { style.justifyContent = 'flex-end'; } return ( <div className="tool-bar-root" style={style} {...others}> {children ? children : <ToolItem items={items}/>} </div> ); } }
viaLabels = {}; viaLabels['streetReference'] = 'Strada di riferimento'; viaLabels['slotNumber'] = 'Numero posti a pagamento'; viaLabels['handicappedSlotNumber'] = 'Numero posti per disabili'; viaLabels['timedParkSlotNumber'] = 'Numero posti disco orario'; viaLabels['freeParkSlotNumber'] = 'Numero posti sosta libera'; viaLabels['subscritionAllowedPark'] = 'Possibilità di sosta con abbonamento pendolare/residente'; viaLabels['areaId'] = "Area";
self.__precacheManifest = (self.__precacheManifest || []).concat([ { "revision": "5d377350105b433a1b43733644463877", "url": "/index.html" }, { "revision": "9b4a4f2630e6b33c014d", "url": "/static/css/2.47e06e2e.chunk.css" }, { "revision": "b100b6149716931fafd5", "url": "/static/css/main.384ab97f.chunk.css" }, { "revision": "9b4a4f2630e6b33c014d", "url": "/static/js/2.6c9b85df.chunk.js" }, { "revision": "0117d6bfe178eaa3446727e0cf23470b", "url": "/static/js/2.6c9b85df.chunk.js.LICENSE.txt" }, { "revision": "b100b6149716931fafd5", "url": "/static/js/main.7b95a03d.chunk.js" }, { "revision": "5d93c6b2d15332364552", "url": "/static/js/runtime-main.cea588d5.js" } ]);
var users = require('../../core/dal/users'), crypt = require('../../core/crypt'); var service = { login: function(data) { return users.findByEmail(data.email).then(function(user) { if (user && crypt.comparePassword(data.password, user.password)) { return user; } throw { errors: { email: 'Неверный логин или пароль' } } }); } }; module.exports = service;
export { default as useDarkMode } from './useDarkMode'; export { default as useDocumentTitle } from './useDocumentTitle'; export { default as useEventListener } from './useEventListener'; export { default as useFetch } from './useFetch'; export { default as useHover } from './useHover'; export { default as useInputValue } from './useInputValue'; export { default as useIntersectionObserver } from './useIntersectionObserver'; export { default as useInterval } from './useInterval'; export { default as useKeyPressed } from './useKeyPressed'; export { default as useLightenDarkenColor } from './useLightenDarkenColor'; export { default as useLocalStorage } from './useLocalStorage'; export { default as useLockBodyScroll } from './useLockBodyScroll'; export { default as useMedia } from './useMedia'; export { default as useModal } from './useModal'; export { default as useScript } from './useScript'; export { default as useToggle } from './useToggle'; export { default as useWebShareApi } from './useWebShareApi'; export { default as useWhyDidYouUpdate } from './useWhyDidYouUpdate';
var http = require('http'); https = require('https'), qs = require('querystring'), env = process.env; var username = env.KARMABOT_USERNAME, password = env.KARMABOT_PASSWORD, useragent = 'karmabot/1.1', playground = {5087:0,6269:0,6495:0}, forMe = new RegExp('^@?' + username), handlers = [], hash = new Buffer(username + ':' + password).toString('base64'); var request = function(method, path, body, callback) { var protocol = https, options = { host : 'convore.com', headers : { 'Authorization' : 'Basic ' + hash, 'Content-Type' : 'application/x-www-form-urlencoded', 'User-Agent' : useragent }, method : method, path : path }; var url; if ( url = /^http(s)?:\/\/([^\/]+)(\/.*)/.exec(path) ) { if ( !url[1] ) protocol = http; options.host = url[2]; options.path = url[3]; options.port = 80; delete options.headers; } if ( typeof body === 'function' ) { callback = body; body = null; } if ( body && typeof body !== 'string' ) { body = qs.stringify(body); if ( options.method === 'post' ) options.headers['Content-Length'] = body.length; else options.path += '?' + body; } var req = protocol.request(options, function(res) { var data = ''; switch ( res.statusCode ) { case 200: if ( !callback ) return; res.on('data', function(chunk) { data += chunk }); res.on('end', function() { if ( /^application\/json/.test(res.headers['content-type']) ) try { data = JSON.parse(data); } catch (e) { console.log('parse error: ' + data) }; callback(data); }); break; default: console.log(res.statusCode); res.on('data', function(chunk) { console.log(chunk) }); process.exit(1); } }); if ( body && options.method === 'post' ) req.write(body); req.end(); } var get = function(path, body, callback) { request('get', path, body, callback); } var post = function(path, body, callback) { request('post', path, body, callback); } var say = function(topic, message, callback) { post('/api/topics/' + topic + '/messages/create.json', { message: message }, callback); } var dispatch = function(msg) { for ( var i in handlers ) { var pattern = handlers[i][0], handler = handlers[i][1]; if ( msg.user.username !== username && ( match = msg.message.match(pattern) ) ) { msg.match = match; msg.say = function(message, callback) { say(msg.topic.id, message, callback); }; handler(msg); } } } var listen = function(cursor) { var body = {};// topic_id : playground }; if ( typeof cursor === 'string' ) body.cursor = cursor; get('/api/live.json', body, function(data) { for ( var i in data.messages ) { var item = data.messages[i]; if ( item.kind === 'message' ) { if ( ! item.topic.id in playground ) continue; if ( forMe.test(item.message) ) dispatch(item); console.log(item.message); } cursor = item._id; } listen(cursor); }); } var command = function(phrase, callback) { handlers.push([phrase, callback]); } get('/api/account/verify.json', listen); command(/help/i, function(msg) { msg.say('I currently answer to \'star me\' and \'rate me\'. You can also ask me about my source and provoke to dual with evilbot', function() { msg.say('You can also ask me to recommend something from the BBC\'s iPlayer'); }); }); command(/source|where do you live/i, function(msg) { msg.say('I live here: https://github.com/mal/karmabot'); }) command(/star me/i, function(msg) { get('/users/' + msg.user.username + '/', function(data) { var match = />Stars received<\/span>\s+<strong>(\d+)</.exec(data), stars = parseInt(match[1]); msg.say('@' + msg.user.username + ' has ' + stars + ' stars!'); }); }); command(/rate me/i, function(msg) { get('/users/' + msg.user.username + '/', function(data) { var recieved = />Stars received<\/span>\s+<strong>(\d+)</.exec(data)[1], given = />Stars given<\/span>\s+<strong>(\d+)</.exec(data)[1], rating = Math.round(parseFloat(given) / parseFloat(recieved) * 1000) / 1000; msg.say('@' + msg.user.username + ' has a star give/take ratio of ' + rating + '!'); }); }); command(/\b(?:draw|dual|fight|kill|attack|freak out|slay|fruitsalad)\b/i, function (msg) { var ideas = ['banana', 'pistol', 'submachine gun', 'cuddly toy', 'M4', 'Rolf Harris', 'south china sea', 'ALIENS', 'banjo', 'KA-BOOM!!!']; msg.say('@evilbot image me ' + ideas[Math.floor(Math.random()*ideas.length)]); }); command(/\b(?:bbc|iplayer)\b/i, function(msg) { get('http://feeds.bbc.co.uk/iplayer/highlights/tv', function(data) { var playlist = [], pattern = /<link rel=\"alternate\" href="([^"]+)" type=\"text\/html\" title=\"([^"]+)\">\s+<media:content>\s+<media:thumbnail url="([^"]+)"/g, epi; while( epi = pattern.exec(data) ) { epi.shift(); playlist.push(epi); } epi = playlist[Math.floor(Math.random()*playlist.length)]; msg.say(epi[1] + '\n' + epi[0] + '\n\n' + epi[2]); }); }); command(/\b(?:twitter|trends?|topic|idea|theme)\b/i, function(msg) { get('http://api.twitter.com/1/trends/current.json', function(data) { for ( time in data.trends ) var trends = data.trends[time]; msg.say('What\'s your opinion on ' + trends[Math.floor(Math.random()*trends.length)].name + '?'); }); });
(function(root, factory) { 'use strict'; if (typeof define === 'function' && define.amd) { define(factory); } else if (typeof module !== 'undefined' && module.exports) { module.exports = factory; } else { root.showAngularStats = factory(); } }(window.self, function() { 'use strict'; var autoloadKey = 'showAngularStats_autoload'; var current = null; // define the timer function to use based upon whether or not 'performance is available' var timerNow = window.self.performance && window.self.performance.now ? function() { return window.self.performance.now(); } : function() { return Date.now(); }; var lastWatchCountRun = timerNow(); var watchCountTimeout = null; var lastWatchCount = getWatcherCount() || 0; var lastDigestLength = 0; var $rootScope; var digestIsHijacked = false; var listeners = { watchCount: {}, digestLength: {} }; // Hijack $digest to time it and update data on every digest. function hijackDigest() { if (digestIsHijacked) { return; } digestIsHijacked = true; var $rootScope = getRootScope(); var scopePrototype = Object.getPrototypeOf($rootScope); var oldDigest = scopePrototype.$digest; scopePrototype.$digest = function $digest() { var start = timerNow(); oldDigest.apply(this, arguments); var diff = (timerNow() - start); updateData(getWatcherCount(), diff); }; } // check for autoload var autoloadOptions = sessionStorage[autoloadKey] || localStorage[autoloadKey]; if (autoloadOptions) { autoload(JSON.parse(autoloadOptions)); } function autoload(options) { if (window.self.angular && getRootScope()) { showAngularStats(options); } else { // wait for angular to load... window.self.setTimeout(function() { autoload(options); }, 200); } } function showAngularStats(opts) { opts = opts !== undefined ? opts : {}; var returnData = { listeners: listeners }; // delete the previous one if (current) { current.$el && current.$el.remove(); current.active = false; current = null; } // Remove autoload if they did not specifically request it if (opts === false || !opts.autoload) { sessionStorage.removeItem(autoloadKey); localStorage.removeItem(autoloadKey); // do nothing if the argument is false if (opts === false) { return; } } opts.position = opts.position || 'top-left'; opts = angular.extend({ digestTimeThreshold: 16, autoload: false, trackDigest: false, trackWatches: false, logDigest: false, logWatches: false, styles: { position: 'fixed', background: 'black', borderBottom: '1px solid #666', borderRight: '1px solid #666', color: 'red', fontFamily: 'Courier', width: 130, zIndex: 9999, textAlign: 'right', top: opts.position.indexOf('top') == -1 ? null : 0, bottom: opts.position.indexOf('bottom') == -1 ? null : 0, right: opts.position.indexOf('right') == -1 ? null : 0, left: opts.position.indexOf('left') == -1 ? null : 0 } }, opts || {}); hijackDigest(); // setup the state var state = current = {active: true}; // auto-load on startup if (opts.autoload) { if (opts.autoload === 'localStorage') { localStorage.setItem(autoloadKey, JSON.stringify(opts)); } else if (opts.autoload === 'sessionStorage' || typeof opts.autoload === 'boolean') { sessionStorage.setItem(autoloadKey, JSON.stringify(opts)); } else { throw new Error('Invalid value for autoload: ' + opts.autoload + ' can only be "localStorage" "sessionStorage" or boolean.') } } // general variables var bodyEl = angular.element(document.body); var noDigestSteps = 0; // add the DOM element state.$el = angular.element('<div><canvas></canvas><div></div></div>').css(opts.styles); bodyEl.append(state.$el); var $text = state.$el.find('div'); // initialize the canvas var graphSz = {width: 130, height: 40}; var cvs = state.$el.find('canvas').attr(graphSz)[0]; // add listeners listeners.digestLength.ngStatsAddToCanvas = function(digestLength) { addDataToCanvas(null, digestLength); }; listeners.watchCount.ngStatsAddToCanvas = function(watchCount) { addDataToCanvas(watchCount); }; track('digest', listeners.digestLength); track('watches', listeners.watchCount, true); log('digest', listeners.digestLength); log('watches', listeners.watchCount, true); function track(thingToTrack, listenerCollection, diffOnly) { var capThingToTrack = thingToTrack.charAt(0).toUpperCase() + thingToTrack.slice(1); if (opts['track' + capThingToTrack]) { returnData[thingToTrack] = []; listenerCollection['track + capThingToTrack'] = function(tracked) { if (!diffOnly || returnData[thingToTrack][returnData.length - 1] !== tracked) { returnData[thingToTrack][returnData.length - 1] = tracked; returnData[thingToTrack].push(tracked); } }; } } function log(thingToLog, listenerCollection, diffOnly) { var capThingToLog = thingToLog.charAt(0).toUpperCase() + thingToLog.slice(1); if (opts['log' + capThingToLog]) { var last; listenerCollection['log' + capThingToLog] = function(tracked) { if (!diffOnly || last !== tracked) { last = tracked; var color = colorLog(thingToLog, tracked); if (color) { console.log('%c' + thingToLog + ':', color, tracked); } else { console.log(thingToLog + ':', tracked); } } }; } } function colorLog(thingToLog, tracked) { var color; if (thingToLog === 'digest') { color = tracked > opts.digestTimeThreshold ? 'color:red' : 'color:green'; } return color; } function addDataToCanvas(watchCount, digestLength) { var averageDigest = digestLength || lastDigestLength; var color = (averageDigest > opts.digestTimeThreshold) ? 'red' : 'green'; lastWatchCount = nullOrUndef(watchCount) ? lastWatchCount : watchCount; lastDigestLength = nullOrUndef(digestLength) ? lastDigestLength : digestLength; $text.text(lastWatchCount + ' | ' + lastDigestLength.toFixed(2)).css({color: color}); if (!digestLength) { return; } // color the sliver if this is the first step var ctx = cvs.getContext('2d'); if (noDigestSteps > 0) { noDigestSteps = 0; ctx.fillStyle = '#333'; ctx.fillRect(graphSz.width - 1, 0, 1, graphSz.height); } // mark the point on the graph ctx.fillStyle = color; ctx.fillRect(graphSz.width - 1, Math.max(0, graphSz.height - averageDigest), 2, 2); } //! Shift the canvas to the left. function shiftLeft() { if (state.active) { window.self.setTimeout(shiftLeft, 250); var ctx = cvs.getContext('2d'); var imageData = ctx.getImageData(1, 0, graphSz.width - 1, graphSz.height); ctx.putImageData(imageData, 0, 0); ctx.fillStyle = ((noDigestSteps++) > 2) ? 'black' : '#333'; ctx.fillRect(graphSz.width - 1, 0, 1, graphSz.height); } } // start everything shiftLeft(); if (!$rootScope.$$phase) { $rootScope.$digest(); } return returnData; } angular.module('angularStats', []).directive('angularStats', function() { 'use strict'; var index = 1; return { scope: { digestLength: '@', watchCount: '@', watchCountRoot: '@', onDigestLengthUpdate: '&?', onWatchCountUpdate: '&?' }, link: function(scope, el, attrs) { hijackDigest(); var directiveIndex = index++; if (attrs.hasOwnProperty('digestLength')) { var digestEl = el; if (attrs.digestLength) { digestEl = angular.element(el[0].querySelector(attrs.digestLength)); } listeners.digestLength['ngStatsDirective' + directiveIndex] = function(length) { digestEl.text((length || 0).toFixed(2)); }; } if (attrs.hasOwnProperty('watchCount')) { var watchCountRoot; var watchCountEl = el; if (scope.watchCount) { watchCountEl = angular.element(el[0].querySelector(attrs.watchCount)); } if (scope.watchCountRoot) { if (scope.watchCountRoot === 'this') { watchCountRoot = el; } else { // In the case this directive is being compiled and it's not in the dom, // we're going to do the find from the root of what we have... var rootParent; if (attrs.hasOwnProperty('watchCountOfChild')) { rootParent = el[0]; } else { rootParent = findRootOfElement(el); } watchCountRoot = angular.element(rootParent.querySelector(scope.watchCountRoot)); if (!watchCountRoot.length) { throw new Error('no element at selector: ' + scope.watchCountRoot); } } } listeners.watchCount['ngStatsDirective' + directiveIndex] = function(count) { var watchCount = count; if (watchCountRoot) { watchCount = getWatcherCountForElement(watchCountRoot); } watchCountEl.text(watchCount); }; } if (scope.onWatchCountUpdate) { listeners.watchCount['ngStatsDirectiveUpdate' + directiveIndex] = function(count) { scope.onWatchCountUpdate({watchCount: count}); }; } if (scope.onDigestLengthUpdate) { listeners.digestLength['ngStatsDirectiveUpdate' + directiveIndex] = function(length) { scope.onDigestLengthUpdate({digestLength: length}); }; } scope.$on('$destroy', function() { delete listeners.digestLength['ngStatsDirectiveUpdate' + directiveIndex]; delete listeners.watchCount['ngStatsDirectiveUpdate' + directiveIndex]; delete listeners.digestLength['ngStatsDirective' + directiveIndex]; delete listeners.watchCount['ngStatsDirective' + directiveIndex]; }); } }; function findRootOfElement(el) { var parent = el[0]; while (parent.parentElement) { parent = parent.parentElement; } return parent; } }); return showAngularStats; // UTILITY FUNCTIONS function getRootScope() { if ($rootScope) { return $rootScope; } var scopeEl = document.querySelector('.ng-scope'); if (!scopeEl) { return null; } $rootScope = angular.element(scopeEl).scope().$root; return $rootScope; } // Uses timeouts to ensure that this is only run every 300ms (it's a perf bottleneck) function getWatcherCount() { window.self.clearTimeout(watchCountTimeout); var now = timerNow(); if (now - lastWatchCountRun > 300) { lastWatchCountRun = now; lastWatchCount = getWatcherCountForScope(); } else { watchCountTimeout = window.self.setTimeout(function() { updateData(getWatcherCount()); }, 350); } return lastWatchCount; } function getWatcherCountForElement(element) { var startingScope = getClosestChildScope(element); return getWatcherCountForScope(startingScope); } function getClosestChildScope(element) { element = angular.element(element); var scope = element.scope(); if (!scope) { element = angular.element(element.querySelector('.ng-scope')); scope = element.scope(); } return scope; } function getWatchersFromScope(scope) { return scope && scope.$$watchers ? scope.$$watchers : []; } // iterate through listeners to call them with the watchCount and digestLength function updateData(watchCount, digestLength) { // update the listeners if (!nullOrUndef(watchCount)) { angular.forEach(listeners.watchCount, function(listener) { listener(watchCount); }); } if (!nullOrUndef(digestLength)) { angular.forEach(listeners.digestLength, function(listener) { listener(digestLength); }); } } function nullOrUndef(item) { return item === null || item === undefined; } function getWatcherCountForScope(scope) { var count = 0; iterateScopes(scope, function(scope) { count += getWatchersFromScope(scope).length; }); return count; } function iterateScopes(current, fn) { if (typeof current === 'function') { fn = current; current = null; } current = current || getRootScope(); current = _makeScopeReference(current); if (!current) { return; } var ret = fn(current); if (ret === false) { return ret; } return iterateChildren(current, fn); } function iterateSiblings(start, fn) { var ret; while (!!(start = start.$$nextSibling)) { ret = fn(start); if (ret === false) { break; } ret = iterateChildren(start, fn); if (ret === false) { break; } } return ret; } function iterateChildren(start, fn) { var ret; while (!!(start = start.$$childHead)) { ret = fn(start); if (ret === false) { break; } ret = iterateSiblings(start, fn); if (ret === false) { break; } } return ret; } function getScopeById(id) { var myScope = null; iterateScopes(function(scope) { if (scope.$id === id) { myScope = scope; return false; } }); return myScope; } function _makeScopeReference(scope) { if (_isScopeId(scope)) { scope = getScopeById(scope); } return scope; } function _isScopeId(scope) { return typeof scope === 'string' || typeof scope === 'number'; } }));
import React, { Component } from 'react' import styled from 'styled-components' import { ChangeImage } from '../DefaultEditors' import { Button } from '../../mia-ui/buttons' import { CheckboxInput, Label, Input } from '../../mia-ui/forms' import { Flex, Box } from 'grid-styled' import { Expander } from '../../mia-ui/expanders' import ImgSrcProvider from '../../shared/ImgSrcProvider' import Joyride from 'react-joyride' import { ImagesQuery } from '../../../apollo/queries/images' export default class ObjEditor extends Component { tourId = 'ObjEditor' initialState = { id: '', title: '', description: '', attribution: '', date: '', accessionNumber: '', medium: '', dimensions: '', currentLocation: '', creditLine: '', pullFromCustomApi: false, localId: '', exp: true } state = { ...this.initialState } render() { if (!this.props.obj || !this.props.organization) return null const { state, handleChange, handleSave, handleCheck, props: { organization, obj }, state: { exp } } = this let disabled = this.props.obj.pullFromCustomApi return ( <Expander open={exp} onRequestOpen={() => this.setState({ exp: true })} onRequestClose={() => this.setState({ exp: false })} id={'obj-editor'} > <Flex flexWrap={'wrap'} w={1}> <Flex w={1}> <Label>Pulling From Custom API</Label> <CheckboxInput name={'pullFromCustomApi'} checked={state.pullFromCustomApi} onChange={handleCheck} disabled /> </Flex> <Box w={1}> <Label>Local ID</Label> <Input placeholder={'Local ID'} name={'localId'} value={state.localId} onChange={handleChange} /> </Box> <Box w={1}> <Label>Title</Label> <Input placeholder={'Title'} name={'title'} value={state.title} onChange={handleChange} disabled={disabled} /> </Box> <Box w={1}> <Label>Attribution</Label> <Input placeholder={'Attribution'} name={'attribution'} value={state.attribution} onChange={handleChange} disabled={disabled} /> </Box> <Box w={1}> <Label>Current Location</Label> <Input placeholder={'Current Location'} name={'currentLocation'} value={state.currentLocation} onChange={handleChange} disabled={disabled} /> </Box> <Box w={1}> <Label>Date</Label> <Input placeholder={'Date'} name={'date'} value={state.date} onChange={handleChange} disabled={disabled} /> </Box> <Box w={1}> <ChangeImage label={'Image'} name={'primaryImageId'} image={obj.primaryImage} onChange={this.handleImageChange} /> </Box> </Flex> {this.props.tour ? ( <Joyride run={this.props.tour.run(this)} steps={this.props.tour.steps(this)} stepIndex={this.props.tour.stepIndex} callback={this.props.tour.callback(this)} styles={{ buttonClose: { display: 'none' }, buttonNext: { display: 'none' }, buttonBack: { display: 'none' } }} disableOverlayClose={true} disableCloseOnEscape={true} /> ) : null} </Expander> ) } handleImageChange = ({ target: { value, name } }) => { this.props.editObj({ id: this.props.objId, primaryImageId: value }) } bounce = true debounce = (func, wait) => { if (this.bounce) { clearTimeout(this.bounce) this.bounce = setTimeout(func, wait) } } handleChange = ({ target: { value, name, checked } }) => { this.setState( () => ({ [name]: value }), () => { this.debounce(this.handleSave, 1000) } ) } handleCheck = ({ target: { name, checked } }) => { this.setState( () => ({ [name]: checked }), () => { this.debounce(this.handleSave, 1000) } ) } handleSave = () => { this.props.editObj({ title: this.state.title, attribution: this.state.attribution, currentLocation: this.state.currentLocation, date: this.state.date }) } componentWillReceiveProps(nextProps) { if (nextProps.obj) { if (nextProps.obj.id !== this.state.id) { let { obj } = nextProps let state = {} Object.keys(obj).forEach(key => { Object.assign(state, { [key]: obj[key] || this.initialState[key] }) }) this.setState(state) } } } } const Container = styled.div` width: 100%; display: flex; flex-direction: column; align-items: flex-start; justify-content: flex-start; height: 100%; border: 1px solid grey; min-height: 500px; `
const chatbot = require('./modules/Main/chatbot'); var context = {session : 'CHAT', actionId:'111'}; var user= 'user1'; var loginAttempt = 0; exports.getResponse = function(type,payload,cb){ switch(type){ case 'SessionEndedRequest' : createResponse("CHAT|I didn't get you there'", function(res){ console.log("Response Session :: "+JSON.stringify(res.response.outputSpeech.text));console.log();console.log(":::::::::::NEXT MESSAGE::::::::::::::");console.log(); return cb(res); }); break; case 'IntentRequest' : processPayload(payload,function(res){ console.log("Response Intent :: "+res); createResponse(res,function(response){ return cb(response); }); }); break; case 'LaunchRequest': if(payload.session.user.accessToken == undefined){ loginAttempt = 0; return cb({ "version": "1.0", "response": { "outputSpeech": { "type": "PlainText", "text": " Please use the companion app to authenticate on Amazon to start using this skill" }, "card": { "type": "LinkAccount" }, "shouldEndSession": true }, "sessionAttributes": {} })}else { if (loginAttempt === 0){ createResponse("BOT|"+JSON.stringify({restype:'T', reply:"Please Provide OTP", next:1000}), function(res){ console.log("Response Session :: "+JSON.stringify(res.response.outputSpeech.text)); loginAttempt++; return cb(res); }); }else { // Check for Time Stamp createResponse("BOT|"+JSON.stringify({restype:'T', reply:"Hey, How can I assist you ?", next:111}), function(res){ console.log("Response Session :: "+JSON.stringify(res.response.outputSpeech.text)); return cb(res); }); } } } } function createResponse(msg,cb){ context.session=msg.split('|')[0]; if (msg.split('|')[0] == 'CHAT'){ var endSession = true; msg = msg.split('|')[1]; } else{ var endSession = false; var obj = JSON.parse(msg.split('|')[1]); context.actionId=obj.next; msg= obj.reply; } var response = { "version": "1.0", "response": { "outputSpeech": { "type": "PlainText", "text": msg }, "shouldEndSession": endSession } }; return cb(response); } function processPayload(payload,cb){ var session= context.session; var message=payload.request.intent.slots; console.log("Message From Client : : " +session+'|'+context.actionId+'|'+message.Message.value); if(session === 'CHAT'){ chatbot.processMsg(user+'|'+session+'|'+message.Message.value,'Alexa',function(response){ //Msg to BOT Engine return cb(response); }); }else{chatbot.processMsg(user+'|'+session+'|'+context.actionId+'|'+message.Message.value,'Alexa',function(response){ //Msg to BOT Engine return cb(response); }); } }
import axios from 'axios'; import { GET_PROFILE } from './types'; // Get Profile export const getProfile = ownerId => dispatch => { axios .get(`/api/location/profile/${ownerId}`) .then(res => dispatch({ type: GET_PROFILE, payload: res.data }) ) .catch(err => dispatch({ type: GET_PROFILE, payload: null }) ); };
import React, { Component } from 'react'; import { Tabs, Col, Divider, Alert } from 'antd'; import LoginForm from './LoginForm'; import SignUpForm from './SignUpForm'; import { Github } from './SocialLogin'; import './UserAuth.scss'; import '../AppMain/AppMain.scss'; import logo from '../../assets/images/flowist-main-light.png'; const TabPane = Tabs.TabPane; function callback(key) { console.log(key); } export class UserAuth extends Component { state = { errorShow: false, error: '' }; handleClose = () => { this.setState({ errorShow: false }); }; showError = (message) => { this.setState({ errorShow: true, error: message }); }; componentDidMount() { document.title = "Log In or Sign Up | Flowist"; } render() { const errorAlert = ( <Alert style={{ marginBottom: 16, textAlign: 'left' }} message="Error" description={this.state.error} showIcon type="error" closable afterClose={this.handleClose} /> ); return ( <div id="main-panel" className="centered"> <Col xs={2} sm={7} md={8} lg={8} xl={9} /> <Col xs={20} sm={10} md={8} lg={8} xl={6} id="main-panel-user-auth"> <div className="card-container"> <div id="app-logo-div"> <img src={logo} id="app-logo" alt="Flowist Logo" /> </div> <Tabs onChange={callback} type="card" style={{ textAlign: 'left' }}> <TabPane tab="Log In" key="1"> <div className="gutter-box"> {this.state.errorShow ? errorAlert : null} <LoginForm showLoginError={this.showError} /> </div> </TabPane> <TabPane tab="Sign Up" key="2"> <div className="gutter-box"> {this.state.errorShow ? errorAlert : null} <SignUpForm showSignUpError={this.showError} /> </div> </TabPane> </Tabs> </div> <Divider style={{ color: '#ccc' }}>or</Divider> <div id="social-login"> <Github className="social-login-btn"/> </div> </Col> <Col xs={2} sm={7} md={8} lg={8} xl={9} /> </div> ); } } export default UserAuth;
// pages/personal/personal.js var app = getApp(); import util from '../../utils/util.js'; Page({ /** * 页面的初始数据 */ data: { address: "", // 地址 provinces_name: "",//省 city_name: "",//市 county_name: "", //县 name: "", //姓名 phone: "", //电话 phone_bak: "", //备用电话 photo: "",//头像地址 qrurl: "" //二维码地址 }, toMyAddress: function () { util.navTo({ url: "../myAddress/myAddress?provinces_name=" + this.data.provinces_name + "&city_name=" + this.data.city_name + "&county_name=" + this.data.county_name + "&address=" + this.data.address }); }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { }, /** * 生命周期函数--监听页面显示 */ onShow: function () { app.netWork.postJson(app.urlConfig.myInformationUrl, {}).then(res => { if (res.errorNo == 0) { this.setData({ address: res.data.address, // 地址 provinces_name: res.data.provinces_name,//省 city_name: res.data.city_name,//市 county_name: res.data.county_name, //县 name: res.data.name, //姓名 phone: res.data.phone, //电话 phone_bak: res.data.phone_bak, //备用电话 photo: res.data.photo,//头像地址 qrurl: res.data.qrurl //二维码地址 }) } }) }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, })
import React, {Component} from 'react'; import {Alert} from 'reactstrap'; class Header extends Component { render() { return ( <div> <Alert color='secondary' style={{textAlign: 'center'}}> <h1>Data table react application</h1> </Alert> </div> ); } } export default Header;
import React, { Component, Fragment } from 'react'; import { Switch, Route } from 'react-router-dom'; import Header from 'components/Header/Header'; import Home from 'pages/Home'; import Survey from 'pages/Survey'; import Results from 'pages/Results'; export default class App extends Component { render() { return ( <Fragment> <Header /> <Switch> <Route exact path="/" component={Home} /> <Route exact path="/survey" component={Survey} /> <Route exact path="/results" component={Results} /> <Route path="/results/:id" component={Results} /> </Switch> </Fragment> ); } }
$(function() { //切换登录方式 $(".loginTopBox>div").click(function () { var i = $(this).index(); $(this).addClass("active").siblings().removeClass("active"); $(".loginAllBox>div").eq(i).show().siblings().hide(); loginMethod(); }); //判断当前是哪种登录方式 function loginMethod() { if($(".loginFirstBox").hasClass("active")){ $("#secondTel").val(""); $(".loginPasswordInp").val(""); $(".loginBtn").removeClass("active"); $(".loginBtn").attr("disabled","disabled"); //手机快捷登录,手机号正确,可以点击发送验证码 $("#firstTel").off().on("input",function(){ var firstTelVal = $("#firstTel").val(); var myreg=/^1\d{10}$/; if(firstTelVal && myreg.test(firstTelVal)){ $("#codeBtn").addClass("active"); $("#codeBtn").removeAttr("disabled"); $(".loginCodeInp").off().on("input",function () { var loginCodeInp = $(".loginCodeInp").val(); var mycodereg=/^\d{6}$/; if(loginCodeInp && mycodereg.test(loginCodeInp)){ $(".loginBtn").addClass("active"); $(".loginBtn").removeAttr("disabled"); }else{ $(".loginBtn").removeClass("active"); $(".loginBtn").attr("disabled","disabled"); } }); //点击获取验证码 var validCode=true; $("#codeBtn").click(function () { var phoneBase = encrypt.encrypt(firstTelVal); var time=60; var $code=$(this); if (validCode) { validCode=false; $.ajax({ url: "https://ms.shougongker.com/index.php?c=Loginnew&a=getCode&accessId=H1707137&time_stamp="+timest()+"&signature="+$.md5("accessId=H1707137&c="+getUrlParamsObj("https://ms.shougongker.com/index.php?c=Loginnew&a=getCode").c+"&a="+getUrlParamsObj("https://ms.shougongker.com/index.php?c=Loginnew&a=getCode").a+"&time_stamp="+timest()+"&secret=3b0ee641beeb0c249a7a8f52682d0544"), type: "post", dataType: "json", async: true, data: { phone: phoneBase, source: "h5" }, success: function (result) { mui.toast(result.info); }, error: function (data) { } }); var t=setInterval(function () { $code.attr("disabled","disabled"); time--; $code.html(time+"s后重发"); if (time==0) { $code.removeAttr("disabled"); clearInterval(t); $code.html("发送验证码"); validCode=true; } },1000); } }); }else{ $("#codeBtn").removeClass("active"); $("#codeBtn").attr("disabled","disabled"); $(".loginBtn").removeClass("active"); $(".loginBtn").attr("disabled","disabled"); } }) }else if($(".loginSecondBox").hasClass("active")){ $("#firstTel").val(""); $(".loginCodeInp").val(""); $(".loginBtn").removeClass("active"); $(".loginBtn").attr("disabled","disabled"); //账号密码登录 $("#secondTel").off().on("input",function () { var secondTelVal = $("#secondTel").val(); var myreg=/^1\d{10}$/; if(secondTelVal && myreg.test(secondTelVal)){ $(".loginPasswordInp").off().on("input",function () { var loginPasswordInp = $(".loginPasswordInp").val(); if(loginPasswordInp){ $(".loginBtn").addClass("active"); $(".loginBtn").removeAttr("disabled"); }else { $(".loginBtn").removeClass("active"); $(".loginBtn").attr("disabled","disabled"); } }); }else { $(".loginBtn").removeClass("active"); $(".loginBtn").attr("disabled","disabled"); } }); } } loginMethod(); //点击显示密码按钮 $(".login_nosee").click(function () { $(".loginPasswordInp").attr("type","text"); $(".login_cansee").show(); $(this).hide(); }); $(".login_cansee").click(function () { $(".loginPasswordInp").attr("type","password"); $(".login_nosee").show(); $(this).hide(); }); //点击登录按钮 $(".loginBtn").click(function () { //获取openid var openid = $.cookie("openid"); if($(".loginFirstBox").hasClass("active")){ //手机快捷登录 var firstTel = encrypt.encrypt($("#firstTel").val()); var loginCodeInp = $(".loginCodeInp").val(); var requestData = { phone: firstTel, code: loginCodeInp, channel: "h5", source: "h5" }; if(openid != "" && openid != null && openid != undefined){ requestData.openid = openid; } if (isWeixin()) { requestData.channel = "weixin"; requestData.openid = openid; } $.ajax({ url: "https://ms.shougongker.com/index.php?c=Loginnew&a=codeLogin&accessId=H1707137&time_stamp="+timest()+"&signature="+$.md5("accessId=H1707137&c="+getUrlParamsObj("https://ms.shougongker.com/index.php?c=Loginnew&a=codeLogin").c+"&a="+getUrlParamsObj("https://ms.shougongker.com/index.php?c=Loginnew&a=codeLogin").a+"&time_stamp="+timest()+"&secret=3b0ee641beeb0c249a7a8f52682d0544"), type: "post", dataType: "json", async: true, data: requestData, success: function (result) { mui.toast(result.info); $.cookie("token", result.data.token); if(result.info == "登录成功"){ if(isWeixin()){ window.history.go(-2); }else{ window.history.back(); } } }, error: function (data) { } }); }else if($(".loginSecondBox").hasClass("active")){ var secondTel = encrypt.encrypt($("#secondTel").val()); var loginPasswordInp = encrypt.encrypt($(".loginPasswordInp").val()); var hasOpenIdData = { phone: secondTel, password: loginPasswordInp, source: "h5", loginType: "phone" }; if(openid != "" && openid != null && openid != undefined){ hasOpenIdData.openid = openid; } $.ajax({ url: 'https://ms.shougongker.com/index.php?c=Loginnew&a=login&accessId=H1707137&time_stamp='+timest()+'&signature='+$.md5("accessId=H1707137&c="+getUrlParamsObj("https://ms.shougongker.com/index.php?c=Loginnew&a=login").c+"&a="+getUrlParamsObj("https://ms.shougongker.com/index.php?c=Loginnew&a=login").a+"&time_stamp="+timest()+"&secret=3b0ee641beeb0c249a7a8f52682d0544"), type: 'post', data: hasOpenIdData, dataType: 'json', success: function (result) { mui.toast(result.info); $.cookie("token", result.data.token); if(result.info == "登录成功"){ if(isWeixin()){ window.history.go(-2); }else{ window.history.back(); } } }, error: function (data) { } }); } }); }); /** * 将url中参数(或公共参数)转换为json对象 * @param href 当前页面url * @returns all url上所有参数 */ function getUrlParamsObj(href) { if (href.indexOf("?") == -1) { return {}; } href = decodeURIComponent(href); var queryString = href.substring(href.indexOf("?") + 1); var parameters = queryString.split("&"); var all = {}; var pos, paraName, paraValue; for (var i = 0; i < parameters.length; i++) { pos = parameters[i].indexOf('='); if (pos == -1) { continue; } paraName = parameters[i].substring(0, pos); paraValue = parameters[i].substring(pos + 1); all[paraName] = paraValue; } return all; } //从1970年开始的毫秒数然后截取10位变成 从1970年开始的秒数 function timest() { var tmp = Date.parse( new Date() ).toString(); tmp = tmp.substr(0,10); return tmp; } //判断是否在微信中打开 function isWeixin() { var ua = navigator.userAgent.toLowerCase(); if (ua.match(/MicroMessenger/i) == "micromessenger") { return true; } else { return false; } }
OC.L10N.register( "lib", { "Cannot write into \"config\" directory!" : "¡No se puede escribir en el directorio «config»!", "This can usually be fixed by giving the webserver write access to the config directory" : "¡No se puede escribir en el directorio «config»!\n\nNormalmente esto se soluciona dándole al servidor web acceso para escribir en el directorio config. \n\nConfiguración de muestra detectado", "See %s" : "ver %s", "This can usually be fixed by %sgiving the webserver write access to the config directory%s." : "Normalmente esto se soluciona %s dándole al servidor web acceso para escribir en el directorio config %s", "Sample configuration detected" : "Configuración de muestra detectada", "It has been detected that the sample configuration has been copied. This can break your installation and is unsupported. Please read the documentation before performing changes on config.php" : "Se detectó que la configuración de muestra se había copiado. Esto puede romper su instalacón y no está respaldado. Por favor lea la documentación antes de realizar cambios en la config.php", "Unknown filetype" : "Tipo de archivo desconocido", "Invalid image" : "Imagen inválida", "today" : "hoy", "yesterday" : "ayer", "last month" : "mes pasado", "_%n month ago_::_%n months ago_" : ["Hace %n mes","Hace %n meses"], "last year" : "año pasado", "_%n hour ago_::_%n hours ago_" : ["Hace %n hora","Hace %n horas"], "_%n minute ago_::_%n minutes ago_" : ["Hace %n minuto","Hace %n minutos"], "seconds ago" : "hace segundos", "None" : "Ninguno", "Username and password" : "Nombre de usuario y contraseña", "Username" : "Nombre de usuario", "Password" : "Contraseña", "File name contains at least one invalid character" : "Nombre de archivo contiene al menos un caracter no válido", "__language_name__" : "Español (México)", "App directory already exists" : "El directorio de la aplicación ya existe", "Can't create app folder. Please fix permissions. %s" : "No se puede crear la carpeta de la aplicación. Corrija los permisos. %s", "No source specified when installing app" : "No se ha especificado origen cuando se ha instalado la aplicación", "No href specified when installing app from http" : "No href especificado cuando se ha instalado la aplicación", "No path specified when installing app from local file" : "Sin path especificado cuando se ha instalado la aplicación desde el archivo local", "Archives of type %s are not supported" : "Archivos de tipo %s no son soportados", "Failed to open archive when installing app" : "Fallo de abrir archivo mientras se instala la aplicación", "App does not provide an info.xml file" : "La aplicación no suministra un archivo info.xml", "App can't be installed because it is not compatible with this version of ownCloud" : "La aplicación no se puede instalar porque no es compatible con esta versión de ownCloud", "App can't be installed because it contains the <shipped>true</shipped> tag which is not allowed for non shipped apps" : "La aplicación no se puede instalar porque contiene la etiqueta\n<shipped>\ntrue\n</shipped>\nque no está permitida para aplicaciones no distribuidas", "Apps" : "Aplicaciones", "General" : "General", "Storage" : "Almacenamiento", "Security" : "Seguridad", "Encryption" : "Cifrado", "Sharing" : "Compartir", "Search" : "Buscar", "%s enter the database username." : "%s ingresar el usuario de la base de datos.", "%s enter the database name." : "%s ingresar el nombre de la base de datos", "Oracle connection could not be established" : "No se pudo establecer la conexión a Oracle", "Oracle username and/or password not valid" : "Usuario y/o contraseña de Oracle no válidos", "DB Error: \"%s\"" : "Error BD: \"%s\"", "Offending command was: \"%s\"" : "Comando infractor: \"%s\"", "You need to enter either an existing account or the administrator." : "Tiene que ingresar una cuenta existente o la del administrador.", "Offending command was: \"%s\", name: %s, password: %s" : "Comando infractor: \"%s\", nombre: %s, contraseña: %s", "PostgreSQL username and/or password not valid" : "Usuario y/o contraseña de PostgreSQL no válidos", "Set an admin username." : "Configurar un nombre de usuario del administrador", "Set an admin password." : "Configurar la contraseña del administrador.", "Invalid Federated Cloud ID" : "ID de Nube Federada Inválida", "%s shared »%s« with you" : "%s ha compartido »%s« contigo", "Sharing %s failed, because this item is already shared with %s" : "No se puedo compartir %s, porque este elemento ya está compartido con %s", "Not allowed to create a federated share with the same user" : "No está permitido compartir de forma federada con el mismo usuario", "Could not find category \"%s\"" : "No puede encontrar la categoria \"%s\"", "A valid username must be provided" : "Se debe proporcionar un nombre de usuario válido", "A valid password must be provided" : "Se debe proporcionar una contraseña válida", "Settings" : "Configuración", "Users" : "Usuarios", "A safe home for all your data" : "Un lugar seguro para todos tus datos", "Imprint" : "pie de imprenta", "Application is not enabled" : "La aplicación no está habilitada", "Authentication error" : "Error de autenticación", "Token expired. Please reload page." : "Token expirado. Por favor, recarga la página.", "Storage is temporarily not available" : "El almacenamiento no está disponible temporalmente" }, "nplurals=2; plural=(n != 1);");
(function() { 'use strict'; angular .module('jhipsterApp') .factory('WealthChart', WealthChart ); WealthChart.$inject = ['$resource', '$log']; function WealthChart ($resource, $log) { var resourceUrl = 'api/wealth-chart'; return $resource(resourceUrl, {}, { 'query': { method: 'GET'}, 'get': { method: 'GET', transformResponse: function (data) { //$log.debug('raw data ' + data); data = angular.fromJson(data); //$log.debug('json data ' + data); //$log.debug('keylist data ' + data.keyList); //$log.debug('valuelist data ' + data.valueList); return data; } } }); } })();
var validator = require('validator'); var getModelValidator = require('./modelValidator'); var isPositiveInt = function(value) { return validator.isInt(value, { min: 1 }); }; var isDate = function(value) { return validator.isDate(value); }; var schema = [ { property: 'externalorderId', test: isPositiveInt, message: 'Saapuneen tilauksen täytyy liittyä ulkoiseen tilaukseen.', }, { property: 'arrivalDate', test: isDate, message: 'Valitse saapumispäivä', }, ]; module.exports = getModelValidator(schema);
function accum(str) { var res = []; for(var i = 0; i < str.length; i++) { var row = ''; for(var j = 0; j < i + 1; j++) { row += j===0 ? str[i].toUpperCase() : str[i].toLowerCase(); } res.push(row); } return res.join('-'); } appreciation0 = accum("abcd"); appreciation1 = accum("RqaEzty"); appreciation2 = accum("cwAt"); console.log(appreciation0 + "\n" ,appreciation1 + "\n" ,appreciation2);
import React, {useState} from 'react'; import { CarouselItem, CarouselCaption, Card, CardImg, CardGroup, CardText, CardBody, CardTitle, CardSubtitle, Button } from 'reactstrap'; import Banner from '../components/Banner'; import CardView from '../components/CardView'; import AutoplaySlider from 'react-awesome-slider'; import 'react-awesome-slider/dist/styles.css'; const imageData = [ { imageSrc:'https://www.publicdomainpictures.net/pictures/320000/velka/background-image.png' }, { imageSrc:'http://tech.akamai.com/image-manager/img/mountain.jpeg' }, { imageSrc:'https://c.pxhere.com/images/5b/9a/69277238603785e61b8d0ef790fd-1567591.jpg!d' } ] const campaignFakeData = [ {title: '新創項目', subtitle:'關於此項目', info: '此項目內容', currentInvestment:100000, requuiredInvestment:200000, imgSrc:'https://www.macmillandictionary.com/external/slideshow/thumb/Grey_thumb.png'}, {title: '新創項目', subtitle:'關於此項目', info: '此項目內容', currentInvestment:100000, requuiredInvestment:200000, imgSrc:'https://www.macmillandictionary.com/external/slideshow/thumb/Grey_thumb.png'}, {title: '新創項目', subtitle:'關於此項目', info: '此項目內容', currentInvestment:100000, requuiredInvestment:200000, imgSrc:'https://www.macmillandictionary.com/external/slideshow/thumb/Grey_thumb.png'}, {title: '新創項目', subtitle:'關於此項目', info: '此項目內容', currentInvestment:100000, requuiredInvestment:200000, imgSrc:'https://www.macmillandictionary.com/external/slideshow/thumb/Grey_thumb.png'}, ] const Main = () => { return( <div className="Main"> <AutoplaySlider bullets={false} style={{ height:'60vh', width:'100%' }}> {imageData.map( (img) => <div data-src={img.imageSrc} /> )} </AutoplaySlider> <p style={{padding:20}}/> <h4 style={{justifySelf:'start'}}>熱門項目</h4> <div style={{padding:'1rem'}}> <CardGroup> {campaignFakeData.map((data, index) => <Card style={{margin:'0.5rem'}}> <CardImg top height='100vh' width='10vh' src={data.imgSrc} alt={'Campaign' + index + 'Image'}/> <CardBody> <CardTitle>{data.title}</CardTitle> <CardSubtitle>{data.subtitle}</CardSubtitle> <CardText>{data.info}</CardText> <Button>進入</Button> </CardBody> </Card> )} </CardGroup> </div> <div style={{padding:'1rem'}}> <CardGroup> {campaignFakeData.map((data, index) => <Card style={{margin:'0.5rem'}}> <CardImg top height='100vh' width='10vh' src={data.imgSrc} alt={'Campaign' + index + 'Image'}/> <CardBody> <CardTitle>{data.title}</CardTitle> <CardSubtitle>{data.subtitle}</CardSubtitle> <CardText>{data.info}</CardText> <Button>進入</Button> </CardBody> </Card> )} </CardGroup> </div> </div> ) } export default Main;
import React from "react"; import PropTypes from "prop-types"; import { Switch, Route, withRouter } from "react-router-dom"; //import { inject, observer, PropTypes as MobxPropTypes } from 'mobx-react'; import App from "../App/container/App"; // import LoginPage from '../Auth/containers/LoginPage'; class Root extends React.Component { // componentWillMount() { // const { authStore, history } = this.props; // authStore.getCurrentSession(); // if (authStore.isUserLoggedIn || authStore.isAuthenticated) { // history.push('/'); // } else { // history.push('/login'); // } // } render() { return ( <Switch> <Route exact component={App} path="/" /> {/* <Route component={LoginPage} path="/login" /> */} </Switch> ); } } Root.propTypes = { // authStore: MobxPropTypes.observableObject.isRequired, history: PropTypes.object }; Root.defaultProps = { history: {} }; const RootWithAuth = withRouter(Root); export default RootWithAuth;
/** * Created by zhoucaiguang on 2017/3/8. */ "use strict"; const mysqlBase_1 = require('./mysqlBase'); // console.log(mysqlBase); class mysql extends mysqlBase_1.mysqlBase { constructor() { super(); } checkDataAndInsert(herfs) { if (herfs) { herfs.forEach((item, index) => { this.find('select id from node_url where url=?', [item]).spread((response) => { if (!response) { this.insert('node_url', { url: item }).then((response) => { }); } }); }); } } addImgTitle(title, imgThums) { return this.insert('node_title', { title: title, imgThums: imgThums }).then((response) => { return response; }); } checkImgDataAndInsert(herfs, title) { this.find('select id from node_title where `title`=?', [title]).spread((response) => { if (!response) { this.addImgTitle(title, herfs[0]).spread((res) => { console.log(res); this.addImgs(herfs, res.insertId); }); } else { this.addImgs(herfs, response.id); } }); } addImgs(herfs, titleId) { if (herfs.length > 0) { herfs.forEach((item, index) => { this.find('select id from node_img where url=?', [item]).spread((response) => { if (!response) { this.insert('node_img', { url: item, titleId: titleId }).then((response) => { console.log('插入成功'); }); } }); }); } } } Object.defineProperty(exports, "__esModule", { value: true }); exports.default = mysql; /* db.select('select * from node_title').spread((response:any)=>{ console.log(response); }).catch((response)=>{ console.log(response); }); */ /* db.insert('node_sort',{namev:'123123'}).spread((response)=>{ console.log(response); }); */ /* db.update('node_sort',{namev:123,text:'123123123',www:'12312321'},'1=1').spread((response)=>{ console.log(response); }).catch((error)=>{ console.log('error:',error); }); */
var items = document.querySelectorAll(" p"); var hitems = document.querySelectorAll(" h3"); var lhitems = document.querySelectorAll(" h2, .card"); function isElementInViewport(el) { var rect = el.getBoundingClientRect(); return ( rect.top >= -200 && rect.left >= -50 && rect.bottom <= (window.innerHeight+50 || document.documentElement.clientHeight) && rect.right <= (window.innerWidth || document.documentElement.clientWidth) ); } function callbackFunc() { for (var i = 0; i < items.length; i++) { // console.log(isElementInViewport(items[i])) if (isElementInViewport(items[i])) { if (!items[i].classList.contains("in-view")) { if (!items[i].classList.contains("description")) { items[i].classList.add("in-view"); items[i].classList.add("animate__animated"); items[i].classList.add("animate__fadeInUp"); items[i].classList.add("animate__slow"); } } } else if(items[i].classList.contains("in-view")) { items[i].classList.remove("in-view"); items[i].classList.remove("animate__animated"); items[i].classList.remove("animate__fadeInUp"); items[i].classList.remove("animate__slow"); } } for (var i = 0; i < hitems.length; i++) { // console.log(isElementInViewport(items[i])) if (isElementInViewport(hitems[i])) { if(!hitems[i].classList.contains("in-view")){ hitems[i].classList.add("in-view"); hitems[i].classList.add("animate__animated"); hitems[i].classList.add("animate__fadeInUp"); hitems[i].classList.add("animate__slow"); } } else if(hitems[i].classList.contains("in-view")) { hitems[i].classList.remove("in-view"); hitems[i].classList.remove("animate__animated"); hitems[i].classList.remove("animate__fadeInUp"); hitems[i].classList.remove("animate__slow"); } } for (var i = 0; i < lhitems.length; i++) { // console.log(isElementInViewport(items[i])) if (isElementInViewport(lhitems[i])) { if(!lhitems[i].classList.contains("in-view")){ lhitems[i].classList.add("in-view"); lhitems[i].classList.add("animate__animated"); lhitems[i].classList.add("animate__zoomIn"); lhitems[i].classList.add("animate__slow"); } } else if(lhitems[i].classList.contains("in-view")) { lhitems[i].classList.remove("in-view"); lhitems[i].classList.remove("animate__animated"); lhitems[i].classList.remove("animate__zoomIn"); lhitems[i].classList.remove("animate__slow"); } } } // console.log('It is working') // window.addEventListener("load", callbackFunc); window.addEventListener("scroll", callbackFunc); // var itemsi = document.querySelectorAll("div .card-img"); // function isElementInViewport(el) { // var rect = el.getBoundingClientRect(); // return ( // rect.top >= -200 && // rect.left >= -50 && // rect.bottom <= (window.innerHeight+200 || document.documentElement.clientHeight) && // rect.right <= (window.innerWidth || document.documentElement.clientWidth) // ); // } // function callbackFuncImg() { // for (var i = 0; i < itemsi.length; i++) { // // console.log(isElementInViewport(items[i])) // if (isElementInViewport(items[i])) { // if(!itemsi[i].classList.contains("in-view")){ // itemsi[i].classList.add("in-view"); // itemsi[i].classList.add("animate__animated"); // itemsi[i].classList.add("animate__rollIn"); // } // } else if(items[i].classList.contains("in-view")) { // itemsi[i].classList.remove("in-view"); // itemsi[i].classList.remove("animate__animated"); // itemsi[i].classList.remove("animate__rollIn"); // } // } // } // // console.log('It is working') // window.addEventListener("load", callbackFuncImg); // window.addEventListener("scroll", callbackFuncImg);
/* eslint-disable react/no-array-index-key */ import React from 'react'; import './index.scss'; import Computer from '../../Components/Computer'; const Buscar = () => { const [RAMFilter, setRAMFilter] = React.useState(['4GB', '8GB', '12GB', '16GB', '24GB', '32GB']); const [grafica, setGrafica] = React.useState(['RX5000', 'GTX1050', 'RTX2060', 'GTX1060 ti', 'RTX2080', 'Sin tarjeta']); const [procesador, setProcesador] = React.useState(['i7 9750H', 'I5 8300H', 'Threadripper 3990X']); const [almacenamiento, setAlmacenamiento] = React.useState([' 0 - 25GB', '25GB - 50GB', '50GB - 100GB', '100GB - 250GB', '250GB - 500GB', '500GB - 1TB']); const [computadores, setComputadores] = React.useState([{ img: `${process.env.PUBLIC_URL}/Images/Computers/Computer ${Math.floor(Math.random() * (3 - 1) + 1)}.png`, name: 'MSI GF75', procesador: 'Intel i7 9750H', procesadorSize: 24, video: 'Nvidia GTX 1060Ti', almacenamiento: 2000, id: 0 }, { img: `${process.env.PUBLIC_URL}/Images/Computers/Computer ${Math.floor(Math.random() * (3 - 1) + 1)}.png`, name: 'ACER AN515', procesador: 'Intel i7 9750H', procesadorSize: 1000, video: 'Nvidia GTX 1060Ti', almacenamiento: 128, id: 1 }, { img: `${process.env.PUBLIC_URL}/Images/Computers/Computer ${Math.floor(Math.random() * (3 - 1) + 1)}.png`, name: 'MSI GF75', procesador: 'Intel i7 9750H', procesadorSize: 24, video: 'Nvidia GTX 1060Ti', almacenamiento: 2000, id: 2 }, { img: `${process.env.PUBLIC_URL}/Images/Computers/Computer ${Math.floor(Math.random() * (3 - 1) + 1)}.png`, name: 'MSI GF75', procesador: 'Intel i7 9750H', procesadorSize: 24, video: 'Nvidia GTX 1060Ti', almacenamiento: 2000, id: 3 }, { img: `${process.env.PUBLIC_URL}/Images/Computers/Computer ${Math.floor(Math.random() * (3 - 1) + 1)}.png`, name: 'ACER AN515', procesador: 'Intel i7 9750H', procesadorSize: 1000, video: 'Nvidia GTX 1060Ti', almacenamiento: 128, id: 4 }, { img: `${process.env.PUBLIC_URL}/Images/Computers/Computer ${Math.floor(Math.random() * (3 - 1) + 1)}.png`, name: 'MSI GF75', procesador: 'Intel i7 9750H', procesadorSize: 24, video: 'Nvidia GTX 1060Ti', almacenamiento: 2000, id: 5 }]); return ( <main className="Buscar"> <article className="Buscar__wrapper"> <div className="Buscar__wrapper__header"> <h2>Encuentra tu equipo</h2> <p className="Buscar__wrapper__header-text">Busca entre las diferentes opciones que puedes encontrar usando el filtro, o navegando en la lista</p> </div> <div className="Buscar__wrapper__body"> {computadores.map((item) => ( <Computer key={item.id} img={item.img} name={item.name} procesador={item.procesador} video={item.video} almacenamiento={item.almacenamiento} /> ))} </div> </article> <article className="Buscar__filters"> <h2>Categorías</h2> <article className="Buscar__filters__wp"> <div className="Buscar__filters__wp-item"> <h3>RAM</h3> <div className="Buscar__filters__wp-item__content"> { RAMFilter.map((item, i) => ( <div className="Buscar__filters__wp-item__content__body" key={i}> <div className="Buscar__filters__wp-item__content__body__box" /> <div className="Buscar__filters__wp-item__content__body__text">{item}</div> </div> ))} </div> </div> <div className="Buscar__filters__wp-item"> <h3>Tarjeta Gráfica</h3> <div className="Buscar__filters__wp-item__content"> { grafica.map((item, i) => ( <div className="Buscar__filters__wp-item__content__body" key={i}> <div className="Buscar__filters__wp-item__content__body__box" /> <div className="Buscar__filters__wp-item__content__body__text">{item}</div> </div> ))} </div> </div> <div className="Buscar__filters__wp-item"> <h3>Procesador</h3> <div className="Buscar__filters__wp-item__content"> { procesador.map((item, i) => ( <div className="Buscar__filters__wp-item__content__body" key={i}> <div className="Buscar__filters__wp-item__content__body__box" /> <div className="Buscar__filters__wp-item__content__body__text">{item}</div> </div> ))} </div> </div> <div className="Buscar__filters__wp-item"> <h3>Almacenamiento</h3> <div className="Buscar__filters__wp-item__content"> { almacenamiento.map((item, i) => ( <div className="Buscar__filters__wp-item__content__body" key={i}> <div className="Buscar__filters__wp-item__content__body__box" /> <div className="Buscar__filters__wp-item__content__body__text">{item}</div> </div> ))} </div> </div> </article> </article> </main> ); }; export default Buscar;
const mongoose = require('mongoose') var d = new Date() const SubscriptionSchema = mongoose.Schema({ email: { type: String, required: true }, date_subscribed: { type: String, default: `${d.getDate()}-${d.getMonth()+1}-${d.getFullYear()}` } }) module.exports = mongoose.model('Subscription', SubscriptionSchema)
// npm install react-transition group --save import React from 'react'; import PropTypes from 'prop-types'; import {withStyles} from '@material-ui/core/styles'; import BlockCard from './BlockCard.js'; import Grow from '@material-ui/core/Grow'; import Fade from '@material-ui/core/Fade'; import Paper from '@material-ui/core/Paper'; import Card from '@material-ui/core/Card'; import CardContent from '@material-ui/core/CardContent'; import Typography from '@material-ui/core/Typography'; const head_style = { textAlign: 'center', marginTop:'5vh', marginBottom:'5vh' } const par_style={ textAlign:'left', marginRight:'30vw', marginLeft:'30vw', marginTop:'5vh', marginBottom:'5vh', } const par1 = "With the Bureau of Labor Statistics predicting a 24% increase in computer science related jobs over the next five years, there’s never been a better time to enter the tech industry. There’s only one problem: finding a job in tech is hard. Technology evolves at breakneck speeds, and with it the alphabet soup of technical skills, making it difficult to know just what you should learn to land your dream job." const par2 = "We aim to change the way you search for a job in the tech industry. With JobStats you have the power to see exactly what technical skills are in demand— right now. JobStats gathers data from Computer Science related job listings posted online, and then performs robust analysis on those listings to see exactly what technical skills are in demand. This way you can tell what skills you should focus on sharpening in order to maximize your chances of landing your dream job. Data is presented in the form of graphs, lists and maps, and is viewable by company, concentration, location, and more." const par3 = "We gather our data from American job listings found on popular job hunting sites." class AboutPage extends React.Component { constructor(props) { super(props); this.state = { reveal_header:true, reveal_text:false, reveal_contact:false, }; } componentDidMount() { setTimeout(function(){this.setState({reveal_text: true})}.bind(this), 1000); setTimeout(function(){this.setState({reveal_contact: true})}.bind(this), 2000); } render() { return ( <div> {this.state.reveal_header && <Fade in={true} timeout={1000}> <Typography style={head_style} variant="h1">- Our Mission -</Typography> </Fade> } {this.state.reveal_text && <div> <Fade in={true} timeout={1000}> <Typography style={par_style} variant="h5">{par1}</Typography> </Fade> <Fade in={true} timeout={1000}> <Typography style={par_style} variant="h5">{par2}</Typography> </Fade> <Fade in={true} timeout={1000}> <Typography style={par_style} variant="h5">{par3}</Typography> </Fade> </div> } {this.state.reveal_contact && <div> <Fade in={true} timeout={1000}> <Typography style={head_style} variant="h4">Questions?</Typography> </Fade> <Fade in={true} timeout={1000}> <Typography style={head_style} variant="h6"> <span> Contact us at contact@jobstats.net</span></Typography> </Fade> </div> } </div> ); } } // SimpleCard.propTypes = { // classes: PropTypes.object.isRequired, // }; // style={{ transformOrigin: '0 0 0' }} // {/* Conditionally applies the timeout property to change the entry speed. */} // <Fade // in={true} // {...(true ? { timeout: 1000 } : {})} // > // </Fade> // {setTimeout(this.renderFade,3000,"hello") // <Typography style={par_style} variant="h5">{par1}</Typography> // <Typography style={head_style} variant="h2">About</Typography> // <Typography style={par_style} variant="h5">{par2}</Typography> export default (AboutPage);
module.exports = function(cas, config) { if (config.env === 'development') { return function(req, res, next) { next() } } else if (config.env === 'production') { return cas.getMiddleware(config.cas) } }
import React, { useEffect } from 'react' import { LoadingIndicator, FTPConnected, NewsEditor } from '../../components' import { setFetchSuccess, setFTPConnectionInfo, setNews } from '../../../redux/actions' import { useSelector, useDispatch } from 'react-redux' import { fetch } from '../../../operations' import { API } from '../../../constants' export const ConnectionPanel = () => { const selectedCredentials = useSelector(state => state.selectedFTPCredentials.selectedFTPCredentials) const dispatch = useDispatch() const connectFTP = () => { dispatch(setFetchSuccess(false)) fetch(API.CONNECT, selectedCredentials).then((response) => { dispatch(setFTPConnectionInfo(response.data)) fetchNews() }).catch((error) => { console.log('ERROR CONNECTION FAILED', error) }) } const fetchNews = () => { fetch(API.DOWNLOAD_NEWS).then((response) => { dispatch(setNews(response.data)) dispatch(setFetchSuccess(true)) }).catch((error) => { console.log('ERROR FETCHING NEWS', error) dispatch(setFetchSuccess(true)) }) } useEffect(() => { connectFTP() }, []) return <div> <LoadingIndicator> <FTPConnected> <NewsEditor /> </FTPConnected> </LoadingIndicator> </div> }
var config = require('../config'); exports.staticFile = function (filePath) { if (filePath.indexOf('http') === 0 || filePath.indexOf('//') === 0) { return filePath; } return config.site_static_host + filePath; };
const animals = [ { "name": "cat", "size": "small", "weight": 5 }, { "name": "dog", "size": "small", "weight": 10 }, { "name": "lion", "size": "medium", "weight": 150 }, { "name": "elephant", "size": "big", "weight": 5000 }]; let animal_names=animals.map((animal)=>{ return animal.name; }) let weight=animals.reduce((weights,animal)=>{ return weights += animal.weight; },0); let weight1=animals.reduce((w1,w2)=>{ return w2.weight+w1; },0); console.log(weight1); // animals.reduce() console.log(animal_names); console.log(weight);
import fs from "fs"; import path from "path"; describe("index",() => { beforeEach(done => { loadTemplate("../../src/App/index.html", html => { document.body.innerHTML = html; done(); }); }); it("loads the markup", () => { expect(document.querySelector("h1")).not.toBeNull(); }); function loadTemplate(viewPath, onLoad){ const filePath = path.join(__dirname, viewPath); fs.readFile(filePath, {encoding: "utf-8"}, (error, data) => { if(!error) { onLoad(data); } else { console.log(error); } }); } });
printProcessMessages = function(theProcess) { theProcess.stdout.on('data', function (data) { console.log(data.toString()); }); theProcess.stderr.on('data', function (data) { console.log('ERROR: ' + data); }); }; var usingWindows = function() { return /^win/.test(process.platform); }; exports.spawn = function(processName, args) { var spawn = require('child_process').spawn; var childProcess; if (usingWindows()) { args = ["/c", processName].concat(args || []); processName = 'cmd'; } childProcess = spawn(processName, args); printProcessMessages(childProcess); return childProcess; };
const path = require('path'); const http = require('http'); const express = require('express'); const socketIO = require('socket.io'); const {generateMessage, generateLocationMessage} = require('./utils/message'); const {isRealString} = require('./utils/validation'); const {Users} = require('./utils/users'); const publicPath = path.join(__dirname, '../public'); const port = process.env.PORT || 3000; var app = express(); var server = http.createServer(app); var io = socketIO(server); var users = new Users(); app.use(express.static(publicPath)); io.on('connection', (socket) => { // ************************************************* // NOTES // // socket.emit emits an event to a single connection // io.emit emits an event to every single connection // // socket.broadcast.emit emits an event to every socket apart from itself // // When having specific rooms // io.to(room name).emit - sends an event to everybody connected to this room // socket.broadcast.to(room name).emit - sends an event to everbody in this room except for this current user // ************************************************* console.log('New user connected'); socket.on('join', (params, callback) => { if(!isRealString(params.name) || !isRealString(params.room)) { return callback('Name and room name are required'); }; // When a user joins, add them to the list socket.join(params.room); // user joins remove users.removeUser(socket.id); // we remove them from any other room users.addUser(socket.id, params.name, params.room); // we add them to the new room // send to everybody connected to this room io.to(params.room).emit('updateUserList', users.getUserList(params.room)); // send message back to single connection, your own socket.emit('newMessage', generateMessage('Admin', 'Welcome to the chat app')); // send message to everyone in this room apart from your self socket.broadcast.to(params.room).emit('newMessage', generateMessage('Admin', `${params.name} has joined`)); callback(); }); // Listen for events sent from the client socket.on('createMessage', (message, callback) => { var user = users.getUser(socket.id); if(user && isRealString(message.text)) { io.to(user.room).emit('newMessage', generateMessage(user.name, message.text)); } // acknowledge meant callback callback(); }); // Listen for events sent from the client socket.on('createLocationMessage', (coords, callback) => { var user = users.getUser(socket.id); if(user) { io.to(user.room).emit('newLocationMessage', generateLocationMessage(user.name, coords.latitude, coords.longitude)); } // acknowledge meant callback callback(); }); // When a user disconnects, remove them from the user list socket.on('disconnect', () => { var user = users.removeUser(socket.id); if(user) { io.to(user.room).emit('updateUserList', users.getUserList(user.room)); io.to(user.room).emit('newMessage', generateMessage('Admin', `${user.name} has left.`)); } console.log('User was disconnected'); }); }); server.listen(port, () => { console.log(`Server is up on port: ${port}`); });
import {Link} from 'react-router-dom' import './index.css' const Header = () => ( <> <nav className="header"> <img className="site-logo" src="https://assets.ccbp.in/frontend/react-js/nxt-trendz-logo-img.png" alt="website logo" /> <ul className="links-to-other"> <Link className="link" to="/"> <li>Home</li> </Link> <Link className="link" to="/products"> <li>Products</li> </Link> <Link className="link" to="/cart"> <li>Cart</li> </Link> <button type="button" className="button"> <li>Logout</li> </button> </ul> <Link className="sm-logout-button" to="/login"> <img className="nav-logout" src="https://assets.ccbp.in/frontend/react-js/nxt-trendz-log-out-img.png " alt="nav logout" /> </Link> </nav> <nav className="sm-nav-bar"> <Link className="link" to="/"> <img className="nav-logout" src="https://assets.ccbp.in/frontend/react-js/nxt-trendz-home-icon.png" alt="nav home" /> </Link> <Link className="link" to="/products"> <img className="nav-logout" src="https://assets.ccbp.in/frontend/react-js/nxt-trendz-products-icon.png" alt="nav products" /> </Link> <Link className="link" to="/cart"> <img className="nav-logout" src="https://assets.ccbp.in/frontend/react-js/nxt-trendz-cart-icon.png" alt="nav cart" /> </Link> </nav> </> ) export default Header
module.exports = { secret: "e-tracker-secret-key" };
// 0. array : 배열 // 배열 생성하기 // 1) new 명령어로 생성하기. let arr0 = new Array(); console.log("arr0 배열 크기 : " + arr0.length); //크기가 0인 배열 생성 let arr1 = new Array(5); console.log("arr1 배열 크기 : " + arr1.length); //크기가 5인 배열 let arr1_1 = new Array(1,2,3,"서동찬"); // 초기 생성시 값 지정 for (let index = 0; index < arr1_1.length; index++) { console.log("arr1_1의"+index+"번째 값 : "+ arr1_1[index]); } let arr2 = []; console.log("arr2 배열 크기 : " + arr2.length); let arr3 = [1,2,3,4]; console.log("arr3 배열 크기 : " + arr3.length); for (let index = 0; index < arr3.length; index++) { console.log("arr3의"+index+"번째 값 : "+ arr3[index]); } // 1. 배열 요소 추가하기 // push let arr4 = [1,2]; console.log(arr4); arr4.push(3); console.log(arr4); arr4.push("서동찬"); console.log(arr4); console.log(""); console.log(""); // 2. 배열 요소 제거 // pop let arr5 = [1,2,3]; let pop_value = arr5.pop(); console.log(pop_value); console.log(arr5); // 3. 배열 배열의 일부분을 선택하여 새로운 배열을 만들기 // slice() let arr6 = [1,2,3,4,5,6,7,"서동찬","김동찬"]; let arr6_1 = arr6.slice(2,8); console.log(arr6.slice(2,8)); // 4. 배열의 특정 값을 추출하고 새로운 값을 넣기 // splice() let arr7 = [1,2,3,4,5,6,7,"서동찬","김동찬"]; console.log(arr7.splice(2,4)); let arr7_1 = arr7.splice(2,4); console.log(arr7_1); arr7 = [1,2,3,4,5,6,7,"서동찬","김동찬"]; let arr7_2 = arr7.splice(2,4,'aaaa', 'bbb'); console.log(arr7); console.log(arr7_2); // filter : 콜백함수에 지정된 조건에 맞는 요소를 반환하여 새로운 배열를 만든다 let arr8 = [1,2,3,4,5,6,7,8,9]; let arr8_1 = arr8.filter( x => { return x > 3 } ); console.log(arr8_1); console.log(""); console.log(""); console.log(""); let arr9 = [1,2,3,4,5,6,7,"서동찬","김동찬"]; let arr9_1 = arr9.filter ( x => { return typeof(x) === 'string'; } ) console.log(arr9_1); console.log(""); console.log(""); console.log(""); // map let arr10 = [1,2,3,4,5,6,7,'서동찬']; let arr10_1 = arr10.map ( x => { if(typeof(x) === 'number'){ if(x%2 === 0){ return '짝수' }else{ return '홀수' } } /*else if(typeof(x) === 'string'){ return '문자열' }*/ } ) console.log(arr10_1);
import React from 'react'; import Api from '../api/api' import {connect} from 'react-redux'; import {UPDATE_PROBLEMS, RESET_EVENTS, SET_VISIBLE_CATEGORY, SET_VISIBLE_LEVEL, SET_HIDDEN_SOLVED} from '../data/store' import Router from 'react-router'; var Link = Router.Link; class Problems extends React.Component { constructor(props) { super(props); this.state = { searchBoxFocused: false, error: null }; } componentWillMount() { // Tap tap API server Api.problems((json) => { this.props.updateProblems(json); this.setState(); }, (mes) => { this.setState({ error: mes }); }) this.props.resetEvents(); } toggleSolvedVisibleState(e) { this.props.hideSolved(e.target.checked); } onSearchBoxFocus(e) { this.setState({ searchBoxFocused: true }) } onCategoryClick(e) { this.props.setVisibleCategory(e.target.getAttribute("data-id")); this.setState({ searchBoxFocused: false }) } onLevelClick(e) { this.props.setVisibleLevel(e.target.getAttribute("data-id")); this.setState({ searchBoxFocused: false }) } clearCatrgory() { this.props.setVisibleCategory(-1); this.setState({ searchBoxFocused: false }) } clearError() { this.setState({ error: null }); } render() { const colors = ["red", "orange", "yellow", "olive", "green", "teal", "blue", "violet", "purple", "pink", "brown", "gray"]; const {teaminfo, solvedTeams, problems, hiddenSolved, visibleCategory, visibleLevel} = this.props; var problem_status = {}; if (teaminfo.questions) { teaminfo.questions.forEach((problem) => { problem_status[problem.id] = problem; }) } var maxPoint = -1; var categories = {}; var cards = []; for (var id in problems) { var problem = problems[id]; var difficulty = []; for (var i = 0; i < problem["points"]; i+=100) { difficulty.push(<i className="lightning icon" key={i}></i>); } maxPoint = maxPoint > problem["points"] ? maxPoint : problem["points"]; categories[problem["category"]["name"]] = problem["category"]["id"]; if (visibleCategory >= 0 && visibleCategory != problem["category"]["id"]) { continue } else if (visibleLevel > 0 && ((visibleLevel * 100) < problem["points"] || ((visibleLevel - 1) * 100) >= problem["points"])) { continue } var solved; if (problem_status[problem["id"]]) { if (problem_status[problem["id"]].points == problem["points"]) { if (hiddenSolved) { continue } solved = <div><i className="large green checkmark icon"></i>Solved</div> } else { solved = <div>{Math.round(problem_status[problem["id"]].points / problem["points"] * 100)}% Solved</div> } } cards.push( <div className={"ui card " + (colors[problem["category"]["id"]] || "black")} key={problem["id"]}> <div className="content"> <Link className="header" to="problem" params={{id: problem["id"]}}>{problem["title"]}</Link> <div className="meta">{problem["category"]["name"]}</div> <div className="ui mini horizontal statistic"> <div className="value"> {problem["points"]} </div> <div className="label"> Points </div> </div> {solved} </div> <div className="content extra"> Difficulty: {difficulty} </div> <div className="content extra"> <i className="users icon"></i> {~~solvedTeams[problem.id]} teams solved </div> <div className="ui bottom attached rogress" data-percent="60"> <div className="bar"></div> </div> </div> ); } var searchInput = ""; var categoryList = [ <div className="result" key="-1" data-id="-1" onClick={this.onCategoryClick.bind(this)}> <div className="content" data-id="-1"> <div className="title" data-id="-1">All</div> </div> </div> ]; for (var key in categories) { categoryList.push( <div className="result" key={categories[key]} data-id={categories[key]} onClick={this.onCategoryClick.bind(this)}> <div className="content" data-id={categories[key]}> <div className="title" data-id={categories[key]}>{key}</div> </div> </div> ); if (visibleCategory == categories[key]) { searchInput = "Category: " + key; } } var levelList = [ <div className="result" key="-1" data-id="-1" onClick={this.onLevelClick.bind(this)}> <div className="content" data-id="-1"> <div className="title" data-id="-1">All</div> </div> </div> ]; for (var i = 100; i <= maxPoint; i += 100) { var difficulty = []; for (var j = 0; j < i; j += 100) { difficulty.push(<i className="lightning icon" key={j}></i>); } levelList.push( <div className="result" key={~~(i / 100)} data-id={~~(i / 100)} onClick={this.onLevelClick.bind(this)}> <div className="content" data-id={~~(i / 100)}> <div className="title" data-id={~~(i / 100)}>{difficulty}</div> </div> </div> ); if (visibleLevel == ~~(i / 100)) { searchInput = "Difficulty: " + ~~(i / 100); } } var errorMessage; if (this.state.error) { errorMessage = ( <div className="ui floating negative message"> <i className="close icon" onClick={this.clearError.bind(this)}></i> <div className="header"> Error </div> <p>{this.state.error[0]}</p> </div> ); } return ( <div className="ui container"> <div className="ui breadcrumb"> <span className="active section">Problems</span> </div> <div className="ui text menu"> <div className="ui item"> <div className="ui toggle checkbox"> <input type="checkbox" name="hide_solved" onChange={this.toggleSolvedVisibleState.bind(this)} checked={hiddenSolved}/> <label>Hide solved problems</label> </div> </div> <div className="ui right aligned category search item"> <div className="ui transparent icon input"> <input className="prompt" type="text" placeholder="Search problems..." onFocus={this.onSearchBoxFocus.bind(this)} value={searchInput}/> <i className={!searchInput ? "search link icon" : "close icon link"} onClick={this.clearCatrgory.bind(this)}></i> </div> <div className="results"></div> <div className={"results transition" + (this.state.searchBoxFocused ? " visible" : "")} > <div className="category"> <div className="name">Category</div> {categoryList} </div> <div className="category"> <div className="name">Level</div> {levelList} </div> </div> </div> </div> <div className="ui three cards"> {cards} </div> <div className="ui divider"> </div> {errorMessage} </div> ); } }; export default connect( (state) => ({ teaminfo: state.teamInfo, solvedTeams: state.solvedTeams, problems: state.problems, visibleCategory: state.visibleCategory, visibleLevel: state.visibleLevel, hiddenSolved: state.hiddenSolved }), (dispatch) => ({ updateProblems: (data) => dispatch({type: UPDATE_PROBLEMS, data: data}), resetEvents: () => dispatch({type: RESET_EVENTS, data: "problems"}), setVisibleCategory: (data) => dispatch({type: SET_VISIBLE_CATEGORY, data: data}), setVisibleLevel: (data) => dispatch({type: SET_VISIBLE_LEVEL, data: data}), hideSolved: (data) => dispatch({type: SET_HIDDEN_SOLVED, data: data}), }) )(Problems);
(function() { var httpRequest, ajaxText1 = document.querySelector('.modelName'), ajaxText2 = document.querySelector('.priceInfo'), ajaxText3 = document.querySelector('.modelDetails'), ajaxButton1 = document.querySelector('#newCar1'), ajaxButton2 = document.querySelector('#newCar2'), ajaxButton3 = document.querySelector('#newCar3'), function makeRequest1(url) { httpRequest = new XMLHttpRequest(); if (!httpRequest) { alert('Giving up, your browser is way too old'); return false; } httpRequest.onreadystatechange = showResult; httpRequest.open('GET', url); httpRequest.send(); } function makeRequest2(url) { httpRequest = new XMLHttpRequest(); if (!httpRequest) { alert('Giving up, your browser is way too old'); return false; } httpRequest.onreadystatechange = showResult; httpRequest.open('GET', url); httpRequest.send(); } function makeRequest3(url) { httpRequest = new XMLHttpRequest(); if (!httpRequest) { alert('Giving up, your browser is way too old'); return false; } httpRequest.onreadystatechange = showResult; httpRequest.open('GET', url); httpRequest.send(); } function showResult() { if (httpRequest.readyState === XMLHttpRequest.DONE) { if(httpRequest.status === 200) { var response = httpRequest.responseText; ajaxText.innerHTML = response; } else { console.log('There was a problem with your request'); } } } ajaxButton1.addEventListener('click', function() { makeRequest1('text.txt'); }, false); ajaxButton2.addEventListener('click', function() { makeRequest2('text.txt'); }, false); ajaxButton3.addEventListener('click', function() { makeRequest3('text.txt'); }, false); })();
module.exports = exports = function(app) { var swagger = require("swagger-node-express"), express = app.get("express"); swagger.setAppHandler(app); // Configures the app's base path and api version. swagger.configureSwaggerPaths("", "api-docs", ""); swagger.configure("http://localhost:"+ app.get("port"), "1.0.0"); var docs_handler = express.static(__dirname + '/lib/swagger_ui/'); app.get(/^\/docs(\/.*)?$/, function(req, res, next) { if (req.url === '/docs') { // express static barfs on root url w/o trailing slash res.writeHead(302, { 'Location' : req.url + '/' }); res.end(); return; } // take off leading /docs so that connect locates file correctly req.url = req.url.substr('/docs'.length); return docs_handler(req, res, next); }); };
/* * RefundPage Messages * * This contains all the text for the RefundPage component. */ import { defineMessages } from 'react-intl' export default defineMessages({ RefundAlertMessage: { id: 'RefundPage RefundAlertMessage', defaultMessage: '手动Refund' }, RefundAlertDescription: { id: 'RefundPage RefundAlertDescription', defaultMessage: '在解质押3天后,资产未到账时,可手动Refund取回资产。' }, OwnerPlaceholder: { id: 'RefundPage OwnerPlaceholder', defaultMessage: '请输入私钥对应的账户名' }, OwnerLabel: { id: 'RefundPage OwnerLabel', defaultMessage: '账户名' } })
/* * @Description: * @Author: yamanashi12 * @Date: 2019-05-10 10:18:19 * @LastEditTime: 2020-10-26 17:27:50 * @LastEditors: Please set LastEditors */ import validator from '@/utils/validator' export default { schema: { type: { // 组件类型 type: 'string', default: 'ImgUpload' }, label: { // 标签文本 type: 'string', default: '名称' }, key: 'string', value: 'any', size: { // 上传文件大小限制 type: 'number', default: 2048 }, fileType: { // 上传文件类型 type: 'array', default: ['jpg', 'png', 'jpeg'] }, maxNum: { // 最大上传数量 type: 'number', default: 5 }, uploadType: { // 上传模式: 0 单图模式 1 多图模式 type: 'number', default: 0 } }, rules: { key: [ { required: true, message: '请输入字段名', trigger: 'blur' }, validator.rule.keyCode ], label: [{ required: true, message: '请输入项目名称', trigger: 'blur' }], size: [{ type: 'number', required: true, message: '请输入限制大小', trigger: 'blur' }], fileType: [ { type: 'array', required: true, message: '请选择图片格式', trigger: 'blur' } ] } }
module.exports = fields => encodeURIComponent(JSON.stringify(fields));
import React from "react"; import { withScriptjs, withGoogleMap, GoogleMap } from "react-google-maps"; import NewMarker from "./Marker"; const NewMap = withScriptjs( withGoogleMap(props => { const markers = props.events.map(e => ( <NewMarker location={{ lat: e.latitudine, lng: e.longitudine }} name={e.titolo} id={e.id} date={e.inizio} /> )); return ( <GoogleMap defaultZoom={11} center={{ lat: 45.79377, lng: 10.27363 }}> {markers} </GoogleMap> ); }) ); export default NewMap;
/* version 001 */ define(function(){ return { cr8Inheritance: cr8Inheritance, addMethod: addMethod } /** * * @param cls * @param methodName * @param method * @return {Function} */ function addMethod (cls,methodName,method){ cls.prototype[methodName] = method function anotherMethod(methodName,method){ cls.prototype[methodName] = method return anotherMethod } return anotherMethod } /** * * @param superClass * @param subClass * @param args * @return {Function} */ function cr8Inheritance (superClass,subClass,args){ //http://phrogz.net/js/classes/OOPinJS2.html //http://www.andre-selmanagic.com/component/content/article/55-cross-browser-proto //http://stackoverflow.com/questions/650764/how-does-proto-differ-from-constructor-prototype //http://joost.zeekat.nl/constructors-considered-mildly-confusing.html // __proto__ does not work in IE function tmpFunc(){ } tmpFunc.prototype = superClass.prototype; subClass.prototype = new tmpFunc(); //subClass.prototype = new superClass(args) subClass.prototype.constructor = subClass subClass.prototype.applyBaseMethod = function(baseFncName,bApplyCalleeArgs){ var t = this, f = superClass.prototype[baseFncName] var calleeArgs if (bApplyCalleeArgs){ var i,ar = arguments.callee.caller.arguments calleeArgs = [] for(i=0;i<ar.length;i++){ calleeArgs.push(ar[i]) } return f.apply(t,calleeArgs); } return function(){ return f.apply(t,arguments); } } // can't use super in IE subClass.prototype.base = function(bApplyCalleeArgs){ var calleeArgs if (bApplyCalleeArgs){ var i,ar = arguments.callee.caller.arguments calleeArgs = [] for(i=0;i<ar.length;i++){ calleeArgs.push(ar[i]) } return superClass.apply(this,calleeArgs); } return function(){ return superClass.apply(t,arguments); } } addMethod.addMethod = addMethod addMethod.addMethod_retrieveBaseMethod = addMethod_retrieveBaseMethod return addMethod function addMethod(methodName,fn){ subClass.prototype[methodName] = fn; return addMethod } function addMethod_retrieveBaseMethod(methodName,fn){ subClass.prototype[methodName] = function(){ var t = this return fn(callBaseFunction,arguments) function callBaseFunction(){ return superClass.prototype[baseFncName].apply(t,arguments); } } return addMethod } } //} })
const ingredients = [ "Картошка", "Грибы", "Чеснок", "Помидоры", "Зелень", "Приправы", ]; const ulIngredientsEl = document.getElementById('ingredients'); const htmlMarkup = ingredients.map((elem) => { const liIngredient = document.createElement("li"); liIngredient.textContent = `${elem}`; //console.log(liIngredient); return liIngredient; }); console.log(...htmlMarkup) ulIngredientsEl.append(...htmlMarkup);
const AWS = require('aws-sdk') const uuid = require('uuid') const s3 = new AWS.S3({ signatureVersion: 'v4' }) module.exports.handler = async () => { const Key = `${uuid.v1()}.jpg` const url = s3.getSignedUrl('putObject', { Bucket: 'dog-finder-images', Key, Expires: 10 }) return Promise.resolve({ statusCode: 200, body: JSON.stringify({ url, imageLink: 'https://dog-finder-images.s3.amazonaws.com/' + Key }) }) }
import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; const useStyle = makeStyles(() => ({ text: { margin: ({ marginText }) => marginText, fontWeight: ({ weightText }) => weightText } })); const tuplesTag = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'span', 'label']; const Text = ({ tag = 'p', marginText, weightText, children }) => { const Component = tuplesTag.includes(tag) ? tag : 'p'; const classes = useStyle({ marginText, weightText }); return <Component data-testid='test-text' className={classes.text}>{children}</Component> }; export default Text
import CONFIG from "web.config"; import MasterPage from "components/website/master/MasterPage"; import { useRouter } from "next/router"; import Header from "components/website/elements/Header"; import { BS } from "components/diginext/elements/Splitters"; import Footer from "components/website/elements/Footer"; import { ListNews } from "components/website/pages/news/list-news/ListNews"; import asset from "plugins/assets/asset"; import { Row, Wrapper } from "components/website/pages/news/NewsElements"; import Link from "next/link"; import { useContext, useEffect, useState } from "react"; import { MainContent } from "components/website/contexts/MainContent"; import Axios from "axios"; import ReactHtmlParser from 'react-html-parser'; import { useNextResponsive } from "plugins/next-reponsive"; import Head from "next/head"; import { FacebookShareButton, FacebookIcon, } from "react-share"; export async function getServerSideProps(context) { const callAPI = async (url, callbackFn) => { let config = { headers: { "X-localization": "vi", }, }; await Axios.get(`${url}`, config) .then((response) => response.data) .catch((error) => console.log(error)); }; const params = context.params; const query = context.query; const slug = context.params.slug; let res1; let postDetail; let postDetailVn; // context.req.session, // context.res // console.log("query222",context.query); // console.log("params",context.params); // console.log("ress", context) // // console.log("SERVER CODE 1111"); let configEn = { headers: { "X-localization": "en", }, }; let configVi = { headers: { "X-localization": "vi", }, }; const res2 = await fetch( `https://api.lipovitan.zii.vn/api/v1/posts/${context.query.slug}`, configEn ); postDetail = await res2.json(); if( !postDetail.data || postDetail.data === null){ res1 = await fetch( `https://api.lipovitan.zii.vn/api/v1/posts/${context.query.slug}`, configVi ); postDetail = await res1.json(); } // console.log("POST",postDetail); // console.log("SERVER CODE 2222"); return { props: { params, query, slug, postDetail }, }; } export default function PasgeNews( props ) { const router = useRouter(); // if (typeof window == "undefined") { // console.log("datatat",postList) // console.log("This code is on server-side"); // } const valueLanguageContext = useContext(MainContent); const [dataDetail, setDataDetail] = useState(); const [idCategory, setDataCategory] = useState(); const [contentDetail, setContentDetail] = useState(); const [contentDetailHTML, setContentDetailHTML] = useState(); const callAPI = async (url, callbackFn) => { let config = { headers: { "X-localization": valueLanguageContext.languageCurrent, }, }; await Axios.get(`${url}`, config) .then((response) => callbackFn(response.data)) .catch((error) => console.log(error)); }; const HtmlComponent = (html) => { return <>{ReactHtmlParser(html)}</>; }; useEffect(() => { // console.log(router.query.slug); // console.log(CONFIG.getBaseURL()); // callAPI( // `https://api.lipovitan.zii.vn/api/v1/posts/${props.query.slug.toString()}`, // setDataDetail // ); setDataDetail(props.postDetail) }, []); useEffect(() => { // callAPI( // `https://api.lipovitan.zii.vn/api/v1/posts/${props.query.slug.toString()}`, // setDataDetail // ); setDataDetail(props.postDetail) // console.log("da12222",dataDetail) },[router.query.slug]); useEffect(() => { if (dataDetail) { setDataCategory(dataDetail.data.postCategory.id); if (valueLanguageContext.languageCurrent === "en") { setContentDetail(dataDetail.data.content.en); } else { setContentDetail(dataDetail.data.content.vi); } console.log("da12222",dataDetail) } }, [dataDetail]); useEffect(() => { console.log( router.asPath); }, [idCategory]); useEffect(() => { setContentDetailHTML(HtmlComponent(contentDetail)) }, [contentDetail, valueLanguageContext]); const contentData = (language) => { switch (language) { case language === "vi": return ( <> <div> <h5> <span> <Link href="/">Homepage</Link> </span> <span> <Link href={"/news"}>news</Link> </span> <span> <Link href="">{dataDetail.data.slug.vi || ""}</Link> </span> </h5> <h3>{dataDetail.data.title.vi}</h3> <div className={"tag"}> <span className={"date"}>{dataDetail.data.createdAt.vi}</span> {dataDetail.data.active.vi ? ( <span className={"status"}>active</span> ) : ( <></> )} </div> <p className="introduce">{dataDetail.data.shortDescription.vi}</p> <img src={ dataDetail.data.image.iv || asset("/images/news-detail-demo.png") } /> <div className="content"> {contentDetailHTML ? contentDetailHTML : <p>None content</p>} {/* <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras sodales mi vel nisi suscipit maximus. Quisque ultricies quam vitae urna pretium, eu aliquet dolor accumsan. Donec scelerisque nisi commodo, elementum metus sed, tristique ante. Praesent urna ipsum, iaculis et tincidunt in, mattis eget sapien. Etiam tempus augue eget augue ornare aliquam. Integer id sagittis enim. Nam orci leo, facilisis in porta et, faucibus vitae lacus. Donec non est non tortor convallis posuere eu at justo. Sed venenatis, risus et facilisis tempor, nibh libero ultricies ligula, eget mollis felis nibh non diam. Pellentesque pulvinar, libero non blandit condimentum, quam sapien laoreet sapien, a luctus massa turpis vel enim. Nullam eu scelerisque odio. Phasellus fringilla turpis sit amet arcu porta, non vulputate libero mollis. Maecenas non nibh sed lorem tristique rhoncus. Donec risus ante, tincidunt vel condimentum placerat, egestas sed orci. Ut pharetra quam vel facilisis convallis. </p> */} </div> <div className="share"> <p>Chia sẻ bài viết</p> <Link href=""> <img src={asset("/images/icon-fb-blue.png")} /> </Link> <Link href=""> <img src={asset("/images/icon-google-blue.png")} /> </Link> </div> </div> </> ); default: break; } }; let responsive = useNextResponsive(); const LayoutDesktop = { background: `url(${asset( "/images/news/bg_top.jpg" )}) no-repeat center top/100% auto #F3F3F3`, "padding-top": "120px", }; const LayoutMobile = { background: `url(${asset( "/images/mb/news/banner.jpg" )}) no-repeat center top/100% auto #F3F3F3`, "padding-top": "80px", }; const [layout, setLayout] = useState(LayoutDesktop); useEffect(() => { switch (responsive.device) { case "mobile": setLayout(LayoutMobile); break; default: setLayout(LayoutDesktop); break; } }, [JSON.stringify(responsive)]); return ( <> <MasterPage // pageName={dataDetail ? props.query.slug : "news"} noneHead={true} > <Head> <title> {"Lipovitan | News"} </title> <meta name="description" content={ props.postDetail.data.metaDescription[`${valueLanguageContext.languageCurrent}`]} /> <meta name="keywords" content={ props.postDetail.data.metaKeyword[`${valueLanguageContext.languageCurrent}`] } /> <meta name="author" content="Lipovitan" /> <link rel="shortcut icon" href={`${CONFIG.getBasePath()}/favicon.ico`} /> <meta property="og:title" content={ props.postDetail.data.title[`${valueLanguageContext.languageCurrent}`] } /> <meta property="og:description" content={ props.postDetail.data.metaDescription[`${valueLanguageContext.languageCurrent}`] } /> <meta property="og:url" content={""} /> <meta property="og:image" content={props.postDetail.data.image} /> <meta property="og:image:width" content="1200" /> <meta property="og:image:height" content="630" /> <meta property="fb:app_id" content={CONFIG.NEXT_PUBLIC_FB_APP_ID} /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0"></meta> </Head> <Header hideButtons></Header> <main id="newsDetailPage" style={layout}> <Wrapper> <Row> {dataDetail ? ( <div> <h5> <span> <i> <Link href="/"> { valueLanguageContext.languageCurrent === "en" ? "Homepage" : "Trang chủ" } </Link> </i> </span> <span> <i> <Link href={"/news"}> { valueLanguageContext.languageCurrent === "en" ? "new" : "Tin tức" } </Link> </i> </span> <span> <i> <a> { valueLanguageContext.languageCurrent === "en" ? dataDetail.data.slug.en : dataDetail.data.slug.vi } </a> </i> </span> </h5> <h3> <i> {valueLanguageContext.languageCurrent === "en" ? dataDetail.data.title.en : dataDetail.data.title.vi} </i> </h3> <div className={"tag"}> <p className={"date"}> <span><i>{dataDetail.data.createdAt}</i></span> </p> {dataDetail.data.active ? ( <p className={"status"}> <span> <i> { valueLanguageContext.languageCurrent === "en" ? "Activities" : "Hoạt động" } </i> </span> </p> ) : ( <></> )} </div> <p className="introduce"> { valueLanguageContext.languageCurrent === "en" ? dataDetail.data.shortDescription.en : dataDetail.data.shortDescription.vi } </p> <div className="img"> <img src={ dataDetail.data.image }/> </div> <div className="content"> {contentDetail ? ( <> {HtmlComponent(contentDetail)} </> ) : ( <p>Loading...</p> )} {/* <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras sodales mi vel nisi suscipit maximus. Quisque ultricies quam vitae urna pretium, eu aliquet dolor accumsan. Donec scelerisque nisi commodo, elementum metus sed, tristique ante. Praesent urna ipsum, iaculis et tincidunt in, mattis eget sapien. Etiam tempus augue eget augue ornare aliquam. Integer id sagittis enim. Nam orci leo, facilisis in porta et, faucibus vitae lacus. Donec non est non tortor convallis posuere eu at justo. Sed venenatis, risus et facilisis tempor, nibh libero ultricies ligula, eget mollis felis nibh non diam. Pellentesque pulvinar, libero non blandit condimentum, quam sapien laoreet sapien, a luctus massa turpis vel enim. Nullam eu scelerisque odio. Phasellus fringilla turpis sit amet arcu porta, non vulputate libero mollis. Maecenas non nibh sed lorem tristique rhoncus. Donec risus ante, tincidunt vel condimentum placerat, egestas sed orci. Ut pharetra quam vel facilisis convallis. </p> */} </div> <div className="share"> <p> <i> { valueLanguageContext.languageCurrent === "en" ? "Share post" : "Chia sẻ bài viết" } </i> </p> <span style={{position:"relative"}}> <img src={asset("/images/icon-fb-blue.png")} /> <div className={"contentFB"}> <FacebookShareButton url={ dataDetail ? `${CONFIG.getBaseURL()}${router.asPath}` : ""} > <FacebookIcon size={32} round={true}></FacebookIcon> </FacebookShareButton> </div> </span> <span style={{position:"relative", display:"none"}}> <img src={asset("/images/icon-google-blue.png")} /> <div className={"contentFB"}> <FacebookShareButton url={ dataDetail ? `${CONFIG.getBaseURL()}/${router.asPath}` : ""} > <FacebookIcon size={32} round={true}></FacebookIcon> </FacebookShareButton> </div> </span> </div> </div> ) : ( <> <p>Loading...</p> </> )} </Row> <Row> { idCategory ? ( <ListNews title={valueLanguageContext.languageCurrent === "en" ? "OTHER NEWS" : "Tin tức khác"} color="#004FC4" linkData={`https://api.lipovitan.zii.vn/api/v1/posts?postCategory=${idCategory}&limit=3`} ></ListNews> ) : ( <span>Loading...</span> )} </Row> </Wrapper> <img src={asset("/images/news/bg_bottom.jpg")} className={"bgBottom"} /> </main> <Footer></Footer> </MasterPage> <style jsx>{` .contentFB{ position:absolute; top: 0; left: 0; width:100%; height:100%; opacity:0; display: flex; align-items: center; } .share { display: flex; justify-content: flex-start; align-items: center; p { font-family: Montserrat-BoldItalic; font-size: 16px; color: #757575; padding-right: 15px; } img{ width: 100%; margin: 25px 0; max-width: 32px; } } .img{ width: 100%; height: 60vh; padding-bottom: 20px; img{ object-fit: cover; height: 100%; } } img { width: 100%; margin: 25px 0; } .content { p { margin: 20px 0; } } .introduce { color: #fff; padding: 10px 0; } .tag { display: flex; flex-direction: row; justify-content: flex-start; p { text-align: center; padding: 8px 10px; margin: 15px; margin-left: 0; text-transform: uppercase; position: relative; font-size: 12px; font-family: Montserrat-BoldItalic; span { display: block; position: relative; z-index: 2; } &:after { content: ""; width: 100%; height: 100%; position: absolute; top: 0; left: 0; transform: skewX(-5deg); } } .date { color: #757575; display: flex; &:after { background-color: #e2e2e2; } } .status { color: #fff; &:after { background-color: #03ac6e; } } } h3 { font-size: 36px; color: #fff; font-family: Montserrat-BoldItalic; text-transform: uppercase; padding: 10px 0; } h5 { padding: 10px 0; span { font-size: 12px; font-family: Montserrat-BoldItalic; text-transform: uppercase; margin: 25px; margin-left: 0; padding-right: 15px; position: relative; a { color: #fff; } } span::after { content: ""; position: absolute; width: 6px; height: 7px; top: 50%; left: 100%; transform: translate(0, -50%); background-image: url(${asset( "/images/icon-arrow-next-white.png" )}); background-size: 100%; background-position: center; } span:last-child { color: #ffe600; } span:last-child::after { display: none; } } #newsDetailPage { position: relative; } .bgBottom { position: absolute; width: 100%; bottom: 0; left: 0; margin: 0; } @media screen and (max-width: 768px) { h3 { font-size: 3vmax; } .introduce{ padding-bottom: 20px; } p { font-size: 1.7vmax; } img { margin:0 0 20px 0; } .content { font-size: 2vmax; margin-bottom: 20px; p { font-size: 2vmax; } } h5 { span { font-size: 10px; padding-right: 10px; margin-right: 15px; a { color: #fff; } } } } `}</style> </> ); }
/** * Created by stijn on 05-Jun-17. */ document.addEventListener('DOMContentLoaded',function () { // Ready to interact with the DOM const primarySelector = document.getElementById('primary-theme-color'); const secondarySelector = document.getElementById('secondary-theme-color'); updateSelectors(primarySelector,secondarySelector); primarySelector.addEventListener('input',updateTheme,false); secondarySelector.addEventListener('input',updateTheme,false); },false); function updateSelectors(primaryInput,secondaryInput) { //Code from stpe 9 to select variables const rootE1=getComputedStyle(document.documentElement); const primaryThemeColor = rootE1.getPropertyValue('--theme-primary').trim(); const secondaryThemeColor = rootE1.getPropertyValue('--theme-secondary').trim(); primaryInput.value = primaryThemeColor; secondaryInput.value = secondaryThemeColor; } function updateTheme() { const inputName = this.getAttribute('name'); const newColor = this.value; document.documentElement.style.setProperty('--theme-'+inputName, newColor); if (inputName === 'primary') { const textColor = getContrastYIQ(newColor); document.documentElement.style.setProperty('--theme-text', textColor); } } function getContrastYIQ(hexcolor) { const color = hexcolor.substring(1); console.log(color); const r = parseInt(color.substr(0,2),16); console.log(r); const g = parseInt(color.substr(2,2),16); console.log(g); const b = parseInt(color.substr(4,2),16); console.log(b); const yiq = ((r*299)+(g*587)+(b*114))/1000; return (yiq >= 128)?'#000000':'#ffffff'; }
function workerFn () { let ctx = null function setCanvas (canvas) { ctx = canvas.getContext('2d') } function clearCanvas () { ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height) ctx.canvas.width = 1 ctx.canvas.height = 1 } function putImageData (imageData, x, y) { let resizeOpts = {} if ((x + imageData.width) > ctx.canvas.width) { resizeOpts.width = x + imageData.width } if ((y + imageData.height) > ctx.canvas.height) { resizeOpts.height = y + imageData.height } if (Object.keys(resizeOpts).length > 0) { resize(resizeOpts) } ctx.putImageData(imageData, x, y) } function resize (opts = {}) { const imageData = ctx.getImageData( 0, 0, ctx.canvas.width, ctx.canvas.height) for (let dimension of Object.keys(opts)) { ctx.canvas[dimension] = opts[dimension] } ctx.putImageData(imageData, 0, 0) } self.addEventListener('message', (evt) => { // eslint-disable-line const { type, payload, key } = evt.data let result if (type === 'clearCanvas') { clearCanvas() } else if (type === 'setCanvas') { setCanvas(payload.canvas) } else if (type === 'putImageData') { putImageData(payload.imageData, payload.x, payload.y) } else if (type === 'getImageBitmap') { result = ctx.canvas.transferToImageBitmap() } self.postMessage({type, key, status: 'FULFILLED', result}) // eslint-disable-line }) } const workerBlob = new Blob( [workerFn.toString().replace(/^function .+\{?|\}$/g, '')], { type:'text/javascript' } ) const workerBlobUrl = URL.createObjectURL(workerBlob) export function workerFactory () { return new Worker(workerBlobUrl) }