text
stringlengths
7
3.69M
let bumpMapTextureFragmentShader = `precision highp float; varying vec2 fTextureCoordinate; varying vec3 fPos; varying vec3 fLight; uniform mat4 normalMatrix; uniform sampler2D textureSampler; uniform sampler2D bumpMapSampler; uniform sampler2D specularMapSampler; vec2 BlinnPhongShading(vec3 surfaceNormal, float intensity, float ambientColor, float diffuseConstant, float specularConstant, float specularExp); void main() { vec4 textureColor = texture2D(textureSampler, fTextureCoordinate); vec4 specularDetails = texture2D(specularMapSampler, fTextureCoordinate); vec3 normal = normalize(((texture2D(bumpMapSampler, fTextureCoordinate).rgb) * 2.0) - 1.0); float ambientColor = 0.1; float specularConstant = 2.0; float diffuseConstant = 0.1; float specularExp = specularDetails.a; float intensity = 1.0; vec2 lightingModifiers = BlinnPhongShading(normal, intensity, ambientColor, diffuseConstant, specularConstant, specularExp); gl_FragColor = vec4((lightingModifiers.x * textureColor.rgb) + (specularDetails.rgb * lightingModifiers.y), 1.0); } vec2 BlinnPhongShading(vec3 surfaceNormal, float intensity, float ambientColor, float diffuseConstant, float specularConstant, float specularExp) { vec3 eye = normalize(-fPos); vec3 lightVector = normalize(fLight); vec3 normal = normalize(surfaceNormal); vec3 halfVec = normalize((eye + lightVector) / length(eye + lightVector)); float ambientComponent = intensity * ambientColor; float diffuseComponent = max(0.0, dot(lightVector, normal)) * intensity * diffuseConstant; float specularComponent = pow(max(0.0, dot(halfVec, normal)), specularExp) * intensity * specularConstant; return vec2(diffuseComponent + ambientComponent, specularComponent); }`
const VuetifyLoaderPlugin = require('vuetify-loader/lib/plugin'); module.exports = { css: { loaderOptions: { sass: { data: ` @import "@/styles/base/_setting.scss"; @import "@/styles/base/_function.scss"; ` } } }, configureWebpack: { plugins: [new VuetifyLoaderPlugin()] }, productionSourceMap: false };
import React from "react"; import classes from "./MyCv.css"; const MyCv = () =>{ return <main className={classes.CV}> <img src="randomkemoboi.jpg" className={classes.profilePhoto} alt="My profile photo failed to load"/> <h2 >Personal Profile Statement</h2> <hr/> <p>An adaptable, calm and result-oriented software engineering graduate, seeking a position where one can develop and utilize technical skills derived from full-stack development. Has an analytical, observant and attentive approach to work. Enthusiastic about new technologies regarding front-end development, AI, cryptography. Displays excellent problem solving skills</p>, <h2>Education</h2> <hr/> <ul> <li>2016-2019(Expected) Izmir Economy University - Software Engineering Bsc</li> <li>2012-2016 Adem Tolunay Anatolian High School</li> </ul> <h2>Experience</h2> <hr/> <ul> <li>Ascenix (internship) January 2019-August 2019></li> </ul> <h2> Technical Skills</h2> <hr/> <ul> <li>Proficient in Javascript(ES6&^ standard), Java programming languages</li> <li>Proficient in technologies like HTML5, CSS(Preferably with modules but can work with SASS or SCSS), React, Redux, Node.js, Gulp, and some J2EE></li> <li>Experienced in database technologies MySql server and MongoDB</li> </ul> <h2>Language Skills</h2> <hr/> <ul> <li>Turkish (Native)</li> <li>English (Proficient C1 / planning to enter to IELTS can rush it on request)</li> <li>Japanese (Level 2 / can't really hold a conversation, still studying)</li> </ul> <h2>Hobbies & Interests</h2> <hr/> <ul> <li>Computer Hardware</li> <li>Gaming</li> <li>Japanese subculture (Anime, manga, light novels---believe me there is more to it than you know)</li> <li>Crypto Currencies</li> <li>Blogging... I guess?</li> </ul> <h2>References</h2> <hr/> <p>Available upon request</p> </main> ; }; export default MyCv;
const initialState = { firstName: '', lastName: '', email: '', createUsername: '', createPassword: '', redirect: '', showSignup: false, image: '', userList: [] } export default function reducer (state = initialState, action) { let tempState = state switch (action.type) { case 'SET_FIRSTNAME': return { ...tempState, firstName: action.payload } case 'SET_LASTNAME': return { ...tempState, lastName: action.payload } case 'SET_EMAIL': return { ...tempState, email: action.payload } case 'SET_CREATE_USERNAME': return { ...tempState, createUsername: action.payload } case 'SET_CREATE_PASSWORD': return { ...tempState, createPassword: action.payload } case 'SET_REDIRECT': return { ...tempState, redirect: action.payload } case 'SHOW_SIGNUP': return { ...tempState, showSignup: action.payload } case 'SET_IMAGE': return { ...tempState, image: action.payload } case 'SET_USER_LIST': return { ...tempState, userList: action.payload } } return tempState }
import ZWayAPI from '../zway/api' const api = new ZWayAPI() export default class DeviceActions { typeCommands = { // 'switchMultilevel', // 'switchBinary', // 'switchRGBW', // 'doorlock', // 'doorLockControl', // 'toggleButton', // 'sensorMultilevel', // 'sensorBinary', // 'sensorDiscrete', // 'thermostat', // 'camera', // 'text', // 'switchControl', // 'sensorMultiline', // 'audioPlayer', // 'poppKeypad' } // constructor() { // // } setDeviceValue(device, variant) { switch (device.deviceType) { case 'switchBinary': this.switchDevice(device.id, variant.value) break } } updateDevice = id => { api.runDataCommand(id, 'update').then(resp => { console.log(resp) }) } switchDevice = (id, state) => api.runDeviceCommand(id, state === true ? 'on' : 'off') }
_.contains = function(value,arg){ return value.indexOf(arg) !== -1; } _.include = _.contains
import React, { useEffect, useRef, useState } from 'react'; import { connect } from 'react-redux'; // import MenuNavbar from '../../components/MenuNavbar/index'; import { Col, Container, Row } from "react-bootstrap"; import Toast from '../../helpers/toast'; import { Form, Input, Button, Card, Radio, Select, Cascader, DatePicker, InputNumber, TreeSelect, Switch, Steps, Typography, } from 'antd'; import { SideNavbar, Navbar } from '../../components/Menu/'; import '../../assets/css/home.css'; import JoditEditor from 'jodit-react'; // import {Card, Form, Input, Steps, TreeSelect} from 'antd'; import Footer from '../../components/Footer'; import * as regusterQuestionsActions from '../../actions/registerQuestions.actions'; import * as bankActions from "../../actions/bank.actions"; import * as institutionActions from "../../actions/institution.actions"; import * as officeActions from "../../actions/office.actions"; import * as diciplineActions from "../../actions/dicipline.actions"; import { yearData } from "../../services/filter/dataSelect"; import { formatDefault, formataDicipline, formataOffice, formatDefaultRegister } from "../../helpers/formatDataToQuery"; import Pagination from "../../components/Pagination"; import registerQuestion from "../../reducers/registeQuestions.reducer"; import Alternative from "../../components/Alternative"; const { Title } = Typography; const answerStyleBox = { float: 'left', height: '150px', }; const ABCDStyle = { float: 'left', marginLeft: '20px', marginTop: '-24px', }; const answerStyle = { marginTop: '5px', }; const { SHOW_PARENT, SHOW_ALL } = TreeSelect; // TODO: Retirar o menu desse componenete e criar um menu para toda a apalicacao const RegisterQuestions = (props) => { const { Step } = Steps; const { getBank, getInstitution, getOffice, getDicipline, // uploadFile, loadingBank, store, bank, loadingInstitution, institution, loadingOffice, office, loadingDicipline, dicipline, qtdUploadQuestions, questions, loadingUpload, loadingRegister } = props const ABCD = ["A", "B", "C", "D"] const editor = useRef(null); const [questionInfo, setQuestionInfo] = useState([]); const [indexQuestion, setIndexQuestion] = useState(0); // general info // const [office, setOffice] = useState(); const [bankValue, setBankValue] = useState([]); const [institutionValue, setInstitutionValue] = useState([]); const [officeValue, setOfficeValue] = useState([]); const [yearValue, setYearValue] = useState([]); // const [diciplineValue, setDiciplineValue] = useState([]); // questions info const [issueResolution, setIssueResolution] = useState(); const [enunciated, setEnunciated] = useState(); const [alternativeA, setAlternativeA] = useState(); const [alternativeB, setAlternativeB] = useState(); const [alternativeC, setAlternativeC] = useState(); const [alternativeD, setAlternativeD] = useState(); const [radioData, setRadioData] = useState([ { radioName: 'radioA', selected: false }, { radioName: 'radioB', selected: false }, { radioName: 'radioC', selected: false }, { radioName: 'radioD', selected: false }, ]) const [toggle, setToggle] = useState(false); // mudar o stado do side bar const [file, setFile] = useState(''); // storing the uploaded file const [progress, setProgess] = useState(0); // progess bar const el = useRef(); // accesing input element useEffect(() => { getBank(); getInstitution(); getOffice(); getDicipline(); }, [getBank, getInstitution, getOffice, getDicipline]); // useEffect(() => { // if(questions.length !== 0) { // setEnunciated(questions[0][0]) // setAlternativeA(questions[0][1]) // setAlternativeB(questions[0][2]) // setAlternativeC(questions[0][3]) // setAlternativeD(questions[0][4]) // } // }, [questions]); const changeRadio = ({ target }) => { const newRadioData = radioData.map((radio) => { const checked = radio.radioName === target.value; return { ...radio, selected: checked } }) setRadioData(newRadioData) } const handleChangeFile = (e) => { setProgess(0) const file = e.target.files[0]; // accesing file console.log(file); setFile(file); // storing file } function renderQuestion(question, index) { setIndexQuestion(index) setEnunciated(question[0]) setAlternativeA(question[1]) setAlternativeB(question[2]) setAlternativeC(question[3]) setAlternativeD(question[4]) setQuestionInfo(question) } function handleSubmit(values) { // values.preventDefault() const idBank = formatDefaultRegister(bankValue, bank); const idInstitution = formatDefaultRegister(institutionValue, institution); const yearArray = formatDefault(yearValue, yearData); const year = yearArray[0] //TODO: finish catch value discipline and office console.log(officeValue) // const idOffice = formataOffice(officeValue, office); const idOffice = '0-0'; const idDicipline = '0-1'; const nameAlternative = [ alternativeA, alternativeB, alternativeC, alternativeD ] const answer = radioData.map((radio) => { return radio.selected }) const data = { // general info idBank, idInstitution, idOffice, year, idDicipline, // questions info issueResolution, enunciated, nameAlternative, answer } store(data) } const uploadFileFunction = () => { const formData = new FormData() formData.append('file', file) props.uploadFile(formData) } return ( <> <div className="B2M-page"> <Navbar toggle={toggle} onToggle={(e) => setToggle(e)} /> {/* MAIN NAVBAR */} <div className="B2M-page-content"> <SideNavbar toggle={toggle} type="RegisterQuestions" /> {/* SIDEBAR */} {/* Page Header */} <div className={`B2M-content-inner side-navbar-active ${toggle ? 'active' : ''}`}> <header className="B2M-page-header"> <h2>Registro de questões</h2> </header> {/* Breadcrumb */} <div className="breadcrumb-holder container-fluid B2M-bg"> <ul className="B2M-breadcrumb"> <li className="breadcrumb-item"><a href="/">Home</a></li> <li className="breadcrumb-item active B2M-text-color-primary">Registro de questões</li> </ul> </div> <Container className="filter-conatiner" > <Row > <span className="filter-titer mx-1 ml-2">Upload da prova:</span> </Row > <div className="file-upload"> <input type="file" ref={el} onChange={handleChangeFile} /> <div className="progessBar" style={{ width: progress }}> {progress} </div> <Button onClick={uploadFileFunction} disabled={loadingUpload} className="filter-btn"> {!loadingUpload ? <>Fazer upload </> : <>Processando... </>} </Button> </div> <hr /> <Form layout="vertical" requiredMark={false} onFinish={handleSubmit}> <div id="generalInfo"> <Row > {/*<Col className="mt-3" xs={6} md={6}>*/} <Col className="mt-3" xs={6} md={6}> <Form.Item name="year" label="Ano da prova" > <TreeSelect treeData={yearData} value={yearValue} maxLength={4} onChange={(value) => { setYearValue(value) }} placeholder="Ano..." className="filter-field" showCheckedStrategy={SHOW_PARENT} maxTagCount='responsive' showSearch treeNodeFilterProp='title' allowClear loading={!yearData} /> </Form.Item> </Col> <Col className="mt-3" xs={6} md={6}> <Form.Item name="bank" label="Banca" > <TreeSelect treeData={bank} value={bankValue} onChange={(value) => { setBankValue(value) }} placeholder="Banca..." className="filter-field" showCheckedStrategy={SHOW_PARENT} maxTagCount='responsive' allowClear showSearch treeNodeFilterProp='title' loading={loadingBank} /> </Form.Item> {/*</Col>*/} </Col> </Row> <Row > <Col className="mt-3" xs={6} md={6}> <Form.Item name="office" label="Cargo" > <TreeSelect showSearch treeData={office} value={officeValue} allowClear onChange={(value) => { setOfficeValue(value) }} placeholder="Cargo..." className="filter-field" showCheckedStrategy={SHOW_ALL} maxTagCount='responsive' treeNodeFilterProp='title' loading={loadingOffice} /> </Form.Item> </Col> <Col className="mt-3" xs={6} md={6}> <Form.Item name="institution" label="Orgão" > <TreeSelect treeData={institution} value={institutionValue} onChange={(value) => { setInstitutionValue(value) }} placeholder="Orgão..." className="filter-field" showCheckedStrategy={SHOW_PARENT} maxTagCount='responsive' showSearch treeNodeFilterProp='title' allowClear loading={loadingInstitution} /> </Form.Item> </Col> </Row> <Row style={{ marginBottom: '50px' }} > <Col className="mt-3" xs={12} md={12}> <Card type="inner" > {questions && questions.map((data, index) => <Button onClick={() => renderQuestion(data, index + 1)}>Questão {index + 1}</Button> )} </Card> </Col> </Row> {questionInfo.length !== 0 && ( <Card type="inner" title={`Questão ${indexQuestion}`} > {/* <Col className="mt-3" xs={6} md={6}> <Form.Item name="institution" label="Orgão" > <TreeSelect treeData={institution} value={institutionValue} onChange={(value) => { setInstitutionValue(value) }} placeholder="Orgão..." className="filter-field" showCheckedStrategy={SHOW_PARENT} maxTagCount='responsive' showSearch treeNodeFilterProp='title' allowClear loading={loadingInstitution} /> </Form.Item> </Col> */} {/* <Col className="mt-3" xs={6} md={6}> <Form.Item name="dicipline" label="Matéria & Assunto" > <TreeSelect treeDataSimpleMode treeData={dicipline} value={diciplineValue} onChange={(value) => { setDiciplineValue(value) }} placeholder="Matéria & Assunto..." className="filter-field" showCheckedStrategy={SHOW_PARENT} maxTagCount='responsive' showSearch allowClear loading={loadingDicipline} /> </Form.Item> </Col> */} <Card type="inner" title={`Estrutura`} > <Row > <Title level={3}>Enunciado</Title> <Col xs={12} md={12}> <JoditEditor ref={editor} value={enunciated} // config={config} tabIndex={0} onBlur={(newContent) => setEnunciated(newContent)} onChange={() => { }} /> </Col> </Row> <Row > <Title level={3}>Alternativa A</Title> <Col xs={12} md={12}> <JoditEditor ref={editor} value={alternativeA} // config={config} tabIndex={0} onBlur={(newContent) => setAlternativeA(newContent)} onChange={() => { }} /> </Col> </Row> <Row> <Title level={3}>Alternativa B</Title> <Col xs={12} md={12}> <JoditEditor ref={editor} value={alternativeB} // config={config} tabIndex={0} onBlur={(newContent) => setAlternativeB(newContent)} onChange={() => { }} /> </Col> </Row> <Row> <Title level={3}>Alternativa C</Title> <Col xs={12} md={12}> <JoditEditor ref={editor} value={alternativeC} // config={config} tabIndex={0} onBlur={(newContent) => setAlternativeC(newContent)} onChange={() => { }} /> </Col> </Row> <Row> <Title level={3}>Alternativa D</Title> <Col xs={12} md={12}> <JoditEditor ref={editor} value={alternativeD} // config={config} tabIndex={0} onBlur={(newContent) => setAlternativeD(newContent)} onChange={() => { }} /> </Col> </Row> </Card> <Card type="inner" title={`Resolução`} > <Row> <Title level={3}>Alternativa correta</Title> <Col xs={12} md={12}> <div style={answerStyleBox}> { radioData.map((lo, idx) => { return <> <div style={answerStyle}> <input key={idx} type="radio" name="answer" value={lo.radioName} checked={!!lo.selected} onChange={changeRadio} /> </div> <div style={ABCDStyle}> {ABCD[idx]} </div> </> }) } </div> </Col> </Row> <Row > <Title level={3}>Resolução</Title> <Col xs={12} md={12}> <JoditEditor ref={editor} value={issueResolution} // config={config} tabIndex={0} // tabIndex of textarea onBlur={(newContent) => setIssueResolution(newContent)} onChange={() => { }} /> </Col> </Row> </Card> <Button htmlType="submit" disabled={loadingRegister}> {!loadingRegister ? <>Cadastrar questão</> : <>Cadastrando...</>} </Button> </Card> )} </div> </Form> </Container> <Footer /> </div> </div> </div> </> ); } const mapStateToProps = state => ({ loadingBank: state.bank.loading, bank: state.bank.bank, loadingInstitution: state.institution.loading, institution: state.institution.institution, loadingOffice: state.office.loading, office: state.office.office, loadingDicipline: state.dicipline.loading, dicipline: state.dicipline.dicipline, qtdUploadQuestions: state.registerQuestion.qtdUploadQuestions, questions: state.registerQuestion.questions, loadingUpload: state.registerQuestion.loadingUpload, loadingRegister: state.registerQuestion.loadingRegister, }) const mapDispatchToProps = { uploadFile: regusterQuestionsActions.uploadFile, store: regusterQuestionsActions.store, getBank: bankActions.getBank, getInstitution: institutionActions.getInstitution, getOffice: officeActions.getOffice, getDicipline: diciplineActions.getDicipline, } export default connect(mapStateToProps, mapDispatchToProps)(RegisterQuestions);
'use strict'; var test = angular.module('app').controller('main.IndexController', mainController); function mainController($scope, $http) { $scope.formDeviceData = {areaID:''}; $scope.formAreaData = {parentID:''}; $scope.areas; $scope.testing = "testing hi"; //var socket = io(); //socket.on('dbUpdate', function (data) { // reloadDB(); //}); $scope.reloadDB = function() { $http.get('/api/users/current').success(function(data) { $scope.usertest = data; //console.log(data); //get all devices $http.get('/openApi/devices/device/'+$scope.usertest._id).success(function(data) { $scope.devices = data; //console.log(data); }) .error(function(data) { console.log('Error: ' + data); }); //get all areas $http.get('/openApi/areas/area/'+$scope.usertest._id).success(function(data) { $scope.areas = data; //console.log(data); }) .error(function(data) { console.log('Error: ' + data); }); try { populateMarkers(); } catch(err) {} }) .error(function(data) { console.log('Error: ' + data); }); } //when loading page get user ID $http.get('/api/users/current').success(function(data) { $scope.usertest = data; console.log(data); //get all devices $http.get('/openApi/devices/device/'+$scope.usertest._id).success(function(data) { $scope.devices = data; console.log(data); try { populateMarkers(); } catch(err) {} }) .error(function(data) { console.log('Error: ' + data); }); //get all areas $http.get('/openApi/areas/area/'+$scope.usertest._id).success(function(data) { $scope.areas = data; console.log(data); }) .error(function(data) { console.log('Error: ' + data); }); }) .error(function(data) { console.log('Error: ' + data); }); // when submitting the add form, send the formData to the node API $scope.createDevice = function() { $scope.formDeviceData.userID = $scope.usertest._id; $http.post('/openApi/devices/device/'+$scope.usertest._id, $scope.formDeviceData) .success(function(data) { $scope.formDeviceData = {areaID:''}; // clear the form so our user is ready to enter another $scope.devices = data; console.log(data); }) .error(function(data) { console.log('Error: ' + data); }); }; // delete a device after checking it $scope.deleteDevice = function(id) { $http.delete('/openApi/devices/device/'+$scope.usertest._id+'/'+id).success(function(data) { console.log(id); $scope.devices = data; console.log(data); $scope.deviceInfo = null; angular.element('.deviceInfoForm').css('display', 'none'); angular.element('.InfoFormTip').css('display', 'block'); }).error(function(data) { console.log('Error: ' + data); }); }; // update a device after checking it $scope.updateDevice = function() { $scope.deviceInfoSend = $scope.deviceInfo $http.put('/openApi/devices/deviceUpdate/'+$scope.usertest._id+'/'+$scope.deviceInfoSend._id, $scope.deviceInfoSend).success(function(data) { //console.log($scope.deviceInfo._id); $scope.devices = data; //console.log(data); //load updated device after updated var id = $scope.deviceInfo._id; $scope.deviceInfo._id = null; angular.element('.deviceInfoForm').css('display', 'none'); angular.element('.InfoFormTip').css('display', 'block'); angular.forEach($scope.devices, function(device) { if(device._id == id) { $scope.deviceInfo = angular.copy(device); angular.element('.InfoFormTip').css('display', 'none'); angular.element('.deviceInfoForm').css('display', 'block'); } }); }).error(function(data) { console.log('Error: ' + data); }); }; ////////////////////////////////////////////////////////////// // when submitting the add form, send the formData to the node API $scope.createArea = function() { $scope.formAreaData.userID = $scope.usertest._id; $http.post('/openApi/areas/area/'+$scope.usertest._id, $scope.formAreaData) .success(function(data) { $scope.formAreaData = {parentID:''}; // clear the form so our user is ready to enter another $scope.areas = data; console.log(data); }) .error(function(data) { console.log('Error: ' + data); }); }; // delete a area after checking it $scope.deleteArea = function(id) { $http.delete('/openApi/areas/area/'+$scope.usertest._id+'/'+id).success(function(data) { console.log(id); $scope.areas = data; console.log(data); $scope.areaInfo = null; angular.element('.areaInfoForm').css('display', 'none'); angular.element('.InfoFormTip').css('display', 'block'); }).error(function(data) { console.log('Error: ' + data); }); }; // update a area after checking it $scope.updateArea = function() { $scope.areaInfoSend = $scope.areaInfo $http.put('/openApi/areas/areaUpdate/'+$scope.usertest._id+'/'+$scope.areaInfoSend._id, $scope.areaInfoSend).success(function(data) { console.log($scope.areaInfo._id); $scope.areas = data; console.log(data); //load updated device after updated var id = $scope.areaInfo._id; $scope.areaInfo._id = null; angular.element('.areaInfoForm').css('display', 'none'); angular.element('.InfoFormTip').css('display', 'block'); angular.forEach($scope.areas, function(area) { if(area._id == id) { $scope.areaInfo = angular.copy(area); angular.element('.InfoFormTip').css('display', 'none'); angular.element('.areaInfoForm').css('display', 'block'); } }); }).error(function(data) { console.log('Error: ' + data); }); }; //Get device info on click $scope.getDeviceInfo = function(device) { console.log(device._id); $scope.deviceInfo = angular.copy(device); angular.element('.InfoFormTip').css('display', 'none'); angular.element('.areaInfoForm').css('display', 'none'); angular.element('.deviceInfoForm').css('display', 'block'); }; //Get area info on click $scope.getAreaInfo = function(area) { console.log(area._id); $scope.areaInfo = angular.copy(area); angular.element('.InfoFormTip').css('display', 'none'); angular.element('.deviceInfoForm').css('display', 'none'); angular.element('.areaInfoForm').css('display', 'block'); }; $scope.locateDevice = function(device) { //console.log(device._id); zoomToDevice(device._id); }; $scope.locateArea = function(area) { //console.log(area._id); zoomToArea(area._id); }; $scope.filterAreaExists = function(object) { if(object.areaID == null) { return (true); } else { var found = false; angular.forEach($scope.areas, function(area) { if(object.areaID == area._id) { found = true; } }); return (!found); } return (false); }; $scope.filterParentExists = function(object) { if(object.parentID == null) { return (true); } else { var found = false; angular.forEach($scope.areas, function(area) { if(object.parentID == area._id) { found = true; } }); return (!found); } return (false); }; };
const express = require('express') const axios = require('axios') const { port, host, db, apiUrl } = require('./configuration') const { connectDb } = require('./helpers/db') const app = express() const startServer = () => { app.listen(port, () => { console.log(`Server AUTH listening on ${port}`) console.log(`On host ${host}`) console.log(`Our db ${db}`) }) } app.get('/test', (req, res) => { res.send('Its works') }) app.get('/api/currentUser', (req, res) => { res.json({ id: "123", email: "aqua@ya.ru" }) }) app.get('/testapidata', async (req, res) => { const result = await axios.get(apiUrl + '/testapidata') res.json(result.data) }) connectDb() .on('error', console.log) .on('disconnect', connectDb) .once('open', startServer)
import Vue from "vue"; import Vuex from "vuex"; import axios from "axios"; Vue.use(Vuex); export default new Vuex.Store({ state: { images: [], search_term: "", resolution_type: "med", current_page: 1, page_limit: "", dialog_status: false, selected_img_data: {}, selected_img_url: "", selected_img_lazy_url: "", selected_image_tags: [], images_loading: false, }, mutations: { setResolution(state, res_type) { state.resolution_type = res_type; }, setImages(state, data) { if (data.append) { state.images = [...state.images, ...data.images]; } else { state.images = data.images; } }, setSelectedImgUrl(state, imgData) { state.selected_img_data = imgData; state.selected_image_tags = imgData.tags.split(","); state.selected_img_lazy_url = imgData.previewURL; state.selected_img_url = imgData.webformatURL; }, setDialogStatus(state, status) { state.dialog_status = status; if (!status) { state.selected_img_lazy_url = ""; state.selected_img_url = ""; } }, setSearchTerm(state, search_term) { state.search_term = search_term; }, setPageNumber(state, page_num) { state.current_page = page_num; }, setPageLimit(state, page_limit) { state.page_limit = page_limit; }, setImageLoadingState(state, loading_state) { state.images_loading = loading_state; }, }, actions: { SET_RESOLUTION_TYPE({ commit }, payload) { commit("setResolution", payload); }, SET_DIALOG_STATUS({ commit }, payload) { commit("setDialogStatus", payload); }, SET_SELECTED_IMAGE_URL({ commit }, payload) { commit("setSelectedImgUrl", payload); }, SET_SEARCH_TERM({ commit }, payload) { commit("setSearchTerm", payload); }, async SET_IMAGES({ commit, getters }, append = false) { let api_url = "https://mayurs-api.netlify.app/.netlify/functions/image-finder"; commit("setImageLoadingState", true); let new_page_number = append ? getters.getPageNumber + 1 : 1; commit("setPageNumber", new_page_number); let url = `${api_url}?page=${new_page_number}&q=${getters.getSearchTerm}`; let image_data = await axios.get(url); let images_data = getters.getImages; let image_only_data = image_data.data.hits; if (append) { images_data.forEach((data) => { image_only_data.forEach((newData, index) => { if (data.id == newData.id) { image_only_data.splice(index, 1); } }); }); } if (!append) { let page_limit = Math.ceil(image_data.data.totalHits / 20); let imgDiv = document.getElementById("image-area"); imgDiv.scrollTop = 0; commit("setPageLimit", page_limit); } commit("setImages", { images: image_only_data, append }); setTimeout(() => commit("setImageLoadingState", false), 1000); }, DOWNLOAD_IMAGE(state, imageDetails) { let download_url = ""; let image_resolution = ""; let image_name = imageDetails.id; if (state.getters.getResolution == "med") { download_url = imageDetails.webformatURL; image_resolution = "640x423"; } else { download_url = imageDetails.largeImageURL; image_resolution = "1280x847"; } fetch(download_url) .then((res) => res.blob()) .then((blob) => { const url = window.URL.createObjectURL(blob); const a = document.createElement("a"); a.style.display = "none"; a.href = url; a.download = `${image_name}_${image_resolution}.jpg`; document.body.appendChild(a); a.click(); window.URL.revokeObjectURL(url); a.remove(); }) .catch((err) => console.log(err)); }, }, modules: {}, getters: { getResolution({ resolution_type }) { return resolution_type; }, getImages({ images }) { return images; }, getImagesCount({ images }) { return images.length; }, getSelectedImageUrl({ selected_img_url }) { return selected_img_url; }, getSelectedImageLazyUrl({ selected_img_lazy_url }) { return selected_img_lazy_url; }, getDialogStatus({ dialog_status }) { return dialog_status; }, getSelectedImageDetails({ selected_img_data }) { return selected_img_data; }, getSearchTerm({ search_term }) { return search_term; }, getPageNumber({ current_page }) { return current_page; }, getPageLimit({ page_limit }) { return page_limit; }, getSelectedImageTags({ selected_image_tags }) { return selected_image_tags; }, getImagesLoadingState({ images_loading }) { return images_loading; }, }, });
/** * @param {string} a * @param {string} b * @return {string} */ var complexNumberMultiply = function(a, b) { var sa = split(a); var sb = split(b); var real = sa.real * sb.real - sa.imaginary * sb.imaginary; var imaginary = sa.real * sb.imaginary + sa.imaginary * sb.real; return real+"+"+imaginary+"i"; }; function split(str) { var [ real, imaginary ]= str.split("+"); imaginary = imaginary.replace("i", ""); return { real: +real, imaginary: +imaginary, } } console.log(complexNumberMultiply("1+-1i", "1+-1i")); console.log(complexNumberMultiply("1+1i", "1+1i"));
module.exports = { lagertown: { title: "Lagertown U.S.A.", id: "lagertown", slug: "lagertown-usa-multichannel-marketing", type: "page", subtitle: "multi-channel marketing", description: "An attractive design to sell to businesses then later be used to sell through to customers", thumbnail: { filename: "lagertown-thumbnail.jpg" }, roles: [ "Visual Design", "Creative Direction" ], tools: [ "Illustrator", "Photoshop" ], platforms: [ "Wordpress", "MailChimp", "Facebook", "Twitter", "Point of Sale", "Print Catalogs" ], headImages: [ { filename: "lagertown-usa-banner.jpg", alt: "Chicago — Lagertown U.S.A. - Local Craft Lagers", widths: [ 324, 648, 1132, 2260, 3390], mobileWidth: '90vw', defaultWidth: '1132px' } ], content: { section1: { header: "Generating Excitement for Local Brands", body: [ "The goal was to create a impactful visual that helped sell a specific category in to retailers, that could also be used as marketing to the consumer.", "I looked to create a brand for this sub-category to generate excitement for the products in our portfolio and create a memorable image. Borrowing the colors from a pale lager and applying them to the city gave the Chicago skyline that hazy summer afternoon look that reflected the time of year and the occasion to drink pale lagers." ], images: [ { filename: "lagertown-logo.svg", alt: "H2O Plus earliest homepage from the 90's", }, { filename: "lagertown-background-b.jpg", alt: "Lagertown background - a yellow silhouette of the skyline of Chicago.", widths: [600, 1200, 1800, 2400], mobileWidth: '100vw', defaultWidth: '600px' } ] }, section2: { header: "Sell in & Sell Through", body: [ "Local is always the biggest selling point in the craft beer market, these smaller breweries have the largest growth potential. Lager is a growing category as imbibers palette's weary of hop assaults. It was also timely as a more drinkable summer beer.", "This program was marketed to retail accounts through a brouchure featuring the beers as well as in our email newsletter campaign, homepage and Facebook." ], images: [ { filename: "lagertown-homepage.jpg", alt: "Lagertown U.S.A. - as a homepage graphic featuring bottles & cans or featured local Chicago lagers.", widths: [234, 390, 780, 1170], mobileWidth: '65vw', defaultWidth: '390px' }, { filename: "lagertown-facebook.jpg", alt: "Lagertown U.S.A. - as a Facebook graphic featuring bottles & cans or featured local Chicago lagers.", widths: [306, 510, 1020, 1530], mobileWidth: '85vw', defaultWidth: '510px' }, { filename: "lagertown-email.jpg", alt: "The Lagertown promotion as a featured section of an email newsletter.", widths: [245, 408, 816, 1232], mobileWidth: '68vw', defaultWidth: '408px' }, { filename: "lagertown-catalog.png", alt: "The Lagertown promotion as a small catalog, brochure featuring all the lagers of Chicago carried by Louis Glunz Beer Inc.", widths: [177, 294, 588, 882], mobileWidth: '49vw', defaultWidth: '294px' } ] }, section3: { header: "Stand Out on the Shelf & At the Bar", body: [ "At the point of sale, choices for even the most experienced craft beer drinker can be crowded and noisey. The Lagertown U.S.A. program can create a standout on the shelf, drawing interest and highlighting the style and locality of the product." ], images: [ { filename: "lagertown-banner.jpg", alt: "Lagertown U.S.A. - as a banner behind the banner featuring local lagers available on premise.", widths: [339, 564, 1128, 1692], mobileWidth: '94vw', defaultWidth: '564px' }, { filename: "lagertown-poster.jpg", alt: "Lagertown U.S.A. - as a poster featuring local lagers available on or off premise.", widths: [159, 264, 528, 792], mobileWidth: '44vw', defaultWidth: '264px' }, { filename: "lagertown-shelf-pos.jpg", alt: "Lagertown U.S.A. – as a long shelf display helping the local lagers standout amoungst a noisy shelf and further brand awareness.", widths: [310, 516, 1032, 1548], mobileWidth: '86vw', defaultWidth: '516px' } ] } } } };
var myArrList = [ { index: 0, data: 'A', next: { index: 1, next: { index: 2, next: { index: 3 } } } }, { index: 1, data: 'B' }, { index: 2, data: 'C', next: { index: 1, next: { index: 4 } } }, { index: 3, data: 'D', next: { index: 4 } }, { index: 4, data: 'E' }, { index: 5, data: 'F', next: { index: 3, next: { index: 4 } } } ]; var myQueue = []; var indegree = [0, 0, 0, 0, 0, 0]; function TopoSort(G) { for (var i = 0; i < G.length; i++) { var p = G[i].next; while (p) { indegree[p.index]++; p = p.next; } } for (var i = 0; i < G.length; i++) { if (indegree[i] === 0) { myQueue.unshift(i); } } var count = 0; while (myQueue.length > 0) { var node = myQueue.pop(); count++; console.log(G[node].data); var p = G[node].next; while (p != null) { indegree[p.index]--; if (indegree[p.index] == 0) { myQueue.unshift(p.index); } p = p.next; } } if (count < G.length) return 0; return 1; } console.log(TopoSort(myArrList));
if (Meteor.isServer) { Meteor.publish("classes", function() { return Classes.find({}); }); }
getData() // calling the main function to get the JSON // assigning document elements to variables const noResultsDiv = document.getElementById("noResultsFound") const perPageDiv = document.getElementById("perPage") const userInput = document.getElementById('search') const addBtn = document.getElementById('addElement') const totalResults = document.getElementById('totalResults') const titleForm = document.getElementById('titleForm') const descriptionForm = document.getElementById('descriptionForm') const imageForm = document.getElementById('imageForm') const form = document.getElementById("myForm") const fade = document.getElementById("pageFade") const formWarn = document.getElementById("formWarn") const instructions = document.getElementById("instructionsMain") // declaring different variables let currentPage = 1 // default page of the table set to 1 let totalPages // will assign a number of pages based on how much data needs to be shown let perPage = perPageDiv.value // will be used to show how many items will be shown on the table at once let locaRawlData // just a variable to keep the received data from the JSON let properData let modalOpened = false // add event listeners addBtn.addEventListener("click", openAddModal) document.onkeydown = keyPressed; // creating an async function to get the data from the JSON async function getData() { const response = await fetch("data.json") let data = await response.json(); processData(data) } function processData(data) { // saving data from the JSON to a global variable in order to access it later localRawData = data properData = localRawData showData() changePage(1) } function showData() { let data = [] for (i in properData) { data.push(properData[i]) } // calculating the number of pages totalPages = Math.ceil(data.length / perPage) totalResults.innerHTML = data.length // keeping in the local data variable only the elements that needs to be shown let elementsToRemove = (currentPage - 1) * perPage data.splice(0, elementsToRemove) data.splice(perPage) addPageButtons() processTable(data) stylePageBtns() } function changePerPage(x) { perPage = perPageDiv.value showData() addPageButtons() changePage(1) } function processTable(data) { let table = document.getElementById("mainTable"); table.innerHTML = '' //create a header table row and table headers let thr = document.createElement("tr") let titleHeader = document.createElement("th") let descrHeader = document.createElement("th") let imageHeader = document.createElement("th") // adding values for headers titleHeader.innerHTML = "Title" descrHeader.innerHTML = "Description" thr.classList.add("headerRow") // appending table headers to the table row thr.appendChild(imageHeader) thr.appendChild(titleHeader) thr.appendChild(descrHeader) // appending table row to the table tag from HTML table.appendChild(thr) for (i in data) { let tr = document.createElement("tr"); let title = document.createElement('td') let descr = document.createElement('td') let imgDiv = document.createElement('td') title.innerHTML = data[i].title descr.innerHTML = data[i].description tr.classList.add("dataRow") title.classList.add("elementTitle") imgDiv.classList.add("elementImage") imgDiv.style.backgroundImage = `url(${data[i].imagePath})` tr.appendChild(imgDiv) tr.appendChild(title) tr.appendChild(descr) table.appendChild(tr) } let remainingRows = perPage - data.length if (remainingRows != 0) { for (i = 0; i < remainingRows; i++) { let tr = document.createElement("tr"); let title = document.createElement('td') let descr = document.createElement('td') let imgDiv = document.createElement('td') tr.classList.add("emptyRow") tr.appendChild(imgDiv) tr.appendChild(title) tr.appendChild(descr) table.appendChild(tr) } } } // add buttons based on how many pages there are function addPageButtons() { let allBtns = document.getElementById('allBtns') allBtns.innerHTML = '' // first remove all the previous buttons (if any) for (i = 1; i <= totalPages; i++) { let btn = document.createElement("button") // create a button element btn.setAttribute('onclick', `changePage(${i})`) // give the attribute for onclick to call the "changePage()" function btn.innerHTML = i // also the text of the button allBtns.appendChild(btn) // append the button to the buttons div in HTML } } // a function that changes the pages of the table based on a value function changePage(x) { if (x === 'prev') { // if the value is equal to 'prev' if (currentPage > 1) { currentPage-- // it subtracts 1 from the currentPage variable } } else if (x === 'next') { // if the value is equal to 'next' if (currentPage !== totalPages) { currentPage++ // it adds 1 from the currentPage variable } } else if (x === 'last') { // if the value is equal to 'next' currentPage = totalPages // it adds 1 from the currentPage variable } else if (typeof x == "number") { // if the value is equal to 'next' currentPage = x // it adds 1 from the currentPage variable } showData() } function stylePageBtns() { // check if user is on the first or last page // so those buttons will be disabled let frontState = false let endState = false if (currentPage === 1) { frontState = true } if (currentPage === totalPages) { endState = true } // disable the buttons let front = document.getElementsByClassName("front-extremity") for (i = 0; i < front.length; i++) { front[i].disabled = frontState } let end = document.getElementsByClassName("end-extremity") for (i = 0; i < end.length; i++) { end[i].disabled = endState } // adding a class to the selected page button let numberedBtns = document.getElementById('allBtns').getElementsByTagName('button') for (i = 0; i < numberedBtns.length; i++) { if (i == currentPage - 1) { numberedBtns[i].style.backgroundColor = "#189AD6" numberedBtns[i].style.color = "white" } } } // function that loops through all data and filter based on user input function search() { properData = [] // an array that will contain the data to be shown in the table let noResults = false let userInputValue = userInput.value // save the user input // looping through all elements (including the ones added by the user) and check if they contain what the user inserted localRawData.forEach(el => { let checkTitle = el.title.toUpperCase().includes(userInputValue.toUpperCase()) let checkDescr = el.description.toUpperCase().includes(userInputValue.toUpperCase()) if (checkTitle || checkDescr) { properData.push(el) } }); // check if the user has typed anything and if the function found any element that fits if (userInputValue.length != 0) { if (properData.length === 0) { noResults = true } } else { properData = localRawData } // the variable noResult has a default state as "false" but it gets "true" after checkups // calling the function "noResultFound" with the boolean state so it will show No results found in the specific case noResultsFound(noResults) showData() // show the data on the table changePage(1) // changing to page 1 of the table } // function that shows or hide the "No results found" div based on a boolean value function noResultsFound(noResults) { if (noResults) { noResultsDiv.style.display = 'flex' } else { noResultsDiv.style.display = 'none' } } // keyboard friendly function that runs everytime the user presses a key function keyPressed(e) { userInputSelected = userInput === document.activeElement // check if the user has selected the search field already // console.log(e.keyCode) if (e.keyCode == 39 && !modalOpened) { changePage('next') // Right arrow key - next table page } else if (e.keyCode == 37 && !modalOpened) { changePage('prev') // Left arrow key - previous table page } else if ((e.keyCode == 36 || e.keyCode == 38) && !modalOpened) { changePage(1) // Home key - first table page } else if ((e.keyCode == 35 || e.keyCode == 40) && !modalOpened) { changePage('last') // End key - last table page } else if (e.keyCode == 13 && modalOpened) { addElement() // Enter key - select the search input } else if (e.keyCode == 45) { openAddModal() // Insert key - add another element } else if (e.keyCode == 27 && userInputSelected) { userInput.value = '' // on ESC key if search input is selected it empties its value search() } else if (e.keyCode == 27) { closeModal() // close the modal on ESC key } else if (e.keyCode == 70 && !modalOpened && !userInputSelected) { setTimeout(focusSearch, 100) // on F key press, focus the search input } } // add another element functions function openAddModal() { modalOpened = true // assigning the true state for the variable so we can use it later formWarn.style.display = "none" // in case we had the empty title warning, now we hide it form.style.display = "block" fade.style.display = "block" form.style.zIndex = 1 fade.style.zIndex = 1 // adding classes in order to show the modal with the form and the "fade filter" over the page form.classList.add("myFormDispalyed") fade.classList.add("pageFadeDisplayed") // just preselect the title field, so the user can type directly the title titleForm.focus() } function focusSearch() { userInput.focus() userInput.value = "" } function addElement() { // getting values from the input fields const title = titleForm.value const descr = descriptionForm.value const img = imageForm.value //checking if the user inserted any title if (title.length > 0) { formWarn.style.display = "none" // creating an object and assigning it to a variable const newElement = { title: title, description: descr, imagePath: img } // emptying all the input fields in case the user wants to add anothe element titleForm.value = '' descriptionForm.value = '' imageForm.value = '' userInput.value = '' localRawData.unshift(newElement) // calling functions to close the modal and searching again in the table // the purpose for this search is to "regenerate" the table with the new data closeModal() search() } else { formWarn.style.display = "block" } } // show or hide the instructions tab function toggleInstructions() { instructions.classList.toggle("instructionsHidden") } function goToGit() { window.open('https://github.com/ConstantinGuiu/Table-challenge') } function closeModal() { modalOpened = false // assigning the false state for the variable // removing the classes that were displaying the modal form.classList.remove("myFormDispalyed") fade.classList.remove("pageFadeDisplayed") // waiting for the hide animations to finish (opacity from 100% to 0%) // then moving the elements behind our content setTimeout(200) form.style.zIndex = -1 fade.style.zIndex = -1 }
var searchData= [ ['normalgamestrategy_2eh',['normalgamestrategy.h',['../normalgamestrategy_8h.html',1,'']]] ];
import s from './Dialogs.module.css' import Dialog from './Dialog/Dialog' import Message from "./Message/Message"; import React from "react"; import {Field, reduxForm} from "redux-form" import {maxLengthCreator, required} from "../../utils/validators/validators"; import {Textarea} from "../../Common/FormsControls/FormControls"; let maxLength10 = maxLengthCreator(10) const DialogForm = (props) => { return ( <form onSubmit={props.handleSubmit}> <div> <Field placeholder={"Send message"} component={Textarea} name={"message"} validate={[required, maxLength10]}/> </div> <div> <button>Add post</button> </div> </form> ) } const DialogReduxForm = reduxForm({form: 'dialogs'})(DialogForm) const Dialogs = (props) => { const newDialogs = props.dialogs.dialogs.map(el => <Dialog name={el.name} id={el.id} key={el.id}/>) const newMessages = props.dialogs.messages.map(el => <Message message={el.message} key={el.messages}/>) const onSubmit = (formData) => { props.addMessage(formData.message) } return ( <div className={s.dialogs}> <div className={s.dialogsItems}> {newDialogs} </div> <div className={s.messages}> {newMessages} <DialogReduxForm {...props} onSubmit={onSubmit} /> </div> </div> ) } export default Dialogs
'use strict'; module.exports = app => { const tableName = 'cg_failed_item_rel'; const { BIGINT, STRING, TINYINT } = app.Sequelize; const Fail = app.model1.define( 'Fail', { /* 通用字段 */ id: { type: BIGINT(19), primaryKey: true }, inspectionId: { type: BIGINT(19) }, categoryId: { type: BIGINT(19) }, fisId: { type: BIGINT(19) }, standardValue: { type: STRING(1000) }, testValue: { type: STRING(1000) }, result: { type: TINYINT(4), comment: '抽检结果:1合格;2不合格' }, resultExp: { type: STRING(500) }, }, { freezeTableName: true, tableName, createdAt: false, updatedAt: false, }); return Fail; };
function unique(array) { var object = {}; for(var i = 0; i < array.length; i++){ var str = array[i]; object[str] = true; } return Object.keys(object); } var strings = ["кришна", "кришна", "харе", "харе", "харе", "харе", "кришна", "кришна", "8-()" ]; console.log(unique(strings));
const shell = require('shelljs'); const glob = require('glob'); const { extname, resolve } = require('path'); const sharp = require('sharp'); const fs = require('fs'); const cmd = 'img:resize'; // TODO: Validate notification handler when use mogrify // dvx img:resize --exc=opengraph module.exports = { cmd, desc: 'Resize images to 1024px width', opts: { source: { alias: 'src', describe: 'Source path of the images to resize', type: 'string', default: 'src/assets/img/dist/', }, use: { describe: 'Tool to use', type: 'string', default: 'mogrify', choices: ['mogrify', 'sharp'], }, width: { alias: 'w', type: 'number', describe: 'Set the width', default: 1024, }, height: { alias: 'he', // TODO: Fix error with --help and -h type: 'number', describe: 'Set the height', }, exclude: { alias: 'exc', describe: 'Files to exclude / ignore, separated by spaces', type: 'array', default: ['opengraph'], }, }, handler: async (argv) => { console.time(cmd); const srcDir = resolve(process.cwd(), argv.src); const width = argv.width; const height = argv.height; Notify.info({ title: 'Resize', message: 'Start resize images task' }); const files = glob.sync(`${srcDir}/**/*.+(png|jpeg|jpg)`, { nodir: true }); const filteredFiles = files.filter((file) => { let include = true; argv.exclude.forEach((exclude) => { if (file.includes(exclude)) { warn('[Resize]:', `File excluded: ${file}, contains: ${exclude}`); include = !include; } }); return include; }); for (let file of filteredFiles) { if (argv.use === 'mogrify') { await useMogrify(file, width, height); } else if (argv.use === 'sharp') { await useSharp(file, width, height); } } Notify.info({ title: 'Resize', message: 'End resize images task' }); console.timeEnd(cmd); }, }; const useMogrify = async (file, width = 1024, height) => { const mogrify = 'mogrify'; try { if (!shell.which(mogrify)) { throw `The command ${mogrify} does not exist.`; } const ext = extname(file).toLowerCase(); let stdOut = ''; const resize = height ? `-resize \"${width}x${height}\" -extent \"${width}x${height}\" ` : `-resize \"${width}>\"`; // console.log(resize); -path processed if (ext.includes('.jpg')) { stdOut = shell.exec( `${mogrify} -verbose -format jpg -layers Dispose ${resize} ${file}`, { async: false, silent: true } ).stdout; } else if (ext.includes('.jpeg')) { stdOut = shell.exec( `${mogrify} -verbose -format jpeg -layers Dispose ${resize} ${file}`, { async: false, silent: true } ).stdout; } else if (ext.includes('.png')) { stdOut = shell.exec(`${mogrify} -verbose -format png ${resize} ${file}`, { async: false, silent: true, }).stdout; } log('[Resize]:', stdOut); } catch (e) { error('[Resize - Error]:', e); shell.exit(1); } }; const useSharp = async (file, width = 1024, height) => { let opts = {}; // TODO: read what is the default height for sharp if (height) { opts = { width, height, }; } else { opts = { width, }; } await sharp(file) .resize({ ...opts, withoutEnlargement: true, }) .toBuffer(function (err, buffer) { fs.writeFileSync(file, buffer); log('[Resize]:', file); }); };
(function (model, root, modules) { var ready = false; var view = require('riko-mvc').V(model, render); document.body.innerHTML = ""; document.body.appendChild(view.target); Object.keys(modules.nodes).forEach(installDir); ready = true; update(); return view; function installDir (name) { try { var dir = modules.nodes[name].nodes['views']; install(dir, name); } catch (e) { console.warn('could not prepare view globals for "' + name + '"', 'because of', e); } } function install (views, name) { views.options = require('extend')(views.options, { globals: function (file) { return { emit: function () { return __.util.emit.apply(null, arguments) }, h: function () { return __.util.h.apply(null, arguments) } } } }) views.events.onAny(update); // live reload console.info('prepared views for', name) } function render (state) { return ready ? root().view(state) : __.util.h('h1', 'preparing views...'); } function update () { view.update(model()); } })
/** * @module yrzb.filters * @requires ionic * @requires yrzb.config * @description * filter 模块功能:<br> * */ (function(){ 'use strict'; var filters = angular.module('yrzb.filters', []) /** * @func upcase * @param {String} text 需转化的字符串 * @return {String} * @description * 将字符串转化成大写 */ .filter('upcase', function(){ return function(text){ return String(typeof(text) === 'string' ? text : '').toUpperCase(); }; }) /** * @func toMillion * @param {Number} amount 需转化的金额 * @return {String} * @description * 将元转化成万元 */ .filter('toMillion', function(){ return function(amount){ return (amount * 1) / (10000 * 100) + '万元'; }; }); }());
const mongoose = require("mongoose"); const dateSchema = new mongoose.Schema({ Quizes:[{ type: String, required: true, }], Assignments:[{ type: String, required:true, }], Lectures:[{ type: String, required: true, }], midsPaper:{ type: String, required: true }, finalsPaper:{ type: String, required: true, } }); const DateSchema = mongoose.model("dateLimits", dateSchema); module.exports = DateSchema;
import { useRef } from 'react'; import useToggle from '../useToggle'; import useForceUpdate from '../useForceUpdate'; /** * * @param { Boolean } visible 控制Modal是否状态是否可见 * @param { Function } onCancel Modal对话框的取消事件 * @param { Function } onOk Modal对话框的确认事件 * @param { Object } config 对应的全部是Antd中Modal的属性 * @param { Object } formConfig 对应Modal中存在的Form的属性 */ const STORE_INIT_KEY = 'row'; const useModal = ({ visible = false, onCancel, onSubmit, config, formConfig = {}, }) => { const [allowOpen, { toggle }] = useToggle(visible); const [submitLoading, { toggleFalse, toggleTure }] = useToggle(false); const forceUpdate = useForceUpdate(); const extraStore = useRef({ store: new Map() }); const { form, parser } = formConfig; const mergeConfig = { ...config }; const handleCancel = () => { if (onCancel) { onCancel(); } toggle(); }; const handleSubmit = async () => { toggleTure(); if (onSubmit) { await onSubmit(); } await toggle(); await toggleFalse(); }; const updateExtraStore = (key, value) => { extraStore.current.store.set(key, value); forceUpdate(); }; const getItem = key => extraStore.current.store.get(key); const actions = { getItem, updateExtraStore, }; mergeConfig.onCancel = handleCancel; mergeConfig.onOk = handleSubmit; mergeConfig.confirmLoading = submitLoading; mergeConfig.actions = actions; mergeConfig.store = getItem(STORE_INIT_KEY); const handleToggle = async value => { await toggle(); updateExtraStore(STORE_INIT_KEY, value); // form 原型已经存在 if (form) { // parser 需要对值类型进行一次格式化, 例如对时间进行设置时, 需要把时间转换为Moment对象 const formatValue = parser ? parser(value) : value; await form.setFieldsValue(formatValue); } }; return { allowOpen, toggle: handleToggle, visible: allowOpen, onCancel: handleCancel, onOk: handleSubmit, formConfig, ...mergeConfig, }; }; export default useModal;
/* 🤖 this file was generated by svg-to-ts*/ export const EOSIconsStorage = { name: 'storage', data: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M2 20h20v-4H2v4zm2-3h2v2H4v-2zM2 4v4h20V4H2zm4 3H4V5h2v2zm-4 7h20v-4H2v4zm2-3h2v2H4v-2z"/></svg>` };
define('app/views/layout/search', [ 'jquery', 'underscore', 'magix', 'app/util/index', 'app/util/dialog/index' ], function ($, _, Magix, Util, Dialog) { return Magix.View.extend({tmpl:"<div class=block-switch-loading></div> <div mx-vframe=true mx-view=\"app/views/common/sitenav\"></div> <div mx-vframe=true mx-view=\"app/views/common/header_search\" id=magix_vf_header></div> <div class=\"main search-main wrap clearfix\"> <div mx-vframe=true id=magix_vf_main> <div bx-name=\"components/spin\"></div> </div> </div> <div bx-name=\"app/exts/fixedtool/fixedtool\" class=fixedtool> <div bx-name=\"app/exts/gotop/gotop\"></div> <div bx-name=\"app/exts/erobot/erobot\"></div> </div> <div mx-vframe=true mx-view=\"app/views/common/footer\"></div>", init: function () { var me = this me.observeLocation({ path: true }) }, render: function (e) { var me = this // 框架只渲染一遍 if (!me.rendered) { me.setViewHTML() $('#' + me.id).attr('data-spm', 1998910419) } me.animateLoading() me._mountVframes() me._destroy() me._spmlog() }, _mountVframes: function () { window.scrollTo(0, 0) var me = this var vom = me.vom var loc = me.location var pn = loc.path var mainVframe = vom.get('magix_vf_main') if (mainVframe) { var view = pn.substring(1).replace('.htm', '') mainVframe.mountView('app/views/' + view) } }, _destroy: function () { Util.hideMask() Dialog.hide() }, _spmlog: function () { var me = this var loc = me.location var pathname = loc.path Util.upSPMB(pathname) Util.sendPV(pathname) Util.genPVID(pathname) } }) })
import { actionTypeConst } from './constants' import { fetchGardenList, fetchGardenPlantList } from './service' const requestGetGardenList = () => ({ type: actionTypeConst.getGarden.REQUEST }) const successGetGardenList = ({ data, code }) => ({ type: actionTypeConst.getGarden.SUCCESS, data: data.data, code }) const failureGetGardenList = ({error, code}) => ({ type: actionTypeConst.getGarden.FAILURE, error, code, }) const requestGetGardenPlantList = () => ({ type: actionTypeConst.getGardenPlant.REQUEST }) const successGetGardenPlantList = ({ data, code }) => ({ type: actionTypeConst.getGardenPlant.SUCCESS, data: data.data, code }) const failureGetGardenPlantList = ({error, code}) => ({ type: actionTypeConst.getGardenPlant.FAILURE, error, code, }) const clearGardenList = () => ({ type: actionTypeConst.clearup }) const clearGardenPlantList = () => ({ type: actionTypeConst.clearupGardenPlant }) export const getGardenList = () => dispatch => { dispatch(requestGetGardenList()) fetchGardenList() .then(response => dispatch(successGetGardenList(response))) .catch(error => dispatch(failureGetGardenList(error))) } export const getGardenPlantList = (_id) => dispatch => { dispatch(requestGetGardenPlantList()) fetchGardenPlantList(_id) .then(response => dispatch(successGetGardenPlantList(response))) .catch(error => dispatch(failureGetGardenPlantList(error))) } export const clearGarden = () => dispatch => dispatch(clearGardenList()) export const clearGardenPlant = () => dispatch => dispatch(clearGardenPlantList())
import React, { Component } from 'react'; import { MsgBox } from './components/MsgBox/MsgBox'; import bg from './components/MsgBox/Bkgrnd03.jpg'; import styles from './components/MsgBox/MsgBox.css'; class Home extends Component { render() { return ( <div style={{ background: `url(${bg}) no-repeat`, backgroundSize: '100%' }} className={styles.MsgBox}> <MsgBox /> </div> ); } } export default Home;
import Vue from "vue"; import VueRouter from "vue-router"; import Home from "../views/Home.vue" import Gg from "../views/gg.vue" import Banner from "../views/banner.vue" import zhuanji from "../components/xiangqing/zhuanji.vue" import playMusic from "../components/xiangqing/playMusic.vue" Vue.use(VueRouter); const routes = [ { path: "/", name: "Home", component: Home }, { path: "/gg", name: "Gg", component: Gg }, { path: "/banner", name: "banner", component: Banner }, { path: "/zhuanji", name: "zhuanji", component: zhuanji }, { path: "/playMusic", name: "playMusic", component: playMusic }, ]; const router = new VueRouter({ // mode: "history", // base: process.env.BASE_URL, routes }); export default router;
'use strict'; chrome.runtime.onInstalled.addListener(function(details) { if(details.reason === 'install') chrome.storage.sync.set({zoomData: '[{"class":"ESET 210","meetingID":"123456789","info":"Click on the info Icon!"}, {"class":"CSCE 222","meetingID":"123456789","info":"HELL MW 10:20 AM"}, {"class":"PHYS 207","meetingID":"123456789","info":"TA SESSION 3:00 PM"}]' }, function() { console.log("Installation Set."); }); console.log(details) }); // chrome.storage.sync.set({zoomData: '[{"class":"ESET 210","meetingID":"756676286","info":"Ta Led class"}, {"class":"ESET 210","meetingID":"756676286","info":"Ta Led class"}]'}, function() { // console.log("The color is working."); // }); // chrome.runtime.onMessage.addListener(data => { // if (data.type === 'notification') { // chrome.notifications.create('', data.options); // } // });
import React, {Component} from "react"; import { View, TouchableHighlight, Text, TextInput, AsyncStorage, Alert, } from "react-native"; import PushNotification from "react-native-push-notification"; import styles from "./Styles.js"; import { getDataFromStorage, setDataToStorage, createNewProfile, } from "./functions/data.js"; const CryptoJS = require("crypto-js"); class LogIn extends Component { componentDidMount = async () => { let passwordHash = await getDataFromStorage("passwordHash", ""); if (passwordHash === "None") { this.props.navigation.navigate("Index", { password: "", }); } this.setState({passwordHash: passwordHash}); }; state = { passwordHash: "", inputPassword: "", message: "", }; deleteProfileAlert = () => { Alert.alert( "TO BO IZBRISALO VSE VAŠE PODATKE IZ TELEFONA", "Če se kasneje premislite, in želite katere vaše podatke, jih ne bo več na telefonu. Podatke, ki jih nistve izvozili ali poslali raziskovalcem bodo izgubljeni za vedno. Ali ste prepričani, da želite izbrisati svoje podatke:", [ { text: "Ne izbriši", onPress: () => {}, style: "cancel", }, { text: "Izbriši", onPress: () => { PushNotification.cancelAllLocalNotifications(); AsyncStorage.clear(); this.props.navigation.replace("Splash", { password: "", }); }, }, {onDismiss: () => {}}, ], ); }; checkPassword = (inputedPassword, savedPassword) => { const passwordHash = CryptoJS.SHA256(inputedPassword).toString( CryptoJS.enc.Base64, ); if (passwordHash === savedPassword) { this.props.navigation.replace("Index", { password: inputedPassword, }); } else { this.setState({message: "To ni pravilno geslo"}); } }; renderLogInScreen = () => { return ( <View style={styles.backgroundStart}> <Text style={{flex: 0.1}} /> <Text style={{ flex: 0.1, fontSize: 20, textAlign: "center", color: "white", }}> Prosim, da vpišete svoje geslo </Text> <Text style={{flex: 0.1}} /> <TextInput style={{ height: 50, borderColor: "black", borderWidth: 1, backgroundColor: "white", width: "90%", alignSelf: "center", }} onChangeText={text => this.setState({inputPassword: text})} /> <Text style={{flex: 0.1}} /> <View style={{flex: 0.1}}> <View style={{ flexDirection: "row", justifyContent: "space-around", flex: 1, }}> <TouchableHighlight style={{ backgroundColor: "#4e9363", padding: 30, height: 40, justifyContent: "center", alignSelf: "center", flex: 0.4, }} onPress={() => this.checkPassword( this.state.inputPassword, this.state.passwordHash, ) }> <Text style={{ fontSize: 20, justifyContent: "center", textAlign: "center", color: "white", }}> Vpiši se </Text> </TouchableHighlight> <TouchableHighlight style={{ backgroundColor: "#4e9363", padding: 30, height: 40, justifyContent: "center", alignSelf: "center", flex: 0.4, }} onPress={() => this.deleteProfileAlert()}> <Text style={{ fontSize: 20, justifyContent: "center", textAlign: "center", color: "white", }}> Izbriši geslo </Text> </TouchableHighlight> </View> </View> <Text style={{flex: 0.1}} /> <Text>{this.state.message}</Text> </View> ); }; render() { return this.renderLogInScreen(); } } export default LogIn;
const baseAction = { navTo: { desc: '链接跳转', params: { url: { type: String } } }, setData: { desc: '设置数据', params: null }, hide: { desc: '隐藏', params: null }, show: { desc: '展示', params: null } } export default baseAction
import React from "react"; import { FormGroup, Input, Button, Card, CardHeader, CardImg, CardBody, CardBlock, Form } from "reactstrap"; import { withRouter } from "react-router-dom"; import { password } from "../../services/appuser.service"; import "react-notifications/lib/notifications.css"; import { NotificationManager } from "react-notifications"; class AppUserPassword extends React.Component { state = { email: "", alert: false, validate: { email: "" } }; handleChange = e => { e.preventDefault(); const name = e.target.name; const value = e.target.value; this.setState({ [name]: value }); }; resetHandler = e => { e.preventDefault(); const { email } = this.state; const req = { email }; password(req) .then(response => { console.log("sent email"); this.onSuccessNotification(); this.setState({ email: "" }); }) .catch(err => { console.log("error"); }); }; restOnClick = () => { this.setState({ email: "" }); }; onSuccessNotification = () => { NotificationManager.success("We just sent you an email"); }; onErrorNotification = () => { NotificationManager.error("That email cannot be found"); }; validateInput(e) { let regexString; let stateValidateName; switch (e.target.name) { case "email": break; default: console.log("switched"); } const validate = { ...this.state.validate }; if (regexString.test(e.target.value)) { validate[stateValidateName] = "has-success"; } else { validate[stateValidateName] = "has-danger"; } this.setState({ validate }); } render() { return ( <React.Fragment> <div className="container-fluid"> <div className="row full-height-vh"> <div className="col-12 d-flex align-items-center justify-content-center" style={{ backgroundColor: "#04b9b6" }} > <Card className="col-4 px-2 py-2 box-shadow-2"> <CardHeader className="card-header text-center"> <CardImg src="http://i67.tinypic.com/vyy1eh.png" alt="company-logo" className="mb-3" width="auto" height="auto" /> <h4 className="text-uppercase text-bold-400 grey darken-1">Password Request</h4> </CardHeader> <CardBody> <CardBlock className="card-block mx-auto"> <Form> <FormGroup> <div className="col-md-12"> <Input type="email" className="form-control form-control-lg" name="email" placeholder="Email" id="email" value={this.state.email} onChange={this.handleChange} /> </div> </FormGroup> <FormGroup className="text-center"> <Button color="danger" className="px-4 py-2 text-uppercase white font-small-4 box-shadow-1 border-0" onClick={this.resetHandler} > Reset Password </Button> </FormGroup> </Form> </CardBlock> </CardBody> </Card> </div> </div> </div> </React.Fragment> ); } } export default withRouter(AppUserPassword);
const express = require('express'); const database = require('../database/index.js'); const app = express(); const port = 3003; const cors = require('cors'); const moment = require('moment'); // const redis = require("redis"); // const client = redis.createClient(); // client.on("error", function(error) { // console.error(error); // }); app.use(cors()); app.options('*', cors()); app.use(express.static('public')); app.use(express.json()); app.use(express.urlencoded()); app.get('/cards', (req, res) => { database.query(`select * from goodBoys`, (err, results) => { if (err) { res.status(404).send(err); } else { res.status(200).send(results); } }); // REDIS: currently gets all cards and stores them to one key; would be better to store each card to an individual id and then only include 20% in the cache // client.get(id, (redisGetError, redisData) => { // if (redisGetError) { // res.status(500).json({ redisGetError }); // return; // } // if (redisData) { // // JSON objects need to be parsed after reading from redis, since it is stringified before being stored into cache // let data = JSON.parse(redisData); // res.status(200).json(data); // console.log('redis has data'); // } else { // database.query(`select * from goodBoys`, (err, results) => { // if (err) { // res.status(404).send(err); // } else { // res.status(200).send(results); // client.set(results.id, JSON.stringify(results), (redisSetError, result) => { // if (redisSetError) { // res.status(500).json({ redisSetError }); // } // }); // console.log('redis set the data') // } // }); // } // }); }); // let idCount = 1; app.post('/', (req, res) => { let result = []; req.body.forEach((ele) => { const formatTime = moment(ele.creationtime).format('lll'); result.push( [ ele.name, ele.description, formatTime, ] ) // REDIS: set keys to id and value to the card object // client.set(idCount, JSON.stringify(ele), (redisSetError, result) => { // if (redisSetError) { // res.status(500).json({ redisSetError }); // } // }); // idCount++; }) const postQuery = `insert into goodBoys (card_name, card_description, creationtime) values ?`; database.query(postQuery, [result], (err, results) => { if (err) { console.log('err', err); res.status(400).send(err); } else { res.status(200).send(results); } }) }); app.delete('/cards/:id', (req, res) => { // console.log(req.params.id); database.query(`delete from goodBoys where id = ${req.params.id}`, (err, results) => { if (err) { res.status(404).send(err); } else { res.status(200).send(results); } }); }); app.patch('/cards/:id', (req, res) => { // console.log(req.body.card_name, req.params.id) database.query(`update goodBoys set card_name = '${req.body.card_name}' where id = ${req.params.id}`, (err, results) => { if (err) { res.status(404).send(err); } else { res.status(200).send(results); } }) // REDIS: set the id to the new result // const { id } = req.params; // database.query(`update goodBoys set card_name = '${req.body.card_name}' where id = ${id}`, (err, results) => { // if (err) { // res.status(404).send(err); // } else { // res.status(200).send(results); // client.set(id, JSON.stringify(results), (redisSetError, result) => { // if (redisSetError) { // res.status(500).json({ redisSetError }); // } // }); // } // }) }); app.listen(port, () => console.log(`Server listening on http://localhost:${port}`))
import React, { Component } from 'react'; import { withStyles } from '@material-ui/core/styles'; import { Typography, Grid } from '@material-ui/core'; // import { CSSTransition } from 'react-transition-group'; import ToggleSwitch from '../components/ToggleSwitch'; import TableRow from '../components/TableRow'; import PricingComparison from '../static/mockDB/comparison.json'; import PricingOptions from '../static/mockDB/pricing.json'; const styles = theme => ({ sectionDisplay: { backgroundColor: '#f7f8fa', padding: '20px 50px', width: 'calc(100% - 100px)', display: 'flex', justifyContent: 'center' }, verticalCard: { width: '100%', borderLeft: '1px solid #d7dce0', // padding: '20px 0', height: 110, }, tableCards: { width: "100%", backgroundColor: 'white', padding: '50px 0', border: '1px solid #d7dce0', borderRadius: '30px', maxWidth: '1470px' }, tableHeader: { display: "grid", gridTemplateColumns: 'repeat(5, 1fr)', justifyItems: 'center', alignItems: 'center', }, sticky: { position: 'sticky', top: 0, zIndex: 100, }, works: { textTransform: "uppercase" }, subworks: { fontStyle: 'italic', fontSize: '1.4rem', fontWeight: 'bold', // minHeight: "calc(1.4rem + 0.35em)" transition: 'visibility 0.3s linear,opacity 0.3s linear' }, displaySticky: { opacity: 1, visibility: 'visible' }, noDisplay: { opacity: 0, visibility: 'hidden', height: 0 } }) export class ComparisonTable extends Component { state = { stickyDisplay: false, monthly: true } componentDidMount() { this.handleScroll(); window.addEventListener('scroll', this.handleScroll); } componentWillUnmount() { window.removeEventListener('scroll', this.handleScroll); } handleScroll = (e) => { let scrollEl = document.getElementById('scrollEl') const posY = scrollEl.getBoundingClientRect().y; if(posY < 62){ this.setState({ stickyDisplay: true }) } else { this.setState({ stickyDisplay: false }) } } togglePrice = () => { this.setState({ monthly: !this.state.monthly }) } render() { const { classes } = this.props; const getTableHeader = PricingOptions.map((option, index) => { const { name, price } = option; const displayPrice = this.state.monthly ? price.monthly : price.yearly; // console.log(option) return ( <Grid container direction='column' justify='center' alignItems='center' className={classes.verticalCard} key={index} > <Grid item> <Typography variant='h6' color={name === "The Works" ? "secondary" : "primary"} align="center" gutterBottom={name === "The Works" ? false : true} className={name === "The Works" ? classes.works : ""} > {name}{name === "True Paperless" && ('\u2122') || name === "Practice Dashboard" && ('\u2122')} </Typography> </Grid> <Grid item> <Typography variant='h6' align="center" gutterBottom={true} className={`${classes.subworks} ${name === "The Works" ? classes.displaySticky : this.state.stickyDisplay ? classes.displaySticky : classes.noDisplay }`} > { name === "The Works" ? !this.state.stickyDisplay ? "Our Most Popular!": `$${displayPrice}` : `$${displayPrice}` } </Typography> </Grid> </Grid> ) }); const getTable = PricingComparison.map( (section, index) => { const objKey = Object.keys(section)[0] const title = objKey.split('_').join(" "); const content = section[objKey]; return ( <TableRow key={index} title={title} content={content} monthly={this.state.monthly} /> ) }) return ( <div className={classes.sectionDisplay}> <div style={{ padding: '0 0 30px 0' }} className={classes.tableCards}> <div className={`${classes.tableHeader} ${classes.sticky}`} style={ { borderRadius: '30px 30px 0 0', backgroundColor: 'white', borderBottom: '1px solid #d7dce0' } } > <Grid container direction='column' justify='center' alignItems='center' className={classes.verticalCard} style={{ borderLeft: 'none' }} > <Grid item> <ToggleSwitch opt1="Monthly" opt2="Yearly" monthly={this.state.monthly} toggle={this.togglePrice} /> </Grid> </Grid> {getTableHeader} </div> {getTable} </div> </div> ) } } export default withStyles(styles, { withTheme: true })(ComparisonTable)
const fs = require('fs') const request = require('superagent') const cheerio = require('cheerio') const dir = require('./config/savedir') const authorId = require('./config/authorid') const authorUrl = require('./config/url') const cookie = require('./config/cookie') const repeat = require('./api/repeat') const getPageNum = require('./api/getpagenum') const savedir = require('./config/saveauthorimg') const imgList = require('./childdata/imgListdown') const imgId = require('./childdata/imgid') async function start(){ await imgList } start()
(function () { 'use strict'; angular.module('app') // .config(routerConfig) .controller('MenuController', MenuController); // .controller('MenuController', ['$state', MenuController]); MenuController.$inject = ['$state', 'AuthenService', 'ApplicationConfig']; function MenuController($state, AuthenService, ApplicationConfig) { var vm = this; vm.currentNavItem = '/home'; vm.menuItems = ApplicationConfig.menuItems; vm.logout = logout; console.log("You are entering home page"); function logout() { console.log("You are request to logout"); AuthenService.logout(); $state.go('login'); } } })();
// Forms functions $(function () { $.fn.hasData = function (key) { return typeof $(this).data(key) !== "undefined"; }; }); // Catalogues functions function loadTable(urlTable, tableSelector) { $.ajax({ type: "POST", url: urlTable, dataType: "json", contentType: "application/json", success: function (response) { if (response.Success) { $(tableSelector).html(response.Data); $(`${tableSelector} table`).DataTable({ responsive: true, lengthMenu: [[15, 25, 50], [15, 25, 50]] }); } else { $(tableSelector).empty(); Swal.fire({ icon: "error", title: "Oops...", text: response.Message, }) } } }); } function getFormData(form) { var serializedArray = form.serializeArray(); var json = {}; $.map(serializedArray, function (value) { json[value["name"]] = value["value"]; }); return JSON.stringify(json); } function saveData(dataForm, modalWindow, callback, callbackParameters) { var data = this.getFormData(dataForm); $.ajax({ type: "POST", url: dataForm.attr("action"), dataType: "json", contentType: "application/json", data: data, success: function (response) { processResponse(response, dataForm, modalWindow, callback, callbackParameters); } }); } function processResponse(response, dataForm, modalWindow, callback, callbackParameters) { if (response.Success) { Swal.fire({ icon: "success", title: "Success...", text: response.SuccessMessage, }) modalWindow.modal("hide"); callback(callbackParameters); } else { dataForm.children("[data-input='true']").removeClass("has-error"); showValidationSummary(response.ErrorList, dataForm); } } function processSimpleResponse(response, callback) { if (response.Success) { bootbox.alert({ message: response.SuccessMessage, size: "small", centerVertical: true }); callback(); } else { Swal.fire({ icon: "error", title: "Oops...", text: response.ErrorMessage, }) } } function deleteData(action, data, confirmationMessage, yesText, cancelText, callback, callbackParameters) { applyProcess(action, data, confirmationMessage, yesText, cancelText, callback, callbackParameters); } function applyProcess(action, data, confirmationMessage, yesText, cancelText, callback, callbackParameters) { Swal.fire({ title: "Confirmation", text: confirmationMessage, icon: "warning", showCancelButton: true, confirmButtonColor: "#3085d6", cancelButtonColor: "#d33", confirmButtonText: yesText, cancelButtonText: cancelText }).then((result) => { if (result.isConfirmed) { $.ajax({ type: "POST", url: action, dataType: "json", contentType: "application/json", data: data, success: function (response) { if (response.Success) { Swal.fire({ icon: "success", title: "Success...", text: response.SuccessMessage, }).then(() => { callback(callbackParameters); }); } else { Swal.fire({ icon: "error", title: "Oops...", text: response.ErrorMessage, }) } } }); } }); } function showValidationSummary(errorList, dataForm) { var $validationSummary = dataForm.children("#ValidationSummary"); $validationSummary.empty(); $(".invalid-feedback").remove(); $.each(errorList, function (index, error) { var inputValidated = dataForm.find(`#${error.property}`); createErrorMessages($validationSummary, inputValidated, error.messages); }); } function createErrorMessages(validationSummary, inputValidated, messages) { var $closeButton = $("<button>", { "class": "btn-close", type: "button", "data-bs-dismiss": "alert" }); inputValidated.addClass("is-invalid"); var $errorList = $("<ul>", { "class": "simple-list p-0 mb-1" }); $.each(messages, function (index, message) { var $errorItem = $("<li>").html(message); $errorList.append($errorItem); var $alert = $("<div>", { "class": "alert alert-danger alert-dismissible mb-2", role: "alert" }); $alert.append($closeButton); $alert.append(message); validationSummary.append($alert); }); var $validationMessage = $("<div>", { "class": "invalid-feedback" }); $validationMessage.append($errorList); inputValidated.after($validationMessage); } form.prototype = { getFormData: function () { return getFormData(this.dataForm); }, showModal: function (data) { var modalWindowSelector = this.modalWindowId || "ModalWindow"; var modalContainerSelector = this.modalContainerId || "ModalContainer"; this.modalWindow = $(`#${modalWindowSelector}`); this.modalContainer = $(`#${modalContainerSelector}`); this.modalContainer.html(data); var self = this; $("#SaveButton").click(function () { self.save(); }); this.modalWindow.modal("show"); }, hideModal: function () { this.modalWindow.modal("hide"); }, create: function () { var self = this; $.get(this.createUrl, function (data) { self.showModal(data); }); }, edit: function edit(id) { var self = this; $.get(this.editUrl, { id }, function (data) { self.showModal(data); }); }, detail: function detail(id) { var self = this; $.get(this.detailUrl, { id }, function (data) { self.showModal(data); }); }, save: function () { if (this.saveFunction === undefined) { var dataFormSelector = this.dataFormId || "DataForm"; this.dataForm = $(`#${dataFormSelector}`); saveData(this.dataForm, this.modalWindow, this.reloadList, this); } else { this.saveFunction(); } }, delete: function (id) { var data = JSON.stringify({ Id: id }); deleteData(this.deleteUrl, data, this.deleteMessage, this.yesMessage, this.noMessage, this.reloadList, this); }, processResponse: function (response) { processResponse(response, this.dataForm, this.modalWindow, this.reloadList); }, processSimpleReponse: function (response) { processSimpleResponse(response, this.reloadList); }, reloadList: function (form) { if (form === undefined || form === null) { form = this; } var tableSelector = form.tableContainerId === undefined ? "#TableContainer" : `#${form.tableContainerId}`; loadTable(form.tableUrl, tableSelector); } }; function form() { var newForm = Object.create(form.prototype); // Action Url's newForm.tableUrl = ""; newForm.createUrl = ""; newForm.editUrl = ""; newForm.detailUrl = ""; newForm.deleteUrl = ""; // Messages newForm.deleteMessage = ""; newForm.yesMessage = ""; newForm.noMessage = ""; // Custom functions newForm.saveFunction = undefined; // Object Id's newForm.dataFormId = undefined; newForm.tableContainerId = undefined; newForm.modalContainerId = undefined; newForm.modalWindowId = undefined; newForm.modalContainer = null; newForm.modalWindow = null; newForm.dataForm = null; return newForm; }
class FontFaceLoader { constructor(url, name) { this.url = url; this.name = name; this.alreadyLoaded = false; }; load() { return new Promise(function(resolve, reject) { var xhr = new XMLHttpRequest(); xhr.responseType = "blob"; xhr.addEventListener("readystatechange", function(event) { if (event.target.readyState === XMLHttpRequest.DONE) { if (event.target.status === 200) { var reader = new window.FileReader(); reader.onloadend = function() { if (!this.fontFaceExists()) { var style = document.createElement('style'); style.setAttribute('FontFaceLoaderName', this.name); style.appendChild(document.createTextNode('@font-face {font-family: "' + this.name + '"; src: url(' + reader.result + ');}')); document.head.appendChild(style); } else { this.alreadyLoaded = true; } resolve(this); }.bind(this); reader.readAsDataURL(event.target.response); } else { reject('Unable to load font from ' + this.url + ', ' + event.target.status + ': ' + event.target.statusText); } } }.bind(this), false); xhr.open("GET", this.url); if (this.fontFaceExists()) { this.alreadyLoaded = true; resolve(this); } else { xhr.send(); } }.bind(this)); }; fontFaceExists() { return (document.head.querySelector('style[fontfaceloadername="' + this.name + '"]') !== null); }; }; export default FontFaceLoader;
module.exports = { gateway: "http://gateway:8080" };
import React, { Fragment } from 'react'; const Home = () => <Fragment> <h1>Andrew's Awesome Restaurant</h1> <div> <p> I'm here to put good food in your mouth </p> </div> </Fragment> export default Home
const ObjectId = require('mongodb').ObjectId; const db = require('./db').getDb(); const posts = db.collection('posts'); const user = require('./user'); const validationService = require('../service/validation-service'); const _ = require('lodash'); //todo check also the value of keys. Could be empty! const formatPost = (p) => { const fieldsRequired = ['userId', 'title', 'body']; return new Promise((resolve, reject) => { const missingFields = validationService.isValidJson(p, fieldsRequired); if(missingFields !== true) return reject({code: 400, message: `Post not valid missing: ${missingFields}`}); let post = _.pick(p, fieldsRequired); post.score = 0; user.getUserById(post.userId).then(() => { post.userId = ObjectId(post.userId); resolve(post); }).catch(() => { return reject({code: 404, message: 'UserId is not valid'}); }); }); }; module.exports.insert = (post) => { return new Promise((resolve, reject) => { formatPost(post).then(postFormatted => { posts.insertOne(postFormatted).then(post => { resolve(post); }).catch(err => { return reject({code: 500, message: err}); }); }).catch(err => { return reject(err); }); }); }; module.exports.getPosts = () => { return new Promise((resolve, reject) => { posts.find().toArray().then(post => { if(posts.length === 0) return reject({code: 404, message: 'Posts not found'}); resolve(post); }).catch(err => { return reject({code: 500, message: err}); }); }); }; module.exports.getPostById = (postId) => { return new Promise((resolve, reject) => { posts.findOne({_id: ObjectId(postId)}).then(post => { if(!post) return reject({code: 404, message: 'Post not found'}); resolve(post); }).catch(err => { return reject({code: 500, message: err}); }); }); }; module.exports.getPostByUserId = (userId) => { return new Promise((resolve, reject) => { posts.find({userId: ObjectId(userId)}).toArray().then(posts => { if(posts.length === 0) return reject({code: 404, message: 'No posts found'}); resolve(posts) }).catch(err => { return reject({code: 500, message: err}); }); }); };
import React from 'react' import cap from './../images/kozel.png' import bact from './../images/bacteria.png' import './style.css'; import Parallax from "react-rellax/lib"; function caps() { return( <div> <div className='cap1'> <Parallax speed={-5}> <img className='cap1' src={bact}/> </Parallax> <div className="cap2"> <Parallax speed={-10}> <img className='cap2' src={cap}/> </Parallax> </div> </div> </div> ) } export default caps;
import { GET_USER_NOW } from "../action/type"; const initState = { name: "User", avatar: "http://localhost:8000/uploads/1612113710892-profile.jpg", }; const UserNow = (state = initState, action) => { switch (action.type) { case GET_USER_NOW: return { ...state, ...action.payload }; default: return state; } }; export default UserNow;
const template = `<div class="character"> <CharacterBase :uid="data.uid" :name="data.name" :element="data.element" :level="data.level" :fetter="data.fetter" :constellation="data.actived_constellation_num" :id="data.id" ></CharacterBase> <CharacterArtifact :artifactList="artifacts" ></CharacterArtifact> <CharacterWeapon :weapon="data.weapon" ></CharacterWeapon> </div>`; import Vue from "../public/js/vue.js"; import { parseURL, request } from "../public/js/src.js"; import CharacterBase from "./character-base.js"; import CharacterArtifact from "./character-artifact.js"; import CharacterWeapon from "./character-weapon.js"; export default Vue.defineComponent( { name: "CharacterApp", template, components: { CharacterBase, CharacterArtifact, CharacterWeapon }, setup() { const urlParams = parseURL( location.search ); const data = request( `/api/character?qq=${ urlParams.qq }&name=${ urlParams.name }` ); function setStyle( colorList ) { document.documentElement.style.setProperty("--baseInfoColor", colorList[0]); document.documentElement.style.setProperty("--contentColor", colorList[1]); document.documentElement.style.setProperty("--backgroundColor", colorList[2]); document.documentElement.style.setProperty("--elementColor", colorList[3]); document.documentElement.style.setProperty("--titleColor", colorList[4]); document.documentElement.style.setProperty("--splitLineColor", colorList[5]); } switch ( data.element ) { case "Anemo": setStyle([ "rgb( 28, 91, 72)", "rgb( 44, 128, 100)", "rgb( 44, 128, 100)", "rgb( 44, 128, 100)", "rgb( 45, 148, 116)", "rgb( 59, 167, 132)" ]); break; case "Cryo": setStyle([ "rgb( 50, 105, 133)", "rgb( 5, 162, 195)", "rgb( 16, 168, 212)", "rgb( 5, 162, 195)", "rgb( 6, 188, 240)", "rgb( 5, 165, 199)" ]); break; case "Dendro": setStyle([ // 暂无 ]); break; case "Electro": setStyle([ "rgb( 46, 34, 84)", "rgb( 81, 56, 151)", "rgb( 83, 66, 146)", "rgb( 81, 56, 151)", "rgb(117, 93, 195)", "rgb( 80, 55, 161)" ]); break; case "Geo": setStyle([ "rgb( 92, 76, 21)", "rgb(176, 141, 46)", "rgb(201, 144, 20)", "rgb(176, 141, 46)", "rgb(206, 171, 66)", "rgb(210, 155, 21)" ]); break; case "Hydro": setStyle([ "rgb( 23, 64, 91)", "rgb( 43, 127, 175)", "rgb( 37, 106, 153)", "rgb( 43, 127, 175)", "rgb( 77, 162, 211)", "rgb( 42, 123, 174)" ]); break; case "Pyro": setStyle([ "rgb(119, 31, 19)", "rgb(176, 45, 28)", "rgb(189, 46, 29)", "rgb(176, 45, 28)", "rgb(218, 52, 34)", "rgb(191, 61, 27)" ]); break; case "None": setStyle([ "rgb( 72, 72, 72)", "rgb(111, 117, 113)", "rgb(111, 111, 111)", "rgb(111, 117, 113)", "rgb(136, 136, 136)", "rgb(123, 123, 123)" ]); break; } let artifacts = []; for ( let i = 1; i <= 5; i++ ) { const info = data.artifacts.find( el => el.pos === i ); artifacts[i] = info ? info : "empty"; } return { urlParams, data, artifacts } } } );
const logUser = document.querySelector("#logUser"); const logPass = document.querySelector("#logPass"); const lForm = document.querySelector("#lf"); //This is a variable for the expected avatar name //this function filters the localstorage of saved data for a match of the inputted value. function loginCheck(a, b) { let savedData = JSON.parse(localStorage.getItem("details")); let filterArr = savedData.filter(function(item) { return a === item["user Name"] && b === item.password; }); if (filterArr.length > 0) { //this is the value for the moniker expected in the global scope let moniker = filterArr[0]["first Name"]; localStorage.setItem("moniker", JSON.stringify(moniker)); //redirects to the homepage if the inputed value has a match in the local storage return location.replace("crud.html"); } else if (logUser.value === "" || logPass.value === "") { alert("Please put in your details"); } else { alert("Username or Password incorrect!"); } } //This function gets the values from the inputs and runs the loginCheck() function login() { let user = logUser.value; let pass = logPass.value; loginCheck(user, pass); } //This is an event listener for the functions above. lForm.addEventListener("click", login);
/** * Created by Jay on 2016/11/11. */ var path = require('path'); var ROOT_PATH = path.resolve(__dirname); var APP_PATH = path.resolve(ROOT_PATH, ""); var RES_PATH = path.resolve(APP_PATH, ""); var CSS_PATH = path.resolve(RES_PATH, "css"); var JS_PATH = path.resolve(RES_PATH, "js"); var IMG_PATH = path.resolve(RES_PATH, "img"); var TEMPLATE_PATH = path.resolve(APP_PATH, ""); var BUILD_PATH = path.resolve(APP_PATH, "build"); var BUILD_RES_PATH = path.resolve(BUILD_PATH, ""); var gulp = require('gulp'); var seq = require('run-sequence'); /* var concat = require('gulp-concat'); //- 多个文件合并为一个; var minifyCss = require('gulp-minify-css'); //- 压缩CSS为一行; */ var clean = require('gulp-clean'); var rev = require('gulp-rev'); //- 对文件名加MD5后缀 var revCollector = require('gulp-rev-collector'); //- 路径替换 var minify = require('gulp-minifier'); var merge = require('magicfish_web/gulp_plugins/merge'); //- 路径替换 var minifyOpt = { minify: true, collapseWhitespace: true, conservativeCollapse: true, minifyJS: true, minifyCSS: true } gulp.rev = function(taskName, folder) { gulp.task(taskName, function(){ return gulp.src([ '**/*' ], { cwd:path.resolve(RES_PATH, folder) }) .pipe(rev()) .pipe(gulp.dest(path.resolve(BUILD_RES_PATH, folder))) .pipe(rev.manifest()) .pipe(gulp.dest(path.resolve(ROOT_PATH, 'rev/' + folder))); }); } gulp.copy = function(taskName, targets, opt) { gulp.task(taskName, function(){ return gulp.src(targets, opt || { cwd:RES_PATH }) .pipe(gulp.dest(BUILD_RES_PATH)); }); } gulp.task('clean', function() { return gulp.src(BUILD_PATH, { read:false }) .pipe(clean()); }); gulp.copy('css', [ 'css/**/*' ], { base:'.' }); gulp.copy('js', [ 'js/**/*' ], { base:'.' }); gulp.copy('html', [ '*.html' ], { base:'.' }); gulp.task('merge', function() { return gulp.src(['*.html'], { base:"." }) .pipe(merge({ rootPath:APP_PATH, buildPath:BUILD_PATH })) .pipe(gulp.dest(BUILD_PATH)); }); gulp.task('mini_res', function() { return gulp.src(['*.json', '**/*.js', '**/*.css', 'img/*', 'fonts/*', '!modules/temp/*', '!./build/**/*'], { base:"." }) .pipe(minify(minifyOpt)) .pipe(gulp.dest(BUILD_PATH)); }); gulp.task('mini_html', function() { return gulp.src([path.resolve(BUILD_PATH, '**/*.html'), '!' + path.resolve(BUILD_PATH, '**/*.html')], { base:BUILD_PATH }) .pipe(minify(minifyOpt)) .pipe(gulp.dest(path.resolve(BUILD_PATH, ""))); }); gulp.task('end', function() { return gulp.src([ path.resolve(ROOT_PATH, 'rev'), path.resolve(BUILD_PATH, 'temp'), path.resolve(BUILD_PATH, 'gulpfile.js') ], { read:false }) .pipe(clean()); }); gulp.task('build', function(done) { seq('clean', 'mini_res', 'merge', 'end', done); }); gulp.task('default', function(done) { seq('build', done); });
const router = require("express").Router(); const projectFormController = require("../../controllers/projectFormController"); // Matches with "/api/projects" router.route("/") .get(projectFormController.find) .post(projectFormController.create); // Matches with "/api/projects/:id" router .route("/:id") .get(projectFormController.findById) .put(projectFormController.update) .delete(projectFormController.remove); module.exports = router;
require('./index.scss'); require('./base.js'); require('./template.js'); require('./controller.js'); require('./view.js'); require('./model.js'); (function () { 'use strict'; function Todo(name) { this.model = new app.model(); this.template = new app.template(); this.view = new app.view(this.template); this.controller = new app.controller(this.model, this.view); } var todo = new Todo('todos-vanillajs'); }());
const BuildsListingsDefaultState = { msg: "", }; export const getBuildsListingReducer = ( state = BuildsListingsDefaultState, action ) => { switch (action.type) { case "page1": return { ...state, msg: "yash" }; } };
let Tree = require('../../4.trees_and_graphs/Tree'); let Node = require('../../4.trees_and_graphs/Node'); const checkSubtree = require('../../4.trees_and_graphs/10_check_subtree'); test('Found subtree', () => { let tree = new Tree(); const subtreeRoot = new Node(2); tree.root.data = 4; tree.root.left = subtreeRoot; tree.root.right = new Node(6); tree.root.left.left = new Node(1); tree.root.left.right = new Node(3); tree.root.right.left = new Node(5); tree.root.right.right = new Node(7); expect(checkSubtree(tree.root, subtreeRoot)).toBeTruthy(); }) test('Found did not found subtree', () => { let tree = new Tree(); tree.root.data = 4; tree.root.left = new Node(2); tree.root.right = new Node(6); tree.root.left.left = new Node(1); tree.root.left.right = new Node(3); tree.root.right.left = new Node(5); tree.root.right.right = new Node(7); let subtree = new Tree(); subtree.root.data = 2; subtree.root.left = new Node(1); subtree.root.right = new Node(7); expect(checkSubtree(tree.root, subtree.root)).toBeFalsy(); })
"use strict"; var _bl = require("bl"); var _bl2 = _interopRequireDefault(_bl); var _pythonStruct = require("python-struct"); var _pythonStruct2 = _interopRequireDefault(_pythonStruct); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var cluster = require("cluster"); var numCPUs = require("os").cpus().length; function split_key_block_helper(keyBlocks, targetTaskNum) { var _this = this; // this._number_format, this._number_width, this._encoding; // TODO 多线程版本 if (cluster.isMaster) { // master // 需要执行的任务数量 var endTaskNum = 0; console.time("main"); console.log("[master]# Master start runing. pid " + process.pid); var workers = []; for (var i = 0; i < numCPUs; i++) { var worker = cluster.fork(); workers.push(worker); } for (var j = 0; j < targetTaskNum; j++) { console.log("[master]# send message to " + j % numCPUs + ": " + keyBlocks[j].length); workers[j % numCPUs].send(keyBlocks[j]); } // finished handler cluster.on("message", function (worker, message) { console.log("[master]# Worker " + worker.id + " finished: " + message); endTaskNum++; if (endTaskNum == targetTaskNum) { console.timeEnd("main"); cluster.disconnect(); } }); // exit handler cluster.on("exit", function (worker, code, signal) { console.log("[master]# Worker " + worker.id + " died, " + code + ", " + signal); }); } else { process.on("message", function (key_block) { console.log("[worker]# starts calculating"); var start = Date.now(); var splitedKey = _split_key_block(new _bl2.default(key_block), _this._number_format, _this._number_width, _this._encoding); console.log("[Worker]# The result of task " + process.pid + " is " + splitedKey.length + ", taking " + (Date.now() - start) + " ms."); // send message to main process.send(splitedKey); }); } } // Note: for performance, this function will wrappered by // a generator function, so this should return a Promise object function _split_key_block(key_block, _number_format, _number_width, _encoding) { var key_list = []; var key_start_index = 0; var key_end_index = 0; // ------ debug start ---- var count = 0; var skbt1 = new Date().getTime(); // ------ debug ends ---- while (key_start_index < key_block.length) { // nextline for debug count += 1; // const temp = key_block.slice(key_start_index, key_start_index + _number_width); // # the corresponding record's offset in record block var key_id = _pythonStruct2.default.unpack(_number_format, key_block.slice(key_start_index, key_start_index + _number_width))[0]; // # key text ends with '\x00' var delimiter = void 0; var width = void 0; if (_encoding == "UTF-16") { delimiter = "0000"; width = 2; } else { delimiter = "00"; width = 1; } var i = key_start_index + _number_width; while (i < key_block.length) { if (new _bl2.default(key_block.slice(i, i + width)).toString("hex") == delimiter) { key_end_index = i; break; } i += width; } var key_text = this._decoder.decode(key_block.slice(key_start_index + _number_width, key_end_index)); key_start_index = key_end_index + width; key_list.push([key_id, key_text]); // next line is for debug // break; } // ------ debug start ---- var skbt2 = new Date().getTime(); // console.log(`readKey#decodeKeyBlock#readOnce#loop#splitKey#splitKeyBlock counts ${count} times`); // console.log(`readKey#decodeKeyBlock#readOnce#loop#splitKey#splitKeyBlock used ${(skbt2 - skbt1) / 1000.0} s`); // ------ debug ends ---- return key_list; }
import React from 'react' const Message = ({ message }) => { return ( <h2> Form is {message} </h2> ) } export default Message;
P.views.profiles = {};
import { css } from 'emotion' import __css from '@styled-system/css' import Box from '../Box' import { tx, forwardProps } from '../utils' import { baseProps } from '../config' // Default ControlBox props types const PropTypes = [Object, Array] const ControlBox = { name: 'ControlBox', inject: ['$theme'], props: { type: { type: String, default: 'checkbox' }, size: { type: [Number, String, Array], default: 'auto' }, _hover: PropTypes, _invalid: PropTypes, _disabled: PropTypes, _focus: PropTypes, _checked: PropTypes, _child: { type: PropTypes, default: () => ({ opacity: 0 }) }, _checkedAndChild: { type: PropTypes, default: () => ({ opacity: 1 }) }, _checkedAndDisabled: PropTypes, _checkedAndFocus: PropTypes, _checkedAndHover: PropTypes, ...baseProps }, computed: { theme () { return this.$theme() }, className () { const checkedAndDisabled = `input[type=${this.type}]:checked:disabled + &, input[type=${this.type}][aria-checked=mixed]:disabled + &` const checkedAndHover = `input[type=${this.type}]:checked:hover:not(:disabled) + &, input[type=${this.type}][aria-checked=mixed]:hover:not(:disabled) + &` const checkedAndFocus = `input[type=${this.type}]:checked:focus + &, input[type=${this.type}][aria-checked=mixed]:focus + &` const disabled = `input[type=${this.type}]:disabled + &` const focus = `input[type=${this.type}]:focus + &` const hover = `input[type=${this.type}]:hover:not(:disabled):not(:checked) + &` const checked = `input[type=${this.type}]:checked + &, input[type=${this.type}][aria-checked=mixed] + &` const invalid = `input[type=${this.type}][aria-invalid=true] + &` const controlBoxStyleObject = __css({ [focus]: tx(this._focus), [hover]: tx(this._hover), [disabled]: tx(this._disabled), [invalid]: tx(this._invalid), [checkedAndDisabled]: tx(this._checkedAndDisabled), [checkedAndFocus]: tx(this._checkedAndFocus), [checkedAndHover]: tx(this._checkedAndHover), '& > *': tx(this._child), [checked]: { ...tx(this._checked), '& > *': tx(this._checkedAndChild) } })(this.theme) return css(controlBoxStyleObject) } }, render (h) { return h(Box, { class: [this.className], props: { display: 'inline-flex', alignItems: 'center', justifyContent: 'center', transition: 'all 120ms', flexShrink: '0', width: this.size, height: this.size, ...forwardProps(this.$props) }, attrs: { 'aria-hidden': 'true' } }, this.$slots.default) } } export default ControlBox
import React from 'react' import Image from '../../../images/Mask.png' import iphoneImage from '../../../images/iphone_12_PNG22.png' import macAdvertisement from '../../../images/mac-air-advertisement.png' import sonyBraviaBanner from '../../../images/sonyBravia-banner.png' import iphoneBanner from '../../../images/banner.png' import buyIcon from '../../../images/buyIcon.png' import './Main-Banner.css' export default function MainBanner() { return ( <div> {/* <img id='bannerImage' src={Image}></img> <div className="content-left"> <h1>GET THE NEW IPHONE 12</h1> </div> */} <div id="carouselExampleCaptions" class="carousel slide carousel-fade mainBanner" data-bs-ride="carousel"> <div class="carousel-indicators"> <button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="0" class="active" aria-current="true" aria-label="Slide 1"></button> <button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="1" aria-label="Slide 2"></button> <button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="2" aria-label="Slide 3"></button> </div> <div class="carousel-inner"> <div class="carousel-item active"> <img src={iphoneBanner} class="d-block w-100 bannerImage img-fluid" alt="..."/> <div class="carousel-caption text-left d-none d-md-block" style={{left:'8%',top:'5rem'}}> <button className='btn btn-warning btn-lg buyButton' style={{color: '#0302FE'}}>Buy Now <img src={buyIcon} style={{marginLeft:'10px'}}></img></button> {/* <h1 className='bannerCaption'>GET THE NEW IPHONE 12 PRO</h1> */} {/* <p className='captionDescription'>A transportive triple-camera system that adds tons of capability without<br/> complexity.</p> */} </div> {/* <div className='productImages'> <img src={iphoneImage}></img> </div> */} </div> <div class="carousel-item"> <img src={macAdvertisement} className="d-block w-100 bannerImage img-fluid" alt="..."/> </div> <div class="carousel-item"> <img src={sonyBraviaBanner} className="d-block w-100 bannerImage img-fluid" alt="..."/> </div> </div> </div> </div> ) }
module.exports = function(mongoose, CONFIG) { var schema = new mongoose.Schema({ text: String, howWeWork: String, sessions: [{ sessionType: { type: String, }, price: { type: String, }, noOfSessions: { type: String, } }], trainers: [{ trainerId: { type: String, }, name: { type: String, }, type: { type: String, } }] }); var coll = mongoose.model('sessions', schema); return coll; }
(function() { // 这些变量和函数的说明,请参考 rdk/app/example/web/scripts/main.js 的注释 var imports = [ 'rd.controls.Selector' ]; var extraModules = [ ]; var controllerDefination = ['$scope','EventService','EventTypes', main]; function main(scope,EventService,EventTypes) { scope.allItems = [ { id: 0, label: "江苏省" }, { id: 1, label: "浙江省" }, { id: 2, label: "广东省" }, { id: 3, label: "广西省" }, { id: 4, label: "河北省" }, { id: 5, label: "河南省" }, { id: 6, label: "湖北省" }, { id: 7, label: "湖南省" }, { id: 8, label: "新疆省" }, { id: 9, label: "四川省" } ]; scope.groupByFun = function(item) { if (item.id < 3) { return 'theme1'; } else if (item.id < 5) { return 'theme2'; } else { return 'theme3'; } } scope.dimSelectedItems = [ { id: 1, label: "浙江省" }, { id: 3, label: "广西省" }, { id: 5, label: "河南省" } ]; //根据同一个groupBy EventService.register("selectorID", EventTypes.CHANGE, function(event, data) { console.log(data);//发生变化的那组 }); scope.changeSelectedItems = function(){ EventService.broadcast("selectorID", EventTypes.SELECT, [{ id: 7, label: "湖南省" }, { id: 8, label: "新疆省" }, { id: 9, label: "四川省" }]); } scope.close = function(){ EventService.broadcast("selectorID", EventTypes.CLOSE); } scope.open = function(){ EventService.broadcast("selectorID", EventTypes.OPEN); } } var controllerName = 'DemoController'; //========================================================================== // 从这里开始的代码、注释请不要随意修改 //========================================================================== define(/*fix-from*/application.import(imports)/*fix-to*/, start); function start() { application.initImports(imports, arguments); rdk.$injectDependency(application.getComponents(extraModules, imports)); rdk.$ngModule.controller(controllerName, controllerDefination); } })();
exports.handler = function (event, context, callback) { if (event.queryStringParameters!=null && event.queryStringParameters.id != null) { var id = event.queryStringParameters.id; var http = require("https"); var options = { "method": "GET", "hostname": "widget.kkbox.com", "port": null, "path": "/v1/?id=" + id + "&type=song&autoplay=true" }; var req = http.request(options, function (res) { var chunks = []; res.on("data", function (chunk) { chunks.push(chunk); }); res.on("end", function () { var body = Buffer.concat(chunks); var regex = /&quot;trial_url&quot;:&quot;(.+?)&quot;/g; var matchs = body.toString().match(regex); var match = RegExp.$1; var response = { "statusCode": 200, "headers": { "Access-Control-Allow-Origin": "*" }, "body": JSON.stringify({resultCode:1,content:match}), "isBase64Encoded": false }; callback(null, response); }); }); req.end(); }else{ callback(null, { "statusCode": 200, "headers": { "Access-Control-Allow-Origin": "*" }, "body": JSON.stringify({resultCode:0}), "isBase64Encoded": false }); } }
export const FETCH_COLORS_REQUEST = 'FETCH_COLORS_REQUEST' export const FETCH_COLORS_SUCCESS = 'FETCH_COLORS_SUCCESS' export const FETCH_COLORS_FAILURE = 'FETCH_COLORS_FAILURE' import { CALL_API } from '../middleware/api' import { config } from '../config.js' export function fetchColors() { return { [CALL_API]: { endpoint: '/api/v1/colors/', authenticated: true, types: [FETCH_COLORS_REQUEST, FETCH_COLORS_SUCCESS, FETCH_COLORS_FAILURE] } } }
import gulp from 'gulp'; import gulpLoadPlugins from 'gulp-load-plugins'; const plugins = gulpLoadPlugins(); gulp.task('lint', () => gulp.src( [ 'gulpfile.babel.js', './config/**/*.js', '.app/**/*.js' ] ) .pipe(plugins.jshint()) .pipe(plugins.livereload())); gulp.task('transpile', ['public'], () => { gulp.src( [ './**/*.js', '!dist/**', '!node_modules/**', '!bower_components/**', '!public/lib/**' ] ) .pipe(plugins.babel({ presets: ['es2015'] })) .pipe(gulp.dest('dist')); }); gulp.task('serve', ['public'], () => { plugins.nodemon({ watch: ['./dist', './app', './config', './public'], script: 'dist/server.js', ext: 'js html jade', env: { NODE_ENV: 'development' } }); }); gulp.task('sass', () => gulp.src('./public/**/*.scss') .pipe(plugins.sass().on('error', plugins.sass.logError)) .pipe(gulp.dest('./dist/css')) .pipe(plugins.livereload())); gulp.task('jasmine', () => { gulp.src('./test/**/*.js') .pipe(plugins.jasmine()); }); gulp.task('test', () => gulp.src( [ './dist/test/game/game.js', './dist/test/user/model.js' ], { read: false } ) .pipe(plugins.coverage.instrument({ pattern: ['**/test*'], debugDirectory: 'debug' })) .pipe(plugins.mocha({ timeout: 15000 })) .pipe(plugins.coverage.gather()) .pipe(plugins.coverage.format()) .pipe(gulp.dest('reports'))); gulp.task('watch', () => { plugins.livereload.listen(); gulp.watch('./public/**/*.scss', ['sass', 'transpile']); gulp.watch('./public/**/*.html', ['sass', 'transpile']); gulp.watch('./public/**/*.css', ['sass', 'transpile']); gulp.watch('./public/**/*.js', ['sass', 'transpile']); }); gulp.task('coveralls', ['test'], () => gulp.src('coverage/lcov.info') .pipe(plugins.coveralls()) .pipe(plugins.exit())); gulp.task('public', () => gulp.src([ './public/**/*', './app/**/*', './config/**/*', './css/**/*', 'test/**/*' ], { base: './' }) .pipe(gulp.dest('dist'))); gulp.task('coverage', (cb) => { gulp.src(['app/**/*.js', 'config/**/*.js']) .pipe(plugins.babel()) .pipe(plugins.istanbul()) .pipe(plugins.istanbul.hookRequire()) .on('finish', () => { gulp.src( [ ('./test/**/*.js') ] ) .pipe(plugins.babel()) .pipe(plugins.injectModules()) .pipe(plugins.jasmine()) // .pipe(plugins.istanbul.writeReports()) .pipe(plugins.istanbul.enforceThresholds({ thresholds: { global: 20 } })) .on('end', cb); }); }); gulp.task('coveralls', ['coverage'], () => gulp.src('coverage/lcov.info') .pipe(plugins.coveralls()) .pipe(plugins.exit())); gulp.task('bower', () => { plugins.bower({ directory: './bower_components' }) .pipe(gulp.dest('./public/lib')); }); gulp.task('default', ['bower', 'transpile', 'serve', 'watch']);
import { Component, Directive, TemplateRef, ViewContainerRef, Injector, ComponentFactoryResolver, Renderer } from '@angular/core'; @Component({ selector: 'alert', template: ` <div class="alert alert-success" role="alert"> <ng-content></ng-content> </div> ` }) export class AlertComponent { } @Directive({ selector: 'template[alert]' }) export class AlertDirective { constructor( templateRef: TemplateRef, viewContainerRef: ViewContainerRef, injector: Injector, componentFactoryResolver: ComponentFactoryResolver, renderer: Renderer ) { this.templateRef = templateRef; this.viewContainerRef = viewContainerRef; this.injector = injector; this.componentFactoryResolver = componentFactoryResolver; this.renderer = renderer; } ngOnInit() { this._windowFactory = this.componentFactoryResolver.resolveComponentFactory(AlertComponent); const nodes = this.getContentNodes(this.templateRef); this._windowRef = this.viewContainerRef.createComponent(this._windowFactory, 0, this.injector, nodes); console.log('This is your AlertComponent instance: ', this._windowRef.instance); } getContentNodes(content) { if (!content) { return []; } else if (content instanceof TemplateRef) { return [this.viewContainerRef.createEmbeddedView(content).rootNodes]; } else { return [[this.renderer.createText(null, `${content}`)]]; } } } /* Gist: https://gist.github.com/tsm91/d9d65e8c688a7ac526e25602a9a086db Usage: @Component({ selector: 'home-page', directives: [AlertComponent, AlertDirective], precompile: [AlertComponent], template: ` <div> <p *ngFor="let alert of alerts"> <template alert>{{ alert }}</template> </p> <button class="btn btn-primary" (click)="addAlert()">Add Alert</button> </div> ` }) export class HomePageComponent { alerts = []; addAlert() { this.alerts.push('This is a dynamically created alert component.'); } } */
import React from 'react'; import PropTypes from 'prop-types'; import { Redirect } from 'react-router-dom'; import DateRangePicker from '@wojtekmaj/react-daterange-picker'; import { MDBAutocomplete } from 'mdbreact'; import { languageHelper } from '../../../tool/language-helper'; import { removeUrlSlashSuffix } from '../../../tool/remove-url-slash-suffix'; import Select from '../general-component/select-with-search/select-with-search'; // import { select } from 'glamor'; // import * as tim from '../../../tim/sdk/webim'; // import * as json2 from '../../../tim/sdk/json2'; // import {webimLogin} from '../../../tim/js/login/login'; class ZepeiReact extends React.Component { constructor(props) { super(props); // state this.state = { date: [new Date(), new Date()], options: [ // {id: 1, label: "Alabama"},{id: 2, label: "Alaska"} 'Alabama', 'Alaska' ] }; // i18n this.text = ZepeiReact.i18n[languageHelper()]; } onChange = date => { this.setState({ date }); }; handleSelectChange = () => { // console.log(selected); }; logValue = () => { // console.log(value); }; render() { const pathname = removeUrlSlashSuffix(this.props.location.pathname); if (pathname) { return <Redirect to={pathname} />; } let id = 1400184624; let sig = 'eJxlj1FPgzAYRd-5FYTXGfdRqFlM9oAMJ0lxIW7G*UIaWliZQG3LmFv870bUiPG*nnNzc8*WbdvOmjxc0jxvu8Zk5k1yx762HXAufqGUgmXUZJ5i-yA-SqF4RgvD1QBdjDECGDuC8caIQnwbG82VP8Ka7bNh46vvA7gz-wr9UUQ5wCRKw3jJp3HxWAXBiTAiYUHyoDvBKix36eRusSTlfVSVU3zc40MgbspeSzl5UUlDSbjqk81a*W0dv1b0dkujZ9W1qE41PO22-Xw*mjSi5j*HwMPIn40vHbjSom0GAYGLXeTBZxzr3foAMUZdvg__'; let imURL = `http://127.0.0.1:8080?id=${id}&sig=${sig}`; return ( <div> <div className="cell-wall"> <div className="cell-membrane"> <div style={{ textAlign: 'center', padding: '30px 30px', boxSizing: 'border-box', }} > <iframe frameBorder="0" src={imURL} style={{ height: `${((1032 * 0.55) / 1280) * 100}vw`, width: `${((1761 * 0.55) / 1280) * 100}vw`, }} /> </div> <DateRangePicker onChange={this.onChange} value={this.state.date} /> <Select title="学校名称" handleSelectChange={this.handleSelectChange} items={[ { checked: false, disabled: false, icon: null, text: '乔治华盛顿大学', value: '1', }, { checked: false, disabled: false, icon: null, text: '加州大学圣地亚哥大学', value: '2', }, { checked: false, disabled: false, icon: null, text: '北京王府学校', value: '3', }, ]} /> <MDBAutocomplete data={this.state.options} label="Choose your favorite state" clear id="input" getValue={this.logValue} /> </div> </div> </div> ); } } ZepeiReact.i18n = [{}, {}]; ZepeiReact.propTypes = { // self // React Router match: PropTypes.object.isRequired, history: PropTypes.object.isRequired, location: PropTypes.object.isRequired, }; export const Zepei = ZepeiReact;
import React from 'react'; import {Text, TouchableOpacity} from 'react-native'; const BottomMenuCounter = (props) => { const {onPress, children} = props; const {buttonStyle, textStyle} = style; return ( <TouchableOpacity style={[buttonStyle, props.style]} onPress={onPress}> <Text style={[textStyle, props.textStyle]}> {children} </Text> </TouchableOpacity> ) } const style = { textStyle: { fontFamily: 'SFUIText-Medium', color: '#1b1b1b', fontSize: 8, margin: 2 }, buttonStyle: { position: 'absolute', top: 0, left: -25, minWidth: 15, backgroundColor: '#ffc200', borderRadius: 12, flexDirection: 'row', paddingHorizontal: 2, alignSelf: 'center', justifyContent: 'center', } } export {BottomMenuCounter};
import React from 'react' import { Redirect } from 'react-router' import axios from "axios"; import { Dropdown, DropdownToggle, DropdownMenu, DropdownItem, NavLink } from 'reactstrap'; // Import authContext to check for authentication state; navbarContext to fetch username to render import { useAuthContext } from '../../services/AuthReducer' import { useNavbarContext } from "../Navbar.components" const NavbarProfile = () => { const auth = useAuthContext(); const navbarContext = useNavbarContext(); // FUNCTIONAL HOOKS const [dropDownState, setDropDownState] = React.useState(false) const onFireDropDown = () => {setDropDownState(!dropDownState)} // REDIRECT HOOKS const [fireRedirectProfile, setFireRedirectProfile] = React.useState(false) const onFireRedirectProfile = () => setFireRedirectProfile(true) const [fireRedirectHome, setFireRedirectHome] = React.useState(false) const onFireRedirectHome = () => {setFireRedirectHome(true)} // Define logout function const onSubmitLogout = async (e) => { try { const res = await axios.post(`${process.env.REACT_APP_BASE_SERVER_URL}/users/logout`, {}, {withCredentials: true}); if (!res.data.error) { auth.handleLogout(); onFireRedirectHome(e) } } catch (err) { throw new Error(err) } }; return ( <> {fireRedirectProfile && <Redirect to="/profile"> push={true} </Redirect>} {fireRedirectHome && <Redirect to="/"> push={true} </Redirect>} <NavLink> <Dropdown hidden={!auth.state.isAuthenticated} isOpen={dropDownState} toggle={onFireDropDown}> <DropdownToggle outline className="btn-dropdown btn-round" caret> <p>{navbarContext.userState.username}</p> </DropdownToggle> <DropdownMenu> <DropdownItem><div onClick = {() => {onFireRedirectProfile()}}>View Profile</div></DropdownItem> <DropdownItem><div onClick = {() => {onSubmitLogout()}}>Logout</div></DropdownItem> </DropdownMenu> </Dropdown> </NavLink> </> ) }; export default NavbarProfile;
$(function() { var rcsdk = null; var platform = null; var subscriptions = null; var loggedIn = false; var rcWebPhone = null; var rcCall = null; var redirectUri = getRedirectUri(); var defaultClientId = ''; var $app = $('#app'); var $authFlowTemplate = $('#template-auth-flow'); var $callTemplate = $('#template-call'); var $callControlTemplate = $('#template-call-control'); var $incomingCallTemplate = $('#template-incoming'); var $callPage = null; var $loadingModal = $('.loading-modal'); function getRedirectUri() { if (window.location.pathname.indexOf('/index.html') > 0) { return window.location.protocol + '//' + window.location.host + window.location.pathname.replace('/index.html', '') + '/redirect.html'; } return window.location.protocol + '//' + window.location.host + window.location.pathname + 'redirect.html'; } function cloneTemplate($tpl) { return $($tpl.html()); } function initCallSDK({ clientId }) { return platform.post('/restapi/v1.0/client-info/sip-provision', { sipInfo: [{transport: 'WSS'}] }).then(function (res) { return res.json() }).then(function(sipProvision) { rcWebPhone = new RingCentral.WebPhone(sipProvision, { clientId, appName: 'RingCentral Call Demo', appVersion: '0.0.1', logLevel: 2 }); window.addEventListener('unload', function () { if (rcWebPhone) { rcWebPhone.userAgent.stop(); } }); rcCall = new RingCentralCall({ webphone: rcWebPhone, sdk: rcsdk, subscriptions }) window.rcCall = rcCall }); } function showCallPage() { $loadingModal.modal('show'); $callPage = cloneTemplate($callTemplate); var $callType = $callPage.find('select[name=callType]').eq(0); var $deviceSelect = $callPage.find('select[name=device]').eq(0); var $phoneNumber = $callPage.find('input[name=number]').eq(0); var $fromNumberSelect = $callPage.find('select[name=fromNumber]').eq(0); var $deviceRefresh = $callPage.find('.device-refresh').eq(0); var $callForm = $callPage.find('.call-out-form').eq(0); var $logout = $callPage.find('.logout').eq(0); var $deviceRow = $callPage.find('#device-row').eq(0); var $fromNumberRow = $callPage.find('#from-number-row').eq(0); function refreshDevices() { $deviceSelect.empty(); var devices = rcCall.devices.filter(function(d) { return d.status === 'Online' }); if (devices.length === 0) { $deviceSelect.append('<option value="">No device availiable</option>'); return; } devices.forEach(function (device) { $deviceSelect.append('<option value="' + device.id + '">' + device.name + '</option>') }); } function refreshFromNumbers() { $fromNumberSelect.empty(); platform.get('/restapi/v1.0/account/~/extension/~/phone-number').then(function (response) { return response.json(); }).then(function (data) { var phoneNumbers = data.records; phoneNumbers.filter(function(p) { return (p.features && p.features.indexOf('CallerId') !== -1) || (p.usageType === 'ForwardedNumber' && p.status === 'PortedIn'); }).forEach(function (p) { $fromNumberSelect.append('<option value="' + p.phoneNumber + '">' + p.phoneNumber + '-' + p.usageType + '</option>') }); }) } function onInitializedEvent() { refreshDevices(); refreshFromNumbers(); refreshCallList(); rcCall.sessions.forEach(function(session) { session.on('status', function() { refreshCallList(); }); }); $('.modal').modal('hide'); } if (rcCall.webphoneRegistered || rcCall.callControlReady) { onInitializedEvent(); } rcCall.on('webphone-registration-failed', onInitializedEvent); rcCall.on('call-control-ready', onInitializedEvent); if ($callType.val() === 'webphone') { $deviceRow.hide(); } $callType.on('change', function () { if ($callType.val() === 'webphone') { refreshFromNumbers(); $deviceRow.hide(); $fromNumberRow.show(); } else { refreshDevices(); $deviceRow.show(); $fromNumberRow.hide(); } }) rcCall.on('new', function(session) { // console.log('new'); // console.log(JSON.stringify(session.data, null, 2)); refreshCallList(); session.on('status', function(event) { // console.log(event); refreshCallList(); }); if (session.direction === 'Inbound') { showIncomingCallModal(session); } }); $callForm.on('submit', function(e) { e.preventDefault(); e.stopPropagation(); var deviceId = $deviceSelect.val(); var phoneNumber = $phoneNumber.val(); var fromNumber = $fromNumberSelect.val(); var callType = $callType.val(); var params = {}; if (phoneNumber.length > 5) { params.phoneNumber = phoneNumber; } else { params.extensionNumber = phoneNumber; } rcCall.makeCall({ type: callType, toNumber: phoneNumber, fromNumber, deviceId, }).then(function (session) { showCallControlModal(session); refreshCallList(); session.on('status', function() { refreshCallList(); }); }); }); $deviceRefresh.on('click', function(e) { e.preventDefault(); rcCall.callControl.refreshDevices().then(function () { refreshDevices(); }); }); $logout.on('click', function(e) { e.preventDefault(); platform.logout().then(function () { window.location.reload(); }); }); $app.empty().append($callPage); document.addEventListener('click', (event) => { var target = event.target; if (target.nodeName !== 'TD') { return; } var sessionId = target.parentElement.getAttribute('data-id'); if (!sessionId) { return; } var session = rcCall.sessions.find(s => s.id === sessionId); if (!session) { return; } var status = session.status; var party = session.party; if (status === 'VoiceMail' || status === 'Disconnected' || !party) { return; } if ((status === 'Proceeding' || status === 'Setup') && party.direction === 'Inbound') { showIncomingCallModal(session); return; } showCallControlModal(session); }); } function refreshCallList() { var $callList = $callPage.find('.call-list').eq(0); $callList.empty(); rcCall.sessions.forEach(function (session) { if (!session.party) { return; } $callList.append( '<tr data-id="' + session.id + '">' + '<td>' + session.direction + '</td>' + '<td>' + session.from.phoneNumber + '</td>' + '<td>' + session.to.phoneNumber + '</td>' + '<td>' + session.status + '</td>' + '<td>' + session.otherParties.map(p => p.status.code).join(',') + '</td>' + '</tr>' ) }); } function showCallControlModal(session) { var $modal = cloneTemplate($callControlTemplate).modal(); var $transferForm = $modal.find('.transfer-form').eq(0); var $transfer = $modal.find('input[name=transfer]').eq(0); var $from = $modal.find('input[name=from]').eq(0); var $to = $modal.find('input[name=to]').eq(0); var $myStatus = $modal.find('input[name=myStatus]').eq(0); var $otherStatus = $modal.find('input[name=otherStatus]').eq(0); var $switchBtn = $modal.find('.switch').eq(0); function refreshPartyInfo() { $from.val(session.from.phoneNumber); $to.val(session.to.phoneNumber); $myStatus.val(session.status); $otherStatus.val(session.otherParties.map(p => p.status.code).join(',')); } refreshPartyInfo(); $modal.find('.hangup').on('click', function() { session.hangup(); $modal.modal('hide'); }); $modal.find('.mute').on('click', function() { session.mute().then(function() { console.log('muted'); }).catch(function(e) { console.error('mute failed', e.stack || e); }); }); $modal.find('.unmute').on('click', function() { session.unmute().then(function() { console.log('unmuted'); }).catch(function(e) { console.error('unmute failed', e.stack || e); }); }); $modal.find('.hold').on('click', function() { session.hold().then(function() { console.log('Holding'); }).catch(function(e) { console.error('Holding failed', e.stack || e); }); }); $modal.find('.unhold').on('click', function() { session.unhold().then(function() { console.log('UnHolding'); }).catch(function(e) { console.error('UnHolding failed', e.stack || e); }); }); $modal.find('.startRecord').on('click', function() { const recordingId = session.recordings[0] && session.recordings[0].id; session.startRecord({ recordingId }).catch(function(e) { console.error('create record failed', e.stack || e); }); }); $modal.find('.stopRecord').on('click', function() { if (session.recordings.length === 0) { return; } const recordingId = session.recordings[0] && session.recordings[0].id; session.stopRecord({ recordingId }).then(function() { console.log('recording stopped'); }).catch(function(e) { console.error('stop recording failed', e.stack || e); }); }); $transferForm.on('submit', function (e) { e.preventDefault(); e.stopPropagation(); var phoneNumber = $transfer.val(); session.transfer(phoneNumber).then(function () { console.log('transfer success'); }).catch(function(e) { console.error('transfer failed', e.stack || e); }); }); session.on('status', function() { refreshPartyInfo(); }); session.on('disconnected', function() { $modal.modal('hide'); }); $switchBtn.css('display', 'inline-block'); if (session.webphoneSession) { $switchBtn.css('display', 'none'); } $switchBtn.on('click', function () { $switchBtn.html('Switching') rcCall.switchCall(session.id).finally(function () { $switchBtn.html('Switch'); }); }); session.on('webphoneSessionConnected', function () { $switchBtn.css('display', 'none'); }); } function showIncomingCallModal(session) { var $modal = cloneTemplate($incomingCallTemplate).modal(); var $from = $modal.find('input[name=from]').eq(0); var $to = $modal.find('input[name=to]').eq(0); var $forwardForm = $modal.find('.forward-form').eq(0); var $forward = $modal.find('input[name=forward]').eq(0); var $answer = $modal.find('.answer').eq(0); $from.val(session.from.phoneNumber); $to.val(session.to.phoneNumber); $modal.find('.toVoicemail').on('click', function() { session.toVoicemail(); }); if (!session.webphoneSessionConnected) { $answer.hide(); session.on('webphoneSessionConnected', function () { $answer.show(); }); } $answer.on('click', function() { if (session.webphoneSession) { session.answer(); } }); $forwardForm.on('submit', function (e) { e.preventDefault(); e.stopPropagation(); var phoneNumber = $forward.val(); var params = {}; if (phoneNumber.length > 5) { params.phoneNumber = phoneNumber; } else { params.extensionNumber = phoneNumber; } session.telephonySession.forward(params).then(function () { console.log('forwarded'); }).catch(function(e) { console.error('forward failed', e.stack || e); }); }); session.on('disconnected', function() { $modal.modal('hide'); }); var hasAnswered = false; session.on('status', function() { if (!hasAnswered && session.status === 'Answered') { hasAnswered = true; $modal.modal('hide'); showCallControlModal(session); } }); } function onLoginSuccess(server, clientId) { localStorage.setItem('rcCallDemoServer', server || ''); localStorage.setItem('rcCallDemoClientId', clientId || ''); initCallSDK({ clientId }).then(function () { showCallPage(); }); } function show3LeggedLogin(server, clientId) { rcsdk = new RingCentral.SDK({ cachePrefix: 'rc-call-demo', clientId: clientId, server: server, redirectUri: redirectUri }); subscriptions = new RingCentral.Subscriptions({ sdk: rcsdk }); platform = rcsdk.platform(); var loginUrl = platform.loginUrl({ usePKCE: true }); platform.loggedIn().then(function(isLogin) { loggedIn = isLogin; if (loggedIn) { onLoginSuccess(server, clientId); return; } platform.loginWindow({ url: loginUrl }) .then(function (loginOptions){ return platform.login(loginOptions); }) .then(function() { onLoginSuccess(server, clientId); }) .catch(function(e) { console.error(e.stack || e); }); }); }; function init() { var $authForm = cloneTemplate($authFlowTemplate); var $server = $authForm.find('input[name=server]').eq(0); var $clientId = $authForm.find('input[name=clientId]').eq(0); var $redirectUri = $authForm.find('input[name=redirectUri]').eq(0); $server.val(localStorage.getItem('rcCallDemoServer') || RingCentral.SDK.server.sandbox); $clientId.val(localStorage.getItem('rcCallDemoClientId') || defaultClientId); $redirectUri.val(redirectUri); $authForm.on('submit', function(e) { e.preventDefault(); e.stopPropagation(); show3LeggedLogin($server.val(), $clientId.val()); }); $app.empty().append($authForm); } init(); });
var Crypto = require("crypto-js"); const Bcrypt = require("bcrypt"); const key = "Aashgdhgafdhgfdjhafsghdfajshdf"; function crypto(){ function cryptPassword(password){ const hash = Bcrypt.hashSync(password, 10); return hash; } function compare(password1, hash) { return Bcrypt.compareSync(password1, hash); } function getEncrypt(input) { const enc = Crypto.AES.encrypt(input, key); return enc.toString(); } function getDecrypt(input) { const dec = Crypto.AES.decrypt(input, key); return dec.toString(Crypto.enc.Utf8); } return { getEncrypt: getEncrypt, getDecrypt: getDecrypt, cryptPassword: cryptPassword, compare: compare } } module.exports = crypto();
// Define the options of our application const Game = { data() { return { playerName: '', gameStarted: false, usedLetters: [], currentAnswer: [], randomAnswer: {}, guessNum: 0, roundOver: false, rounds: [], answers: [ { answer: "birthday", hint: "Annual celebration" }, { answer: "kremlin", hint: "Russia's Whitehouse." }, { answer: "andromeda", hint: "A galaxy not so far away." }, { answer: "elated", hint: "Happy." }, { answer: "hydrogen", hint: "Sun fuel." }, { answer: "lakshmi", hint: "Mother goddess." }, { answer: "sodium", hint: "Salt of the earth." }, { answer: "mordor", hint: "One does not simply walk." }, { answer: "maradona", hint: "Hand of God (sports)." }, { answer: "satoshi", hint: "Elusive cryptocurrency genius." } ] } }, computed: { roundWon() { let fullCurrentAnswer = this.currentAnswer.join(""); return (fullCurrentAnswer == this.randomAnswer.answer); }, allWins() { let wonRounds = this.rounds.filter( w => w.won); return wonRounds.length; }, allLosses() { let lostRounds = this.rounds.filter( l => !l.won); return lostRounds.length; } }, methods: { /** * Initializes the properties of a guess. * A random answer is selected from the array of possible answers. The current answer which is * essentially the users guess is initialized to an array of dashes (-) */ initGuess() { let rnd = Math.floor(Math.random() * Math.floor(this.answers.length)); let rndAnswer = {}; let answer = this.answers[rnd]; rndAnswer.index = rnd; rndAnswer.answer = answer.answer; rndAnswer.hint = answer.hint; this.randomAnswer = rndAnswer; this.currentAnswer = '-'.repeat(answer.answer.length).split(''); }, /** * Starts the game. The player name must not be empty. The first guess is initialized. */ startGame() { if(this.playerName.trim().length > 0) { this.gameStarted = true } this.initGuess(); }, /** * Invoked at the end of each round via an event. * @param event */ closeRound(event) { let round = {}; let fullCurrentAnswer = this.currentAnswer.join(""); round.won = (fullCurrentAnswer == this.randomAnswer.answer); this.rounds.push(round); this.roundOver = false; this.guessNum = 0; this.initGuess(); }, /** * Processes a guess from the user. The event is propagated with information * about the current user guess which is a single letter and the index of the answer that it needs to be checked against. * @param event The event */ processGuess(event) { let guessedLetter = event.guess; let correctAnswer = this.answers[event.index].answer; //ensure the letter is actually numeric if((/[a-zA-Z]/).test(guessedLetter)) { let guessedRight = false; let foundLetters = 0; //loop through all letters to see if the match the guessed letter for(let i = 0; i < correctAnswer.length; i++) { if(correctAnswer[i] === guessedLetter) { this.currentAnswer[i] = guessedLetter; foundLetters++; } } guessedRight = (foundLetters > 0); if(guessedRight) { let fullCurrentAnswer = this.currentAnswer.join(""); if(fullCurrentAnswer === this.randomAnswer.answer) { this.roundOver = true; } }else { this.guessNum++; if(this.guessNum == 6) { this.roundOver = true; } } } } }, }; /** * A component that represents a user's guess. */ const PlayerGuess = { name: 'PlayerGuess', data() { return { playerGuess: '', currentLetter: '', usedLetters: '' } }, props: { answer: Object, ans: Array, guessingOver: Boolean }, computed: { correctAnswer() { return this.answer.answer; }, hint() { return this.answer.hint; }, dashes() { let word = '-'.repeat(this.answer.answer.length); return word; } }, methods: { /** * Updates letters already used. * @param l * @returns */ updateUsedLetters(l) { let found = false; let letter = l.toLowerCase(); for( let i =0; i < this.usedLetters.length;i++) { if(this.usedLetters[i].toLowerCase() === letter) { found = true; break; } } if(!found) { this.usedLetters += letter; return true; } return false; }, submitGuess() { if(this.currentLetter.length > 0 && this.updateUsedLetters(this.currentLetter)) { this.playerGuess += this.currentLetter; let lastGuess = {}; lastGuess.index = this.answer.index; lastGuess.guess = this.currentLetter this.currentLetter = ''; this.$emit('guessed-letter',lastGuess); } }, nextRound() { this.usedLetters = ''; this.$emit('round-over'); } }, template: '#player-guess' } /* * A Hangman State component. Holds state of current game with images */ const HangmanState = { name: 'HangmanState', data() { return { maxState: 6, images: [ 'images/hangman0.png', 'images/hangman1.png', 'images/hangman2.png', 'images/hangman3.png', 'images/hangman4.png', 'images/hangman5.png', 'images/hangman6.png' ], hangman: false, currentImage: 'images/hangman0.png', } }, props: ['state'], template: '#hangman-state' }; const app = Vue.createApp(Game); app.component('hangman-state',HangmanState); app.component('player-guess',PlayerGuess); // Create a new Vue instance using our options app.mount('#app');
$(document).ready(function () { showMap(document.getElementById("map"), 50, 20); function showMap(mapElement, lat, lon) { var center = new google.maps.LatLng(lat, lon); var marker = new google.maps.Marker({ position: center, animation: google.maps.Animation.BOUNCE, label: "I am draggable!", draggable: true }); var mapProp= { center: center, zoom: 10, disableDefaultUI: true, mapTypeId: 'terrain' }; var map =new google.maps.Map(mapElement, mapProp); marker.setMap(map); } });
import http from "../../HTTP/http" import { useEffect, useState } from "react" import { useParams } from "react-router-dom" import CardServico from '../../Componentes/CardServico' const Servico = () => { const {id} = useParams() const [servico, setServico] = useState({}) useEffect(() => { http.get('servicos/'+id) .then(response => setServico(response.data)) }, [id]) return( <CardServico nome={servico.nome} preco={servico.preco} id={servico.id} /> ) } export default Servico
import React, {useState} from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import style from './Tabs.module.css'; const Tabs = props => { const [selectedTabIndex, changeSelectedTab] = useState(0); const tabs = props.children.map((item, index) =>( <li className={classNames(style.tab, index === selectedTabIndex && style.selected)} key = {index} onClick={() =>changeSelectedTab(index)} > {item.props.title} </li> )); return ( <div> <ul className={style.list}> {tabs} </ul> <div className={style.tab}>{props.children[selectedTabIndex]}</div> </div> ); }; Tabs.propTypes = { }; export default Tabs;
import React from 'react' import styled from 'styled-components' import { withSnackbar } from 'notistack' const StyledNav = styled.nav` border-right: 1px solid white; min-height: 83vh; min-width: 15vw; ` const NavBar = (props) => ( <StyledNav> This is the Nav Bar. </StyledNav> ) export default withSnackbar(NavBar)
export const INCURSION_ENTRY = 'INCURSION_ENTRY' export const incursionEntry = payload => ({ type: INCURSION_ENTRY, payload })
function reverseString(str) { let reversedString = ''; for (i = str.length - 1; i >= 0; i--) { reversedString += str[i]; } return reversedString; } if (require.main === module) { console.log(reverseString('hi')) console.log("Expecting: 'ih'"); console.log("=>", reverseString('ih')); console.log(""); console.log(reverseString("catbaby")); console.log("Expecting: 'ybabtac'"); console.log("=>", reverseString('catbaby')); } module.exports = reverseString; // Please add your pseudocode to this file // create empty string // iterate str backward // add the charater at i to the empty string
const router = require('koa-router')() const { login } = require('../controller/user') const { SuccessModel, ErrorModel } = require('../model/resModel') router.prefix('/api/user') router.post('/login', async function(ctx, next) { const { username, password } = ctx.request.body const user = await login(username, password) if (user.username) { // 操作cookie // res.setHeader('Set-Cookie', `username=${user.username}; path=/; httpOnly; expires=${getCookieExpires()}`) ctx.session.username = user.username ctx.session.realname = user.realname ctx.body = new SuccessModel() return } ctx.body = new ErrorModel('登录失败') }); router.get('/session-test', async function(ctx, next) { if (ctx.session.viewCount == null) { ctx.session.viewCount = 0 } ctx.session.viewCount++ ctx.body = { errorno: 0, viewCount: ctx.session.viewCount } }) module.exports = router
const commentsReducer = (state = [], action) => { switch (action.type) { case "loadComments": if (action.comments === undefined) { return []; } // return { ...state, post: action.comments }; return { ...state, [action.postId]: action.comments }; default: return state; } }; export default commentsReducer;
function remainder(num1,num2) { return num1%num2; } console.log(remainder(1,3)); console.log(remainder(3,4)); console.log(remainder(-9,45)); console.log(remainder(5,5));
const APIError = require("./APIError"); class ServerError extends APIError { constructor(name, message, status) { let cname = "ServerError"; if (name instanceof Array) { name.push(cname); } else if (typeof(name) != "string") { name = cname; } else { name = [ name, cname ] } super(name, "FATAL", message, status || 500); } } module.exports = ServerError;
function Car(name, age) { this.name = name; this.age = age; this.drive = true; var welcome = "Welcome"; function fullInformation() { return name + " : " + age; }; this.welcome = function() { console.log(welcome + " : " + fullInformation()); } } var car = new Car("Mazda", 2000); // console.log(car.name); car.welcome();
const ArticleVerif = require('../../../db/ArticleVerif'), User = require('../../../db/User'), Com = require ('../../../db/commentaire') module.exports = { list: async (req, res) => { dbCom = await Com.find({ article_id: req.params.id }), Coms = dbCom.reverse() res.render('admin/commentaire/listCommentaire',{ dbCom : Coms, comDel : req.flash('comDel') }) }, delCom: async (req, res) => { const dbCom = await Com.findById({ _id: req.params.id }) dbCom.deleteOne({ _id: req.params.id }) req.flash('comDel', '.') res.redirect('back') } }
/** * Author: Tyler Rimaldi * * Project: BottledUp * * Description: Server, API, and mongoDB config * */ /* Constants */ const express = require('express'); const app = express(); const parser = require("body-parser"); const assert = require('assert'); const dotenv = require('dotenv').config(); const MongoClient = require('mongodb').MongoClient; /* App Config */ app.use('/static', express.static('client/public')); app.use(parser.urlencoded({ extended: true })); app.use(parser.json()); /* Route Config */ // Bring us to the home page (in our case it's the entire site bc its a spa) app.get('/', function (req, res) { grab_bag("plastic"); grab_bag("metal"); res.sendFile('index.html', { root: './client/views' }); }); // Container is a bottle or can, lets get their respective collections app.get('/get_all_containers/:id', function(req, res, next){ var resultArray = []; var table = req.params.id; MongoClient.connect(process.env.MONGO_DB_URL_ENV, function(err, client) { assert.equal(null, err); const db = client.db(process.env.MONGO_DB_ENV); var cursor = db.collection(table).find(); cursor.forEach(function(doc, err) { assert.equal(null, err); resultArray.push(doc); },function() { res.send(resultArray.length.toString()); client.close(); }); }); }); // Container is a bottle or can, lets get their respective collections app.get('/get_current_containers/:id', function(req, res, next){ var resultArray = []; var table = req.params.id; var date_to_check; if (table.toString() == "plastic") { date_to_check = plastic_bag_time; } else { date_to_check = metal_bag_time; } MongoClient.connect(process.env.MONGO_DB_URL_ENV, function(err, client) { assert.equal(null, err); const db = client.db(process.env.MONGO_DB_ENV); var cursor = db.collection(table).find( { date: {"$gte": new Date(date_to_check) }} ); cursor.forEach(function(doc, err) { assert.equal(null, err); resultArray.push(doc); },function() { res.send(resultArray.length.toString()); client.close(); }); }); }); // Insert container of specific type app.post('/insert_container', function(req, res, next) { var table = req.body.material; var container = { material: req.body.material, date: new Date() } MongoClient.connect(process.env.MONGO_DB_URL_ENV, function(err, client){ assert.equal(null, err); const db = client.db(process.env.MONGO_DB_ENV); db.collection(table).insertOne(container, function(err, result){ assert.equal(null, err); res.status(201).send(container); client.close(); }); }); }); // Empty current bag of certain type, put in a new one app.post('/insert_new_bag/:id', function(req, res, next) { var new_bag = req.params.id.toString(); var new_time = new Date() if (new_bag == "plastic") { plastic_bag_time = new Date(new_time); } else { metal_bag_time = new Date(new_time); } var table = `${req.params.id}_bag`; var new_values = { $set: {time: new Date(new_time) } }; MongoClient.connect(process.env.MONGO_DB_URL_ENV, function(err, client){ assert.equal(null, err); const db = client.db(process.env.MONGO_DB_ENV); db.collection(table).updateOne({}, new_values, function(err, result) { if (err) throw res.status(401).send(`Failed to update ${table}`); res.status(201).send(`Updated ${table}`); client.close(); }); }); }); // Grab the updated bag app.patch('/get_bag/:id', function(req, res, next){ grab_bag(`${req.params.id}_bag`); }); /* Helper */ // Make sure we are grabbing the correct bags on load function grab_bag(param) { var table = `${param}_bag`; MongoClient.connect(process.env.MONGO_DB_URL_ENV, function(err, client) { assert.equal(null, err); const db = client.db(process.env.MONGO_DB_ENV); var cursor = db.collection(table).findOne() .then(function(doc) { assert.equal(null, err); if (table == "plastic_bag") { plastic_bag_time = new Date(doc.time); res.status(201).send(doc); } else if (table == "metal_bag") { metal_bag_time = new Date(doc.time); res.status(201).send(doc); } else { res.status(404).send("error"); } client.close(); }); }); } app.listen(process.env.PORT_ENV, () => console.log(`Collecting bottles and their respective types on port ${process.env.PORT_ENV}`));
var mongoose = require( 'mongoose' ); mongoose.Promise = global.Promise; var Schema = mongoose.Schema; var PostSchema = new Schema({ postTime: { type: Number, required: true }, username: { type: String, required: true }, endTime: { type: Number, required: true }, setup: { type: Schema.Types.Mixed, default: [] }, interests: { type: String, default: '' } }) module.exports = mongoose.model('Post', PostSchema);
import React from 'react'; import PropTypes from 'prop-types'; import './styles/whiteFlash.css'; export const WhiteFlash = ({ isShowWhiteFlash, whiteFlashClassName, whiteFlashTransitionClassName }) => { const flashDoTransition = isShowWhiteFlash ? whiteFlashTransitionClassName : ''; const flashClasses = `${whiteFlashClassName} ${flashDoTransition}`; return ( <div className={flashClasses}> </div> ); }; WhiteFlash.propTypes = { whiteFlashClassName: PropTypes.string.isRequired, whiteFlashTransitionClassName: PropTypes.string.isRequired, isShowWhiteFlash: PropTypes.bool.isRequired }; export default WhiteFlash;
let areaCircle = (r) => { const PI = 3.14; return PI * r * r; } console.log(areaCircle(7)); let areaCircle = r => 3.14 * r * r; console.log(areaCircle(5));
//@flow import { GLView } from 'expo-gl'; import React from 'react'; import { PanResponder, PixelRatio } from 'react-native'; import PIXI from '../Pixi'; import { takeSnapshotAsync } from '../utils'; global.__ExpoSketchId = global.__ExpoSketchId || 0; type Props = { strokeColor: number | string, strokeWidth: number, strokeAlpha: number, onChange: () => PIXI.Renderer, onReady: () => WebGLRenderingContext, initialLines?: Array<Point>, }; const scale = PixelRatio.get(); function scaled({ locationX: x, locationY: y }) { return { x: x * scale, y: y * scale }; } type Point = { x: number, y: number, color: string | number, width: number, alpha: number, }; export default class Sketch extends React.Component<Props> { lines = []; stage: PIXI.Stage; graphics; points = []; lastPoint: Point; lastTime: number; ease: number = 0.3; // only move 0.3 in the direction of the pointer, this smooths it out delay: number = 10; panResponder: PanResponder; renderer: PIXI.Renderer; componentWillMount() { global.__ExpoSketchId++; this.setupPanResponder(); } setupPanResponder = () => { const onEnd = event => { this.drawLine(scaled(event), false); setTimeout(() => this.props.onChange && this.props.onChange(this.renderer), 1); }; this.panResponder = PanResponder.create({ onStartShouldSetResponder: () => true, onStartShouldSetPanResponderCapture: () => true, onMoveShouldSetPanResponder: (evt, gestureState) => true, onPanResponderGrant: ({ nativeEvent }) => { const { x, y } = scaled(nativeEvent); const { strokeColor: color, strokeWidth: width, strokeAlpha: alpha } = this.props; this.drawLine( { x, y, color, width, alpha, }, true ); }, onPanResponderMove: ({ nativeEvent }) => { const point = scaled(nativeEvent); // throttle updates: once for every 10ms const time = Date.now(); const delta = time - this.lastTime; if (delta < this.delay) return; this.lastTime = time; this.drawLine( { x: this.lastPoint.x + this.ease * (point.x - this.lastPoint.x), y: this.lastPoint.y + this.ease * (point.y - this.lastPoint.y), color: this.props.strokeColor, width: this.props.strokeWidth, alpha: this.props.strokeAlpha, }, false ); }, onPanResponderRelease: ({ nativeEvent }) => onEnd(nativeEvent), onPanResponderTerminate: ({ nativeEvent }) => onEnd(nativeEvent), }); }; shouldComponentUpdate = () => false; persistStroke = () => { if (this.graphics) { this.graphics.points = this.points; this.lines.push(this.graphics); } this.lastTime = 0; this.points = []; }; drawLine(point: Point, newLine: boolean) { if (!this.renderer || (!newLine && !this.graphics)) { return; } if (newLine) { this.persistStroke(); this.graphics = new PIXI.Graphics(); this.stage.addChild(this.graphics); this.lastPoint = point; this.points = [point]; return; } this.lastPoint = point; this.points.push(point); this.graphics.clear(); for (let i = 0; i < this.points.length; i++) { const { x, y, color, width, alpha } = this.points[i]; if (i === 0) { this.graphics.lineStyle( width || this.props.strokeWidth || 10, color || this.props.strokeColor || 0x000000, alpha || this.props.strokeAlpha || 1 ); this.graphics.moveTo(x, y); } else { this.graphics.lineTo(x, y); } } this.graphics.currentPath.shape.closed = false; this.graphics.endFill(); /// TODO: this may be wrong: need stroke this.renderer._update(); } undo = () => { if (!this.renderer) { return null; } const { children } = this.stage; if (children.length > 0) { const child = children[children.length - 1]; this.stage.removeChild(child); this.renderer._update(); // TODO: This doesn't really work :/ setTimeout(() => this.props.onChange && this.props.onChange(this.renderer), 2); return child; } else if (this.points.length > 0) { this.persistStroke(); return this.undo(); } }; clear = () => { this.provider.reset(); if (!this.renderer) { return null; } if (this.stage.children.length > 0) { this.stage.removeChildren(); this.renderer._update(); } return null; }; takeSnapshotAsync = (...args) => { return takeSnapshotAsync(this.glView, ...args); }; onContextCreate = async (context: WebGLRenderingContext) => { this.context = context; this.stage = new PIXI.Container(); const getAttributes = context.getContextAttributes || (() => ({})); context.getContextAttributes = () => { const contextAttributes = getAttributes(); return { ...contextAttributes, stencil: true, }; }; this.renderer = PIXI.autoDetectRenderer( context.drawingBufferWidth, context.drawingBufferHeight, { context, antialias: true, backgroundColor: 'transparent', transparent: true, autoStart: false, } ); this.renderer._update = () => { this.renderer.render(this.stage); context.endFrameEXP(); }; this.props.onReady && this.props.onReady(context); const { initialLines } = this.props; if (initialLines) { for (let line of initialLines) { this.buildLine(line); } this.lines = initialLines; } }; buildLine = ({ points, color, alpha, width }) => { for (let i = 0; i < points.length; i++) { this.drawLine({ color, alpha, width, ...points[i] }, i === 0); } }; onLayout = ({ nativeEvent: { layout: { width, height }, }, }) => { if (this.renderer) { const scale = PixelRatio.get(); this.renderer.resize(width * scale, height * scale); this.renderer._update(); } }; setRef = ref => { this.glView = ref; }; render() { return ( <GLView {...this.panResponder.panHandlers} onLayout={this.onLayout} key={'Expo.Sketch-' + global.__ExpoSketchId} ref={this.setRef} {...this.props} onContextCreate={this.onContextCreate} /> ); } }
let [seconds, minutes, hours] = [0, 0, 0]; let timer; let pauseButton = document.getElementById('pause'); let resetButton = document.getElementById('reset'); let startButton = document.getElementById('start'); let timerElement = document.getElementById('timer'); startButton.addEventListener('click', () => { timer = setInterval(() => { seconds++; if (seconds == 60) { seconds = 0; minutes++; } if (minutes == 60) { minutes = 0; hours++; } timerElement.innerHTML = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`; }, 1000); resetButton.disabled = true; }); pauseButton.addEventListener('click', () => { timer = clearInterval(timer); resetButton.disabled = false; }); resetButton.addEventListener('click', () => { timer = clearInterval(timer); resetButton.disabled = true; [seconds, minutes, hours] = [0, 0, 0]; timerElement.innerHTML = '00:00:00'; });
function Navbar() { return( <ul className="uk-navbar-nav"> {/* <li className="uk-active"><a href="index.html">Home</a></li> */} </ul> ); } export default Navbar;
/* * @Descripttion: * @version: 1.0 * @Author: Ankang * @Date: 2021-05-25 21:31:10 * @LastEditors: Ankang * @LastEditTime: 2021-05-25 22:17:06 */ const router = require('express').Router() const { index, add, store, pages } = require('../../controller/admin/userController') // 列表 router.get('/index', index); // // 分页数据 // router.get('/pages', pages); // // 添加显示 // router.get('/add', add); // 添加处理 router.post('/add', store); module.exports = router
/* globals requester localStorage */ const HTTP_HEADER_KEY = "x-auth-key", KEY_STORAGE_USERNAME = "username", KEY_STORAGE_AUTH_KEY = "authKey"; var dataService = (function(){ function login(user) { return requester.postJSON("php/login.php", user) .then(respUser => { var resp = JSON.parse(respUser); localStorage.setItem("username", user.username); localStorage.setItem("authKey", resp.result.authKey); return respUser; }); } function register(user) { return requester.postJSON("php/register.php", user); } function logout() { return Promise.resolve() .then(() => { localStorage.removeItem(KEY_STORAGE_USERNAME); localStorage.removeItem(KEY_STORAGE_AUTH_KEY); }); } function isLoggedIn() { return Promise.resolve() .then(() => { return !!localStorage.getItem(KEY_STORAGE_USERNAME); }); } function getUsername() { return localStorage.getItem(KEY_STORAGE_USERNAME); // return new Promise((resolve, reject) => { // if (localStorage.getItem(KEY_STORAGE_USERNAME)) // resolve(localStorage.getItem(KEY_STORAGE_USERNAME)); // else reject(); // }); } function getUsers() { return requester.get("php/users.php"); } function getUser(name) { let options = { headers: { [KEY_STORAGE_USERNAME]: name, [HTTP_HEADER_KEY]: localStorage.getItem(KEY_STORAGE_AUTH_KEY) } }; return requester.get(`php/user.php`, options); } function allEsps() { return requester.get("php/book.php"); } function allEspsToCompare() { let options; if(isLoggedIn()) { options = { headers: { [KEY_STORAGE_USERNAME]: localStorage.getItem(KEY_STORAGE_USERNAME), [HTTP_HEADER_KEY]: localStorage.getItem(KEY_STORAGE_AUTH_KEY) } }; } return requester.get("php/getAllEspsByLogedIn.php", options); } function addESP(esp) { return controllESP(esp,`php/addEsp.php`); } function removeESP(esp) { return controllESP(esp,`php/removeEsp.php`); } function renameESP(esp) { return controllESP(esp,`php/renameEsp.php`); } function changeStatusESP(esp) { return controllESP(esp,`php/changeStatusEsp.php`); } function controllESP(esp,service) { let options = { headers: { username: localStorage.getItem(KEY_STORAGE_USERNAME), [HTTP_HEADER_KEY]: localStorage.getItem(KEY_STORAGE_AUTH_KEY) } }; return requester.postJSON(service, esp, options); } function getEspData(espData){ let service = "php/getEspData.php?"; service += "unic_id=" + espData.unic_id; service += "&fromDay=" + espData.from.day; service += "&fromMonth=" + espData.from.month; service += "&fromYear=" + espData.from.year; service += "&fromHour=" + espData.from.hour; service += "&fromMinute=" + espData.from.minute; service += "&toDay=" + espData.to.day; service += "&toMonth=" + espData.to.month; service += "&toYear=" + espData.to.year; service += "&toHour=" + espData.to.hour; service += "&toMinute=" + espData.to.minute; return requester.get(service) .then(respUser => { // var resp = JSON.parse(respUser); // localStorage.setItem("username", user.username); // localStorage.setItem("authKey", resp.result.authKey); return respUser; }); } return { login, register, logout, isLoggedIn, getUsername, getUsers, getUser, allEsps, allEspsToCompare, addESP, removeESP, renameESP, changeStatusESP, getEspData // getEspsData } })();
/* 确认订单页面 */ const sessionKey = 'confirmOrder' const bestPlanKey = 'bestPlan' export const state = () => ({ // 商品列表 后期会有多个 productList: [], // 购物车最终结果 bestPlan: null }) export const mutations = { productUpdate(state, payload) { let data = payload.map(item => { // 商品最小购买数量 购买数量 return Object.assign(item, { maxNum: item.maxNum || item.availableStock, minNum: 1, num: 1 }) }) sessionStorage[sessionKey] = JSON.stringify(data) state.productList = data }, bestPlanUpdate(state, payload) { let data = payload sessionStorage[bestPlanKey] = JSON.stringify(data) state.bestPlan = data } } export const getters = { products(state) { try { console.log(sessionStorage[sessionKey]) return state.productList.length > 0 ? state.productList : JSON.parse(sessionStorage[sessionKey]) } catch (e) { return state.productList } }, getBestPlan(state) { try { return state.bestPlan ? state.bestPlan : JSON.parse(sessionStorage[bestPlanKey]) } catch (e) { return state.bestPlan } } }
import React from "react"; import { Backdrop, Box, Button, Card, CircularProgress, Dialog, DialogActions, DialogContent, DialogTitle, Divider, Fade, makeStyles, Modal, TextField, } from "@material-ui/core"; import moment from "moment"; import axios from "../api/index"; import { useSelector } from "react-redux"; import { Formik } from "formik"; import { addNewInstockItemValidation } from "../utils/formValidation"; const cardStyles = makeStyles((theme) => ({ root: { padding: "0.75rem", marginBottom: "1rem", }, container: { display: "flex", flexDirection: "row", justifyContent: "space-between", alignItems: "center", }, input: { marginBottom: "1rem", }, buttonContainer: { marginTop: "0.5rem", }, modal: { display: "flex", alignItems: "center", justifyContent: "center", }, paper: { backgroundColor: theme.palette.background.paper, border: "2px solid #000", boxShadow: theme.shadows[5], padding: theme.spacing(2, 4, 3), }, })); const InstockItemCard = ({ item }) => { const classes = cardStyles(); const [open, setOpen] = React.useState(false); const [loading, setLoading] = React.useState(false); const [dialogOpen, setDialogOpen] = React.useState(false); const [editDialogOpen, setEditDialogOpen] = React.useState(false); const auth = useSelector((state) => state.auth); const handleOpen = () => { setOpen(true); }; const handleClose = () => { setOpen(false); }; return ( <Card elevation={3} className={classes.root}> <Box className={classes.container}> <p className="text-lg">{item.name}</p> <p className="text-lg text-green-700"> Total : <strong>{item.quantity}</strong> </p> </Box> <p className="text-sm text-gray-400"> {moment(item.createdAt).fromNow()} </p> <Divider style={{ margin: "0.5rem 0" }} /> <Box className={classes.buttonContainer}> {item.picURL ? ( <Button color="secondary" variant="outlined" size="small" onClick={handleOpen} > View Image </Button> ) : null} <Button style={{ marginLeft: "0.25rem" }} variant="contained" size="small" color="primary" onClick={() => setEditDialogOpen(true)} > Edit </Button> <Button color="secondary" variant="contained" size="small" style={{ marginLeft: "0.25rem" }} onClick={() => setDialogOpen(true)} > Delete </Button> {/* Down below dialog is for Delete action and Modal is for viewing image */} <Modal aria-labelledby="transition-modal-title" aria-describedby="transition-modal-description" className={classes.modal} open={open} onClose={handleClose} closeAfterTransition BackdropComponent={Backdrop} BackdropProps={{ timeout: 500, }} > <Fade in={open}> <div className={classes.paper}> <img src={item.picURL} alt="" style={{ height: "250px" }} className="rounded-3xl" /> </div> </Fade> </Modal> <Dialog open={editDialogOpen} onClose={() => setEditDialogOpen(false)}> <DialogTitle id="alert-dialog-slide-title2"> Edit for {item.name} </DialogTitle> {loading ? ( <CircularProgress style={{ margin: "0.5rem 1rem" }} /> ) : null} <DialogContent> <Formik validationSchema={addNewInstockItemValidation} initialValues={{ name: item.name, quantity: item.quantity, }} onSubmit={async ({ name, quantity }) => { setLoading(true); const payload = { name, quantity, }; await axios .put(`/api/instock/${item.uniqueId}`, payload, { headers: { Auth: auth.token, }, }) .then(() => { setLoading(false); alert("Edited!"); }) .catch((err) => { setLoading(false); console.log(err); }); }} > {({ values, errors, handleChange, handleSubmit, handleBlur, touched, }) => ( <form onSubmit={handleSubmit}> <TextField fullWidth variant="outlined" value={values.name} id="name" onChange={handleChange} onBlur={handleBlur} error={Boolean(touched.name) && Boolean(errors.name)} helperText={Boolean(touched.name) && errors.name} label="Name" className={classes.input} /> <TextField fullWidth variant="outlined" value={values.quantity} id="quantity" onChange={handleChange} onBlur={handleBlur} error={ Boolean(touched.quantity) && Boolean(errors.quantity) } helperText={Boolean(touched.quantity) && errors.quantity} label="Quantity" className={classes.input} /> <Button type="submit" onClick={handleSubmit} variant="contained" color="primary" > Save </Button> </form> )} </Formik> </DialogContent> </Dialog> <Dialog open={dialogOpen} onClose={() => setDialogOpen(false)} aria-labelledby="alert-dialog-slide-title" aria-describedby="alert-dialog-slide-description" > <DialogTitle id="alert-dialog-slide-title"> {`Delete ${item.name}?`} </DialogTitle> {loading ? ( <CircularProgress style={{ margin: "0.5rem 1rem" }} /> ) : null} <DialogActions> <Button onClick={() => setDialogOpen(false)} color="primary" variant="outlined" > Cancel </Button> <Button onClick={() => { setLoading(true); axios .delete(`/api/instock/${item.uniqueId}`, { headers: { Auth: auth.token, }, }) .then(() => { setLoading(false); alert("Deleted!"); setDialogOpen(false); }) .catch((err) => { setLoading(false); console.log(err); setDialogOpen(false); }); }} style={{ backgroundColor: "red", color: "white" }} variant="contained" > Confirm </Button> </DialogActions> </Dialog> </Box> </Card> ); }; export default InstockItemCard;
export const operatorStart = { name: 'operatorStart', match: 'Operator{', onMatch: (match, program, context) => { context.push({name: 'operator'}) }, }
import React from 'react'; export const Task = (props) => { return ( <> { props.tasks.map(el => { return ( <div key={el.id} className="row p-4 bg-light border"> <h2 className="col-11">{el.name}</h2> <button onClick={props.onClose} id={el.id} name={el.name} className="col-1 btn btn-outline-danger" > X </button> </div> ); }) } </> ); }
function scroll_about() { var about = document.getElementById("main-about"); about.scrollIntoView( { behavior: "smooth" }); } function scroll_portfolio() { document.querySelector('#main-portfolio').scrollIntoView( { behavior: "smooth" }); } function scroll_contact() { document.querySelector('#main-contact').scrollIntoView( { behavior: "smooth" }); } // Scroll indicator window.onscroll = function() { var height = window.innerHeight; var about = document.getElementById("main-about").getBoundingClientRect().top; var portfolio = document.getElementById("main-portfolio").getBoundingClientRect().top; var contact = document.getElementById("main-contact").getBoundingClientRect().top; var aboutHeight = document.getElementById("main-about").clientHeight; var portfolioHeight = document.getElementById("main-portfolio").clientHeight; var contactHeight = document.getElementById("main-contact").clientHeight; if (document.getElementById("intro-text").getBoundingClientRect().top < 300) { document.getElementById("header").style.padding = "0px"; document.getElementById("name").style.fontSize = "18px"; } else { document.getElementById("header").style.padding = "5px"; document.getElementById("name").style.fontSize = "22px"; } if (about <= 0.5*height && about > -0.8*aboutHeight) { document.getElementById("nav-about").style.backgroundColor = "#eee"; document.getElementById("nav-about").style.color = "black"; document.getElementById("nav-about").style.color = "white"; document.getElementById("nav-portfolio").style.backgroundColor = "inherit"; document.getElementById("nav-portfolio").style.color = "white"; document.getElementById("nav-contact").style.backgroundColor = "inherit"; document.getElementById("nav-contact").style.color = "white"; } else if (portfolio <= height && portfolio > -portfolioHeight) { document.getElementById("nav-about").style.backgroundColor = "inherit"; document.getElementById("nav-about").style.color = "white"; document.getElementById("nav-portfolio").style.backgroundColor = "#eee"; document.getElementById("nav-portfolio").style.color = "black"; } else if (contact <= height && contact > 0){ document.getElementById("nav-about").style.backgroundColor = "inherit"; document.getElementById("nav-about").style.color = "white"; document.getElementById("nav-portfolio").style.backgroundColor = "inherit"; document.getElementById("nav-portfolio").style.color = "white"; document.getElementById("nav-contact").style.backgroundColor = "#eee"; document.getElementById("nav-contact").style.color = "black"; } else { document.getElementById("nav-about").style.backgroundColor = "inherit"; document.getElementById("nav-about").style.color = "white"; document.getElementById("nav-portfolio").style.backgroundColor = "inherit"; document.getElementById("nav-portfolio").style.color = "white"; document.getElementById("nav-contact").style.backgroundColor = "inherit"; document.getElementById("nav-contact").style.color = "white"; } } // Slideshow var index = 0; showSlide(index); function slide(n) { index += n; showSlide(index); } function showSlide(n) { var slides_arr = document.getElementsByClassName("slides"); if (n >= slides_arr.length) { index = 0; } if (n < 0) { index = slides_arr.length - 1; } for (var i=0; i<slides_arr.length; i++) { slides_arr[i].style.display = "none"; } slides_arr[index].style.display = "block"; } //Modal var modal = document.getElementById("modal"); function btnClick() { modal.style.display = "block"; } function closeClick() { modal.style.display = "none"; } window.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; } }
import './Modal.css'; import React, { useState, useEffect } from "react"; import Popup from "reactjs-popup"; import { PernHeader, PernContent } from "./content/Pern"; import { InteractiveWebsiteHeader, InteractiveWebsiteContent } from "./content/InteractiveWebsite"; import { JavascriptGameHeader, JavascriptGameContent } from "./content/JavascriptGame"; import { JSListmakerHeader, JSListmakerContent } from "./content/JSListmaker"; import { PortfolioHeader, PortfolioContent } from "./content/Portfolio"; export const LearnMoreModal = ({ keyword, openModal, setOpenModal, url }) => { const [header, setHeader] = useState(null); const [content, setContent] = useState(null); const [buttonText, setButtonText] = useState(null); useEffect(() => { switch (keyword) { case 'pern-web-app': setHeader(<PernHeader />); setContent(<PernContent url={url} />); setButtonText("Go to Kit Collab"); break; case 'interactive-website': setHeader(<InteractiveWebsiteHeader />); setContent(<InteractiveWebsiteContent url={url} />); setButtonText("Visit site"); break; case 'javascript-game': setHeader(<JavascriptGameHeader />); setContent(<JavascriptGameContent url={url} />); setButtonText("Let's play!"); break; case 'listmaker-app': setHeader(<JSListmakerHeader />); setContent(<JSListmakerContent url={url} />); setButtonText("Check it out") break; case 'portfolio': setHeader(<PortfolioHeader />); setContent(<PortfolioContent />); setButtonText("Check it out") break; default: console.log("keyword not recognised"); } // eslint-disable-next-line react-hooks/exhaustive-deps }, []); const close = () => { console.log('modal closed'); setOpenModal(false); } return ( <Popup open={openModal} closeOnDocumentClick onClose={close}> <div className="modal"> <button className="close" onClick={close}>&times;</button> <div className="header">{header}</div> <div className="content"> {content} </div> <div className="actions"> { url ? <a href={url} target="_blank" rel="noreferrer noopener"> <button className="pillbox-button lighten-on-hover-button modal-button"> {buttonText} </button> </a> : null } <button className="pillbox-button lighten-on-hover-button modal-button" onClick={close} > Close modal </button> </div> </div> </Popup> ) }
!(function (e) { 'use strict' function t(e, t, s) { return ( t in e ? Object.defineProperty(e, t, { value: s, enumerable: !0, configurable: !0, writable: !0, }) : (e[t] = s), e ) } function s(e) { for (let s = 1; s < arguments.length; s++) { var i = arguments[s] != null ? arguments[s] : {} let a = Object.keys(i) typeof Object.getOwnPropertySymbols === 'function' && (a = a.concat( Object.getOwnPropertySymbols(i).filter(function (e) { return Object.getOwnPropertyDescriptor(i, e).enumerable }) )), a.forEach(function (s) { t(e, s, i[s]) }) } return e } const i = { captureInterval: 150, feedbackInterval: 2e3, width: 1280, height: 720, facingMode: 'environment', documentType: 'ID_CARD', returnDetectedImage: 'SUCCESS_ONLY', } const a = { 1: { code: 901, message: 'Try to straighten up the document' }, 2: { code: 902, message: 'Position the document so that it fills the rectangle', }, 3: { code: 903, message: 'Try to straighten up the document' }, 4: { code: 904, message: 'Try to straighten up the document' }, 5: { code: 905, message: 'Try to straighten up the document' }, 6: { code: 906, message: 'Move the ID document away from strong discrete light sources', }, 7: { code: 907, message: 'Try to holder the document in a steady position', }, 8: { code: 908, message: 'Move the ID to a position where there is a plain background', }, 9: { code: 909, message: 'Try to straighten up the document.' }, 10: { code: 910, message: 'Too much movement, hold the document steady.', }, 11: { code: 911, message: 'Could not find document, place the document in the scanning area.', }, 12: { code: 912, message: 'Move the ID document away from strong discrete light sources.', }, } function r(e, t) { return fetch(e, { method: 'post', headers: { 'Content-Type': 'application/octet-stream' }, body: t, }).then((e) => { if (e.ok || e.status === 400) return e.json() throw new Error(e.status + ' ' + e.statusText) }) } const n = 'You must set message priorities with configureMessagePriorities(yourConfig)' const o = 'You must set a timeout interval' const c = 'You must provide a callback' class u { constructor(e) { if (!e) throw n ;(this.messagePriorities = e), (this.queue = []) } pushArray(e) { Array.prototype.push.apply(this.queue, e) } getPriorityMessage() { return h(this.messagePriorities, this.queue) } enableAutoGetPriorityMessage(e, t) { if (!e || typeof e !== 'number') throw o if (!t || typeof t !== 'function') throw c return ( (this.intervalId = setInterval(() => { this.intervalId && t(h(this.messagePriorities, this.queue)) }, e)), this.intervalId ) } disableAutoGetPriorityMessage() { clearInterval(this.intervalId) } } function h(e, t) { if (!e) throw n if (!t || !t.length) return let s = void 0 for (let i = 1; i <= 12; i++) { const a = e[i] if ((s = t.find((e) => e && a && e.code === a.code))) break } return (t.length = 0), s ? s.message : void 0 } function d(e) { return e ? e.getVideoTracks() : [] } function g(e) { const t = d(e) return t.length ? t[0].getSettings() : {} } function m(e) { return !!d(e).find((e) => e.readyState === 'live') } class l { get videoTracks() { return d(this.stream) } get isReady() { return m(this.stream) } get settings() { return g(this.stream) } start(e, t) { return navigator.mediaDevices .getUserMedia({ video: e, audio: !1 }) .then( (e) => ( (this.stream = e), t && (this.videoEl = t), this.videoEl || (this.videoEl = document.createElement('video')), (this.videoEl.srcObject = e), this.videoEl ) ) } stop() { this.videoTracks.forEach((e) => e.stop()) } } const p = 'Capture source not valid' class f { capture(e) { if (e && m(e.srcObject)) { return ( this.canvas || (this.canvas = document.createElement('canvas')), (this.canvas.width = e.videoWidth), (this.canvas.height = e.videoHeight), this.canvas .getContext('2d') .drawImage(e, 0, 0, e.videoWidth, e.videoHeight), new Promise((e, t) => { try { this.canvas.toBlob((t) => e(t), 'image/jpeg', 1) } catch (e) { t(e) } }) ) } throw p } getImageData(e) { if (e && m(e.srcObject)) { this.canvas || (this.canvas = document.createElement('canvas')), (this.canvas.width = e.videoWidth), (this.canvas.height = e.videoHeight) const t = this.canvas.getContext('2d') return ( t.drawImage(e, 0, 0, e.videoWidth, e.videoHeight), t.getImageData(0, 0, e.videoWidth, e.videoHeight) ) } throw p } } const v = "Configuration 'url' is mandatory" const y = 'Camera not ready' class I { constructor() { ;(this.camera = new l()), (this.captureCanvas = new f()) } startCamera(e, t) { this.messageCache = new u(this.qualityAssesmentMessages) const s = (function (e, t) { const s = {} return ( e && (t && (s.deviceId = { exact: t }), e.facingMode && !t && (s.facingMode = e.facingMode), e.height && (s.height = e.height), e.width && (s.width = e.width)), s ) })(this.config, t) return this.camera.start(s, e).then( (e) => ( (function (e, t) { const s = g(e.srcObject) let i = s && s.facingMode return ( !i && navigator.userAgent.match( /(Android|webOS|iPhone|iPad|iPod|BlackBerry|Windows Phone)/i ) && (i = t), i === 'user' || !i ) })(e, this.config.facingMode) && !t && (function (e) { ;(e.style['-webkit-transform'] = 'scaleX(-1)'), (e.style.transform = 'scaleX(-1)') })(e), (function (e) { e.attributes.autoplay || e.setAttribute('autoplay', ''), e.attributes.playsinline || e.setAttribute('playsinline', '') })(e), { videoEl: this.camera.videoEl } ) ) } getUrl(e, t) { const { documentType: i, returnDetectedImage: a } = this.config return (function (e, t) { const s = new URL(e, window.location.origin) return ( Object.keys(t).forEach((e) => t[e] && s.searchParams.append(e, t[e])), s ) })( this.config.url, s({ documentType: i, returnDetectedImage: a, hintFacePresent: t }, e) ) } startAutoCapture(e, t) { if (((this.queue = []), !this.camera.isReady)) throw y this.pendingPromise = void 0 const s = () => { this.pictureTakingTimeoutId = setTimeout(() => { if (this.pictureTakingTimeoutId) { try { this.pendingPromise || this.captureCanvas .capture(this.camera.videoEl) .then( (s) => ( (this.pendingPromise = r(this.getUrl(), s) .then((t) => { if (t.result === 'PASS') return ( this.stopAutoCapture(), e( (function (e, t) { return { result: t.result, sentBlobImage: e, responseBase64Image: t.documentImage && t.documentImage.image, } })(s, t) ) ) Array.prototype.push.apply(this.queue, t.feedback) }) .catch((e) => { this.stopAutoCapture(), t(e) }) .finally(() => { this.pendingPromise = void 0 })), this.pendingPromise ) ) .catch((e) => this.onCaptureError(e)) } catch (e) { this.onCaptureError(e) } s() } }, this.config.captureInterval) } const i = () => { this.messageCleanupTimeoutId = setTimeout(() => { if (this.messageCleanupTimeoutId) { const t = h(this.qualityAssesmentMessages, this.queue) e({ result: 'FAIL', feedback: t }), i() } }, this.config.feedbackInterval) } s(), i() } onCaptureError(e) { throw (this.stopAutoCapture(), e) } stopAutoCapture() { clearTimeout(this.messageCleanupTimeoutId), clearInterval(this.pictureTakingTimeoutId) } capture() { return this.captureCanvas .capture(this.camera.videoEl) .then((e) => this.assessQuality(e)) } captureFrame() { return this.captureCanvas.capture(this.camera.videoEl) } assessQuality(e, t, s) { if (!this.config || !this.config.url) throw v return r(this.getUrl(t, s), e).then((t) => { const s = { result: t.result, sentBlobImage: e, responseBase64Image: t.documentImage && t.documentImage.image, message: t.message, } return ( t.result === 'FAIL' && (s.feedback = h(this.qualityAssesmentMessages, t.feedback)), s ) }) } stopCamera() { this.camera.stop() } isReady() { return this.camera.isReady } } class b extends I { constructor(e) { super(), (this.config = s({}, i, e)), (this.qualityAssesmentMessages = a) } } ;(b.VERSION = '1.1.8'), (e.DocumentCapture = b) })((this.Daon = this.Daon || {}))
(function () { function padEnd( str, len, pad ) { len = len || 0; pad = pad || '0'; var tmp = []; if ( str.length > len ) return str; len = len - str.length; // 需要添加的数据 var count = Math.ceil( len / pad.length ); // 计算需要添加几组字符串 for ( var i = 0; i < count; i++ ) { tmp.push( pad ); } var padstr = tmp.join( '' ).slice( 0, len ); return str + padstr; } function padStart( str, len, pad ) { len = len || 0; pad = pad || '0'; var tmp = []; if ( str.length > len ) return str; len = len - str.length; // 需要添加的数据 var count = Math.ceil( len / pad.length ); // 计算需要添加几组字符串 for ( var i = 0; i < count; i++ ) { tmp.push( pad ); } var tmpjoin = tmp.join( '' ); var padstr = tmpjoin.slice( tmpjoin.length - len ); return padstr + str; } window._ = { padEnd: padEnd, padStart: padStart }; })();
import { disableCanvas, hideControls, enableCanvas, showControls, resetCanvas } from "./paint"; import { disableChat, enableChat } from "./chat"; const PLAY_TIME = 29; const board = document.getElementById("jsPBoard"); const notifs = document.getElementById("jsNotifs"); let countTime = PLAY_TIME; let interval = null; const addPlayers = players => { board.innerHTML = ""; players.forEach(player => { const playerElement = document.createElement("span"); playerElement.innerText = `${player.nickname}: ${player.points}`; board.appendChild(playerElement); }); }; const setNotifs = text => { notifs.innerText = " "; notifs.innerText = text; }; export const handlePlayerUpdate = ({ sockets }) => addPlayers(sockets); export const handleGameStarted = () => { setNotifs(""); disableCanvas(); hideControls(); enableChat(); }; export const handleLeaderNotif = ({ word }) => { enableCanvas(); showControls(); disableChat(); let inputText = ""; interval = setInterval(() => { inputText = `당신은 출제자 입니다. 제시어: ${word} / 남은시간 : ${countTime}`; notifs.innerText = inputText; countTime--; }, 1000); }; export const handlePlayerNotif = () => { let inputText = "문제를 풀어주세요."; notifs.innerText = inputText; }; export const handleGameEnded = () => { setNotifs("게임 오버."); disableCanvas(); hideControls(); resetCanvas(); endInterval(); }; const endInterval = () => { countTime = PLAY_TIME; clearInterval(interval); }; export const handleGameStarting = () => setNotifs("곧 게임이 시작됩니다.");
import React from 'react' function SingleWorkStatsItem({statsPercent, statsTitle, statsDesc}) { return( <> <div className="col-6 single-stat-box anim-bot"> <h3>{statsPercent}<span>%</span></h3> <h6>{statsTitle}</h6> <p>{statsDesc}</p> </div> </> ) } export default SingleWorkStatsItem
// 1. Declare and initialize an empty multidimensional array. // (Array of arrays) var num = [[],[],[]] // 2. Declare and initialize a multidimensional array // representing the following matrix: num[0] = [0,1,2,3] num[1] = [1,0,1,2] num[2] = [2,1,0,1] document.write(num[0]+"<br/>"+num[1]+"<br/>"+num[2]+"<br/>") // 3. Write a program to print numeric counting from 1 to 10. for (var i = 1; i <= 10; i++){ document.write(i+"<br/>") } // 4. Write a program to print multiplication table of any // number using for loop. Table number & length should be // taken as an input from user. var table = +prompt("Enter a number to show its multiplication table"); var length = +prompt("Enter Multiplication table" ); document.write("Multiplication Table of " +table+"<br/> length"+length+ "<br/>") for(var i = 1; i <= length; i++){ document.write(table+" x "+i+" = "+table*i+"<br/>") } // 5. Write a program to print items of the following array // using for loop: // fruits = [“apple”, “banana”, “mango”, “orange”, // “strawberry”] var fruits = ["apple", "banana", "mango", "orange", "strawberry"] var arr = fruits.length for(var i = 0; i <arr; i++){ document.write("Element at index "+i+" is "+fruits[i]+"<br/>") } // 6. Generate the following series in your browser. See // example output. // a. Counting: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 // b. Reverse counting: 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 // c. Even: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 // d. Odd: 1, 3, 5, 7, 9, 11, 13, 15, 17, 19 // e. Series: 2k, 4k, 6k, 8k, 10k, 12k, 14k, 16k, 18k, 20k var num = []; var odd = []; var even = []; var series = []; for(var i = 0; i <=15; i++){ num[i] = i+1; } document.write("counting :"+num+"<br/>") document.write(" Reverse counting :"+num.reverse()+"<br/>") for(var a = 1; a <= 20; a++){ if(a % 2 !==0){ even[a] = a; } } document.write("Even :"+even+"<br/>") for(var b = 1; b <= 20; b++){ if(b % 2 === 0){ odd[b] = b; } } document.write("Odd :"+odd+"<br/>") for(var d = 1; d <= 20; d++){ if(d % 2 === 0){ series[d] = d+"k"; } } document.write("Series :"+series+"<br/>") // 7. You have an array // A = [“cake”, “apple pie”, “cookie”, “chips”, “patties”] // Write a program to enable “search by user input” in an // array. // After searching, prompt the user whether the given item is // found in the list or not. Example: var a = ["cake","apple pie","cookie","chips","patties"] var user = prompt("Welcome to ABC Bkery what do you want to order sir/ma'am") var b = a.indexOf(user) if(b<0){ alert("we are sorry"+user+"is not available in our bakery") } else{ alert(user+"is available at index "+b+" in our bakery") } // 8. Write a program to identify the largest number in the // given array. // A = [24, 53, 78, 91, 12]. var arr = [24,53,78,91,12]; var max = Math.max.apply(Math,arr) var min = Math.min.apply(Math,arr) console.log(max , min) document.write( "Array items: "+arr+ "<br/> The largest number is " +max+ "<br/> The samllest number is " +min ) // 9. Write a program to identify the smallest number in the // given array. // A = [24, 53, 78, 91, 12] var arr = [24,53,78,91,12]; var max = Math.max.apply(Math,arr) var min = Math.min.apply(Math,arr) console.log(max , min) document.write( "Array items: "+arr+ "<br/> The largest number is " +max+ "<br/> The samllest number is " +min+"<br/>" ) // 10. Write a program to print multiples of 5 ranging 1 to // 100. for(var i = 1; i<=100; i++){ if(i%5 === 0){ document.write(i+" ,") } }