text
stringlengths
7
3.69M
import React, { Component } from 'react'; import './App.css'; // This component doesn't use any data in the store! Fix this. class DisplayTodos extends Component { render = () => { return (<div> I need to get implemented </div>) } } export default DisplayTodos;
import React from 'react'; import {string} from 'prop-types'; import './next-portfolio-screen.scss'; import {withRouter} from 'react-router-dom' import classNames from 'classnames'; export class NextPortfolioScreenComponent extends React.Component { static propTypes = { nextPageHref: string }; state = { fixed: false }; // handleScroll = event => { // if (this.state.fixed) { // window.scrollTo(0, 0); // } // if ((window.scrollY + window.innerHeight) === document.documentElement.offsetHeight) { // this.setState({fixed: true}); // window.scrollTo(0, 0); // setTimeout(() => { // window.scrollTo(0, 0); // this.props.history.push(this.props.nextPageHref); // }, 10); // } // }; // // componentDidMount() { // window.addEventListener('scroll', this.handleScroll); // } // // componentWillUnmount() { // window.removeEventListener('scroll', this.handleScroll); // } render() { const {fixed} = this.state; return ( <div className={classNames('next-portfolio-screen', {'next-portfolio-screen__fixed': fixed})}> <h2 className="next-portfolio-screen__label">Следующая работа</h2> </div> ); } } export const NextPortfolioScreen = withRouter(NextPortfolioScreenComponent);
const Koa = require("koa"); const Router = require("koa-router"); const BodyParser = require("koa-bodyparser"); const app = new Koa(); const router = new Router(); const config = require("./config"); const vectorTile = require("./vector_tile"); const cors = require("@koa/cors"); app.use(cors()); app.use(router.routes()); app.use(BodyParser()); router.get(`/vt/status`, (ctx)=> { ctx.body = { status: "running" } }) router.get(`/vt/tile/:z/:x/:y`, vectorTile.tile) app.listen(config.port, () => { console.log(`Mapnik Vector Tile Server Running At: ${config.port}`) })
export function Route(name, htmlName, purpose) { try { if (!name || !htmlName) { throw Error('Name and htmlName params are mandatories'); } this.constructor(name, htmlName, purpose); } catch (e) { console.error(e); } } Route.prototype = { constructor: function(name, htmlName, purpose) { this.name = name; this.htmlName = htmlName; this.purpose = purpose || 'nav'; }, isActiveRoute: function(hashedPath) { return hashedPath.replace('#', '') === this.name; } };
var express = require('express'); var loginRouter = express.Router(); var loginAdminRouter = express.Router(); var logoutRouter = express.Router(); var loginGuestRouter = express.Router();//dontgetconfused,this is the signup router :) var authMiddleware = require('./middlewares/auth'); var db = require('../../lib/database')(); loginRouter.route('/') .get(authMiddleware.noAuthed, (req, res) => { res.render('auth/views/login', req.query); }) loginAdminRouter.route('/') .get(authMiddleware.noAuthed, (req, res) => { res.render('auth/views/login', req.query); }) .post((req, res) => { console.log('POST LOGIN'); db.query(`SELECT * FROM user WHERE varchar_username="${req.body.user_username}"`, (err, results, fields) => { if (err) throw err; if (results.length === 0) return res.redirect('/login?incorrect'); var user = results[0]; if (user.varchar_password !== req.body.user_password) return res.redirect('/login?incorrect'); if(user.char_usertype == "Admin"){ delete user.varchar_password; // req.session.admin = req.body.user_username; req.session.admin = user; console.log(req.session); return res.redirect('/admin/emergency'); } }); }) logoutRouter.get('/', (req, res) => { req.session.destroy(err => { if (err) throw err; res.redirect('/login'); }); }); exports.loginadmin= loginAdminRouter; exports.login = loginRouter; exports.logout = logoutRouter;
import React, { useEffect, useState } from 'react'; import ItemDetail from '../ItemDetail/ItemDetail'; import './ItemDetailContainer.css'; import { db } from '../../firebase'; import { useParams } from 'react-router-dom'; const ItemDetailContainer = () => { const [item, setItem] = useState([]); const [loading, setLoading] = useState(true); const { id } = useParams(); const getData = async () => { db.collection('productos').onSnapshot((querySnapshot) => { const docs = []; querySnapshot.forEach((doc) => { docs.push({ ...doc.data(), id: doc.id }); }); const product = docs.find((elem) => { return elem.id === id; }); setItem(product); setLoading(false); }); }; useEffect(() => { getData(); //eslint-disable-next-line }, []); return ( <div className="container-detail"> {!loading && <ItemDetail data={item} />} </div> ); }; export default ItemDetailContainer;
const express = require('express'); const validator = require('validator'); const db = require('../database.js'); const nodemailer = require('nodemailer'); const { transporter, sendEmail } = require('../email.js') const router = express.Router(); router.post('/', (req, res) => { let code; try { let sqlQuery = "INSERT INTO rooms (roomname) Values (?)" db.query(sqlQuery, ["Theory"], (err, result) => { if (err) { res.status(400).json({ error: err.message }); } else { console.log(result.insertId); let sql1 = "SELECT Email FROM user WHERE Type=(?)"; db.query(sql1, ["Admin"], async (err1, Emails) => { if (err1) { console.log(err1); res.status(400).json({ error: err1.message }); } else { console.log(Emails); Emails = JSON.parse(JSON.stringify(Emails)) Emails.forEach(async (Email) => { console.log(Email); // const mailOptions = { // from: "ClassroomManagementSystems@outlook.com", // to: Email.Email, // subject: "New Classroom Registered.", // text: "Room No. " + result.insertId + " has been successfully registered." // }; //sendEmail(transporter, mailOptions); res.status(200).json({ message: "success" }); }); } }); } }) let sqlallrooms = "SELECT idrooms FROM rooms" db.query(sqlallrooms, [], (err, result) => { if (err) { res.status(400).json({ error: err.message }); } else { result = result.map(({ idrooms }) => idrooms) console.log(result); } }) } catch (error) { res.status(200).json({ code: code, error: error.message }) } }) module.exports = router;
/** * @class widgets.GUI.RadioGroup * Controle de radio button. * @alteracao 09/07/2015 191657 Projeto Carlos Eduardo Santos Alves Domingos * Criação. */ var args = arguments[0] || {}; /** * @property {Object} listControl Lista de controles no componente. */ var listControl = []; /** * @property {Number} selectedIndex controle selecionado. */ var selectedIndex = 0; /** * @method start * Inicia o componente. * @private * @alteracao 09/07/2015 191657 Projeto Carlos Eduardo Santos Alves Domingos * Criação. */ function start(){ $.groupTitle.setText(args.titulo); $.getView().width = args.width; $.getView().height = args.height; } /** * @method setGroup * Adiciona os controles no grupo. * @param {Object} colecao Vetor contendo os titulos dos controles. * @param {Object} index Indice do controle que inicia ativado. * @alteracao 09/07/2015 191657 Projeto Carlos Eduardo Santos Alves Domingos * Criação. */ $.setGroup = function(colecao, index){ if(index){ selectedIndex = index; } for(var i = 0; i < colecao.length; i++){ var container = Ti.UI.createView({ width: Ti.UI.SIZE, height: Ti.UI.SIZE, layout: 'horizontal', top: i>0?5:0, left: "5%" }); var sty = $.createStyle({ classes: ["meuSwitch"], apiName: 'Switch' }); var archSwitch = Ti.UI.createSwitch({ value: i==selectedIndex?true:false, index: i }); archSwitch.applyProperties(sty); container.add(archSwitch); var lblDesc = Ti.UI.createLabel({ text: colecao[i], left: 7 }); container.add(lblDesc); $.listaSwitch.add(container); listControl.push({index: i, source: archSwitch, title: colecao[i]}); archSwitch.addEventListener("change", function(e){ if(e.value == false && e.source.index == selectedIndex){ e.source.value = true; return; } if(e.source.index != selectedIndex && e.value == true){ var tempIndex = selectedIndex; selectedIndex = e.source.index; listControl[tempIndex].source.value = false; $.trigger('change', $.getSelected()); return; } }); } }; /** * @method getSelected * Pega o indice do controle selecionado * @return {Object} Item Retorno * @return {Number} return.index Indice do controle selecionado. * @return {String} return.title Texto do controle. * @return {Object} return.source Controle selecionado. * @alteracao 09/07/2015 191657 Projeto Carlos Eduardo Santos Alves Domingos * Criação. */ $.getSelected = function(){ return {index: selectedIndex, title: listControl[selectedIndex].title, source: listControl[selectedIndex].source}; }; //Inicio o componente. start();
const sqlite3 = require('sqlite3').verbose() let uniqid = require('uniqid') const ipcRenderer = require('electron').ipcRenderer /** |-------------------------------------------------- | @function fetchData is called on onload method on body, | so that folder list will be fetched before rendering |-------------------------------------------------- */ function fetchData() { const db = new sqlite3.Database('./database.sqlite3') db.all("SELECT * FROM bookmarkfolder", [], function (err, rows) { setTable(rows) }); db.close(); } /** |-------------------------------------------------- | @function saveData will saving giving folder name and its id to the SQLite3 database | @param id will take given folder id | @param name will take folder name as string |-------------------------------------------------- */ function saveData(id, name) { newTableRow(id, name) const db = new sqlite3.Database('./database.sqlite3') db.run("INSERT INTO bookmarkfolder (folderId, folderName) values (?, ?)", [id, name]) db.close(); } /** |-------------------------------------------------- | @function removeFromDatavabase function will call sql statement and delete | given @param id folder and it will delete first joined data from database | and then it will remove folder from database |-------------------------------------------------- */ function removeFromDatabase(id) { const db = new sqlite3.Database('./database.sqlite3') db.serialize(function () { db.run("DELETE FROM bookmark WHERE bmFolderid = (?)", [id]) db.run("DELETE FROM bookmarkfolder WHERE folderId = (?)", [id]) }) db.close(); } /** |-------------------------------------------------- | @function fetchSavedBookmakrs will fetch all bookmarks which has given @param folderId as | foreign key and return promise as arraylist of bookmarks or error |-------------------------------------------------- */ function fetchSavedBookmarks(folderId) { return promise = new Promise(function (resolve, reject) { const db = new sqlite3.Database('./database.sqlite3') db.all("SELECT * FROM bookmarks where bmFolderId = (?)", [folderId], function (err, rows) { if (err) { reject(err) } else { resolve(rows) } }); db.close(); }) } /** |-------------------------------------------------- | @function openNewFolderForm function will activate JqueryUi plugin | and slide open input from where use can insert new folder name and save it |-------------------------------------------------- */ function openNewFolderForm() { $(document).ready(function () { let options = {} $("#form").toggle("blind", options, 500) }); } /** |-------------------------------------------------- | @function changeHeaderButtonText will change given text and onclick function call | @param text takes string as param | @param functionCall takes string as param |-------------------------------------------------- */ function changeHeaderButtonText(text, functionCall) { let button = document.getElementById("header-button") button.innerHTML = text button.setAttribute("onclick", functionCall) } /** |-------------------------------------------------- | @Function setTable will loop given array and call @function newTablerow | to create table rows and inserting given data | @param data will take array as param which are fetched from database |-------------------------------------------------- */ function setTable(data) { for (let i = 0; i < data.length; i++) { newTableRow(data[i].folderId, data[i].folderName) } } /** |-------------------------------------------------- | @function onFormSubmit when user insert new folder name on the input field | and pressed save new folder button. Function fetch given data by getElementByid function | and then will call @function saveData which pass @function uniqid() generated id and given | @param folderName string |-------------------------------------------------- */ function onFormSubmit() { let folderName = document.getElementById("folder-name").value; if (folderName.length !== 0) { saveData(uniqid(), folderName) } } /** |-------------------------------------------------- | @function newTableRow will create new row and insert given data to the cells | @param id takes given string | @param title takes given String |-------------------------------------------------- */ function newTableRow(id, title) { //Fetch Table element by id let table = document.getElementById("folder-table") // Insert new row at bottom of the table let row = table.insertRow(-1) // Set given class with value to the new row row.setAttribute("class", "folder-row-style") // insert first cell to the row let tblButton = row.insertCell(0) // insert second cell to the row let folderName = row.insertCell(1); jQuery(folderName).addClass('folder-title-style') // Give id attribute with given id string to the second cell folderName.setAttribute("id", id) // Given onclick attribute to the second cell with given function folderName.setAttribute("onclick", "openSubTable(this)") // Insert to the first cell custom created delete button tblButton.appendChild(createDeleteButton()) // Set to the second row text of the given title string folderName.innerText = title } /** |-------------------------------------------------- | @function createDeleteButton creates delete button and returns it |-------------------------------------------------- */ function createDeleteButton() { // Create new button element let newButton = document.createElement("button"); // Set button text value newButton.innerText = "Delete" //Set onclick and class attributes to the button element newButton.setAttribute("onclick", "deleteRow(this)") newButton.setAttribute("class", "delete-button") newButton.setAttribute("id", "delete-button") return newButton } /** |-------------------------------------------------- | @function deleteRow will delete folder from database | and row from table | @param x take onclicked button element |-------------------------------------------------- */ function deleteRow(x) { // Takes button element parent cell element to the variable let cell = x.parentNode // Takes cell element its paren element to the variable let rowValue = cell.parentNode // Will get index position from row element let index = rowValue.rowIndex // Will get row element id and save it to the variable let folderId = rowValue.getElementsByTagName("td")[1].id // delete row from table by given index document.getElementById("folder-table").deleteRow(index) // call function and pass given folderid so, that function can delete it from database removeFromDatabase(folderId) } /** |-------------------------------------------------- | When click row title cell it will call @function openSubTable | and hide other listed folder rows from the table. | And will be inserting second row so we can create table on it And listed saved bookmarks on it | @param value will take clicked title element |-------------------------------------------------- */ function openSubTable(value) { // Will get called function parent element and save it to the variable let parentElement = value.parentElement // Get selected folder row index position and save it to the variable let rowPosition = parentElement.rowIndex let delButton = parentElement.childNodes[0] delButton.style.visibility = "hidden" //Set attribute to the selcted row, so it will be easier on the animations and other // specified styles on selected row parentElement.setAttribute("id", "selected") let rowHeight = parentElement.offsetHeight // Will disable folder table rows, so that it will be not creating // more than 1 row tables on the showcase jQuery(parentElement).addClass('selected disable-click-event') // disabled onclick event, so other rows cannot be clicked while selected folder animation is executed // and set non-selected folders visibility to the hidden jQuery("tr:not(#selected)").addClass('not-selected disable-click-event') // Call function, so that selected folder row can be moved to the top of the table moveTableRow(rowPosition, rowHeight, "selected") setTimeout( function() { //Set little timeout on subtable creating function, so that other folder are full hidden createSubTableRow(rowPosition, rowHeight, value.id) }, 1000) } /** |-------------------------------------------------- | @function createSubTableRow will create second row under selected folder row | and creates second table on it, so that user can see selected folder bookmarks | @param value = int, takes selected folder row index position | @param folderHeight = int, takes folder row height | @param folderId = string, selected folder id value |-------------------------------------------------- */ function createSubTableRow(value, folderHeight, folderId) { //Takes folder table and save it to the variable let table = document.getElementById("folder-table") // Create new row under selected folder row, so // we can insert subtable with bookmark data on it let row = table.insertRow(value + 1) // insert 1 cell, so that only bookmark tile is showcased on it let bookmarkTable = row.insertCell(0) // Give subtable row id attribute row.setAttribute("id", "subTable") // Give subtable row styles bookmarkTable.setAttribute("class", "sub-table-style") // Compine cells so that bookmark title text will be nicely centered bookmarkTable.setAttribute("colspan", "2") // Fetch bookmark from database and then create rows from bookmarks and // append to the subtable fetchSavedBookmarks(folderId) .then(function (result) { bookmarkTable.appendChild(constructBookmarkData(result)) }) .catch(function (err) { throw new Error(err) }) .finally(function () { //Change header button text and onclick function, so that we can close selected folder changeHeaderButtonText("Close Folder", "closeOpenFolder()") document.getElementById("header").appendChild(createNewBmButton()) }) //title.appendChild(createDummyData()) moveTableRow(value, folderHeight, "subTable") } function createNewBmButton() { // Create new button element let newButton = document.createElement("button"); // Set button text value newButton.innerText = "Create new bookmark" //Set onclick and class attributes to the button element newButton.setAttribute("onclick", "openCreateNewBmWindow()") newButton.setAttribute("id", "new-bm-button") newButton.setAttribute("class", "Header-Button") return newButton } /** |-------------------------------------------------- | @function closeOpenFolder will remove given saved style | and set header button to the create new folder function |-------------------------------------------------- */ function closeOpenFolder() { let selected = document.getElementById("selected") let delButton = selected.childNodes[0] selected.removeAttribute("style") jQuery("#subTable").remove() jQuery("#new-bm-button").remove() jQuery("tr").removeClass('not-selected ') setTimeout(function () { jQuery(selected).removeClass('selected disable-click-event') jQuery("tr").removeClass('disable-click-event') delButton.removeAttribute('style') selected.removeAttribute("id") }, 1000) changeHeaderButtonText("+ New Folder", "openNewFolderForm()") } /** |-------------------------------------------------- | @function moveTableRow will takes 3 different parameter, | which then will move selected folder to the top of the table. | Table height is based rows height and how many rows is in the table (rows height * rows = table height), | So to move selected row to the top will take selected row height and multiply its index position | then its need to change to the negative value by calling @conconvertToNegative it will convert | and then it will be set to the translateY() | @param rowIndex selected row index which will be multiply | @param rowHeight single given row height | @param elemId selected row id which will be rising to the top |-------------------------------------------------- */ function moveTableRow(rowIndex, rowheight, elemId) { let value = convertToNegative(rowheight) * rowIndex let selected = document.getElementById(elemId) selected.style.transform = `translateY(${value}px)` } /** |-------------------------------------------------- | @function convertToNegative will convert given integer value to the its negative value | and return it | @param value takes integer value |-------------------------------------------------- */ function convertToNegative(value) { return -Math.abs(value) } /** |-------------------------------------------------- | @function constructBookmarkData will create table with | bookmark object datas on it | @param list will take array bookmark objects |-------------------------------------------------- */ function constructBookmarkData(list) { let table = document.createElement("table") for (let i = 0; i < list.length; i++) { let row = table.insertRow(i) row.setAttribute("id", list[i].bmId) let cell = row.insertCell(0) cell.setAttribute("class", "subTable-title") cell.setAttribute("onclick", "openBookMarkWindow(this)") cell.innerText = list[i].title } return table } //Dummy data, which tested will subtable work /* function createDummyData() { let table = document.createElement("table"); for (let i = 0 ; i < 25; i++) { let row = table.insertRow(i) let cell = row.insertCell(0) cell.innerText = i } return table }*/ function openBookMarkWindow(x) { let selectedBookmarkId = x.parentElement.id ipcRenderer.send('receive-and-send-bookmark-id', selectedBookmarkId) } function openCreateNewBmWindow() { let selectedFolderId = document.getElementById("selected").childNodes[1].id ipcRenderer.send('open-new-bookmark-window', selectedFolderId) }
module.exports = { HOST: "10.110.3.162", PORT: 27017, DB: "exam-manager" };
class A { } class B extends /*EXPECTED [ { "word" : "A" }, { "word" : "Object" }, { "word" : "Error" }, { "word" : "EvalError" }, { "word" : "RangeError" }, { "word" : "ReferenceError" }, { "word" : "SyntaxError" }, { "word" : "TypeError" }, { "word" : "Transferable" }, { "word" : "ArrayBufferView" }, { "word" : "Uint8Array" }, { "word" : "IteratorResult" }, { "word" : "Generator" } ] */ /*JSX_OPTS --complete 4:1 */
import XBody from './src/index.vue' XBody.install = (vue) => { vue.component(XBody.name, XBody) } export default XBody
import React, { Component } from "react"; import NotLoggedIn from "./notLoggedIn"; import axios from 'axios'; import "./jobs.css"; import { withRouter } from 'react-router-dom' class Savedjobs extends Component { constructor(props) { super(props); this.state = { info: [], } }; componentDidMount() { // if (this.props.isloggedin) { console.log(this.props) // if (!this.props.isloggedin) { // this.props.history.push("/loggedout") // } this.getJobs(); // } }; getJobs = () => { axios.get('/api/saved') .then(res => { console.log(res.data); if (res.data.length < 1) { document.getElementById('cardTitle').innerHTML = 'No Saved Jobs'; this.setState({ info: [] }) } else { document.getElementById("startSurvey").style.visibility = "hidden" document.getElementById('cardTitle').innerHTML = 'Saved Jobs' const jobInfo = []; for (let i = 0; i < res.data.length; i++) { jobInfo.push({ id: res.data[i]._id, title: res.data[i].title, description: res.data[i].description, salary: res.data[i].medianSalary, jobsAvailable: res.data[i].projectedJobs, link: res.data[i].link, hourly: res.data[i].hourlyWage, rent: res.data[i].rent, image: res.data[i].image }) } console.log(jobInfo); this.setState({ info: jobInfo }) } }); } deleteJobs = (info) => { let id = info.id; let URL = "/api/delete/" + id console.log('DELETING THIS'); console.log(id); axios.delete(URL) .then(() => { this.getJobs() }) } renderSavedJobs = () => { return ( <div className="container"> <h3 id="cardTitle"></h3> {this.state.info.map((info, index) => ( <div className="card mb-3"> {/* key={info.id}> */} <div className="row no-gutters"> <div className="col-md-4"> <img className="img-responsive job-img" src={info.image} alt="job-image" /> </div> <div className="col-md-8"> <div id="cardInfo" className="card-info" > <h3>{(info.title)}</h3> <p><strong>Description:</strong> {(info.description)}</p> <p><strong>Median Salary:</strong> {(info.salary) + "/yr"}</p> <p><strong>Median Hourly Wage:</strong> {(info.hourly + "/hr")}</p> <p><strong>Rent You Could Afford:</strong> {(info.rent) + "/mo"}</p> <p><strong>Available Jobs:</strong> {(info.jobsAvailable)}</p> {/* Buttons */} <a href={(info.link)} target="_blank" className="infobtn seemoreButton btn btn-info"><h6>See More</h6></a> <button className="infobtn deleteButton btn btn-danger" onClick={() => { this.deleteJobs(info) }}><h6>Delete</h6></button> </div> </div> </div> </div> ))} <div id="surveyBtnDiv"><a href="/jobs" id="startSurvey" className="btn button">See Job Results</a></div> </div> ) } render() { return <div> {this.renderSavedJobs()} {/* {this.props.isloggedin ? this.renderSavedJobs() : <NotLoggedIn />} */} </div> } } // export default (Savedjobs); export default withRouter(Savedjobs);
import React, { useState, useEffect } from 'react'; const HoldingItem = ({ holding }) => { const [dayChange, setDayChange] = useState(0); const [marketValue, setMarketValue] = useState(0); useEffect(() => { setDayChange(Math.round(holding.quote.dayChange * 100) / 100); setMarketValue(Math.round(holding.numberOfShares * holding.quote.price * 100) / 100); }, []); return ( <div className="details-holding-item"> <div className="details-col1 details-symbol">{holding.symbol}</div> <div className="details-col2">{holding.name}</div> <div className="details-col3">{holding.numberOfShares}</div> <div className="details-col4">${holding.basisPrice}</div> <div className="details-col5">{`$${holding.quote.price} (${dayChange}%)`}</div> <div className="details-col6">${holding.costBasis}</div> <div className="details-col7">${marketValue}</div> <div className="details-col8">${Math.round((marketValue - holding.costBasis) * 100) / 100}</div> </div> ); }; export default HoldingItem;
function calc (num) { for (let i = 2; i <= num/2; i++){ if (num % i == 0){ return "not prime"; } } return "prime"; } console.log(calc(63));
import React from "react"; import "./OccupantList.css"; import { connect } from "react-redux"; import OccupantItem from "./OccupantItem"; const OccupantList = ({ occupants, dispatch }) => { return occupants.map((occupant) => { return ( <OccupantItem // occupantsList={occupant} {...occupant} key={occupant.id} dispatch={dispatch} /> ); }); }; const mapStateToProps = (state) => { const { occupants } = state; return { occupants }; }; export default connect(mapStateToProps)(OccupantList);
import './Home.css' import React from 'react'; import { useEffect } from 'react'; import { useState } from 'react'; import { fetchMovies,fetchGenre, fetchMovieByGenre, fetchPersons, fetchTopratedMovie } from '../../service'; import RBCarousel from "react-bootstrap-carousel"; import "react-bootstrap-carousel/dist/react-bootstrap-carousel.css"; import { Link } from 'react-router-dom'; import ReactStars from "react-rating-stars-component"; function Home() { const [nowPlaying, setNowPlaying] = useState([]); const [genres, setGenres] = useState([]); const [movieByGenre, setMovieByGenre] = useState([]); const [persons, setPersions] = useState([]); const [topRated, setTopRated] = useState([]); const [isLoaded, setIsLoaded] =useState(false) useEffect(() => { const fetchAPI = async () => { setNowPlaying(await fetchMovies()); setGenres(await fetchGenre()); setMovieByGenre(await fetchMovieByGenre()); setPersions(await fetchPersons()); setTopRated(await fetchTopratedMovie()); setIsLoaded(true) } fetchAPI(); }, []) const handleGenreClick = async (genre_id) => { setMovieByGenre(await fetchMovieByGenre(genre_id)) } const movies = nowPlaying.slice(0, 5).map((item, index) => { return ( <div className="slider" key={index}> <div className="carousel-center slider-container"> <img className="slider-img" src={item.backPoster} alt={item.title} /> </div> <div className="carousel-center slider-icon"> <Link to={`/movie/${item.id}/`}> <i className="far fa-play-circle" style={{ fontSize: 70, color: '#fcf9c2' }}></i> </Link> </div> <div className="slider-overlay"> <div className="carousel-caption" style={{fontSize: 30}}> {item.title} </div> </div> </div> ) }) const genreList = genres.map((item, index) => { return ( <li className="list-inline-item" key={index}> <button onClick={() => handleGenreClick(item.id)} type="button" className="btn btn-outline-light"> {item.name} </button> </li> ) }) const movieList = movieByGenre.slice(0, 8).map((item, index) => { return ( <div className="col-md-3 col-sm-6 mb-3 movie-item" key={index}> <div className="card"> <Link to={`/movie/${item.id}`}> <img className="img-fluid poster-item" src={item.poster} alt={item.title}></img> </Link> </div> <Link to={`/movie/${item.id}`} className="link-detail "> <div className="overlay-item mt-2"> <p className="movie-title" >{item.title}</p> <p className="movie-rating" >Rated: {item.rating}</p> <ReactStars count={item.rating} size={20} color={"#f4c10f"}></ReactStars> </div> </Link> </div> ) }) const trendingPersons = persons.slice(0, 4).map((item, index) => { return ( <div className="col-md-3 col-sm-6 text-center" key={index}> <img src={item.profileImg} alt={item.name} className="img-fluid rounded-circle " /> <p className="font-weight-bold text-center mt-3">{ item.name}</p> </div> ) }) const topRatedList = topRated.slice(0, 4).map((item, index) => { return ( <div className="col-md-3 col-sm-6 mt-2 mb-3 movie-item" key={index}> <div className="card"> <Link to={`/movie/${item.id}`}> <img className="img-fluid poster-item" src={item.poster} alt={item.title}></img> </Link> </div> <Link to={`/movie/${item.id}`} className="link-detail "> <div className="overlay-item mt-2"> <p className="movie-title" >{item.title}</p> <p className="movie-rating">Rated: {item.rating}</p> <ReactStars count={item.rating} size={20} color={"#f4c10f"}></ReactStars> </div> </Link> </div> ) }) if (isLoaded === false) { return <h2 className="text-center" style={{color: "#756666", marginTop: 100}}>Please waiting...</h2> } return ( <div className="container"> {/* Carousel */} <div className="row mt-4"> <div className="col carousel"> <RBCarousel autoplay={true} pauseOnVisibility={true} slideshowSpeed={5000} version={4} className="carousel-fade" > {movies} </RBCarousel> </div> </div> {/* Genres */} <div className="row mt-4 "> <div className="col"> <ul className="list-inline"> {genreList} </ul> </div> </div> {/* Movie list */} <div className="row mt-3"> <div className="col"> <p className="font-weight-bold" style={{ color: "#5a606b", fontSize: 20 }}> NOW PLAYING </p> </div> <div className="col icon-right"> <i className="far fa-arrow-alt-circle-right"></i> </div> </div> <div className="row"> {movieList} </div> {/* Actor list */} <div className="row mt-3"> <div className="col"> <p className="font-weight-bold" style={{ color: "#5a606b", fontSize: 20 }}> TRENDING PERSIONS ON THIS WEEK </p> </div> <div className="col icon-right"> <i className="far fa-arrow-alt-circle-right"></i> </div> </div> <div className="row mt-3">{trendingPersons}</div> {/* Top rated list */} <div className="row mt-3"> <div className="col"> <p className="font-weight-bold" style={{ color: "#5a606b", fontSize: 20 }}> TOP RATED MOVIE </p> </div> <div className="col icon-right"> <i className="far fa-arrow-alt-circle-right"></i> </div> </div> <div className="row">{topRatedList}</div> {/* Footer */} <hr className="mt-5" style={{ borderTop: "1px solid #5a606b" }}></hr> <div className="row"> <div className="col-md-4 col-sm-12"> <p className="text-center" style={{ color: " #756666", fontSize: 20 }}>Question? Contact us now</p> <ul className="text-center" style={{paddingLeft: 0}}> <li className="infomation-item"> <a href="/" className="link-contact" > <i className="fab fa-facebook"><span style={{marginLeft: 5}}>Facebook</span></i> </a> </li> <li className="infomation-item"> <a href="/" className="link-contact"> <i className="fab fa-youtube"><span style={{marginLeft: 5}}>Youtube</span></i> </a> </li> <li className="infomation-item"> <a href="/" className="link-contact"> <i className="fab fa-twitter"><span style={{marginLeft: 5}}>Twitter</span></i> </a> </li> <li className="infomation-item"> <a href="/" className="link-contact"> <i className="fab fa-instagram"><span style={{marginLeft: 5}}>Instagram</span></i> </a> </li> </ul> </div> <div className="col-md-8 col-sm-12"> <p className="text-center" style={{ color: " #756666", fontSize: 20 }}>Thank you for watching!!!</p> <div className="infomation text-center"> <ul style={{flex: 1}}> <li className="infomation-item">FAQ</li> <li className="infomation-item">Terms of Use</li> <li className="infomation-item">Help Center</li> <li className="infomation-item">Cookie Preferences</li> </ul> <ul style={{flex: 1}}> <li className="infomation-item">Media Center</li> <li className="infomation-item">Privacy</li> <li className="infomation-item">Legal Notices</li> <li className="infomation-item">Corporate Information</li> </ul> </div> </div> </div> </div> ); } export default Home;
import { GetMemberInfo, GetCourseTagInfo, GetAllClass, GetEnterPriseCourse, GetShopCourse, GetAllDepartment, GetRoleList, GetChaine, GetPosition, GetHelpType, GetFriendlyLink, GetHelp, GetAD, GetAllMember, GetAllArticleType, GetArticleByEnterprise, GetRoleMenu, GetArticleList } from '@/api/index' import { GET_USERS, GET_COURSE_TAG, GET_CLASS, GET_EP_COURSE, GET_SHOP_COURSE, GET_DEPARTMENT, GET_ALLROLE, GET_CHAINE, GET_POS, GET_HT, GET_FRIEND, GET_HELP, GET_AD, GET_TREE, GET_ARTICE_TYPE, GET_ARTICE_WORD, ALL_ROLE_MENU, GET_ARTICLE, HAVE_ROLE, } from './mutations-type' export default { // 获取人员 async getUsers ({commit}, params) { const result = await GetMemberInfo(params) commit(GET_USERS, { userTable: result }) }, // 获取全部标签 async GetCourseTag ({commit}, params) { const result = await GetCourseTagInfo(params) commit(GET_COURSE_TAG, { GetCourseTag: result }) }, // 获取全部分类 async GetAllClass ({commit}, params) { const result = await GetAllClass(params) commit(GET_CLASS, { GetAllClass: (JSON.parse(result).Data).reverse() }) }, // 获取企业课程列表 async GetEPCourse ({commit}, params) { const result = await GetEnterPriseCourse(params) commit(GET_EP_COURSE, { EnterPriseCourse: result }) }, // 获取课程商课程列表 async GetSPCourse ({commit}, params) { const result = await GetShopCourse(params) commit(GET_SHOP_COURSE, { shopCourse: result }) }, // 获取全部部门 async AllDepartmen ({commit}) { const result = await GetAllDepartment() commit(GET_DEPARTMENT, { allDepartment: result }) }, // 获取全部角色 async AllRole ({commit}, params) { const result = await GetRoleList(params) commit(GET_ALLROLE, { allRole: result }) }, // 获取频道列表 async GetChaine ({commit}, params) { const result = await GetChaine(params) commit(GET_CHAINE, { chaineList: result }) }, // 获取广告列表 async GetPos ({commit}, params) { const result = await GetPosition(params) commit(GET_POS, { position: result }) }, // 获取帮助分类列表 async GetHT ({commit}, params) { const result = await GetHelpType(params) commit(GET_HT, { helpType: result }) }, // 获取友情链接 async GetFriend ({commit}, params) { const result = await GetFriendlyLink(params) commit(GET_FRIEND, { friendLink: result }) }, // 获取帮助列表 async GetHelpInfo ({commit}, params) { const result = await GetHelp(params) commit(GET_HELP, { helpList: result }) }, // 获取广告列表 async GetADInfo ({commit}, params) { const result = await GetAD(params) commit(GET_AD, { allAD: result }) }, // 获取企业组织 async getTree ({commit}, params) { const result = await GetAllMember(params) commit(GET_TREE, { getTreeList: result }) }, // 获取文章列表 async GetArticle ({commit}, params) { const result = await GetArticleList(params) commit(GET_ARTICLE, { articleList: result }) }, // 获取企业组织 async getarticeType ({commit}, params) { const result = await GetAllArticleType(params) commit(GET_ARTICE_TYPE, { articeType: JSON.parse(result)}) }, // 获取企业文章 async getarticeword ({commit}, params) { const result = await GetArticleByEnterprise(params) commit(GET_ARTICE_WORD, { ArticleWord: result}) }, // 获取权限菜单 async AllRoleMenu ({commit}) { const result = await GetRoleMenu() commit(ALL_ROLE_MENU, { roleMenu: result.Data.RoleMenu }) }, // 当前用户权限 // 获取权限菜单 async GetHaveRole ({commit}, params) { const result = await GetRoleMenu(params) commit(HAVE_ROLE, { haveRole: result.Data.HaveRoleMenu }) } }
/** MIT License Copyright (c) 2022 Sasikumar Ganesan Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ /** * A sample code to help x25519 key sharing and secret creation * * Author: Sasikumar Ganesan * */ const crypto = require("crypto"); /*** * XOR the given two values */ function getXOR(base64Value1, base64Value2){ const value1 = Buffer.from(base64Value1, "base64"); const value2 = Buffer.from(base64Value2, "base64"); let outBuf = Buffer.alloc(value1.length); for (let n = 0; n < value1.length; n++) outBuf[n] = value1[n] ^ value2[n % value2.length]; return outBuf; } /*** * Create the session key using the secret and xoredNonce * * secret - byte array * xoredNonce - byte array * * returns base64encoded key */ function getSessionKey(secret, xoredNonce) { const salt = xoredNonce.slice(0,20); return Buffer.from(crypto.hkdfSync("sha256", secret, salt, "", 32)).toString("base64"); } /** * Generate key pair for x25519 * **/ function generateKeyPair(password){ const x25519Keys = crypto.generateKeyPairSync("x25519", { publicKeyEncoding: { type: "spki", format: "der" }, privateKeyEncoding: { type: "pkcs8", format: "pem", cipher: "aes-256-cbc", passphrase: password } }); return x25519Keys; } /*** * Convert the hex private key to jwk encoded key */ function getPrivateKeyFromHex(x25519Hex, x25519PublicHex){ const privateKey = crypto.createPrivateKey({ key: { kty: "OKP", crv: "X25519", x: Buffer.from(x25519PublicHex, "hex").toString("base64url"), d: Buffer.from(x25519Hex, "hex").toString("base64url"), }, format: "jwk" }) return privateKey; } /*** * Convert the hex public key to der encoded key */ function getPublicKeyFromHex(x25519PublicHex){ const publicKey = crypto.createPublicKey({ key: { kty: "OKP", crv: "X25519", x: Buffer.from(x25519PublicHex,"hex").toString("base64url") }, format: "jwk" }); return publicKey; } /** * * Here is the sample that shows how to take advantage of the above function. */ const peerPublicKey = "de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f"; const base64RemoteNonce = "WY9hFnr4WLFd9mVvItMIdBjFygVDpPpoi/BZ3Z3lBfY="; const base64YourNonce = "2OZz6xYAnS6a83WcOZFLQH/0YVcl1vWE+zespfGAWFo="; /** * Often you may want to load this key from a pem file or auto generate it using a cache. * So feel free to use the logic thats necessary. * generateKeyPair this method will create a key for you when you are in need. */ const ourPrivateKey = "77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a"; const ourPublicKey = "8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a"; const ourPrivateKeyObject = getPrivateKeyFromHex(ourPrivateKey, ourPublicKey); const peerPublicKeyBuffer = getPublicKeyFromHex(peerPublicKey); const secret = crypto.diffieHellman({privateKey: ourPrivateKeyObject, publicKey: peerPublicKeyBuffer}); /** * Note: This method could have potential performance bottle neck as the key derivation happens * in sync mode. It would good if any one can test it for performance. */ const sharedSecret = getSessionKey(secret, getXOR(base64YourNonce, base64RemoteNonce)); /** * The keys used or samples from the RFC. So the shared secret key should be * 4a5d9d5ba4ce2de1728e3bf480350f25e07e21c947d19e3376f09b3c1e161742 */ console.log("Secret Key in hex format: " + secret.toString("hex")); /** * For the given xor value the session key should be * 3b434ed3f93ce5ef1115a89955a50c0fa3ef09f449a842fed3bf81c2939f4261 */ console.log("Shared session key in hex: " + Buffer.from(sharedSecret,"base64").toString("hex") );
import { stripTrailingSlash } from '../utils'; const BASE_DEVICE_MONITORING_URL_V2 = stripTrailingSlash(process.env.REACT_APP_BASE_URL_V2); export const GET_DEVICE_STATUS_SUMMARY = `${BASE_DEVICE_MONITORING_URL_V2}/monitor/device/status`; export const GET_NETWORK_UPTIME = `${BASE_DEVICE_MONITORING_URL_V2}/monitor/network/uptime`; export const GET_DEVICE_UPTIME_LEADERBOARD = `${BASE_DEVICE_MONITORING_URL_V2}/monitor/device/uptime/leaderboard`; export const GET_DEVICE_BATTERY_VOLTAGE = `${BASE_DEVICE_MONITORING_URL_V2}/monitor/devices/battery`; export const GET_DEVICE_SENSOR_CORRELATION = `${BASE_DEVICE_MONITORING_URL_V2}/monitor/device/sensors/correlation`; export const DEVICE_MAINTENANCE_LOG_URI = `${BASE_DEVICE_MONITORING_URL_V2}/monitor/device/maintenance_logs/`; export const ALL_DEVICES_STATUS = `${BASE_DEVICE_MONITORING_URL_V2}/monitor/devices/status`; export const DEVICES_UPTIME = `${BASE_DEVICE_MONITORING_URL_V2}/monitor/devices/uptime`; export const GET_ONLINE_OFFLINE_MAINTENANCE_STATUS = `${BASE_DEVICE_MONITORING_URL_V2}/monitor/devices/online_offline`; export const GENERATE_AIRQLOUD_UPTIME_SUMMARY_URI = `${BASE_DEVICE_MONITORING_URL_V2}/monitor/uptime`;
"use strict"; /// <reference path="./GameBuildSettings.d.ts" /> Object.defineProperty(exports, "__esModule", { value: true }); const GameBuildSettingsEditor_1 = require("./GameBuildSettingsEditor"); const buildGame_1 = require("./buildGame"); SupClient.registerPlugin("build", "game", { settingsEditor: GameBuildSettingsEditor_1.default, build: buildGame_1.default });
/** * 导航栏移动效果 */ $(".navname a").on("mouseover", function() { $(this).addClass("active"); var leftsize = $(window).width()*0.5; var size = leftsize-200; $(".navmsg").css("margin-left",size+"px"); $(".navmsg").removeClass("hide"); $(".navmsg").text($(this).text()); $(this).on("mouseout", function() { $(this).removeClass("active"); $(".navmsg").addClass("hide"); }) }); /** * 自动切换轮播图 */ var time = 3000; setInterval(imgchange, time); function imgchange() { var val = $(".imgbox").css("left"); if(val == "0px") { $(".imgbox").css("left", "-200px"); } else { $(".imgbox").css("left", "0px"); } }
/* * @akoenig/website * * Copyright(c) 2017 André König <andre.koenig@gmail.com> * MIT Licensed * */ /** * @author André König <andre.koenig@gmail.com> * */ import React from "react"; import styled from "styled-components"; const Wrapper = styled.section` background: rgba(255, 255, 255, 0.8); padding: 2rem 0.5rem 0; `; const Headline = styled.h3` color: rgba(0, 0, 0, 0.8); font-size: 70%; font-weight: 800; text-transform: uppercase; `; const Articles = styled.ul` list-style-type: none; margin: 0; padding: 0; `; const Article = styled.li``; const ArticleMeta = styled.div` align-items: center; display: flex; line-height: 0.9em; `; const ArticlePublicationDate = styled.span` color: #f44336; font-size: 70%; font-weight: 100; `; const ArticleTags = styled.ul` font-size: 70%; list-style-type: none; margin: 0 0 0 1.5em; padding: 0; `; const ArticleTag = styled.li` border: 1px solid rgba(0, 0, 0, 0.1); border-radius: 3px; color: rgba(0, 0, 0, 0.4); display: inline-block; font-size: 80%; margin: 0 1em 0 0; padding: 0.2em 0.4em; `; const ArticleHeadline = styled.a` border-bottom: 1px solid transparent; font-size: 90%; display: inline-block; cursor: pointer; color: rgba(0, 0, 0, 0.6); padding: 0; padding-bottom: 0.4em; margin: 0.4em 0 0 0; transition: border-color 0.2s ease-in-out, color 0.4s ease-in-out; &:hover { border-bottom: 1px solid #f44336; text-decoration: none; color: #000; } `; const LatestArticles = () => ( <Wrapper> <Headline>Latest Articles</Headline> <Articles> <Article> <ArticleMeta> <ArticlePublicationDate>10th July 2019</ArticlePublicationDate> <ArticleTags> <ArticleTag>Kubernetes</ArticleTag> <ArticleTag>Knative</ArticleTag> <ArticleTag>Serverless</ArticleTag> </ArticleTags> </ArticleMeta> <ArticleHeadline href="https://dev.to/andre/first-impressions-of-knative-eventing-bn5" target="_blank" > First Impressions of Knative Eventing </ArticleHeadline> </Article> <Article> <ArticleMeta> <ArticlePublicationDate>14th February 2018</ArticlePublicationDate> <ArticleTags> <ArticleTag>GraphQL</ArticleTag> <ArticleTag>Error handling</ArticleTag> </ArticleTags> </ArticleMeta> <ArticleHeadline href="https://dev.to/andre/handling-errors-in-graphql--2ea3" target="_blank" > Handling errors in GraphQL </ArticleHeadline> </Article> <Article> <ArticleMeta> <ArticlePublicationDate>13th February 2018</ArticlePublicationDate> <ArticleTags> <ArticleTag>GraphQL</ArticleTag> <ArticleTag>Prisma</ArticleTag> <ArticleTag>Kubernetes</ArticleTag> </ArticleTags> </ArticleMeta> <ArticleHeadline href="https://dev.to/andre/deploying-a-prisma-cluster-to-kubernetes--3lbi" target="_blank" > Deploying a Prisma cluster to Kubernetes </ArticleHeadline> </Article> <Article> <ArticleMeta> <ArticlePublicationDate>10th October 2017</ArticlePublicationDate> <ArticleTags> <ArticleTag>Security</ArticleTag> <ArticleTag>Linux</ArticleTag> <ArticleTag>Docker</ArticleTag> <ArticleTag>Firewall</ArticleTag> </ArticleTags> </ArticleMeta> <ArticleHeadline href="https://dev.to/andre/docker-restricting-in--and-outbound-network-traffic-67p" target="_blank" > Docker: Restricting in- and outbound network traffic </ArticleHeadline> </Article> <Article> <ArticleMeta> <ArticlePublicationDate>2nd October 2017</ArticlePublicationDate> <ArticleTags> <ArticleTag>GraphQL</ArticleTag> <ArticleTag>React</ArticleTag> <ArticleTag>Apollo</ArticleTag> </ArticleTags> </ArticleMeta> <ArticleHeadline href="https://dev.to/andre/react-apollo-an-approach-to-handle-errors-globally-jg" target="_blank" > react-apollo: An approach for handling errors globally </ArticleHeadline> </Article> </Articles> </Wrapper> ); export { LatestArticles }; /* <section className="IndexPage__blog"> <h3 className="IndexPage__blog__headline">Latest Article</h3> <div className="IndexPage__blog__meta"> <span className="IndexPage__blog__articleDate">2nd October 2017</span> <ul className="IndexPage__blog__tags"> <li className="IndexPage__blog__tags__tag">GraphQL</li> <li className="IndexPage__blog__tags__tag">React</li> <li className="IndexPage__blog__tags__tag">Apollo</li> </ul> </div> <div className="IndexPage__blog__article"> <h4 className="IndexPage__blog__article__headline"> </h4> </div> </section>*/
let age = 20; if (age >= 18 && age <= 25) { document.write("You can enter the bar!"); }
let animals = ['dog', 'cat', 'seal', 'walrus', 'lion']; let index = animals.indexOf('seal'); console.log(animals.lastIndexOf('walrus')); console.log(animals.splice(index, 1));
const name=require('../Test'); const assert=require('chai').assert; describe('should test',()=>{ it('should test smth', ()=>{ assert.equal(name(1),3); }); });
'use strict'; var mongoose = require('mongoose'); require('mongoose-type-url'); var Schema = mongoose.Schema; var SellerSchema = new Schema({ name:{ type:String, default:"username", }, }); module.exports = mongoose.model('sel_Seller', SellerSchema);
const db = require("../db"); const partialUpdate = require("../helpers/partialUpdate"); const ExpressError = require("../helpers/expressError"); class Product { /** find all products (can filter on terms) */ static async findAll(data){ let baseQuery = `SELECT id, name, image, brand, price, category, count_in_stock, description, rating, num_reviews FROM products`; let whereExpression = []; let queryValues = []; if(data.search){ queryValues.push(`%${data.search}%`); whereExpression.push(`name ILIKE $${queryValues.length}`) } if(whereExpression.length > 0){ baseQuery += " WHERE "; } // finalize query and return result let finalQuery = baseQuery + whereExpression.join(" AND ") + " ORDER BY name"; const products = await db.query(finalQuery, queryValues); return products.rows; } /** given a product, return data about product. */ static async findOne(id){ const result = await db.query( `SELECT id, name, image, brand, price, category, count_in_stock, description, rating, num_reviews FROM products WHERE id = $1`, [id] ); const product = result.rows[0]; if(!product){ throw new ExpressError(`There exists no product of id '${id}'`, 404) } // one to many relationships from products to reviews table const reviewRes = await db.query( `SELECT id, title, rating, comment FROM reviews WHERE product_id = $1`, [id] ); product.reviews = reviewRes.rows; return product; } /** create a new product */ static async create(data){ const checkDuplicate = await db.query( `SELECT id, name FROM products WHERE id = $1`, [data.id] ); if(checkDuplicate.rows[0]){ throw new ExpressError( `There already exists a product with product id ${data.id}` ) } const result = await db.query( `INSERT INTO products( name, image, brand, price, category, count_in_stock, description ) VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING name, image, brand, price, category, count_in_stock, description `, [ data.name, data.image, data.brand, data.price, data.category, data.count_in_stock, data.description ] ); return result.rows[0]; } /** update product */ static async update(id, data){ let { query, values } = partialUpdate( "products", data, "id", id ); const result = await db.query(query, values); const product = result.rows[0]; if(!product){ throw new ExpressError(`There exists no product of id '${id}'`, 404); } return product; } /** delete product from database; returns undefined */ static async remove(id){ const result = await db.query( `DELETE FROM products WHERE id = $1 RETURNING id `, [id] ); if(result.rows.length === 0){ throw new ExpressError(`There is no product of id '${id}'`, 404); } } /** add review of the product */ static async addReview(id, data){ //find product const product = await this.findOne(id); //insert into reviews const result = await db.query( `INSERT INTO reviews (product_id, title, rating, comment) VALUES ($1, $2, $3, $4) RETURNING id, product_id, title, rating, comment`, [ id, data.title, data.rating, data.comment ] ); // update reviews and ratings of product: const numReviews = product.reviews.length + 1; product.reviews.push(result.rows[0]); const avgRating = product.reviews.reduce((a, c) => a + c.rating, 0) / numReviews // update product as reviews changed await db.query( `UPDATE products SET num_reviews = $1, rating = $2 WHERE id = $3`, [numReviews, avgRating, product.id] ); return result.rows[0]; } /** get reviews from product id */ static async findAllReviewsByProductId( id ){ const result = await db.query( `SELECT id, product_id, title, rating, comment FROM reviews WHERE product_id = $1`, [id] ); return result.rows; } /** delete review from database, returns undefined */ static async removeReview(id, rId){ const result = await db.query( `DELETE FROM reviews WHERE id = $1 RETURNING title`, [rId] ); if(result.rows.length === 0){ throw new ExpressError(`There is no review of id '${rId}'`, 404); } const product = await this.findOne(id); const numReviews = product.reviews.length; // remove a review from reviews for(let i = 0; i < numReviews; i++){ if(product.reviews[i] === rId){ product.review.splice(i, 1); } } const avgRating = ( product.reviews.reduce((a, c) => a + c.rating, 0) / numReviews ) || 0; // update product as reviews changed await db.query( `UPDATE products SET num_reviews = $1, rating = $2 WHERE id = $3`, [numReviews, avgRating, id] ); } } module.exports = Product;
const result = document.getElementById("coin_result") function convertCurrency(form) { const from = form.from_coin.value const to = form.to_coin.value const amount = form.coin_val.value if(from === to ) { letter = from == "E" ? " €" : (from == "D" ? " $": " ¥") result.innerHTML = amount + letter } if(from == "E" && to == "D") { result.innerHTML = (amount*1.11).toFixed(2) + " $" } if(from == "E" && to == "Y") { result.innerHTML = (amount*119.40).toFixed(2) + " ¥" } if(from == "D" && to == "E") { result.innerHTML = (amount*0.90).toFixed(2) + " €" } if(from == "D" && to == "Y") { result.innerHTML = (amount*107.91).toFixed(2) + " ¥" } if(from == "Y" && to == "D") { result.innerHTML = (amount*0.0093).toFixed(2) + " $" } if(from == "Y" && to == "E") { result.innerHTML = (amount*0.90).toFixed(2) + " €" } console.log(from) console.log(to) }
import React from 'react'; import moment from 'moment'; import styles from './stats.module.css'; const formattedMoment = (dateString) => moment(dateString, 'YYYY-MM-DD'); // https://stackoverflow.com/questions/25150570/get-hours-difference-between-two-dates-in-moment-js function getNumDaysAbroad() { const europe = moment.duration(formattedMoment('2018-3-18').diff(formattedMoment('2018-2-6'))).asDays(); const latAm = moment.duration(formattedMoment('2018-9-6').diff(formattedMoment('2018-5-12'))).asDays(); const asiaBeyond = moment.duration(formattedMoment(new Date()).diff(formattedMoment('2018-11-27'))).asDays(); return Math.ceil(europe + latAm + asiaBeyond); } const Stat = ({ num, thing, emoji }) => ( <div className={styles.statsItem}> <div className={styles.statsNum}> {num} </div> <div className={styles.statsThing}> {thing} </div> <div className={styles.statsEmoji}> {emoji} </div> </div> ); export default ({ numCities, numCountries }) => ( <div className={styles.stats}> <Stat num={numCities} thing="cities" emoji="🏙" /> <Stat num={numCountries} thing="countries" emoji="✈️" /> <Stat num={getNumDaysAbroad()} thing="days traveling" emoji="⏳" /> </div> );
var test = require('tape'); var textSlicer = require('../'); test('chopWords should return a well formed array of words', function (t) { var chunks = textSlicer.chopWords(' mon petit chat gris : '); t.deepEqual(chunks, [ 'mon', ' ', 'petit', ' ', 'chat', ' ', 'gris', ' ', ':' ]); t.end(); }); test('chopChars should return a well formed array of chars', function (t) { var chunks = textSlicer.chopChars(' mon petit chat gris : '); t.deepEqual(chunks, [ 'm', 'o', 'n', ' ', 'p', 'e', 't', 'i', 't', ' ', 'c', 'h', 'a', 't', ' ', 'g', 'r', 'i', 's', ' ', ':' ]); t.end(); });
const fetchFallbackImage = type => { switch (type) { case 'Bird': return require('../images/fallbacks/bird-ph.png'); case 'Barnyard': return require('../images/fallbacks/barnyard-ph.png'); case 'Cat': return require('../images/fallbacks/cat-ph.png'); case 'Dog': return require('../images/fallbacks/dog-ph.png'); case 'Horse': return require('../images/fallbacks/horse-ph.png'); case 'Rabbit': return require('../images/fallbacks/rabbit-ph.png'); case 'Shelter': return require('../images/fallbacks/shelter-ph.png') case 'Scales, Fins & Other': return require('../images/fallbacks/fish-ph.png'); case 'Small & Furry': return require('../images/fallbacks/small-ph.png'); default: return require('../images/fallbacks/dog-ph.png'); } } export { fetchFallbackImage, }
import React from "react"; import PropTypes from "prop-types"; import Notification from "../Notification/Notification"; const Statistics = ({ onGood, onNeutral, onBad, onTotalFeedback, onPositivePercentage, }) => { return ( <> {onTotalFeedback !== 0 ? ( <ul className="list"> <li>Good: {onGood}</li> <li>Neutral: {onNeutral}</li> <li>Bad: {onBad}</li> <li>Total: {onTotalFeedback}</li> <li>Positive feedback: {onPositivePercentage}</li> </ul> ) : ( <Notification message="No feedback given" /> )} </> ); }; export default Statistics; Statistics.propTypes = { onGood: PropTypes.number.isRequired, onNeutral: PropTypes.number.isRequired, onBad: PropTypes.number.isRequired, onTotalFeedback: PropTypes.number.isRequired, onPositivePercentage: PropTypes.string.isRequired, };
/* * Copyright (c) 2017 American Express Travel Related Services Company, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ import React from "react"; import { act } from "react-dom/test-utils"; import { mount } from "enzyme"; import { Wizard, Steps, Step } from "../../src"; function setup(wizardProps) { const returnValue = {}; act(() => { mount( <Wizard {...wizardProps}> {props => { Object.assign(returnValue, props); return ( <Steps> <Step id="gryffindor"> <div /> </Step> <Step id="slytherin"> <div /> </Step> </Steps> ); }} </Wizard> ); }); return returnValue; } describe("Wizard", () => { describe("with no props", () => { let wizard; beforeEach(() => { wizard = setup(); }); it("should go to the next and previous steps", () => { const { onNext, onPrevious } = wizard; expect(wizard.step).toEqual({ id: "gryffindor" }); act(() => onNext()); expect(wizard.step).toEqual({ id: "slytherin" }); act(() => onPrevious()); expect(wizard.step).toEqual({ id: "gryffindor" }); }); it("should push steps onto the stack", () => { const { push } = wizard; expect(wizard.step).toEqual({ id: "gryffindor" }); act(() => push("slytherin")); expect(wizard.step).toEqual({ id: "slytherin" }); }); it("should replace steps in the stack", () => { const { replace } = wizard; act(() => replace()); expect(wizard.step).toEqual({ id: "slytherin" }); }); it("should pull steps off the stack", () => { const { onNext, go } = wizard; expect(wizard.step).toEqual({ id: "gryffindor" }); act(() => onNext()); expect(wizard.step).toEqual({ id: "slytherin" }); act(() => go(-1)); expect(wizard.step).toEqual({ id: "gryffindor" }); }); it("should do nothing if an invalid step is pushed", () => { const { push } = wizard; act(() => push("hufflepuff")); expect(wizard.step).toEqual({ id: "gryffindor" }); }); }); describe("with onNext prop", () => { const onWizardNext = jest.fn(({ push }) => push()); let wizard; beforeEach(() => { wizard = setup({ onNext: onWizardNext }); }); it("call onNext and go to the next step", () => { const { onNext } = wizard; act(() => onNext()); expect(onWizardNext).toHaveBeenCalled(); expect(wizard.step).toEqual({ id: "slytherin" }); }); }); describe("with existing history", () => { const history = { push: () => null, replace: () => null, listen: () => () => null, location: { pathname: "/slytherin" } }; let wizard; beforeEach(() => { wizard = setup({ history }); }); it("starts at the step in history", () => { expect(wizard.step).toEqual({ id: "slytherin" }); }); }); describe("with existing history and non-strict route matching", () => { const history = { push: () => null, replace: () => null, listen: () => () => null, location: { pathname: "/slytherin/snape" } }; let wizard; beforeEach(() => { wizard = setup({ history, exactMatch: false }); }); it("matches the step", () => { expect(wizard.step).toEqual({ id: "slytherin" }); }); }); describe("without a function as a child", () => { let mounted; beforeEach(() => { act(() => { mounted = mount( <Wizard> <Steps> <Step id="gryffindor"> <div /> </Step> <Step id="slytherin"> <div /> </Step> </Steps> </Wizard> ); }); }); it("should render the snapshot correctly", () => { expect(mounted).toMatchSnapshot(); }); }); describe("with a function as a child", () => { let mounted; beforeEach(() => { act(() => { mounted = mount( <Wizard> {() => ( <Steps> <Step id="gryffindor"> <div /> </Step> <Step id="slytherin"> <div /> </Step> </Steps> )} </Wizard> ); }); }); it("should render the snapshot correctly", () => { expect(mounted).toMatchSnapshot(); }); }); });
config = { blog_name: "天狼星 ● 文档", per_page: 10, // 首页每次载入文章列表数量 file_server: "http://"+window.location.hostname+":8001", };
import React from 'react'; import { MDBRow, MDBCol, MDBView, MDBCard, MDBCardBody, MDBTable, MDBTableHead, MDBTableBody, } from 'mdbreact'; import Spinner from '../Spinner' export default function FilmsPage({ result_film, isLoading }) { return isLoading ? ( <Spinner /> ) : ( <> {/* <MDBCard className="mb-5"> <MDBCardBody id="breadcrumb" className="d-flex align-items-center justify-content-between"> <MDBBreadcrumb> <MDBBreadcrumbItem>Home</MDBBreadcrumbItem> <MDBBreadcrumbItem active>Films</MDBBreadcrumbItem> </MDBBreadcrumb> <MDBFormInline className="md-form m-0"> <input className="form-control form-control-sm" type="search" placeholder="Type your query" aria-label="Search" /> <MDBBtn size="sm" color="yellow" className="my-0" type="submit"><MDBIcon icon="search" /></MDBBtn> </MDBFormInline> </MDBCardBody> </MDBCard> */} <MDBRow> <MDBCol md="12"> <MDBCard className="mt-5"> <MDBView className="gradient-card-header yellow darken-2"> <h4 className="h4-responsive text-white">Films Tables</h4> </MDBView> <MDBCardBody> <MDBTable striped responsive> <MDBTableHead> <tr> <th>Title</th> <th>Episode</th> <th>Opening Crawl</th> <th>Director</th> <th>Released Date</th> </tr> </MDBTableHead> <MDBTableBody> {result_film.map((film, i) => { return ( <tr key={i}> <td>{film.title}</td> <td>{film.episode_id}</td> <td>{film.opening_crawl}</td> <td>{film.director}</td> <td>{film.release_date}</td> </tr> ) })} </MDBTableBody> </MDBTable> </MDBCardBody> </MDBCard> </MDBCol> </MDBRow> </> ) } // const FilmsPage = () => { // return ( // <React.Fragment> // <BreadcrumSection /> // </React.Fragment> // ) // } // export default FilmsPage;
const aux = document.getElementById('aux'); const bac = document.getElementById('dd1'); const bac2 = document.getElementById('dd333');
const puppeteer = require('puppeteer'); const CREDS = require('./creds'); async function run() { const browser = await puppeteer.launch({ headless: false }); const page = await browser.newPage(); await page.goto('https://github.com/login'); // dom element selectors const USERNAME_SELECTOR = '#login_field'; const PASSWORD_SELECTOR = '#password'; const BUTTON_SELECTOR = '#login > form > div.auth-form-body.mt-3 > input.btn.btn-primary.btn-block'; await page.click(USERNAME_SELECTOR); await page.keyboard.type(CREDS.username); await page.click(PASSWORD_SELECTOR); await page.keyboard.type(CREDS.password); await page.click(BUTTON_SELECTOR); await page.waitForNavigation(); /* const userToSearch = 'john'; const searchUrl = `https://github.com/search?q=${userToSearch}&type=Users&utf8=%E2%9C%93`; await page.goto(searchUrl); await page.waitFor(2 * 1000); const LIST_USERNAME_SELECTOR = '#user_search_results > div.user-list > div:nth-child(4) > div.flex-auto > div:nth-child(1) > div.f4.text-normal > a.text-gray > em' const LIST_EMAIL_SELECTOR = '#user_search_results > div.user-list > div:nth-child(4) > div.flex-auto > div.d-flex.flex-wrap.text-small.text-gray > div:nth-child(2) > a' const LENGTH_SELECTOR_CLASS = 'user-list-item'; */ } run();
// @flow import * as React from 'react'; type ShowDateViewProps = { formatter: Date => string, date: Date, prefix?: string } export const ShowDateView: React.ComponentType<ShowDateViewProps> = ({ date, formatter, prefix = '-> ' }) => ( <div>{prefix}{formatter(date)}</div> );
const gulp = require('gulp'); //utilities const del = require('del'); const plumber = require('gulp-plumber'); //css const sass = require('gulp-sass'); const autoprefixer = require('gulp-autoprefixer'); //html const htmlReplace = require('gulp-html-replace'); const htmlMin = require('gulp-htmlmin'); //images const imagemin = require('gulp-imagemin'); //watch & BrowserSync const browserSync = require('browser-sync'); const server = browserSync.create(); function reload(done) { server.reload(); done(); } function serve(done) { server.init({ server: { baseDir: './' } }); done(); } //styles:development gulp.task('stylesDev', () => { return gulp .src('./sass/*.sass') .pipe(plumber()) .pipe(sass({ outputStyle: 'enhanced' }).on('error', sass.logError)) .pipe(autoprefixer()) .pipe(gulp.dest('./css')); }); //styles:distribution gulp.task('styles', () => { return gulp .src('./sass/*.sass') .pipe(plumber()) .pipe(sass({ outputStyle: 'compressed' }).on('error', sass.logError)) .pipe(autoprefixer()) .pipe(gulp.dest('./dist/css')); }); gulp.task('images', () => { return gulp .src('./img/*') .pipe( imagemin([ imagemin.gifsicle({ interlaced: true }), imagemin.jpegtran({ progressive: true }), imagemin.optipng({ optimizationLevel: 5 }), imagemin.svgo({ plugins: [{ removeViewBox: true }, { cleanupIDs: false }] }) ]) ) .pipe(gulp.dest('./dist/img')); }); gulp.task('html', function() { return gulp .src('./*.html') .pipe( htmlReplace({ css: './css/style.css' }) ) .pipe( htmlMin({ sortAttributes: true, sortClassName: true, collapseWhitespace: true }) ) .pipe(gulp.dest('./dist/')); }); gulp.task('clean', () => { return del(['./dist/**', '!./dist']); }); //watch gulp.task( 'default', gulp.series( 'clean', gulp.parallel('images', 'stylesDev', 'html', serve, function watchFiles() { // gulp.watch('./sass/*.sass', gulp.series('stylesDev', reload)); gulp.watch('/img/*', gulp.series('images', reload)); gulp.watch('./*.html', gulp.series('html', reload)); }) ) ); //distribution build gulp.task('build', gulp.series('clean', gulp.parallel('images', 'styles', 'html')));
var searchData= [ ['genvariable_114',['GenVariable',['../structGenVariable.html',1,'']]] ];
jQuery().ready(function() { if (jQuery('form.ecapForm') && typeof(Validation) !== "undefined" && typeof(ZipValidation) !== "undefined") { Validation.initialize('form.ecapForm'); ZipValidation.initialize('form.ecapForm'); } }); var getQueryStringParam = getQueryStringParam || function(param) { param = param.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]"); var regexS = "[\\?&]" + param + "=([^&#]*)"; var regex = new RegExp(regexS); var results = regex.exec(window.location.search); if (results == null) { return ""; } else { return decodeURIComponent(results[1].replace(/\+/g, " ")); } }; var updateQueryStringParam = updateQueryStringParam || function (key, value, url) { var re = new RegExp('([?&])' + key + '=.*?(&|#|$)(.*)', 'gi'); var hash; if (!url) { url = window.location.href; } if (re.test(url)) { if (typeof value !== 'undefined' && value !== null) { return url.replace(re, '$1' + key + '=' + value + '$2$3'); } else { hash = url.split('#'); url = hash[0].replace(re, '$1$3').replace(/(&|\?)$/, ''); if (typeof hash[1] !== 'undefined' && hash[1] !== null) { url += '#' + hash[1]; } return url; } } else { if (typeof value !== 'undefined' && value !== null) { var separator = (url.indexOf('?') !== -1) ? '&' : '?'; hash = url.split('#'); url = hash[0] + separator + key + '=' + value; if (typeof hash[1] !== 'undefined' && hash[1] !== null) { url += '#' + hash[1]; } return url; } else { return url; } } }; var Validation = { errorElement: jQuery(document.createElement('SPAN')).addClass('errEmailAddress').html('Please check your email address'), initialize: function(selector) { jQuery(selector).submit(this.controller); }, controller: function(event) { var value = jQuery(event.target).find('input.formbox[name=email]')[0].value; if (!Validation.isValid(value)) { jQuery(event.target).find('input.formbox[name=email]').after(Validation.errorElement); event.preventDefault(); return false; } else { Validation.errorElement.remove(); } }, isValid: function(value, regex) { return value.match(/^[a-zA-Z0-9._\-\+]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,4}$/); } }; var ZipValidation = { errorElement: jQuery(document.createElement('SPAN')).addClass('errZipCode').html('Please check your zip code'), initialize: function(selector) { if (ZipValidation.zipCodeInputExists(selector)) { jQuery(selector).submit(this.controller); } }, controller: function(event) { var value = jQuery(event.target).find('input[name=zipcode]')[0].value; if (!ZipValidation.isValid(value)) { jQuery(event.target).find('input[name=zipcode]').after(ZipValidation.errorElement); event.preventDefault(); return false; } else { ZipValidation.errorElement.remove(); } }, isValid: function(value, regex) { return value.match(/^[0-9]{5}$/) || value.match(/^[0-9]{5}\-[0-9]{4}$/); }, zipCodeInputExists: function(selector) { return jQuery(selector).find('input[name=zipcode]').length > 0; } }; var TrackingPixel = { image: function(imagePath) { jQuery(document).ready(function() { var img = document.createElement('img'); img.src = imagePath; img.width = 0; img.height = 0; img.alt = ''; img.style.cssText = 'display:none'; document.body.appendChild(img); }); }, script: function(scriptPath, callback) { var el = document.createElement('script'); el.src = scriptPath; el.type = 'text/javascript'; document.body.appendChild(el); if (callback != undefined && callback.typeOf == 'function') { callback(); } } }; var Transcript = { closeButton: jQuery('#closeBtn'), viewButton: jQuery('#viewTs'), transcript: jQuery('#transcript'), show: function() { Transcript.viewButton.hide(); Transcript.closeButton.show(); Transcript.transcript.slideDown(); }, hide: function() { Transcript.closeButton.hide(); Transcript.viewButton.show(); Transcript.transcript.slideUp(); } }; // This code is for use on pages where we do an apparent redirect when the user tries to leave the page. // In fact, we replace the current page content with an iframe showing another page; the user gets a // dialog box so they can escape if they wish. var LastChanceOnExit = { PreventExitSplash: false, // Function to replace the contents of the body with the // inline frame so it appears to have jumped to a new page. DisplayExitSplash: function() { if (LastChanceOnExit.PreventExitSplash == false) { if (typeof(analytics) !== "undefined") { analytics.track('Exit Pop', { category: 'Video', label: 'Video', value: 0 }); } if (typeof pageLoadTime != 'undefined') { exitSplashDisplayTime = Math.round(Date.now() / 1000) - pageLoadTime; timerParams = "&exitSplashDisplayTime=" + exitSplashDisplayTime; } else { timerParams = ""; } LastChanceOnExit.PreventExitSplash = true; if (typeof(exitSplashPageUrl) !== "undefined" && exitSplashPageUrl != null) { window.scrollTo(0, 0); divtag = document.createElement("div"); divtag.setAttribute("id", "ExitSplashMainOuterLayer"); divtag.style.position = "absolute"; divtag.style.width = "100%"; divtag.style.height = "100%"; divtag.style.zIndex = "99"; divtag.style.left = "0px"; divtag.style.top = "0px"; divtag.innerHTML = '<iframe src="' + exitSplashPageUrl + timerParams + '" width="100%" height="100%" align="middle" frameborder="0"></iframe>'; theBody = document.body; if (!theBody) { theBody = document.getElementsByTagName("body")[0]; } theBody.innerHTML = ""; theBody.topMargin = "0px"; theBody.rightMargin = "0px"; theBody.bottomMargin = "0px"; theBody.leftMargin = "0px"; theBody.style.overflow = "hidden"; theBody.appendChild(divtag); } return exitSplashMessage; } }, SetSourceCodes: function() { var pageSourceCode = LastChanceOnExit.GetSourceCode(window.location.href); source = (pageSourceCode == "") ? defaultSourceCode : pageSourceCode; // source all the links that do not have one var allLinks = document.links; for (var i = 0; i < allLinks.length; i++) { var thisLink = allLinks[i]; if (thisLink.hash == ""){ var thisLinkSource = LastChanceOnExit.GetActualSourceCode(thisLink.href); if (thisLinkSource == "") { thisLink.href += (/\?/.test(thisLink.href)) ? "&" : "?"; thisLink.href += "source=" + source; } } } // Ensure that there is a source on the url for the exit splash page if (typeof(exitSplashPageUrl) !== "undefined" && exitSplashPageUrl != null && exitSplashPageUrl != "") { var exitSplashUrlSrc = LastChanceOnExit.GetActualSourceCode(exitSplashPageUrl); if (exitSplashUrlSrc == "") { exitSplashPageUrl += (/\?/.test(exitSplashPageUrl)) ? "&" : "?"; exitSplashPageUrl += "source=" + source; } } }, SetAidCodes: function() { var pageAidCode = LastChanceOnExit.GetAidCode(window.location.href); var aid = (pageAidCode == "") ? defaultAidCode : pageAidCode; // 'aid' all the links that do not have one var allLinks = document.links; for (var i = 0; i < allLinks.length; i++) { var thisLink = allLinks[i]; if (thisLink.hash == ""){ var thisLinkAid = LastChanceOnExit.GetActualAidCode(thisLink.href); if (thisLinkAid == "") { thisLink.href += (/\?/.test(thisLink.href)) ? "&" : "?"; thisLink.href += "aid=" + aid; } } } // Ensure that there is a source on the url for the exit splash page if (typeof(exitSplashPageUrl) !== "undefined" && exitSplashPageUrl != null && exitSplashPageUrl != "") { var exitSplashUrlAid = LastChanceOnExit.GetActualAidCode(exitSplashPageUrl); if (exitSplashUrlAid == "") { exitSplashPageUrl += (/\?/.test(exitSplashPageUrl)) ? "&" : "?"; exitSplashPageUrl += "aid=" + aid; } } }, // If it exists in a URL string, extract the source code which could be 'psource', 'source' or 'src'. GetSourceCode: function(url) { return LastChanceOnExit.GetCode(url, ['psource', 'source', 'src']); }, // If it exists in a URL string, extract the source code, just 'source'. GetActualSourceCode: function(url) { return LastChanceOnExit.GetCode(url, ['source']); }, // If it exists in a URL string, extract the 'paid' or 'aid' code. GetAidCode: function(url) { return LastChanceOnExit.GetCode(url, ['paid', 'aid']); }, // If it exists in a URL string, extract the 'aid', just 'aid'. GetActualAidCode: function(url) { return LastChanceOnExit.GetCode(url, ['aid']); }, // If it exists in a URL string, extract the source/aid/whatever code. GetCode: function(url, searchItemsArray) { var name, value, nameValuePair; if (/\?/.test(url)) { var nameValuePairs = url.substring(url.indexOf("?") + 1).split("&"); for (i in nameValuePairs) { nameValuePair = nameValuePairs[i]; if (typeof(nameValuePair) !== 'string') { continue; } if (nameValuePair.split("=").length > 0) { name = nameValuePair.split("=")[0]; if (searchItemsArray.indexOf(name) > -1) { value = nameValuePair.split("=")[1]; return value; } } } } return ""; } } function threedsojs(exitSplashPageUrl, timeDelayToShowBuyLink) { if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) { /*** Redirect all mobile traffic to landing page ***/ window.onbeforeunload = function() {}; // Disable exit pop. var sourceCode = LastChanceOnExit.GetSourceCode(window.location.href); // Strip hard-coded source. All *mobile* traffic should keep the incoming source. var redirectUrl = exitSplashPageUrl.replace(/[\?&]source=.{16}/, ''); var sourceParam = (/\?/.test(redirectUrl)) ? "&source=" + sourceCode : "?source=" + sourceCode; var mobileRedirectParam = "&mobileredirect=true"; window.location.replace(redirectUrl + sourceParam + mobileRedirectParam); } var trackCell = function(testName, cellName) { var img = document.createElement('img'); img.src = "http://www.fool.com/tracking/vs/vs_track.gif?log=1&TestID=" + testName + "&CellID=" + cellName; img.width = 0; img.height = 0; img.className = 'vs-tracking-px'; document.body.appendChild(img); }; /*** These can be overridden by Testing Shim component rendered prior to this component. ***/ var defaultSourceCode = defaultSourceCode || ''; // Can be empty so long as you call the page with a source in the query string var exitSplashMessage = exitSplashMessage || '\n\nWhoa! Hold on there Foolish investor... \n\n You are about to navigate away and miss the presentation. \n\n Press OK to continue.\n\n Or press Cancel to read the transcript. \n\n It could be the most profitable decision you have ever made!\n\n'; var defaultAidCode = defaultAidCode || ''; jQuery(window).load(function() { Date.now = Date.now || function() { return (new Date).valueOf(); }; pageLoadTime = Math.round(Date.now() / 1000); var specifiedStartNowDisplay = Math.round(timeDelayToShowBuyLink / 1000); // Intercept leaving the page window.onbeforeunload = LastChanceOnExit.DisplayExitSplash; // Make link to Start Now appear after some predetermined time if (document.getElementById("startNow")) { setTimeout(function() { jQuery(".hideUntilStartNow").each(function(i) { jQuery(this).css('visibility', 'visible'); }); // Send dataLayer event for floodlight retargeting window.dataLayer = window.dataLayer || []; window.dataLayer.push({ 'event': 'startNowAppeared' }); jQuery("#startNow").css('visibility', 'visible'); jQuery("#startNow > a").css('visibility', 'visible'); actualStartNowDisplay = Math.round(Date.now() / 1000) - pageLoadTime; if (typeof(Wistia) !== "undefined") { jQuery('#video_container').click(function() { window.onbeforeunload = function() {}; var href = jQuery("#startNow a").attr("href"); window.location.href = href; }); } }, timeDelayToShowBuyLink); jQuery("#startNow").on("click", function() { window.onbeforeunload = function() {}; var specifiedStartNowDisplay = 1000; var startNowClickAfterDisplay = Math.round(Date.now() / 1000) - actualStartNowDisplay - pageLoadTime; var clickDataParams = "&specifiedStartNowDisplay=" + specifiedStartNowDisplay + "&actualStartNowDisplay=" + actualStartNowDisplay + "&startNowClickAfterDisplay=" + startNowClickAfterDisplay; var href = jQuery("#startNow a").attr("href"); jQuery("#startNow a").attr("href", href + clickDataParams); }); }; jQuery(".noExitPop").on("click", function() { window.onbeforeunload = function() {}; }); if (window.location.href.indexOf('exitpop=false') > -1) { window.onbeforeunload = function() {}; } // Ensure source/aid codes are appended to links LastChanceOnExit.SetSourceCodes(); LastChanceOnExit.SetAidCodes(); }); }
// Strict Mode On (엄격모드) "use strict"; "use warning"; var PlayZClausePopup = new function() { var INSTANCE = this; var bg_common; var allPass; var license; var personal_information; var focus_purchase; var btn_confirm = []; var btn_detail = []; var check = []; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// var step = 0; var step_1_focus = 0; var step_2_focus = 0; var bg_common_x = 340, bg_common_y = 145; var step_1_check = 0; var step_2_check = 0; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// INSTANCE.setResource = function(onload) { var PATH = ROOT_IMG + "popup/playz/"; btn_confirm = []; btn_detail = []; check = []; var imgParam = [ [bg_common = new Image(), PATH + "bg_common" + EXT_PNG], [allPass = new Image(), PATH + "allPass" + EXT_PNG], [license = new Image(), PATH + "license" + EXT_PNG], [personal_information = new Image(), PATH + "personal_information" + EXT_PNG], [focus_purchase = new Image(), PATH + "focus_purchase" + EXT_PNG], [btn_confirm = [], HTool.getURLs(PATH, "confirm_", EXT_PNG, 2)], [btn_detail = [], HTool.getURLs(PATH, "detail_", EXT_PNG, 2)], [check = [], HTool.getURLs(PATH, "check_", EXT_PNG, 3)], ]; ResourceMgr.makeImageList(imgParam, function() { imgParam = null; onload(); }, function(err) { onload(); appMgr.openDisconnectPopup("PlayZClausePopup setResource Fail!!!!", this); }); }; return { toString: function() { return "PlayZClausePopup"; }, init: function(onload) { step = 0; step_1_focus = 0; step_2_focus = 0; step_1_check = 0; step_2_check = 0; onload(); }, start: function() { }, run: function() { UIMgr.repaint(); }, paint: function() { g.drawImage(bg_common, bg_common_x, bg_common_y); g.setColor(COLOR_BLACK); g.setPlayZFont(FONT_30); HTextRender.playZRender(g, "구매 약관 동의", SCREEN_WIDTH / 2, bg_common_y + 53, HTextRender.CENTER); g.drawImage(allPass, bg_common_x + 100, bg_common_y + 101); g.drawImage(license, bg_common_x + 100, bg_common_y + 151); g.drawImage(personal_information, bg_common_x + 100, bg_common_y + 201); for (var i = 0; i < 2; i++) { g.drawImage(btn_detail[0], bg_common_x + 420, bg_common_y + 151 + (i * 50)); } g.drawImage(btn_confirm[0], bg_common_x + 199, bg_common_y + 280); switch(step) { case 0: g.drawImage(focus_purchase, bg_common_x + 100, bg_common_y + 101); break; case 1: if (step_1_focus == 0) { g.drawImage(focus_purchase, bg_common_x + 100, bg_common_y + 151); } else if (step_1_focus == 1) { g.drawImage(btn_detail[1], bg_common_x + 420, bg_common_y + 151); } break; case 2: if (step_2_focus == 0) { g.drawImage(focus_purchase, bg_common_x + 100, bg_common_y + 201); } else if (step_2_focus == 1) { g.drawImage(btn_detail[1], bg_common_x + 420, bg_common_y + 201); } break; case 3: g.drawImage(btn_confirm[1], bg_common_x + 186, bg_common_y + 280); break; default: break; } if (step_1_check + step_2_check == 2) { g.drawImage(check[2], bg_common_x + 110, bg_common_y + 111); } if (step_1_check == 1) { g.drawImage(check[2], bg_common_x + 110, bg_common_y + 161); } if (step_2_check == 1) { g.drawImage(check[2], bg_common_x + 110, bg_common_y + 211); } }, stop: function() { }, dispose: function() { bg_common = null; allPass = null; license = null; personal_information = null; focus_purchase = null; btn_confirm = null; btn_detail = null; check = null; }, onKeyPressed: function(key) { if (isOnPopup) { if (key == KEY_ENTER || key == KEY_PREV) { document.getElementById("onPop").src = ""; document.getElementById("onPop").style.visibility = "hidden"; isOnPopup = false; } return; } switch(key) { case KEY_PREV: PopupMgr.changePopup(POPUP.POP_PLAYZ_CLAUSE, POPUP.POP_PLAYZ_PURCHASE); break; case KEY_ENTER: switch(step) { case 0: if (step_1_check + step_2_check > 0) { step_1_check = 0; step_2_check = 0; } else { step_1_check = 1; step_2_check = 1; } break; case 1: if (step_1_focus == 0) { if (step_1_check == 1) { step_1_check = 0; } else if (step_1_check == 0) { step_1_check = 1; } } else if (step_1_focus == 1) { console.error("isOnPopup >> " + isOnPopup); document.getElementById("onPop").src="http://61.251.167.91/html5/Btv/heb/verification/index.html?verification=" + step; document.getElementById("onPop").style.visibility = "visible"; document.getElementById("onPop").focus(); isOnPopup = true; } break; case 2: if (step_2_focus == 0) { if (step_2_check == 1) { step_2_check = 0; } else if (step_2_check == 0) { step_2_check = 1; } } else if (step_2_focus == 1) { console.error("isOnPopup >> " + isOnPopup); document.getElementById("onPop").src="http://61.251.167.91/html5/Btv/heb/verification/index.html?verification=" + step; document.getElementById("onPop").style.visibility = "visible"; document.getElementById("onPop").focus(); isOnPopup = true; } break; case 3: if (step_1_check + step_2_check == 2) { PopupMgr.changePopup(POPUP.POP_PLAYZ_CLAUSE, POPUP.POP_PLAYZ_VERIFICATION); } else { // 안드로이드 토스트 팝업 PopupMgr.openPopup(appMgr.getMessage0BtnPopup("모든 필수 항목의 동의가 필요합니다."), null, 1500); console.error("약관에 동의 하셔야 합니다."); } break; } break; case KEY_LEFT: switch(step) { case 1: step_1_focus = 0; break; case 2: step_2_focus = 0; break; } break; case KEY_RIGHT: switch(step) { case 1: step_1_focus = 1; break; case 2: step_2_focus = 1; break; } break; case KEY_UP: switch (step) { case 3: step = 2; break; case 2: step = 1; break; case 1: step = 0; break; } // step = HTool.getIndex(step, -1, 4); step_1_focus = 0; step_2_focus = 0; break; case KEY_DOWN: switch (step) { case 0: step = 1; break; case 1: step = 2; break; case 2: step = 3; break; } // step = HTool.getIndex(step, 1, 4); step_1_focus = 0; step_2_focus = 0; break; default: break; } UIMgr.repaint(); }, onKeyReleased: function(key) { switch(key) { case KEY_ENTER : break; } }, getInstance: function() { return INSTANCE; } }; };
import { connect } from 'react-redux'; import Rule from './Rule'; import rules from '../../../generated/rules'; import { push } from 'react-router-redux'; const mapStateToProps = (_, { match }) => { const { category, rule } = match.params; return { ...rules[category][rule] || { docs: {} }, }; }; const mapDispatchToProps = { onClick: (category, rule) => { if (rule) { return push(`/category/${category}/rule/${rule}`); } return push(`/category/${category}`); }, }; const mergeProps = ({ categoryUrl, ruleUrl, ...rest }, { onClick }) => { const keys = Object.keys(rules[categoryUrl]); const index = keys.indexOf(ruleUrl); const nextRule = keys[index + 1]; const prevRule = keys[index - 1]; return { ...rest, onNextClick: nextRule ? () => onClick(categoryUrl, nextRule) : () => onClick(categoryUrl), onPrevClick: prevRule ? () => onClick(categoryUrl, prevRule) : () => onClick(categoryUrl), }; }; export default connect(mapStateToProps, mapDispatchToProps, mergeProps)(Rule);
$(document).ready(function(){ $('.table').DataTable({ paging: false }); $(".export").on('click', function (event) { exportTableToCSV.apply(this, [$('.table'), 'task_data.csv']); }); }); loading('start'); angular.module('ViewTask', ['datatables', 'ngResource']) .controller('TaskViewCtrl', TaskViewController); loading('end'); function TaskViewController($resource) { var vm = this; vm.dtOptions = { paging: false }; $resource('/api/getAllDepartments').query().$promise.then(function(allDepartments){ vm.allDepartments = allDepartments; $.jTimeout.reset(); }); $resource('/api/getDepartments').query().$promise.then(function(departments){ vm.departments = departments; $.jTimeout.reset(); }); $('.department').on('change', function(){ var department_id = $(this).val(); console.log(department_id); $resource('/api/getTasks?department_id=:department_id', {department_id: department_id}).query().$promise.then(function (tasks) { vm.tasks = tasks; for(var i = 0; i < tasks.length; i++) { tasks[i]['department_id'] = department_id; tasks[i]['department_name'] = $('.department :selected').text(); } $.jTimeout.reset(); }); }); }
/* eslint-disable react/destructuring-assignment */ import React, { Component } from 'react'; import { BrowserRouter, Route } from 'react-router-dom'; // import rootReducer from './reducers/index'; import { connect } from 'react-redux'; import Todos from './components/Todos'; import NavBar from './components/NavBar'; import Home from './components/Home'; import Form from './components/Form'; import Contact from './components/Contact'; import Counter from './components/hooks/Counter'; import EditableItem from './components/hooks/EditableItem'; import './App.css'; // function App() { // return ( // <div className="todo-app container"> // <h2 className="center blue-text">{/* <Todos todos={todos} /> */}</h2> // </div> // ); // } class App extends Component { // eslint-disable-next-line react/state-in-constructor state = { todos: [ { id: 1, content: 'buy some milk' }, { id: 2, content: 'play mario kart' }, ], }; deleteTodo = id => { // eslint-disable-next-line react/destructuring-assignment // eslint-disable-next-line react/no-access-state-in-setstate const todos = this.state.todos.filter(todo => todo.id !== id); this.setState({ todos, }); }; render() { return ( <BrowserRouter> <div className="app"> <NavBar /> <Route exact path="/" component={Home} /> <Route path="/form" component={Form} /> <Route path="/contact" component={Contact} /> <div className="todo-app container"> <h1 className="center blue-text">Todo's</h1> <Todos todos={this.state.todos} deleteTodo={this.deleteTodo} /> <Counter /> <EditableItem /> </div> </div> </BrowserRouter> ); } } export default App;
/** * Copyright 2016 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ (function(module){ if(typeof Object.values === 'undefined') { Object.prototype.values = function(object) { return Object.keys(object).map(function(key) { return object[key]; }); }; } function DashDB(ibmdb, config) { this.driver = ibmdb; this.config = config; this.connection = null; } DashDB.prototype.connect = function(){ var promise = function(resolve, reject){ var connectionCallback = function(error, connection) { if(error) { return reject(error); } return resolve(this.connection = connection); }.bind(this); this.driver.open("DRIVER={DB2};DATABASE=" + this.config.db + ";UID=" + this.config.username + ";PWD=" + this.config.password + ";HOSTNAME=" + this.config.hostname + ";port=" + this.config.port, connectionCallback); }.bind(this); return this.isConnected().catch(function(){ return new Promise(promise); }); }; DashDB.prototype.isConnected = function() { if(!this.connection) { return Promise.reject('call connect first before using this method'); } return Promise.resolve(this.connection); }; DashDB.prototype.create = function(table, data){ var promise = function(connection){ var keys = Object.keys(data); var values = Object.values(data); var filler = (new Array(keys.length)).fill('?'); return this.query('INSERT INTO ' + table + ' ("' + keys.join('", "') + '") VALUES('+ filler.join(',') +')', values); }.bind(this); return this.isConnected().then(promise); }; DashDB.prototype.query = function(query, params) { var promise = function(resolve, reject) { if(!this.connection) { return reject('call connect first before using the query method'); } if(!(params instanceof Array)) { params = []; } this.connection.query(query, params,function(error, result) { if(error) { return reject(error); } resolve(result); }); }.bind(this); return new Promise(promise); }; DashDB.prototype.disconnect = function(){ var promise = function(resolve, reject){ if(this.connection) { this.connection.close(resolve); } else { resolve('connection is not open'); } }.bind(this); return new Promise(promise); }; module.exports = DashDB; })(module);
const request = require('request') const cheerio = require('cheerio') const moment = require('moment-timezone') const { createLogger, format, transports } = require('winston') const mongo = require('mongodb').MongoClient var ObjectId = require('mongodb').ObjectID require('dotenv').config() const URL = process.env.CURRENT_URL let db = null let client = null let col = null const logger = createLogger({ level: 'info', format: format.combine( format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }), format.errors({ stack: true }), format.splat(), format.json() ), defaultMeta: { service: 'current-crawler' }, transports: [ new transports.File({ filename: 'error.log', level: 'error' }), new transports.File({ filename: 'info.log', level: 'info' }) ] }) if (process.env.NODE_ENV !== 'production') { logger.add( new transports.Console({ format: format.combine(format.colorize(), format.simple()) }) ) } function getData() { request(URL, function(err, res, body) { if (err) { logger.error(err) return } let $ = cheerio.load(body) const date = $('.js-datepicker-field') .val() .substring(0, 10) let continuar = true let element = $('.hour').first() let ampm = element .find('.hour-header') .text() .split('to')[0] .includes('am') ? 'am' : 'pm' console.log(ampm) while (continuar) { element = element.next() if (element.hasClass('song')) { procesarSong(element, date, ampm) } else if (element.hasClass('hour')) { ampm = element .find('.hour-header') .text() .split('to')[0] .includes('am') ? 'am' : 'pm' } else { continuar = false } } }) } function procesarSong(element, date, ampm) { const id = element.attr('id') const title = element.find('h5.title').text() const artist = element.find('h5.artist').text() const time = element.find('time').text() let song = {} song.timestamp = date + ' ' + time.trim() + ' ' + ampm.toUpperCase() song.date = moment(song.timestamp, 'YYYY-MM-DD hh:mm A') .tz('America/Winnipeg') .toDate() song.id = id song.title = title song.artist = artist song.dateInsert = new Date() col.find({ timestamp: song.timestamp }).toArray((err, items) => { if (err) { logger.error(err) } else if (items.length == 0) { saveSong(song) } }) } function saveSong(song) { col.insertOne(song, (err, obj) => { if (err) logger.error(err) else logger.info( `${song.dateInsert} - ${song.id} - ${song.timestamp} - ${ song.title } - ${song.artist}` ) }) } async function initDB() { client = await mongo.connect(process.env.DATABASE_URL, { useNewUrlParser: true }) db = client.db('current') col = db.collection('songs') console.log('Conectado a BD') } async function main() { await initDB() getData() setInterval(() => { getData() }, process.env.SEG_FRECUENCIA * 1000) } main()
import React from 'react'; /*const layout = (props) => { console.log(props.childern); return ( <div> <div>toolbar,lottu,losku</div> <main> {props.childern} </main> </div> ) };*/ class Layout extends React.Component { render() { return ( <div> <div>toolbar,lottu,losku</div> <main>{this.props.children}</main> </div> ) } } export default Layout;
// scripts/MYNAMESPACE/init.js var namespace = new Namespace('MYNAMESPACE'); // Cria namespace no nível global namespace.myClassA = new MyClassA(); // Adiciona as classes ao namespace namespace.myClassA.init(); // inicializa um método público da classe equivalente à window.MYNAMESPACE.myClassA.init();
// tGallery.js file var base = require("./base.js"); var ActorGala = require("tpp-test-gallery"); add(new ActorGala(base, { dialog_type: "dialog", dialog: [ "Did you know they're building a gym just for me in Surldab City?", "I'll be able to keep taunting you guys forever there!", function(){ this.showEmote(":D", 40); }, "WAHAHAHAHAHAHAHAHAHAHAHAHAHA!!", ], }));
import './App.css'; import { useEffect, useState, useRef } from "react" import PlayerForm from "./components/PlayerForm" import GameArea from "./components/GameArea" import {packPlayerMessage, packChatMessage} from "./utils/messages" import replaceValue from "./utils/replaceValue" import guessAPILocation from "./utils/guessAPILocation" import getRandomSpiderName from "./utils/names" const settings = require('./settings') const uuid = require('uuid'); const playerID = uuid.v4(); // web-sockets let wws = null; let pws = null; const App = () => { const proposedAPILocation = guessAPILocation(window.location.href, settings.DEFAULT_API_LOCATION); const [playerName, setPlayerName] = useState(getRandomSpiderName()); const [apiLocation, setApiLocation] = useState(proposedAPILocation); const [inGame, setInGame] = useState(false); const [playerMap, setPlayerMap] = useState({}); const [playerX, setPlayerX] = useState(null); const [playerY, setPlayerY] = useState(null); const [halfSizeX, setHalfSizeX] = useState(null); const [halfSizeY, setHalfSizeY] = useState(null); const [playerH, setPlayerH] = useState(false) const [generation, setGeneration] = useState(0) const [lastSent, setLastSent] = useState(null) const [lastReceived, setLastReceived] = useState(null) const [chatItems, setChatItems] = useState([]) // With useRef we can make the updated state accessible from within the callback // that we will attach to the websocket. // see https://stackoverflow.com/questions/57847594/react-hooks-accessing-up-to-date-state-from-within-a-callback const generationRef = useRef() generationRef.current = generation // Same for the player position/status, since it will be accessed within callbacks: const playerXRef = useRef() playerXRef.current = playerX const playerYRef = useRef() playerYRef.current = playerY const playerHRef = useRef() playerHRef.current = playerH // keyboard-controlled movements const handleKeyDown = ev => { if(inGame){ if ( ev.keyCode === 37 ){ setPlayerX( x => x-1 ) setPlayerH(false) } if ( ev.keyCode === 38 ){ setPlayerY( y => y-1 ) setPlayerH(false) } if ( ev.keyCode === 39 ){ setPlayerX( x => x+1 ) setPlayerH(false) } if ( ev.keyCode === 40 ){ setPlayerY( y => y+1 ) setPlayerH(false) } if( ev.keyCode === 72 ){ setPlayerH(h => !h) } } } useEffect( () => { if(inGame){ if(wws === null || pws === null){ // we must create the websockets and attach callbacks to them wws = new WebSocket(`${apiLocation}/ws/world/${playerID}`) pws = new WebSocket(`${apiLocation}/ws/player/${playerID}`) pws.onopen = evt => { const msg = packPlayerMessage(generationRef.current, playerName, playerXRef.current, playerYRef.current, playerHRef.current) setLastSent(msg) pws.send(msg) } wws.onmessage = evt => { setLastReceived(evt.data) try { const updateMsg = JSON.parse(evt.data) if ( updateMsg.messageType === 'player' ){ // Received update on some player through the 'world' websocket const thatPlayerID = updateMsg.playerID setPlayerMap(plMap => { const newPlMap = replaceValue(plMap, thatPlayerID, updateMsg.payload) return newPlMap }) // We compare generations before receiving an update to self, to avoid update loops // from player updates delivered back to us asynchronously: if ((thatPlayerID === playerID) && (updateMsg.payload.generation >= generationRef.current - 1)){ if ( updateMsg.payload.x !== null){ setPlayerX(updateMsg.payload.x) setPlayerY(updateMsg.payload.y) } } } else if ( updateMsg.messageType === 'geometry' ) { // we received initial geometry info from the API setHalfSizeX(updateMsg.payload.halfSizeX) setHalfSizeY(updateMsg.payload.halfSizeY) setPlayerX(updateMsg.payload.halfSizeX - 1) setPlayerY(updateMsg.payload.halfSizeY - 1) setPlayerH(false) } else if ( updateMsg.messageType === 'chat' ) { // we received a new chat item. Let's make room for it // first we add the playerID to the chat-item object const chatPayload = {...updateMsg.payload, ...{playerID: updateMsg.playerID}} // then we concatenate it to the items to display (discarding the oldest if necessary) setChatItems( items => items.concat([chatPayload]).slice(-settings.MAX_ITEMS_IN_CHAT) ) } else { // another messageType console.log(`Ignoring messageType = ${updateMsg.messageType} ... for now`) } } catch (e) { console.log(`Error "${e}" while receiving message "${evt.data}". Ignoring message, the show must go on`) } } } } else { if(wws !== null || pws !== null){ // we notify the API that we are leaving if(pws && pws.readyState === 1){ const msg = packPlayerMessage(generationRef.current, playerName, null, null, playerH) setLastSent(msg) pws.send(msg) } setGeneration( g => g+1 ) // it is time to disconnect the websockets if(wws === null){ wws.disconnect() wws = null; } if(pws === null){ pws.disconnect() pws = null; } } } // eslint-disable-next-line }, [inGame]) const sendChatItem = text => { const ttext = text.trim() if (ttext !== '' && pws && pws.readyState === 1){ const msg = packChatMessage(playerName, text) setLastSent(msg) pws.send(msg) } } useEffect( () => { if (inGame) { if(pws && pws.readyState === 1){ const msg = packPlayerMessage(generationRef.current, playerName, playerX, playerY, playerH) setLastSent(msg) pws.send(msg) } // we increment the generation number to recognize and ignore 'stale' player updates bouncing back to us setGeneration( g => g+1 ) } // we are handling generation increase explicitly within this hook, so we don't react to it: // eslint-disable-next-line }, [inGame, playerName, playerX, playerY, playerH]) return ( <div className="App"> <header className="App-header"> <PlayerForm apiLocation={apiLocation} setApiLocation={setApiLocation} playerName={playerName} setPlayerName={setPlayerName} inGame ={inGame} setInGame ={setInGame} setPlayerMap={setPlayerMap} playerID={playerID} setLastSent={setLastSent} setLastReceived={setLastReceived} setGeneration={setGeneration} /> </header> {inGame && <GameArea playerName={playerName} playerID={playerID} playerMap={playerMap} playerX={playerX} setPlayerX={setPlayerX} playerY={playerY} setPlayerY={setPlayerY} boardWidth={2 * halfSizeX - 1} boardHeight={2 * halfSizeY - 1} handleKeyDown={handleKeyDown} lastSent={lastSent} lastReceived={lastReceived} setGeneration={setGeneration} setPlayerH={setPlayerH} halfSizeX={halfSizeX} halfSizeY={halfSizeY} chatItems={chatItems} sendChatItem={sendChatItem} />} </div> ); } export default App;
/** * * @auth: db, created at 2013.10.19 * www.yynote.com * */ function trim(str) {    return str.replace(/(^\s*)|(\s*$)/g, ""); } function ltrim(str) {    return str.replace(/(^\s*)/g,""); } function rtrim(str) {    return str.replace(/(\s*$)/g,""); } /** * 0 : view * 1 : edit */ var g_editor_mode = 0; function showEditor(title, content) { $("#yy-wysiwyg-editor #editor").html(content); $('#title-in-edit-mode input').val(trim(title)); $('#content').css('display', 'none'); $("#yy-wysiwyg-editor").css('display', 'inline-block'); $('#btnEdit').css('display', 'none'); $('#btnSave').css('display', 'inline-block'); $('#yy-edit-article-title #title-in-view-mode').css('display', 'none'); $('#yy-edit-article-title #title-in-edit-mode').css('display', 'inline-block'); g_editor_mode = 1; } function showViewer(title, content) { $("#yy-edit-article-title #title-in-view-mode p#title0").text(title); $("#content").html(content); $('#content').css('display', 'inline-block'); $("#yy-wysiwyg-editor").css('display', 'none'); $('#btnEdit').css('display', 'inline-block'); $('#btnSave').css('display', 'none'); $('#yy-edit-article-title #title-in-view-mode').css('display', 'inline-block'); $('#yy-edit-article-title #title-in-edit-mode').css('display', 'none'); g_editor_mode = 0; } function hideAlertInputTitleMsg() { var obj = $("#alert-msg"); obj.fadeOut("500", function() { }); } function showAlertInputTitleMsg(now) { var obj = $("#alert-msg"); if (now) { obj.css('display', 'inline'); } else { obj.fadeIn("500", function() { }); } } function edit(str) { var actived = $("#list-detail-items .yy-list-items ul li.active"); if (actived.length <= 0) {editNew(); return ;} var contents = $('#content').html(); var title = trim($('#title-in-view-mode #title0').text()); showEditor(title, contents); } function editNew() { if (g_editor_mode == 1) { var ret = SaveAndCloseAllEditors(""); if (ret == 1) { return; } } $("#btnEditNew").hide(); $("#btnEdit").show(); $("#btnDel").show(); var actived = $('#list-detail-items .yy-list-items ul').find("li.active"); if (actived.length > 0) { actived.removeClass("active"); } var htmlContent = '<li class="active" data-section="1">' + '<div class="title"> Unknown Title' + '</div> ' + '<div class="description">' + '<span class="date">2013-10-15</span>' + '<span class="summary">Our life is important....</span>' + '</div>' + '</li>'; $("#list-detail-items .yy-list-items ul").prepend(htmlContent); var total = $('#list-detail-items .yy-list-items ul').find("li"); if (total.length > 5) { $("#list-detail-items .yy-list-items ul li").last().remove(); } $('#title-in-edit-mode input').attr("placeholder", "Input new title"); showEditor("", ""); } function SaveAndCloseAllEditors(str) { var title = trim($("#title-in-edit-mode input").val()); if (title == "") { showAlertInputTitleMsg(true); return 1; } var contents = $("#yy-wysiwyg-editor #editor").html(); showViewer(title, contents); var summary = trim($("#yy-wysiwyg-editor #editor").text()).substr(0, 45) + " ..."; $("#list-detail-items .yy-list-items ul li.active").find("div.title").text(title); $("#list-detail-items .yy-list-items ul li.active").first().find("div.description span.summary").html(summary); return 0; } function delNote() { var actived = $("#list-detail-items .yy-list-items ul li.active"); if (actived.length <= 0) { return ;} var nextObj = actived.next(); if (nextObj.length <= 0) { /* * TODO: load next note from server */ nextObj = actived.prev(); if (nextObj.length <= 0) { actived.remove(); showViewer("", ""); $("#btnEditNew").show(); $("#btnEdit").hide(); $("#btnDel").hide(); return; } } nextObj.addClass("active"); actived.remove(); var titleHtml_0 = nextObj.find(".title").text(); var contentHtml_0 = '<div>' + '<p> Date:' + nextObj.find(".description .date").text() + '</p>' + 'summary:' + nextObj.find(".description .summary").text() + '<ul>' + '<li>' + '<span> First Test</span>' + '<br>' + '</li>' + '<li>' + '<span>dasfadsfa</span>' + '<br>' + '</li>' + '</ul>' + '</div>'; showViewer(titleHtml_0, contentHtml_0); var summary = trim($("#yy-wysiwyg-editor #editor").text()).substr(0, 45) + " ..."; nextObj.find("div.title").text(title); nextObj.find("div.description span.summary").html(summary); } $(function() { /** * not support -- 2013-11-03 * * $("div.yy-side-nav-menu-item").click(function() { var parent = $(this).parent(); var pparent = parent.parent(); var sub_menu = parent.find("ul.yy-side-nav-sub-menus"); var kz = parent.attr("class"); var expand = sub_menu.attr("expand"); if (kz == "active") { if (sub_menu.length > 0) { if (expand == "true") { sub_menu.slideUp("noraml", function() {}); sub_menu.attr("expand", "false"); $(this).find("span i:last").removeClass("icon-caret-down"); $(this).find("span i:last").addClass("icon-caret-right"); } else if (expand == "false") { sub_menu.slideDown("noraml", function() {}); sub_menu.attr("expand", "true"); $(this).find("span i:last").removeClass("icon-caret-right"); $(this).find("span i:last").addClass("icon-caret-down"); } } else { } } else { var actived = pparent.find("li.active"); var icon_dom = actived.find(".yy-side-nav-menu-item span i:last"); var actived_submenu = actived.find(".yy-side-nav-sub-menus"); if (actived_submenu.length > 0) { actived_submenu.slideUp("noraml", function() { actived.removeClass("active"); }); actived_submenu.attr("expand", "false"); icon_dom.removeClass("icon-caret-down"); icon_dom.addClass("icon-caret-right"); } else { actived.removeClass("active"); } if (sub_menu.length > 0) { sub_menu.slideDown("noraml", function() { parent.toggleClass("active"); }); sub_menu.attr("expand", "true"); $(this).find("span i:last").removeClass("icon-caret-right"); $(this).find("span i:last").addClass("icon-caret-down"); } else { parent.toggleClass("active"); } } }); * * end of -- not support */ $(".yy-side-nav-sub-menus li").click(function() { var kz = $(this).attr("class"); if (kz == "sub-active") { return; } var actived = $(this).parent().find("li.sub-active"); if (actived.length > 0) { actived.removeClass("sub-active"); } $(this).addClass("sub-active"); }); $('#title-in-edit-mode input').click(function() { hideAlertInputTitleMsg(); }); $('#editor').click(function() { hideAlertInputTitleMsg(); }); }); $(function() { $('#list-detail-items .yy-list-items ul#yy-list-items-wrap').delegate('li' ,"click", function() { var kz = $(this).attr("class"); if (kz == "active") { return; } if (g_editor_mode == 1) { var ret = SaveAndCloseAllEditors(""); if (ret == 1) { return; } } hideAlertInputTitleMsg(); var actived = $(this).parent().find("li.active"); if (actived.length > 0) { actived.removeClass("active"); } $(this).addClass("active"); var data_section = $(this).attr("data-section"); var headerHtml_0 = trim($(this).find(".title").text()); var contentHtml_0 = '<div>' + 'data-section:' + data_section + '<ul>' + '<li>' + '<span> First Test</span>' + '<br>' + '</li>' + '<li>' + '<span>dasfadsfa</span>' + '<br>' + '</li>' + '</ul>' + '</div>'; $("#yy-edit-article-title #title-in-view-mode p#title0").text(headerHtml_0); $("#content").html(contentHtml_0); }); }); $(function() { $('#list-detail-items #yy-new-note-btns-group #btnNew').click(editNew); }); $(function() { $("ul.navigation-bar-top li").hover(function() { //$(this).find("a span").css("border-bottom"," 1px solid #0088cc"); //$(this).find("a span.nav-text").css("color","#0088cc"); }, function() { var kz = $(this).attr("class"); if (kz == "currently") { return; } //$(this).find("a span").css("border-bottom","0px"); //$(this).find("a span.nav-text").css("color","#777777"); }); }); $(function() { $("div.content-area span").hover(function() { $(this).css("background-color", "#f2f2f2"); $(this).css("border-radius", "4px"); }, function() { $(this).css("background-color", "#ffffff"); }); $("div.content-area p span").click(function() { var word = $(this).text(); word = word.toLowerCase(); $("div#rd-tool-side-dics").css("display", "block"); $("div#rd-tool-side-dics #rd-tool-side-dics-wd").html(word); }); $("#rd-tool-side-close").click(function() { var obj = $("div#rd-tool-side-dics"); obj.fadeOut("500", function() { obj.css("display", "none"); }); }); }); $(function() { $("#add-dict").click(function() { var data = { "word" : "two", "b_pr" : "[kad]", "a_pr" : "[ked]", "sm" : "n,一个\nv,大个", "synonym" : "word-s", "antonym" : "word-a", "usage" : "a word\n big word\nwords like", "tense_1" : "worded", "tense_2" : "", "tense_3" : "wording", "tense_4" : "", "tense_5" : "", "plural" : "word-p", } // Post $.post('http://192.168.56.101/dict/add/one', data, function(data, status) { alert("OK"); alert(respons.code.code); alert(respons.code); }); }); });
/** * @author: @joatin */ require('ts-node/register'); var helpers = require('./helpers'); exports.config = { baseUrl: 'https://localhost:3000/', /** * Use `npm run e2e` */ specs: [ helpers.root('features/**/*.feature') // accepts a glob ], exclude: [], framework: 'custom', frameworkPath: require.resolve('protractor-cucumber-framework'), allScriptsTimeout: 110000, cucumberOpts: { compiler: "ts:ts-node/register", require: [ helpers.root('features/step_definitions/**/*.ts'), helpers.root('features/support/**/*.ts') ], strict: true, format: ['pretty', 'pretty:output.txt'], "format-options": ['{ "snippetInterface": "promise"}'] }, directConnect: true, capabilities: { 'browserName': 'chrome', 'chromeOptions': { 'args': ['show-fps-counter=true'] } }, onPrepare: function() { browser.ignoreSynchronization = true; browser.manage().window().maximize(); }, /** * Angular 2 configuration * * useAllAngular2AppRoots: tells Protractor to wait for any angular2 apps on the page instead of just the one matching * `rootEl` */ useAllAngular2AppRoots: true };
/** * Choropleth Element for React-Dashboard * Author Paul Walker (https://github.com/starsinmypockets) * * Based on the following projects: * * React D3 Map Choropleth (https://github.com/react-d3/react-d3-map-choropleth) * Apache 2.0 License * * Mike Bostock's Choropleth (https://github.com/react-d3/react-d3-map-choropleth for documentation) * GNU/GPL License https://opensource.org/licenses/GPL-3.0 * **/ import BaseComponent from './BaseComponent'; import React, { Component } from 'react'; import {Legend} from 'react-d3-core'; import Registry from '../utils/Registry'; import {makeKey} from '../utils/utils'; import {MapChoropleth} from 'react-d3-map-choropleth'; import {mesh, feature} from 'topojson'; import {range} from 'd3'; import Dataset from '../models/Dataset'; // @@TODO we need dynamic values here let legendWidth = 500, legendHeight = 400, legendMargins = {top: 40, right: 50, bottom: 40, left: 50}, legendClassName = "test-legend-class", legendPosition = 'left', legendOffset = 90; // Whack some css into the page function addStyleString(str) { var node = document.createElement('style'); node.innerHTML = str; document.head.appendChild(node); } // Fetch css function fetchStyleSheet(url) { return new Promise((resolve, reject) => { fetch(url) .then(res => { return res.text(); }) .then(css => { resolve(css); }) .catch(e => { reject(e); }); }); } export default class Choropleth extends BaseComponent { constructor(props){ super(props); this.levels = this.props.settings.levels; this.randKey = makeKey(4); this.assignChoroplethFunctions(); } /** * Override in sublass to customize behavior **/ assignChoroplethFunctions() { let domainField = this.props.settings.domainField; let domainKey = this.props.settings.domainKey; Object.assign(this, { choroplethFunctions : { tooltipContent: d => { let label = this.props.settings.tooltip.label; let val = d[d[this.props.settings.domainMapKey]]; let tt = {}; tt[label] = val; return tt; }, domainValue: d => { return Number(d[domainField]); }, domainKey: d => { return d[domainKey]; }, mapKey: d => { Object.assign(d, d.properties); return d[this.props.settings.domainMapKey]; return d.properties[this.props.settings.domainMapKey]; //omainKey; } } }); } // fetchData should set topoData and domainData onDataReady(data) { this.setState({domainData: data.domainData, topodata: data.topodata}); } componentDidMount () { // add stylesheet if (this.props.settings.cssPath) { fetchStyleSheet(this.props.settings.cssPath) .then(css => { addStyleString(css) }) .catch(e => { }); } if (this.props.fetchData) { this.fetchData().then(this.onData.bind(this)).catch(e => { console.log('Error fetching data', e); }); } addStyleString(this.css()); super.componentDidMount(); } fetchData() { return new Promise((resolve, reject) => { let dataset = new Dataset(this.props.settings.dataset); let response = {}; fetch(this.props.settings.mapDataUrl) .then(res => { let d = res.json(); return d; }) .then(data => { response.topodata = data; dataset.fetch() .then(data => { dataset.query({}) .then(data => { response.domainData = data.hits; return resolve(response); }) }) .catch(e => { console.log('Dataset fetch failed', e); return reject(e); }) }) .catch(e => { return reject(e); }); }); } _attachResize() { window.addEventListener('resize', this._setSize.bind(this), false); } // generate css string from colors array css () { let _css = ''; let randKey = this.randKey; let colors = this.props.settings.colors; for (var i = 0; i < this.levels; i++) { _css += `.${randKey}${i}-${this.levels} { fill:${colors[i]}; }`; } return _css; } legendSeries () { let series = []; let domainScale = this.domainScale(this.state.domainData); let step = ((domainScale.domain[1] - domainScale.domain[0]) / this.props.settings.levels); let r = range(domainScale.domain[0], domainScale.domain[1], step); r.push(domainScale.domain[1]); let prec = this.props.settings.legendValPrecision; for (var i = 0; i < this.levels; i++) { let lower = r[i].toFixed(prec); let upper = r[i+1].toFixed(prec); let item = { field: `${lower} -- ${upper}`, name: `${lower} -- ${upper}`, color: this.props.settings.colors[i] } series.push(item); } return series; } domainScale(data) { let settings = this.props.settings; let randKey = this.randKey; let dScale = ({ scale: 'quantize', domain: [Number(settings.domainLower), Number(settings.domainUpper)], range: range(settings.levels).map(i => { return `${randKey}${i}-${settings.levels}`; }) }); return dScale; } render () { let v; let settings = Object.assign({}, this.props.settings); if (this.state.domainData) { Object.assign(settings, this.state.data, {type : this.props.type}, this.choroplethFunctions); settings.topodata = this.state.topodata; settings.domainData = this.state.domainData; if (settings.mapFormat === 'topojson') { if (settings.polygon) { settings.dataPolygon = feature(settings.topodata, settings.topodata.objects[settings.polygon]).features; } if (settings.mesh) { settings.dataMesh = mesh(settings.topodata, settings.topodata.objects[settings.mesh], function(a, b) { return a !== b; }); } } else if (settings.mapFormat === 'geojson') { settings.dataPolygon = settings.topodata.features; } settings.scale = this.props.settings.gridWidth; settings.domain = this.domainScale(this.state.domainData); v = <div className="choropleth-container"> <MapChoropleth ref="choropleth" {...settings} /> <div className="legend-container"> <h3 className="legend-header">{settings.legendHeader}</h3> <Legend width= {legendWidth} height= {legendHeight} margins= {legendMargins} legendClassName= {legendClassName} legendPosition= {legendPosition} legendOffset= {legendOffset} chartSeries = {this.legendSeries()} /> </div> </div>; } else { v = <p ref="choropleth" className='laoding'>Loading...</p>; } return(v); } } Registry.set('Choropleth', Choropleth);
$(document).ready(function() { setTimeout(function() { $('#fullpage').css("-webkit-filter", "blur(5px)") }, 1); setTimeout(function() { $('#fullpage').css("-webkit-filter", "blur(4px)") }, 400); setTimeout(function() { $('#fullpage').css("-webkit-filter", "blur(3px)") }, 600); setTimeout(function() { $('#fullpage').css("-webkit-filter", "blur(2px)") }, 800); setTimeout(function() { $('#fullpage').css("-webkit-filter", "blur(1px)") }, 1000); setTimeout(function() { $('#fullpage').css("-webkit-filter", "blur(0px)") }, 1200); var hellos = setTimeout(function() { $("#hi").fadeIn(1500); $("#hi").fadeOut(100); $("#im").fadeIn(2500); $("#im").fadeOut(100); $("#clare").fadeIn(4000); 1000 }); var videos = document.getElementsByClassName("work"); var modals = document.getElementsByClassName("reveal-modal"); $(videos).click(function() { if ($(modals).is(':hidden')) { for (i = 0; i < videos.length; i++) { videos[i].pause(); } } else { console.log("modals are closed"); }; }); });
// import moment from 'moment'; // import uuid from 'node-uuid'; const moment = require('moment'); const uuid = require('node-uuid'); module.exports = (sequelize, DataTypes) => { return sequelize.define('release_log', { id: { type: DataTypes.STRING, primaryKey: true }, date: DataTypes.DATE, assets: DataTypes.TEXT, tagName: { type: DataTypes.STRING, field: 'tag_name' }, body: DataTypes.STRING, projectId: { type: DataTypes.STRING, field: 'project_id' }, createdAt: { type: DataTypes.DATE, field: 'created_at' }, updatedAt: { type: DataTypes.DATE, field: 'updated_at' } }, { underscored: true, timestamps: true, classMethods: { getRelease(id) { return this.findById(id); }, getReleases(start, end) { const where = {}; where.date = { $between: [start, end] }; return this.findAll({ where }); }, getReleasesCount(start, end) { const where = {}; where.date = { $between: [start, end] }; return this.count({ where }); }, getProjectReleases(projectId, start, end) { const where = { projectId }; where.date = { $between: [start, end] }; return this.findAll({ where }); }, createLog(logInfo) { logInfo.id = uuid.v4(); return this.create(logInfo); }, upsertLog(logInfo) { const defaultRelease = { id: uuid.v4() }; return this.findOrCreate({ where: logInfo, defaults: defaultRelease }) .then((instance, created) => { const isUpdated = moment(instance.date).diff(moment(logInfo.date)) > 0; return (created || isUpdated) ? instance : this.update(logInfo); }); } } }); };
import React from 'react' import styled from 'styled-components'; function Details() { return ( <Container> <Background> <img src="https://images.squarespace-cdn.com/content/v1/583ed05c59cc68a8c3e45c0f/1600856532768-ATU3GLRFMRJ395DCE94E/bao-animationscreencaps.com-793.jpg?format=2500w"/> </Background> <ImgTitle> <img src="/images/baoo.png"/> </ImgTitle> <Controls> <PlayButton> <img src="/images/play-icon-black.png"/> <span>PLAY</span> </PlayButton> <TrailerButton> <img src="/images/play-icon-white.png"/> <span>Trailer</span> </TrailerButton> <AddButton> <span>+</span> </AddButton> <GroupWatchButton> <img src="/images/group-icon.png"/> </GroupWatchButton> </Controls> <SubTitle> 2018 7m Family, Fantasy, Kids, Animation </SubTitle> <Description> Pick a movie or a show you'd like to watch and play it. With the playback on, click the Up button on your remote to bring up the menu icon, and select it. The Subtitles option appears in the menu, navigate to it, and press the selection button to choose between On and Off. </Description> </Container> ) } export default Details const Container=styled.div ` min-height:calc(100vh -70px); padding:0 calc(3.5vw + 5px); position:relative; ` const Background=styled.div ` z-index:-1; position:fixed; left:0; right:0; top:0; bottom:0; opacity:0.6; img{ width:100%; height:100%; object-fit:cover; } ` const ImgTitle=styled.div ` height:30vh; width:35vw; min-width:200px; min-height:170px; img{ width:100%; height:100%; object-fit:contain; } ` const Controls=styled.div ` display:flex; align-items:center; ` const PlayButton=styled.button ` border-radius:4px; font-size:15px; display:flex; align-items:center; cursor:pointer; height:56px; background:rgb(249,249,249); padding:0 24px; border:none; margin-right:24px; letter-spacing:1.8px; &:hover{ background:rgb(198,198,198); } ` const TrailerButton=styled(PlayButton) ` background:rgba(0,0,0,0.3); color:rgb(249,249,249); border:1px solid rgb(249,249,249); text-transform:uppercase; ` const AddButton=styled.button ` width:44px; height:44px; cursor:pointer; display:flex; align-items:center; justify-content:center; border-radius:50%; background:rgba(0,0,0,0.6); border:2px solid white; margin-right:16px; span{ font-size:30px; color:rgb(249,249,249); } ` const GroupWatchButton=styled(AddButton)` background:rgb(0,0,0); ` const SubTitle=styled.div` color:rgb(249,249,249); font-size:18px; min-height:20px; margin-top:26px; ` const Description=styled.div ` color:rgb(249,249,249); line-height:1.4; width:800px; font-size:20px; margin-top:16px; `
// Here we are testing exceptions and the handler should be ours, we need to avoid tape-catch import tape from 'tape'; import includes from 'lodash/includes'; import MockAdapter from 'axios-mock-adapter'; import splitChangesMock1 from './splitChanges.since.-1.json'; import mySegmentsMock from './mySegments.nico@split.io.json'; import splitChangesMock2 from './splitChanges.since.1500492097547.json'; import splitChangesMock3 from './splitChanges.since.1500492297547.json'; import { SplitFactory } from '../../'; import SettingsFactory from '../../utils/settings'; import { __getAxiosInstance } from '../../services/transport'; // Set the mock adapter on the current axios instance const mock = new MockAdapter(__getAxiosInstance()); const settings = SettingsFactory({ core: { authorizationKey: '<fake-token>' } }); mock.onGet(settings.url('/splitChanges?since=-1')).reply(function() { return new Promise((res) => { setTimeout(() => res([200, splitChangesMock1]), 1000);}); }); mock.onGet(settings.url('/splitChanges?since=1500492097547')).reply(200, splitChangesMock2); mock.onGet(settings.url('/splitChanges?since=1500492297547')).reply(200, splitChangesMock3); mock.onGet(settings.url('/mySegments/nico@split.io')).reply(200, mySegmentsMock); mock.onPost().reply(200); const assertionsPlanned = 3; let errCount = 0; const factory = SplitFactory({ core: { authorizationKey: '<fake-token-1>', key: 'nico@split.io' }, startup: { eventsFirstPushWindow: 100000, readyTimeout: 0.5, requestTimeoutBeforeReady: 100000 }, scheduler: { featuresRefreshRate: 1.5, segmentsRefreshRate: 100000, metricsRefreshRate: 100000, impressionsRefreshRate: 100000, eventsPushRate: 100000 } }); tape('Error catching on callbacks - Browsers', assert => { let previousErrorHandler = window.onerror || null; const client = factory.client(); const exceptionHandler = err => { if (includes(err, 'willThrowFor')) { errCount++; assert.pass(`But this should be loud, all should throw as Uncaught Exception: ${err}`); if (errCount === assertionsPlanned) { const wrapUp = () => { window.onerror = previousErrorHandler; mock.restore(); assert.end(); }; client.destroy().then(wrapUp).catch(wrapUp); } return true; } assert.fail(err); return false; }; // Karma is missbehaving and overwriting our custom error handler on some scenarios. function attachErrorHandlerIfApplicable() { if (window.onerror !== exceptionHandler) { previousErrorHandler = window.onerror; window.onerror = exceptionHandler; } } client.on(client.Event.SDK_READY_TIMED_OUT, () => { attachErrorHandlerIfApplicable(); null.willThrowForTimedOut(); }); client.once(client.Event.SDK_READY, () => { attachErrorHandlerIfApplicable(); null.willThrowForReady(); }); client.once(client.Event.SDK_UPDATE, () => { attachErrorHandlerIfApplicable(); null.willThrowForUpdate(); }); attachErrorHandlerIfApplicable(); });
//var appState = undefined; //var AboutProjectModel = undefined; var aboutProject = undefined; var appState = undefined; var projectNews = undefined; var coaches = undefined; var projects = undefined; $(function () { var Controller = Backbone.Router.extend({ routes: { "": "main", "!/": "main", "!/news": "news", "!/about": "about", "!/projects": "projects" }, main: function () { aboutProject.fetch({ success: function (response) { console.log(aboutProject.get('description')); appState.set({"currentSection": "main"}); } } ); }, news: function () { projectNews.fetch({ success: function (response) { console.log(projectNews.size()); appState.set({"currentSection": "news"}); } } ); }, about: function () { coaches.fetch( { success: function(response) { console.log(coaches.size()); appState.set({"currentSection": "about"}); } }); }, projects: function() { appState.set({"currentSection": "projects"}); } }); var controller = new Controller(); Backbone.history.start(); });
import React, { Component } from 'react'; import classNames from 'classnames'; import autobind from 'autobind-decorator'; import { Form, Text, Radio, RadioGroup, Select } from 'react-form'; import stateOptions from '../../models/brackets/state/states'; import { formatCurrency, formatPercent, numbersOnly } from '../../utils/string-utils'; import taxCalculator from '../../models/brackets/calculator'; @autobind export default class Homepage extends Component { constructor(props) { super(props); this.state = {}; } taxResults() { const values = this.state.formValues || {}; const isMarried = values.filingStatus === 'married'; const rawIncome = values.income || '0'; const income = parseInt(numbersOnly(rawIncome), 10); return taxCalculator(income, isMarried); } result(type, title) { const results = this.taxResults(); const result = results[type]; const tax = formatCurrency(result.tax); const rate = formatPercent(result.effective_rate); return ( <div className={classNames('result', type)}> {title} <div className="amount">{tax}</div> <div className="rate">{rate}</div> </div> ); } get results() { return ( <div className={classNames('results')}> {this.result('current', 'Current Law:')} {this.result('house', 'House Bill:')} {this.result('senate', 'Senate Bill:')} </div> ); } get form() { return ( <Form formDidUpdate={this.formDidUpdate}> { (formApi) => ( <form onSubmit={formApi.submitForm} id="form2"> <label htmlFor="income">How much will you make in 2018?</label> <Text field="income" id="income" /> <label htmlFor="filingStatus">How will you file?</label> <RadioGroup field="filingStatus"> { (group) => ( <div> <label htmlFor="single" className="single">Single</label> <Radio group={group} value="single" id="single" className="group-value single" /> <label htmlFor="married" className="married">Married</label> <Radio group={group} value="married" id="married" className="group-value married" /> </div> )} </RadioGroup> <label htmlFor="status" className="d-block">Which state do you live in?</label> <Select field="status" id="status" options={stateOptions} /> </form> )} </Form> ); } formDidUpdate(formState = {}) { console.log('formDidUpdate', formState); this.setState({ formValues: formState.values, }); } render() { return ( <div className="homepage"> {this.form} {this.results} </div> ); } }
import { productConstants } from "../actions/constants" const initialState = { products: [], priceRange: {}, productsByPrice: {}, productsVariants: [], pageRequest: false, page: {}, error: null, productDetails: {}, productVariants: [], productsSearch: [], loading: false } export default (state = initialState, action) => { switch(action.type){ case productConstants.GET_PRODUCTS_BY_SLUG: state = { ...state, products: action.payload.products, productsVariants: action.payload.variants, priceRange: action.payload.priceRange, productsByPrice: { ...action.payload.productsByPrice } } break; case productConstants.GET_PRODUCT_PAGE_REQUEST: state = { ...state, pageRequest: true } break; case productConstants.GET_PRODUCT_PAGE_SUCCESS: state = { ...state, page: action.payload.page, pageRequest: false } break; case productConstants.GET_PRODUCT_PAGE_FAILURE: state = { ...state, pageRequest: false, error: action.payload.error } break; case productConstants.GET_PRODUCT_DETAILS_BY_ID_REQUEST: state = { ...state, loading: true } break; case productConstants.GET_PRODUCT_DETAILS_BY_ID_SUCCESS: state = { ...state, loading: false, productDetails: action.payload.productDetails, productVariants: action.payload.productVariants } break; case productConstants.GET_PRODUCT_DETAILS_BY_ID_FAILURE: state = { ...state, loading: false, error: action.payload.error } break; case productConstants.RATE_PRODUCT_DETAILS_BY_ID_REQUEST: state = { ...state, loading: true } break; case productConstants.RATE_PRODUCT_DETAILS_BY_ID_SUCCESS: state = { ...state, loading: false } break; case productConstants.RATE_PRODUCT_DETAILS_BY_ID_FAILURE: state = { ...state, loading: false, error: action.payload.error } break; case productConstants.SEARCH_PRODUCTS_REQUEST: state = { ...state, loading: true } break; case productConstants.SEARCH_PRODUCTS_SUCCESS: state = { ...state, loading: false, productsSearch: action.payload.products } break; case productConstants.SEARCH_PRODUCTS_FAILURE: state = { ...state, loading: false, error: action.payload.error } break; case productConstants.GET_BEST_OFFER_PRODUCTS_REQUEST: state = { ...state, loading: true } break; case productConstants.GET_BEST_OFFER_PRODUCTS_SUCCESS: state = { ...state, loading: false, products: action.payload.products } break; case productConstants.GET_BEST_OFFER_PRODUCTS_FAILURE: state = { ...state, loading: false, error: action.payload.error } break; } return state; }
"use strict"; (function() { let current_issue_text = 'VIEW PREVIOUS ISSUE'; let hidden_issue_text = 'VIEW CURRENT ISSUE'; let hidden_issue = document.getElementById('issue-4'); let current_issue = document.getElementById('issue-5'); const issue_btn = document.getElementById('issue-btn'); issue_btn.innerText = current_issue_text; hidden_issue.style.display = 'none'; issue_btn.onclick = function showIssue(_) { // Switch issue variables are pointing to [current_issue, hidden_issue] = [hidden_issue, current_issue]; [current_issue_text, hidden_issue_text] = [hidden_issue_text, current_issue_text]; // Show current issue current_issue.style.display = ''; // Hide hidden issue hidden_issue.style.display = 'none'; issue_btn.innerText = current_issue_text; }; })();
getNextStream = function() { var msg = {}; msg["msg"] = "play"; socket.send( JSON.stringify(msg)); } startPlaying = function() { playNext( playing ); } audioEnded = function() { console.log( "length: " + audios.length ); console.log( "playing: " + playing ); playing++; playNext( playing ); } playNext = function() { /* this shoud be here, but... it wasn't working with it... */ //if( playing < audios.length ) { audios[playing].play(); //} } createSocket = function() { socket = new WebSocket("ws://localhost:8888/audio"); socket.onopen = function() { console.log("open..."); } socket.onclose = function() { console.log("closed."); } socket.onmessage = function(msg){ /* on message, create new audio objects push to array */ var data = "data:audio/wav;base64,"+msg.data; temp = new Audio(data); // create the HTML5 audio element temp.addEventListener('ended', audioEnded, false); audios.push( temp ); /* once you've loaded the audio go get the next item from the server */ getNextStream(); /* stack up at least 5 audio clips then start playing */ if( audios.length > 5 ) { startPlaying(); } } } var socket; var audios = Array(); var playing = 0; $(document).ready( function() { $("#play").click( function( event ) { event.preventDefault(); getNextStream(); }); createSocket(); })
/* global Tone */ app.config(function($stateProvider) { $stateProvider.state('versus', { url: '/versus/:songId/?chosenLevel&chosenLevelP2', templateUrl: 'js/versus/versus.html', resolve: { song: function(SongFactory, $stateParams) { return SongFactory.getSongById($stateParams.songId); } }, params: { mod1: 1, mod2: 1 }, controller: function($scope, $q, ArrowFactory, ToneFactory, song, SongFactory, $stateParams, ScoreFactory, $state, $timeout, WorkerFactory, FreqOpacAnimFactory) { $scope.numBars = []; var bars = window.innerWidth / 20; for(var i = 0; i < bars; i++) { $scope.numBars.push(i); } $scope.ready = false; var currentSong = song; const TIMING_WINDOW = ScoreFactory.TIMINGWINDOWS.Great; currentSong.offset = parseFloat(currentSong.offset); var P1difficulty = $stateParams.chosenLevel, P2difficulty = $stateParams.chosenLevelP2; var P1chartId = currentSong.Charts[P1difficulty].stepChart; var P2chartId = currentSong.Charts[P2difficulty].stepChart; var mainBPM = currentSong.bpms[0].bpm; var config1 = { TIMING_WINDOW: TIMING_WINDOW, ARROW_TIME: ((ArrowFactory.SPEED_1X/$stateParams.mod1) * 4 / mainBPM), //Factor for timing how fast arrow takes (this number / bpm for seconds) BEAT_TIME: 1/(mainBPM/60/4)/4, //Number of seconds per measure SPEED_MOD: $stateParams.mod1, }; config1.BEAT_VH = 100/(((ArrowFactory.SPEED_1X/$stateParams.mod1) * 4)/mainBPM) * config1.BEAT_TIME; var config2 = { TIMING_WINDOW: TIMING_WINDOW, ARROW_TIME: ((ArrowFactory.SPEED_1X/$stateParams.mod2) * 4 / mainBPM), //Factor for timing how fast arrow takes (this number / bpm for seconds) BEAT_TIME: 1/(mainBPM/60/4)/4, //Number of seconds per measure SPEED_MOD: $stateParams.mod2, }; config2.BEAT_VH = 100/(((ArrowFactory.SPEED_1X/$stateParams.mod2) * 4)/mainBPM) * config2.BEAT_TIME; var arrowWorker1, arrowWorker2, tone; //This is only so the user can read the loading screen and have heightened anticipation! setTimeout(function () { $q.all([SongFactory.getChartById(P1chartId), SongFactory.getChartById(P2chartId)]) .then(function (charts) { prepSong(charts[0], charts[1]); }) }, 2000); function prepSong(P1stepChart, P2stepChart) { // we need to know which player has a slower modifier--we will start the slower player's arrows first // we also need to use the slower player's config in the Tone Factory var playerOffset = config1.ARROW_TIME - config2.ARROW_TIME; var configForTone = playerOffset >= 0 ? config1 : config2; tone = new ToneFactory("/audio/"+currentSong.music, mainBPM, currentSong.offset, configForTone); //to set the stepChart on the player object ScoreFactory.setStepChart(P1stepChart, 1); ScoreFactory.setStepChart(P2stepChart, 2); // if player 1 is slower, her offset is 0, and player 2's var player1Offset, player2Offset; if (playerOffset >= 0) { // player 1's arrows start first player1Offset = 0; player2Offset = playerOffset; } else { // player 2's arrows start first player1Offset = -playerOffset; player2Offset = 0; } // this allows us to pass the offset on to the arrow factory in the config object config1.animationOffset = player1Offset; config2.animationOffset = player2Offset; ScoreFactory.setTotalArrows(1); ScoreFactory.setTotalArrows(2); var arrows1 = ArrowFactory.makeArrows(P1stepChart.chart, mainBPM, config1, currentSong, 1); var arrows2 = ArrowFactory.makeArrows(P2stepChart.chart, mainBPM, config2, currentSong, 2); // gives arrowWorker first chart arrowWorker1 = new WorkerFactory('/js/animation/animationWorker.js', 1); arrowWorker2 = new WorkerFactory('/js/animation/animationWorker.js', 2); // important to use the same config as the one that started the music to calculate timeStamps on the worker arrowWorker1.prepStepChart(currentSong, configForTone, mainBPM, P1stepChart.chart); arrowWorker2.prepStepChart(currentSong, configForTone, mainBPM, P2stepChart.chart); arrowWorker1.handleMessages($scope, arrows1, tone, 2); arrowWorker2.handleMessages($scope, arrows2, tone, 2); Tone.Buffer.onload = runInit; }; function runInit () { ArrowFactory.resumeTimeline(); tone.start(); var $gameplayContainer = $('#gameplayAnimationContainer'); FreqOpacAnimFactory.init($scope.numBars, $gameplayContainer, tone); var startTime = Date.now() - currentSong.offset*1000; arrowWorker1.worker.postMessage({ type: 'startTime', startTime }); arrowWorker2.worker.postMessage({ type: 'startTime', startTime }); arrowWorker1.addListener(tone, startTime); arrowWorker2.addListener(tone, startTime); // videofactory please Jay, put into models var videoOffset = (config1.ARROW_TIME + Number(currentSong.offset))*1000; if (currentSong.title === 'Caramelldansen') { $scope.videoSrc = '/video/Caramelldansen.mp4'; videoOffset += 1000; } else if (currentSong.title === 'Sandstorm') { $scope.videoSrc = '/video/Darude - Sandstorm.mp4'; } else { $scope.imageSrc = `/img/background/${song.background}`; } setTimeout(function() { var video = document.getElementById('bg-video'); video.play(); }, videoOffset); $scope.ready = true; $scope.$digest(); } } }); });
import { Box, Button, CircularProgress, FormControl, Grid, InputLabel, makeStyles, MenuItem, Paper, Select, Snackbar, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, TableSortLabel, TextField, Typography } from '@material-ui/core'; import axios from 'axios'; import React, { useContext, useEffect, useState } from 'react'; import MuiAlert from '@material-ui/lab/Alert'; import CheckCircleIcon from '@material-ui/icons/CheckCircle'; import HourglassEmptyIcon from '@material-ui/icons/HourglassEmpty'; import InfiniteScroll from 'react-infinite-scroll-component'; import { useHistory } from 'react-router'; import { DateRangePicker } from "materialui-daterange-picker"; import jsPDF from 'jspdf' import 'jspdf-autotable'; import { AuthContext } from '../../../context/authContext'; const HistoryComponent = () => { const [paymentHistory, setPaymentHistory] = useState([]); const [loading, setLoading] = useState(true); const [open, setOpen] = React.useState(false); const [message, setMessage] = React.useState(''); const [severity, setSeverity] = React.useState('success'); const [orderBy, setOrderBy] = useState('hotel'); const [order, setOrder] = React.useState('asc'); const [starting_after, setStarting] = useState(''); const [hasMore, setHasMore] = useState(true); const [fetched, setFetched] = useState(false); const [openDate, setOpenDate] = React.useState(false); const [dateRange, setDateRange] = React.useState(null); const [filterDate, setFilterDate] = React.useState(''); const [hotelList, setHotelList] = useState([]); const [hotel, setHotel] = useState(''); const authContext = useContext(AuthContext); const history = useHistory(); useEffect(() => { getPaymentHistory(); getHotelList(); // eslint-disable-next-line }, []); const useStyles = makeStyles({ root: { width: '100%', }, container: { }, paper: { display: 'flex', // alignItems: 'center', // justifyContent: 'center', minHeight: '300px' } }); const classes = useStyles(); const columns = [ { id: 'createdAt', label: 'Transaction Date' }, { id: 'hotel', label: 'Hotel' }, { id: 'name', label: 'Name' }, { id: 'email', label: 'Email' }, { id: 'contact', label: 'Contact' }, { id: 'checkIn', label: 'CheckIn' }, { id: 'checkOut', label: 'CheckOut' }, { id: 'amount', label: 'Amount' }, { id: 'action', label: 'Action' } ]; const getPaymentHistory = async () => { setLoading(true); try { const startingAfter = (starting_after.length > 0) ? `&starting_after=${starting_after}` : ''; const response = await axios.get(`${process.env.REACT_APP_API_URL}/payments?limit=${10}${startingAfter}`); if (response) { if (response.data.data.length === 0) { setHasMore(false); } setPaymentHistory(paymentHistory.concat(response.data.data)); setMessage(response.data.message); setSeverity('success'); setOpen(true); setLoading(false); return response; } } catch (error) { setLoading(false); setMessage(error.message); setSeverity('error'); setOpen(true); console.log(error); } } const Alert = ((props) => { return <MuiAlert elevation={6} variant="filled" {...props} />; }); const createSortHandler = (property) => (event) => { handleRequestSort(event, property); }; const displayHotelList = () => { return ( hotelList.map((item) => { return <MenuItem value={item._id}>{item.name}</MenuItem> }) ) } const downloadHistoryPdf = () => { const doc = new jsPDF(); var header = function (data) { doc.setFontSize(18); doc.setTextColor(40); doc.setFontStyle('normal'); //doc.addImage(headerImgData, 'JPEG', data.settings.margin.left, 20, 50, 50); doc.text("Testing Report", data.settings.margin.left, 50); }; doc.autoTable({ html: '#my-table', styles: { fontSize: 8 }, theme: 'grid', columnStyles: { 0: { minCellWidth: '100px' }, 1: { minCellWidth: '100px' }, 2: { minCellWidth: '100px' } }, // Cells in first column centered and green }); const docName = (filterDate) ? filterDate : 'history'; doc.save(`${docName}.pdf`); } const handleRequestSort = (event, property) => { const isAsc = orderBy === property && order === 'asc'; setOrder(isAsc ? 'desc' : 'asc'); setOrderBy(property); }; const handleClose = (event, reason) => { if (reason === 'clickaway') { return; } setOpen(false); }; const toggle = () => setOpenDate(!openDate); const chooseDate = (range) => { setDateRange(range); setOpenDate(false); let { startDate, endDate } = range; startDate = convertDate(startDate); endDate = convertDate(endDate); setFilterDate(`${startDate} - ${endDate}`) } const getHotelList = async () => { try { const hotelList = await axios.get(`${process.env.REACT_APP_API_URL}/hotel`); setHotelList(hotelList.data.data); } catch (error) { setMessage(error.message); setSeverity('error'); setOpen(true); } } const convertDate = (givenDate) => { let date = new Date(givenDate); return ((date.getMonth() > 8) ? (date.getMonth() + 1) : ('0' + (date.getMonth() + 1))) + '/' + ((date.getDate() > 9) ? date.getDate() : ('0' + date.getDate())) + '/' + date.getFullYear() } const fetchMoreData = async () => { setFetched(true); const id = paymentHistory[paymentHistory.length - 1].id; const filterData = (dateRange) ? `&gte=${Math.floor(dateRange.startDate.getTime() / 1000)}&lte=${Math.floor(dateRange.endDate.getTime() / 1000)}` : ''; const hotelFilter = (hotel) ? `&hotel=${hotel}`: ''; const response = await axios.get(`${process.env.REACT_APP_API_URL}/payments?limit=${10}&starting_after=${id}${filterData}${hotelFilter}`); if (response.data.data.length === 0) { setHasMore(false); } setStarting(id); setPaymentHistory(paymentHistory.concat(response.data.data)); setFetched(false); } function descendingComparator(a, b, orderBy) { if (b[orderBy] < a[orderBy]) { return -1; } if (b[orderBy] > a[orderBy]) { return 1; } return 0; } function getComparator(order, orderBy) { return order === 'desc' ? (a, b) => descendingComparator(a, b, orderBy) : (a, b) => -descendingComparator(a, b, orderBy); } function stableSort(array, comparator) { const stabilizedThis = array.map((el, index) => [el, index]); stabilizedThis.sort((a, b) => { const order = comparator(a[0], b[0]); if (order !== 0) return order; return a[1] - b[1]; }); return stabilizedThis.map((el) => el[0]); } const createRefund = async (event, value) => { event.preventDefault(); if (window.confirm('Do you want to refund the amount ?')) { try { const response = await axios.post(`${process.env.REACT_APP_API_URL}/payments/refund`, value); setMessage(response.data.message); history.push('/'); history.replace('/history'); setOpen(true); setSeverity('success'); setTimeout(() => { }, 1000); } catch (error) { console.log(error); setMessage(error.response.data.message); setOpen(true); setSeverity('error'); } } } const filterHistory = async () => { console.log(hotel); if (hotel.length === 0 && !dateRange) { setMessage('Select hotel or date for filter'); setSeverity('error'); setOpen(true); return; } setLoading(true); try { const hot = (hotel) ? `&hotel=${hotel}` : ''; const gte = (dateRange && dateRange.startDate) ? `&gte=${Math.floor(dateRange.startDate.getTime() / 1000)}` : ''; const lte = (dateRange && dateRange.endDate) ? `&lte=${Math.floor(dateRange.endDate.getTime() / 1000)}`: ''; const response = await axios.get(`${process.env.REACT_APP_API_URL}/payments?limit=${10}${gte}${lte}${hot}`); setPaymentHistory(response.data.data); setLoading(false); } catch (error) { console.log(error); setMessage(error.response.data.message); setOpen(true); setSeverity('error'); setLoading(false); } } const clearFilter = async () => { setLoading(true); try { const response = await axios.get(`${process.env.REACT_APP_API_URL}/payments?limit=${10}`); setPaymentHistory(response.data.data); setLoading(false); } catch (error) { setLoading(false); setMessage(error.response.data.message); setOpen(true); setSeverity('error'); } setDateRange(null); setFilterDate(''); setHotel(''); } return ( <Box display="flex" width="98%" justifyContent="center" alignItems="center" height="100%"> <Snackbar open={open} autoHideDuration={2000} onClose={handleClose} > <Alert onClose={handleClose} severity={severity}> {message} </Alert> </Snackbar> { loading ? <CircularProgress color="secondary" /> : null} { !loading ? <Grid container> <Box display="flex" flexDirection="column" className={classes.root}> <Paper className={classes.paper}> <div className={classes.root} > <Grid item style={{ margin: '16px' }}> <Box display="flex" flexDirection="column"> <Box display="flex" alignItems="center"> { authContext.admin ? <Box display="flex" alignItems="center" > <FormControl required margin="normal" style={{ marginLeft: '30px', width: '200px' }} variant="outlined"> <InputLabel variant="outlined" required id="Select Hotel">Filter By Hotel</InputLabel> <Select labelId="Filter By Hotel" id="hotel" value={hotel} onChange={(e) => setHotel(e.target.value)} label="Hotel" > <MenuItem value="">None</MenuItem> {displayHotelList()} </Select> </FormControl> </Box> : null } <Box display="flex" alignItems="center" > <TextField label="Filter By Date" name="filterDate" variant="outlined" color="secondary" required value={filterDate} margin="normal" type="text" style={{marginLeft: '30px', width: '200px'}} autoComplete="off" onFocus={e => setOpenDate(!openDate)} onClick={e => setOpenDate(!openDate)} /> <Button onClick={filterHistory} style={{ marginLeft: '16px' }} variant="contained" color="primary"> Filter </Button> </Box> <Button onClick={clearFilter} style={{ marginLeft: '16px' }} variant="contained" color="secondary"> Clear </Button> <Button disabled={paymentHistory.length === 0} onClick={downloadHistoryPdf} style={{ marginLeft: '16px' }} variant="contained" color="warning"> Download </Button> </Box> <DateRangePicker open={openDate} toggle={toggle} onChange={(range) => chooseDate(range)} /> </Box> </Grid> {paymentHistory.length > 0 ? <Grid item> <TableContainer className={classes.container} id="scrollableDiv" style={{ height: 440, overflow: "auto" }}> <InfiniteScroll dataLength={paymentHistory.length} next={fetchMoreData} style={{ display: 'flex', flexDirection: 'column', justifyContent: 'center', alignContent: 'center' }} //To put endMessage and loader to the top. hasMore={hasMore} scrollableTarget="scrollableDiv" loader={fetched ? <Box margin="8px 0px" display="flex" justifyContent="center"> <CircularProgress color="secondary" /> </Box> : null} endMessage={<Box margin="8px 0px" display="flex" justifyContent="center"> NO MORE HISTORY FOUND </Box>} > <Table id="my-table" stickyHeader aria-label="sticky table" > <TableHead> <TableRow> {columns.map((column) => ( <TableCell key={column.id} align={column.align} > <TableSortLabel active={orderBy === column.id} direction={orderBy === column.id ? order : 'asc'} onClick={createSortHandler(column.id)} > {column.label} </TableSortLabel> </TableCell> ))} </TableRow> </TableHead> <TableBody> {stableSort(paymentHistory, getComparator(order, orderBy)) .map((row, index) => { return ( <TableRow hover role="checkbox" tabIndex={-1} key={row.code} style ={ index % 2? { background : '#fafafa' }:{ background : '#fff' }}> {columns.map((column) => { const value = row[column.id]; return ( <TableCell key={column.id} align={column.align} > { column.id === 'action' ? <Box> { row.refunded ? <Box display="flex" alignItems="center"> <CheckCircleIcon color="primary" /> Refunded </Box> : <Box> { row.amountReceived === row.amount ? <Button variant="contained" color="primary" onClick={(event) => createRefund(event, row)}>Refund</Button> : <Box display="flex" alignItems="center"> <HourglassEmptyIcon color="primary" /> Payment Pending</Box> } </Box> } </Box> : <Box> {column.id === 'amount' ? `$${value / 100}` : value}</Box>} </TableCell> ); })} </TableRow> ); })} </TableBody> </Table> </InfiniteScroll> </TableContainer> </Grid> : <Box height="100%" display="flex" justifyContent="center" alignItems="center">No Payment History Found</Box>} </div> </Paper> </Box> </Grid> : null} </Box> ) } export default HistoryComponent;
// Concatenation const fname = 'Suraj'; const age = 19; // using + console.log('My name is ' + fname + ' and I am ' + age); // using template strings console.log(`My name is ${fname} and I am ${age}`); let s = 'Hello Duniya!'; console.log(s.length); console.log(s.toUpperCase()); console.log(s.toLowerCase()); console.log(s.substring(2,9).toUpperCase()); console.log(s.substr(5,4).toUpperCase()); console.log(s.split('')); console.log(s.split('l')); console.log(s.split('o'));
const ShowdownWrapper = require("./LibsWrappers/ShowdownWrapper"); const FileSystemWrapper = require("./LibsWrappers/FileSystemWrapper"); const MarkdownService = require("./Services/MarkdownService"); const FolderService = require("./Services/FolderService"); const Builder = require("./Builder"); const PrintService = require("./Services/PrinterService"); const articles = require("../Articles/articles"); function BuilderFactory(){ function createBuilder({articlesDistPath}){ return Builder({ articles: articles, folderService: createFolderService({articlesDistPath: articlesDistPath}), markdownService: createMarkdownService(), fileSystemWrapper: FileSystemWrapper() }); function createFolderService({articlesDistPath}){ return FolderService({ articlesDistPath: articlesDistPath, fileSystemWrapper: FileSystemWrapper() }) } function createMarkdownService(){ return MarkdownService({ fileSystemWrapper: FileSystemWrapper(), showdownWrapper: ShowdownWrapper(), printerService: PrintService()}) } } return { createBuilder: createBuilder } } module.exports = BuilderFactory();
import styled from "styled-components"; const H2 = styled.h2` font: normal normal 600 32px 'Nunito'; letter-spacing: 0px; color: #0A194E; opacity: 1; `; const P = styled.p` font-family: 'Nunito', sans-serif; letter-spacing: 0px; color: #FFFFFF; opacity: 1; text-align: ${({ noF }) => ( noF ? "center" : "")}; color: ${({ noF }) => ( noF ? "#707070" : "")}; `; const H3 = styled.h3` text-align: left; font: normal normal 600 18px 'Nunito'; font: ${({ fro }) => (fro ? "normal normal normal 14px 'Nunito'" : "")}; letter-spacing: 0px; color: #0A194E; opacity: 1; margin-right: 0.5rem; margin-top: ${({ fro }) => (fro ? "-0.5rem" : "")}; `; const Span = styled.span` letter-spacing: 0px; color: #0D1F5F; opacity: 1; font: normal normal bold 12px/16px 'Nunito', sans-serif; font: ${({ nav, navP, navPa }) => (nav || navP || navPa ? "normal normal 600 16px Nunito" : "")}; margin-left: 0.5rem; margin: ${({ navP }) => (navP ? "auto 0.5rem auto 1.5rem" : "")}; margin: ${({ navPa }) => (navPa ? "0.5rem auto" : "")}; cursor: ${({ navPa }) => (navPa ? "pointer" : "")}; `; export { P, Span, H3, H2, }
/* * The MIT License (MIT) * Copyright (c) 2019. Wise Wild Web * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * @author : Nathanael Braun * @contact : n8tz.js@gmail.com */ import React from "react"; import is from "is"; import Actions from "App/store/actions"; const SimpleObjectProto = ({}).constructor; import {connect} from 'react-redux' function walknGet( obj, path, isKey ) { if ( is.string(path) ) path = path.split('.'); return path.length ? obj[path[0]] && walknGet(obj[path[0]], path.slice(1)) : obj; } function isReactRenderable( obj ) { return obj.prototype instanceof React.Component || obj === React.Component || obj.$$typeof || is.fn(obj); } /** * Add internationalization function t to the target component * @param argz * @returns {*} */ export default function usePopins( ...argz ) { let BaseComponent = (!argz[0] || isReactRenderable(argz[0])) && argz.shift(), opts = (!argz[0] || argz[0] instanceof SimpleObjectProto) && argz.shift() || {}; if ( !BaseComponent ) { return function ( BaseComponent ) { return usePopins(BaseComponent, opts) } } const PopinComp = connect(( { popins }, props ) => ({ popins, ref: props.forwardedRef }), { ...Actions.popins })(BaseComponent); let withRef = React.forwardRef(( props, ref ) => { return <PopinComp {...props} forwardedRef={ref}/>; }); withRef.displayName = BaseComponent.displayName; return withRef; }
const RestaurantHelper = { ucfirst (string) { return (string.length) ? string.charAt(0).toUpperCase() + string.slice(1) : '' }, uniqueArray (array) { return array.filter(function (value, index, self) { return self.indexOf(value) === index }) }, formatCategories (categories) { return categories.map(item => this.ucfirst(item)).join(' • ') }, formatAddress (options) { const cityName = options.city || '' const streetName = options.street_name || options.streetName || '' const streetNumber = options.street_number || options.streetNumber || '' const zipCode = options.zipcode || '' return (options) ? `${streetName} ${streetNumber}, ${zipCode} ${cityName}` : '' } } export default RestaurantHelper
import { createStore, combineReducers, applyMiddleware } from 'redux'; import { reducer as reduxFormReducer } from 'redux-form'; import thunk from 'redux-thunk'; import { authReducer } from './reducers/authreducer'; import { tabsReducer } from './reducers/tabsreducer'; import { tasksReducer } from './reducers/tasksreducer'; const reducer = combineReducers({ form: reduxFormReducer, authReducer, tabsReducer, tasksReducer }); const store = createStore(reducer, applyMiddleware(thunk)); export default store;
/** * @license * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview * Registers a language handler for CSS. * * * To use, include prettify.js and this file in your HTML page. * Then put your code in an HTML tag like * <pre class="prettyprint lang-css"></pre> * * * http://www.w3.org/TR/CSS21/grammar.html Section G2 defines the lexical * grammar. This scheme does not recognize keywords containing escapes. * * @author mikesamuel@gmail.com */ // This file is a call to a function defined in prettify.js which defines a // lexical scanner for CSS and maps tokens to styles. // The call to PR['registerLangHandler'] is quoted so that Closure Compiler // will not rename the call so that this language extensions can be // compiled/minified separately from one another. Other symbols defined in // prettify.js are similarly quoted. // The call is structured thus: // PR['registerLangHandler']( // PR['createSimpleLexer']( // shortcutPatterns, // fallThroughPatterns), // [languageId0, ..., languageIdN]) // Langugage IDs // ============= // The language IDs are typically the file extensions of source files for // that language so that users can syntax highlight arbitrary files based // on just the extension. This is heuristic, but works pretty well in // practice. // Patterns // ======== // Lexers are typically implemented as a set of regular expressions. // The SimpleLexer function takes regular expressions, styles, and some // pragma-info and produces a lexer. A token description looks like // [STYLE_NAME, /regular-expression/, pragmas] // Initially, simple lexer's inner loop looked like: // while sourceCode is not empty: // try each regular expression in order until one matches // remove the matched portion from sourceCode // This was really slow for large files because some JS interpreters // do a buffer copy on the matched portion which is O(n*n) // The current loop now looks like // 1. use js-modules/combinePrefixPatterns.js to // combine all regular expressions into one // 2. use a single global regular expresion match to extract all tokens // 3. for each token try regular expressions in order until one matches it // and classify it using the associated style // This is a lot more efficient but it does mean that lookahead and lookbehind // can't be used across boundaries to classify tokens. // Sometimes we need lookahead and lookbehind and sometimes we want to handle // embedded language -- JavaScript or CSS embedded in HTML, or inline assembly // in C. // If a particular pattern has a numbered group, and its style pattern starts // with "lang-" as in // ['lang-js', /<script>(.*?)<\/script>/] // then the token classification step breaks the token into pieces. // Group 1 is re-parsed using the language handler for "lang-js", and the // surrounding portions are reclassified using the current language handler. // This mechanism gives us both lookahead, lookbehind, and language embedding. // Shortcut Patterns // ================= // A shortcut pattern is one that is tried before other patterns if the first // character in the token is in the string of characters. // This very effectively lets us make quick correct decisions for common token // types. // All other patterns are fall-through patterns. // The comments inline below refer to productions in the CSS specification's // lexical grammar. See link above. PR['registerLangHandler']( PR['createSimpleLexer']( // Shortcut patterns. [ // The space production <s> [PR['PR_PLAIN'], /^[ \t\r\n\f]+/, null, ' \t\r\n\f'] ], // Fall-through patterns. [ // Quoted strings. <string1> and <string2> [PR['PR_STRING'], /^\"(?:[^\n\r\f\\\"]|\\(?:\r\n?|\n|\f)|\\[\s\S])*\"/, null], [PR['PR_STRING'], /^\'(?:[^\n\r\f\\\']|\\(?:\r\n?|\n|\f)|\\[\s\S])*\'/, null], ['lang-css-str', /^url\(([^\)\"\']+)\)/i], [PR['PR_KEYWORD'], /^(?:url|rgb|\!important|@import|@page|@media|@charset|inherit)(?=[^\-\w]|$)/i, null], // A property name -- an identifier followed by a colon. ['lang-css-kw', /^(-?(?:[_a-z]|(?:\\[0-9a-f]+ ?))(?:[_a-z0-9\-]|\\(?:\\[0-9a-f]+ ?))*)\s*:/i], // A C style block comment. The <comment> production. [PR['PR_COMMENT'], /^\/\*[^*]*\*+(?:[^\/*][^*]*\*+)*\//], // Escaping text spans [PR['PR_COMMENT'], /^(?:<!--|-->)/], // A number possibly containing a suffix. [PR['PR_LITERAL'], /^(?:\d+|\d*\.\d+)(?:%|[a-z]+)?/i], // A hex color [PR['PR_LITERAL'], /^#(?:[0-9a-f]{3}){1,2}\b/i], // An identifier [PR['PR_PLAIN'], /^-?(?:[_a-z]|(?:\\[\da-f]+ ?))(?:[_a-z\d\-]|\\(?:\\[\da-f]+ ?))*/i], // A run of punctuation [PR['PR_PUNCTUATION'], /^[^\s\w\'\"]+/] ]), ['css']); // Above we use embedded languages to highlight property names (identifiers // followed by a colon) differently from identifiers in values. PR['registerLangHandler']( PR['createSimpleLexer']([], [ [PR['PR_KEYWORD'], /^-?(?:[_a-z]|(?:\\[\da-f]+ ?))(?:[_a-z\d\-]|\\(?:\\[\da-f]+ ?))*/i] ]), ['css-kw']); // The content of an unquoted URL literal like url(http://foo/img.png) should // be colored as string content. This language handler is used above in the // URL production to do so. PR['registerLangHandler']( PR['createSimpleLexer']([], [ [PR['PR_STRING'], /^[^\)\"\']+/] ]), ['css-str']);
import React, { useEffect } from 'react' import styled from 'styled-components' import { SortType } from '../../../Constant'; const Container = styled.div` display:flex; flex-flow: column nowrap; /* background-color: white; */ margin-bottom: 0; `; const SearchField = styled.input` margin: 0px 1rem 0px 1rem; padding: 0.5rem; border-radius: 1rem; border: none; /* background-color: white; */ background-color: #f3f3f5; `; const Filter = styled.select` margin: 8px; border-radius: 30px; border:none; /* background-color: blue; */ background-color: #f3f3f5; padding: 6px; /* background: none; */ `; const FilterOption = styled.option` `; const FilterContainer = styled.div` margin: 8px 8px 8px 8px; display:flex; flex-flow: row wrap; align-items: center; `; function FiltersComponent(props) { const { applyFilter, filter } = props; let search = ""; let sort = SortType.A_Z; if (filter !== undefined){ search = filter.search; sort = filter.sort; } const onChangeSearchValue = (e) => { if(applyFilter === undefined){ console.error("applyFilter is undefined") return; } search = e.target.value; applyFilter({ search: search, sort: sort }); } const onChangeSortValue = (e) => { if(applyFilter === undefined){ console.error("applyFilter is undefined") return; } sort = e.target.value; applyFilter({ search: search, sort: sort }); } return ( <Container> <SearchField type="text" placeholder="Rechercher un plat" onChange={onChangeSearchValue}></SearchField> <FilterContainer> <Filter name="Trier par" id="tri" onChange={onChangeSortValue} defaultValue={sort}> <FilterOption value={SortType.A_Z}>A - Z</FilterOption> <FilterOption value={SortType.Z_A}>Z - A</FilterOption> </Filter> </FilterContainer> </Container> ) } export default FiltersComponent
/** * Created by smoseley on 12/14/2015. */ (function(module){ var getCurrentStates = function(){ return [ { state: 'default', config: { url: '/home', controller: 'HomeController as vm', templateUrl: 'app/home/templates/home.template.html' } } ]; } var configureRoutes = function($stateProvider, $urlRouterProvider){ var states = getCurrentStates() states.forEach(function(state){ $stateProvider.state(state.state, state.config); }) var otherwise = '/home'; $urlRouterProvider.otherwise(otherwise); }; module.config(configureRoutes); })(angular.module('app'));
import { useEffect, useRef } from "react"; export const usePrevius = (data) => { const previusData = useRef(); useEffect(() => { previusData.current = data; }, []); return previusData.current; };
'use strict'; var expand = document.querySelectorAll('[data-plugin="expand"]'); expand.forEach(function (item) { item.addEventListener('click', function (e) { e.target.parentElement.nextElementSibling.classList.toggle("hidden"); }); });
import filter from "lodash/filter"; import orderBy from "lodash/orderBy"; import format from "date-fns/format"; /** * @param {array} data * @param {string} key * @param {string} sortMode * @return {array} sorded by the key field */ export const sortData = (data, key, sortMode) => { //console.log("sorting for: ", key); return orderBy(data, key, sortMode); }; /** * @param {array} data * @param {string} key * @return {array} element with key */ export const filterById = (data, key) => { const filtered = filter(data, elem => elem.id === key); return filtered; }; /** * @param {string} date * @return {date} new date in format 1 Feb 2019 13:58:42 PM */ export const formateDate = date => { return format(new Date(date), "d MMM y pp"); }; export const sortConversationsDesc = (data, currentSortField) => { return [...data].sort(function(a, b) { return b.conversation[currentSortField] - a.conversation[currentSortField]; }); }; /** * @param {string} param - parameter in URL * @return {string} parameter value */ export const getURLParam = param => { const parsedURL = new URL(window.location.href); let searchParam__date = parsedURL.searchParams.get(param); if (!searchParam__date) { console.log("query error"); } return searchParam__date; };
var apiNo = context.getVariable("apiNo"); var faultName = context.getVariable ("fault.name"); var errorResponse = JSON.parse(context.getVariable ("error.content")); var faultString = errorResponse.fault.faultstring; context.setVariable("isoTimestamp", ISODateString()); // Prints something like 2009-09-28T19:03:12+08:00 if(faultString !== null && faultString.toUpperCase().includes("SC-VALIDATETOKENCONNECTID FAILED")) faultName = "TokenValidationFailed"; switch (faultName) { case "TokenValidationFailed": context.setVariable("exceptionName", "exceptionName"); context.setVariable("errorCode", "401."+apiNo+".101"); context.setVariable("errorDesc", "Unauthorized"); context.setVariable("errorMessage", "Token Validation Failed"); context.setVariable("httpError", "401"); break; case "SpikeArrestViolation": context.setVariable("exceptionName", "exceptionName"); context.setVariable("errorCode", "429."+apiNo+".101"); context.setVariable("errorDesc", "Too Many Requests"); context.setVariable("errorMessage", "Spike arrest violation"); context.setVariable("httpError", "429"); break; case "QuotaViolation": context.setVariable("exceptionName", "exceptionName"); context.setVariable("errorCode", "429."+apiNo+".102"); context.setVariable("errorDesc", "Too Many Requests"); context.setVariable("errorMessage", "Rate limit quota violation. Quota limit exceeded"); context.setVariable("httpError", "429"); break; case "ConcurrentRatelimtViolation": context.setVariable("exceptionName", "exceptionName"); context.setVariable("errorCode", "429."+apiNo+".103"); context.setVariable("errorDesc", "Too Many Requests"); context.setVariable("errorMessage", "Concurrent rate limit connection exceeded"); context.setVariable("httpError", "429"); break; case "ScriptExecutionFailed": context.setVariable("exceptionName", "exceptionName"); context.setVariable("errorCode", "500."+apiNo+".101"); context.setVariable("errorDesc", "Internal Server Error"); context.setVariable("errorMessage", "JavaScript runtime error"); context.setVariable("httpError", "500"); break; case "InvalidApiKeyForGivenResource": context.setVariable("exceptionName", "exceptionName"); context.setVariable("errorCode", "500."+apiNo+".102"); context.setVariable("errorDesc", "Internal Server Error"); context.setVariable("errorMessage", "Invalid ApiKey for given resource"); context.setVariable("httpError", "500"); break; case "ExecutionFailed": context.setVariable("exceptionName", "exceptionName"); context.setVariable("errorCode", "500."+apiNo+".103"); context.setVariable("errorDesc", "Internal Server Error"); context.setVariable("errorMessage", "Request input is malformed or invalid"); context.setVariable("httpError", "500"); break; case "InvalidJSONPath": context.setVariable("exceptionName", "exceptionName"); context.setVariable("errorCode", "500."+apiNo+".104"); context.setVariable("errorDesc", "Internal Server Error"); context.setVariable("errorMessage", "Invalid JSON path"); context.setVariable("httpError", "500"); break; case "RaiseFault": context.setVariable("exceptionName", "exceptionName"); context.setVariable("errorCode", "404."+apiNo+".101"); context.setVariable("errorDesc", "Resource not found"); context.setVariable("errorMessage", "Resource not found/Invalid resource"); context.setVariable("httpError", "404"); break; default: context.setVariable("exceptionName", "exceptionName"); context.setVariable("errorCode", "500."+apiNo+".100"); context.setVariable("errorDesc", "Internal Server Error"); context.setVariable("errorMessage", faultName); context.setVariable("httpError", "500"); break; } function padWithZero(number, strLength) { var newString = '' + number; while (newString.length < strLength) { newString = '0' + newString; } return newString; } /* Use a function for the exact format desired... */ function ISODateString() { var now = new Date(), tzo = -now.getTimezoneOffset(), dif = tzo >= 0 ? '+' : '-', pad = function(num) { var norm = Math.abs(Math.floor(num)); return (norm < 10 ? '0' : '') + norm; }; return now.getFullYear() + '-' + pad(now.getMonth()+1) + '-' + pad(now.getDate()) + 'T' + pad(now.getHours()) + ':' + pad(now.getMinutes()) + ':' + pad(now.getSeconds()) + dif + pad(tzo / 60) + ':' + pad(tzo % 60); }
/** * Auth Sagas */ import { all, call, put, takeEvery,select,delay } from 'redux-saga/effects'; // app config import AppConfig from '../constants/AppConfig'; import {getAxiosRequestAuth, AsyncStorage} from "../util/helpers/helpers" import { getCommsSuccess, getCommsFailure } from '../actions'; const getComms = async () => { const userToken = await AsyncStorage.getObjectData('authToken'); var config = { headers: { 'gravitoUid': userToken } }; const request = await getAxiosRequestAuth().get(`/user/events`,config) return await request; } /** * Get the communication events */ function* getLoggedInEvents() { try { // call api to get user events const response = yield call(getComms); yield put(getCommsSuccess(response)) } catch (error) { yield put(getCommsFailure()); console.log("error",error) } } export const commsSagas = [ takeEvery('GET_USER_EVENTS', getLoggedInEvents) ] /** * Default Consents Root Saga */ export default function* rootSaga() { yield all([ ...commsSagas, ]) }
import { groupBy, maxBy } from 'lodash'; import reviewNetwork from './contracts/review-network'; import wallet from './wallet'; class Survey { async create(publicKey, title, surveyJsonHash, rewardPerSurvey, maxAnswers) { const rn = await reviewNetwork.contract; let rewardPerSurveyFormatted = await wallet.getTotalTokenAmount(rewardPerSurvey); return reviewNetwork.sendSigned( rn.methods.createSurvey( publicKey, title, surveyJsonHash, rewardPerSurveyFormatted, maxAnswers, ), ); } async fund(surveyJsonHash, amount) { const rn = await reviewNetwork.contract; let totalAmount = await wallet.getTotalTokenAmount(amount); return reviewNetwork.sendSigned( rn.methods.fundSurvey(surveyJsonHash, totalAmount), ); } async start(surveyJsonHash) { const rn = await reviewNetwork.contract; return reviewNetwork.sendSigned(rn.methods.startSurvey(surveyJsonHash)); } async complete(surveyJsonHash) { const rn = await reviewNetwork.contract; return reviewNetwork.sendSigned(rn.methods.completeSurvey(surveyJsonHash)); } async getEvents(event, options = {}) { const { ownOnly, reflectState, currentOnly } = options; // events that depend on each other // one cannot be emmited before another const dependentEvents = [ 'LogSurveyAdded', 'LogSurveyFunded', 'LogSurveyStarted', 'LogSurveyCompleted', ]; // map statuses by events: const status = { LogSurveyAdded: 'IDLE', LogSurveyFunded: 'FUNDED', LogSurveyStarted: 'IN_PROGRESS', LogSurveyCompleted: 'COMPLETED', }; async function getEvent(event, ownOnly) { const filter = ownOnly ? { creator: wallet.getMyAddress() } : {}; const rn = await reviewNetwork.contract; return rn.getPastEvents(event, { fromBlock: 0, filter, }); } if (reflectState) { // start slicing events from the desired event: const eventsToFetch = dependentEvents.slice( dependentEvents.indexOf(event), ); // fetch all required events: return Promise.all( eventsToFetch.map(event => getEvent(event, ownOnly).then(receivedEvents => { return receivedEvents.map(receivedEvent => ({ ...receivedEvent, status: status[event], })); }), ), ).then(result => { const allEventsMerged = Array.prototype.concat.apply([], result); console.log({ allEventsMerged }); const dividedByHash = groupBy( allEventsMerged, 'returnValues.surveyJsonHash', ); console.log({ dividedByHash }); const eventsToReturn = Object.values(dividedByHash).map(val => maxBy(val, i => i.blockNumber), ); if (currentOnly) { return eventsToReturn.filter(e => e.event === event); } return eventsToReturn; }); } // just fetch all events and return them: return getEvent(event, ownOnly).then(events => { return events.map(e => ({ ...e, status: status[event] })); }); } } export default new Survey();
// You will be given two arrays of integers and asked to determine all integers that satisfy the following two conditions: // 1) The elements of the first array are all factors of the integer being considered // 2) The integer being considered is a factor of all elements of the second array // These numbers are referred to as being between the two arrays. You must determine how many such numbers exist. /* * Complete the 'getTotalX' function below. * * The function is expected to return an INTEGER. * The function accepts following parameters: * 1. INTEGER_ARRAY a * 2. INTEGER_ARRAY b */ function getTotalX(a, b) { const [max_a, min_b] = [Math.max(...a), Math.min(...b)]; const integers = Array(min_b - max_a).from( { length: min_b - max_a + 1 }, (_, id) => id + max_a ); return integers.filter( v => a.every(num => v % num === 0) && b.every(num => num % v === 0) ).length; let validCount = 0; for (let x = Math.max(...a); x <= Math.min(...b); x++) { if (a.every(num => x % num === 0)) { if (b.every(num => num % x === 0)) { validCount += 1; } } } return validCount; } function main() { const a = [2, 4]; const b = [16, 32, 96]; console.log(getTotalX(a, b)); // -> 3 } main();
Polymer({ is: "paper-toolbar", hostAttributes: { role: "toolbar" }, properties: { bottomJustify: { type: String, value: "" }, justify: { type: String, value: "" }, middleJustify: { type: String, value: "" } }, attached: function() { this._observer = this._observe(this), this._updateAriaLabelledBy() }, detached: function() { this._observer && this._observer.disconnect() }, _observe: function(t) { var e = new MutationObserver(function() { this._updateAriaLabelledBy() }.bind(this)); return e.observe(t, { childList: !0, subtree: !0 }), e }, _updateAriaLabelledBy: function() { for (var t, e = [], i = Polymer.dom(this.root).querySelectorAll("content"), r = 0; t = i[r]; r++) for (var s, o = Polymer.dom(t).getDistributedNodes(), a = 0; s = o[a]; a++) if (s.classList && s.classList.contains("title")) if (s.id) e.push(s.id); else { var l = "paper-toolbar-label-" + Math.floor(1e4 * Math.random()); s.id = l, e.push(l) } e.length > 0 && this.setAttribute("aria-labelledby", e.join(" ")) }, _computeBarExtraClasses: function(t) { return t ? t + ("justified" === t ? "" : "-justified") : "" } });
'use strict'; Wia.DEFAULT_PROTOCOL = 'https'; Wia.DEFAULT_HOST = 'api.wia.io'; Wia.DEFAULT_PORT = '443'; Wia.DEFAULT_BASE_PATH = '/v1/'; Wia.DEFAULT_STREAM_PROTOCOL = 'mqtts'; Wia.DEFAULT_STREAM_HOST = 'api.wia.io'; Wia.DEFAULT_STREAM_PORT = '8883'; Wia.PACKAGE_VERSION = require('./package.json').version; Wia.USER_AGENT = { bindings_version: Wia.PACKAGE_VERSION, lang: 'node', lang_version: process.version, platform: process.platform, publisher: 'wia' }; var os = require('os'); var exec = require('child_process').exec; var resources = { Commands : require('./lib/resources/Commands'), Devices: require('./lib/resources/Devices'), Events: require('./lib/resources/Events'), Functions : require('./lib/resources/Functions'), Locations : require('./lib/resources/Locations'), Logs : require('./lib/resources/Logs'), Organisations : require('./lib/resources/Organisations'), Sensors : require('./lib/resources/Sensors'), TeamMembers : require('./lib/resources/TeamMembers'), Users : require('./lib/resources/Users') }; Wia.resources = resources; var WiaStream = require('./lib/WiaStream'); var request = require('request'); var Error = require('./lib/Error'); var fs = require('fs'); var os = require('os'); function Wia(opt) { var self = this; if (!(this instanceof Wia)) { return new Wia(opt); } this._api = { accessToken: null, publicKey: null, secretKey: null, appKey: null, rest: { host: Wia.DEFAULT_HOST, port: Wia.DEFAULT_PORT, protocol: Wia.DEFAULT_PROTOCOL, basePath: Wia.DEFAULT_BASE_PATH }, stream: { protocol: Wia.DEFAULT_STREAM_PROTOCOL, host: Wia.DEFAULT_STREAM_HOST, port: Wia.DEFAULT_STREAM_PORT }, agent: null, debug: false, enableCommands: true }; this._prepResources(); this._prepStream(); if (!opt || opt.length == 0) { var contents = fs.readFileSync(os.homedir() + '/.wia/config', 'utf8'); if (contents) { var contentsObj = JSON.parse(contents); if (contentsObj) { for (var k in contentsObj) { if (opt.hasOwnProperty(k)) { this._api[k] = contentsObj[k]; } } this.setAccessToken(contentsObj.accessToken || contentsObj.secretKey); } } } else if (typeof opt === "object") { for (var k in opt) { if (opt.hasOwnProperty(k)) { this._api[k] = opt[k]; } } this.setAccessToken(opt.accessToken || opt.secretKey); } else { this.setAccessToken(opt); } } Wia.prototype = { setAccessToken: function(accessToken) { if (accessToken) { this._setApiField('accessToken', accessToken); var self = this; request.get(self.getApiUrl() + "whoami", { auth: { bearer: self.getApiField('accessToken') }, json: true, headers: self.getHeaders() }, function (error, response, body) { if (error) throw new Error.WiaRequestException(0, error); if (response.statusCode == 200) { self.clientInfo = body; if (self.clientInfo.device) { self.devices.update("me", { systemInformation: { arch: os.arch(), cpus: os.cpus(), hostname: os.hostname(), networkInterfaces: os.networkInterfaces(), platform: os.platform(), totalmem: os.totalmem(), type: os.type() } }, function(err, data) { if (err) console.log(err); }); } } else { throw new Error.WiaRequestException(response.statusCode, body || ""); } }); } }, _setApiField: function(key, value) { this._api[key] = value; }, getApiField: function(key, subkey) { if (subkey) { return this._api[key][subkey]; } return this._api[key]; }, getApiUrl: function() { return this.getApiField('rest', 'protocol') + "://" + this.getApiField('rest', 'host') + ":" + this.getApiField('rest', 'port') + this.getApiField('rest', 'basePath'); }, getConstant: function(c) { return Wia[c]; }, getClientUserAgent: function(cb) { if (Wia.USER_AGENT_SERIALIZED) { return cb(Wia.USER_AGENT_SERIALIZED); } exec('uname -a', function(err, uname) { Wia.USER_AGENT.uname = uname || 'UNKNOWN'; Wia.USER_AGENT_SERIALIZED = JSON.stringify(Wia.USER_AGENT); cb(Wia.USER_AGENT_SERIALIZED); }); }, getHeaders: function() { var obj = {}; if (this.getApiField('publicKey')) { obj['x-org-public-key'] = this.getApiField('publicKey'); } return obj; }, generateAccessToken: function(data, cb) { request.post(this.getApiUrl() + "auth/token", { body: data, json: true, headers: this.getHeaders() }, function (error, response, body) { if (cb) { if (error) return cb(error, null); if (response.statusCode) cb(null, body); else cb(new Error.WiaRequestException(response.statusCode, body || ""), null); } }); }, _prepResources: function() { for (var name in resources) { this[ name[0].toLowerCase() + name.substring(1) ] = new resources[name](this); } }, _prepStream: function() { this.stream = new WiaStream(this); } }; module.exports = Wia;
const Hashids = require('hashids/cjs') const hashids = new Hashids('', 10, 'abcdefghijklmnopqrstuvwxyz1234567890') const { standardToUSDate } = require('../../utilities/string') module.exports = (models, Sequelize, sequelize) => { models.report.createNew = (params) => { return sequelize.transaction(async (t) => { const { to, from, workQ, clientUrn } = params const [report] = await models.report.findOrCreate( { where: { to, from, clientUrn }, defaults: { to, from, workQ, clientUrn }, transaction: t }) const reportId = hashids.encode(report.dataValues.id) return report.update({ reportId }, { transaction: t }) }) } models.report.reportsByClientUrn = async (clientUrn) => { const reports = await models.report.findAll({ where: { clientUrn }, order: [ ['from', 'DESC'], ['to', 'DESC'] ], attributes: ['reportId', 'to', 'from', 'clientUrn'] }) const formattedReport = reports.map((report) => { const { reportId, to, from, clientUrn } = report return { reportId, clientUrn, to: standardToUSDate(to), from: standardToUSDate(from) } }) return formattedReport } }
// @flow strict import * as React from 'react'; import { graphql } from '@kiwicom/mobile-relay'; import { DateFormatter } from '@kiwicom/mobile-localization'; import { withHotelsContext } from '../HotelsContext'; import type { Stay22HotelsSearchQueryResponse } from './__generated__/Stay22HotelsSearchQuery.graphql'; import Stay22PaginationContainer from './Stay22PaginationContainer'; import HotelsSearch from './HotelsSearch'; type Props = {| +checkin: Date | null, +checkout: Date | null, +currency: string, +getGuestCount: () => number, +longitude: number | null, +latitude: number | null, +onClose: () => void, |}; const query = graphql` query Stay22HotelsSearchQuery( $search: Stay22HotelsSearchInput! $first: Int $after: String ) { ...Stay22PaginationContainer } `; export class Stay22HotelsSearch extends React.Component<Props> { renderAllHotelsSearchList = ( propsFromRenderer: Stay22HotelsSearchQueryResponse, ) => { return <Stay22PaginationContainer data={propsFromRenderer} />; }; render() { const { checkin, checkout, latitude, longitude, currency } = this.props; const shouldRenderDateError = checkin === null || checkout === null || latitude === null || longitude === null; return ( <HotelsSearch onClose={this.props.onClose} shouldRenderDateError={shouldRenderDateError} query={query} variables={{ first: 50, search: { latitude, longitude, checkin: DateFormatter(checkin ?? new Date()).formatForMachine(), checkout: DateFormatter(checkout ?? new Date()).formatForMachine(), guests: this.props.getGuestCount(), currency, }, }} render={this.renderAllHotelsSearchList} /> ); } } export default withHotelsContext(state => ({ checkin: state.checkin, checkout: state.checkout, currency: state.currency, getGuestCount: state.getGuestCount, latitude: state.latitude, longitude: state.longitude, onClose: state.closeHotels, }))(Stay22HotelsSearch);
import React, { Component } from "react"; import { googStock as googData } from "./data/googStock"; import ChartHighstock from "./ChartHighstock"; import Paper from "@material-ui/core/Paper"; import { Header } from "semantic-ui-react"; import { graph } from "../actions/viewkra"; import { connect } from "react-redux"; class Graph extends Component { constructor(props) { super(props); this.state = { data: googData }; } componentDidMount = () => { this.props.graph(this.props.selfId); }; render() { let content = ( <ChartHighstock data={this.props.graphKra} title={this.state.title} /> ); if (this.props.graphKra.length > 0) { return ( <Paper style={{ width: "80%" }}> <Header as="h1" content="Performance Graph" textAlign="center" /> <div className="Graph"> <div className="container">{content}</div> </div> </Paper> ); } else { return <div>No data to show , please fill your KRA first.</div>; } } } const mapStateToProps = state => { return { graphKra: state.addKra.graphdata, selfId: state.auth.user.userdata._id // userName: state.HRfields }; }; export default connect(mapStateToProps, { graph })(Graph);
import PreviewBox from './src/index.vue' PreviewBox.install = (vue) => { vue.component(PreviewBox.name, PreviewBox) } export default PreviewBox
$(window).load(function(){ Dashboard.init(); }); Dashboard = { lock : false, init: function() { console.log("Starting dashboard..."); this.order(); this.product(); }, order: function() { $.ajax({ url: "/dashboard/order", async: true, method: "POST", data: { } }).done(function(data) { $("#orderStatistics_Today").text(data.orderStatistics.todayQuantity); }); }, product: function() { $.ajax({ url: "/dashboard/product", async: true, method: "POST", data: { } }).done(function(data) { Morris.Donut({ element: 'morris-donut-chart', data:data.productStatistics.quantity, resize: false }); }); } }; $(function() { Morris.Area({ element: 'morris-area-chart', data: [ // { // period: '', // iphone: 10687, // ipad: 4460, // itouch: 2028 // }, { // period: '2015 Q2', // fralda: 8432, // berco: 5713 // } ], xkey: 'period', ykeys: ['fralda', 'berco'], labels: ['fralda', 'berco'], pointSize: 2, hideHover: 'auto', resize: true }); });
import React, { useState, useEffect } from "react"; import SafeIlustration from "../../../assets/ilustrastion/safe-ilustration.png"; import { getSafe } from "../../../services"; import { Modal, Button } from "antd"; import "./Opening.scss"; import { useDispatch } from "react-redux"; const Opening = ({ navigation }) => { const [isModalVisible, setIsModalVisible] = useState(false); const token = localStorage.getItem("token"); const [safes, setSafes] = useState([]) const handleOk = () => { setIsModalVisible(false); }; const handleCancel = () => { setIsModalVisible(false); }; useEffect(() => { getSafe(token) .then((res) => { setSafes(res?.data) if (res.data && res.data.length) { setIsModalVisible(false); } else { setIsModalVisible(true); } }) }, []) return ( <div> <Modal visible={isModalVisible} onOk={handleOk} onCancel={handleCancel} footer={null} > <div className="create-first"> <h2>Create Your First Safe</h2> <p> KAS-E help you to keep in track the money you are spending from safe </p> <img style={{ height: 200, marginLeft: 150, marginRight: 150 }} src={SafeIlustration} alt="illus" /> <div className="open-modal-btn"> <Button htmlType="submit" block size="large" onClick={() => navigation.next()}> Create New Safe </Button> </div> </div> </Modal> </div> ); }; export default Opening;
import tw from 'tailwind-styled-components' export const CenterColumn = tw.section` block w-56 ml-6 flex-shrink-0 `
//API call to get employee data to poplate our table import axios from "axios"; var employeeNum = 500; export default { getUsers: function() { return axios.get("https://randomuser.me/api/?results=" + employeeNum + "&nat=us"); } };
// 初始化Web Uploader function upload(box,name,num,type,inputName,inputIndex){ var accept = {}; if(type) { accept = { title: 'Files', extensions: 'pdf,doc,docx', mimeTypes: 'application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document' +',application/pdf' } if(type=='pj'){ accept = { title: 'Images,Applications', extensions: 'jpg,jpeg,pdf', mimeTypes: 'image/jpg,image/jpeg,application/pdf' } } } else { accept = { title: 'Images', extensions: 'gif,jpg,jpeg,png', mimeTypes: 'image/jpg,image/jpeg,image/png,image/gif' } }; var uploader = WebUploader.create({ // 选完文件后,是否自动上传。 auto: true, swf:'/pc/libs/webuploader/Uploader.swf', // 文件接收服务端。 server: "http://jk.szhan.com/up/hzcupload.php", fileNumLimit:num!=1?num:50, // fileSizeLimit:60000, // 选择文件的按钮。可选。 // 内部根据当前运行是创建,可能是input元素,也可能是flash. pick:{ id:$('.filePicker_'+box), multiple : num==1?false:true }, // 只允许选择图片文件。 formData:{'filetype': name}, accept:accept, fileSingleSizeLimit: 8 * 1024 * 1024 }); function removeFile(file) { uploader.removeFile(file); } //上传成功后 uploader.onUploadSuccess = function(file,response){ var imgBoxClass = '.' +name; $list= $('.'+file['id']); var count = $( '.' +inputName).length; if(inputIndex) { count = inputIndex; } if(num > 1) { $("<input type='hidden' class='"+inputName+"' name='"+inputName+"["+count+"]' >").appendTo($list); } else { $("<input type='hidden' class='"+inputName+"' name='"+inputName+"' >").appendTo($list); } if(response.status=='success') { $list.children('input').val(response.data['file_url']); } else { alert(response.msg) } } //超出数量或者大小 uploader.onError = function(file){ if(file=='Q_TYPE_DENIED'){ alert('图片格式不正确!'); } if(file == 'F_EXCEED_SIZE'){ alert('图片大小超出限制!'); } if(num != 1){ var number = uploader.getStats()['successNum']; if(isNaN(num) === false && number>=num){ alert('最多上传'+num+'张图片'); } } } //当有文件添加进来的时候 uploader.on( 'fileQueued', function(file) { var $li = $( '<span class="file-item '+file['id']+'">' + '<img src="" alt="" />' + '<div class="text-center fileName">' + file['name'] + '</div>' + '<div class="del"><i class="iconfont iconshanchu"></i></div>' + '</span>' ), $img = $li.find('img'); $list= $('.fileList_'+box); var delwrap = $li.find(".del") $li.on("mouseenter", function() { delwrap.stop().animate({ height: 25 }) }) $li.on("mouseleave", function() { delwrap.stop().animate({ height: 0 }) }) var delbtn = delwrap.find("i") delbtn.on("click", function() { $(this).parent().parent().remove(); uploader.removeFile(file); }) if(num == 1){ $list.children('span').remove(); $list.html(''); } // $list为容器jQuery实例 $list.append($li); // 创建缩略图. // 如果为非图片文件,可以不用调用此方法。 // thumbnailWidth x thumbnailHeight 为 100 x 100 if(box<15||box>22){ var thumbnailWidth = 200; var thumbnailHeight = 200; }else{ var thumbnailWidth = 160; var thumbnailHeight = 112; } uploader.makeThumb(file,function(error,src) { if ( error ) { $img.replaceWith('<span>不能预览</span>'); return; } $img.attr( 'src', src ); },thumbnailWidth, thumbnailHeight ); // $btns.on( 'click', 'span', function() { // $(this).parents('.file-item').remove(); // removeFile(file,true); // }) //文件上传过程中创建进度条实时显示 uploader.on("uploadProgress", function(file, percentage) { var $li = $("." + file.id); var $percent = $li.find(".progress .progress-bar"); //避免重复创建 if (!$percent.length) { $percent = $('<div class="progress">' + '<div class="progress-bar">' + '</div>' + '</div>').appendTo($li).find(".progress .progress-bar"); } // $li.find('span.state').text('上传中...') $percent.css('width', percentage * 100 + '%') $percent.text(percentage * 100 + '%') }); uploader.on("uploadSuccess", function(file, response) { $('.' + file.id).append('<span class="uploaderSuccess"></span>'); }) uploader.on("uploadComplete", function(file) { $('.' + file.id).find('.progress').fadeOut(); }) }); //删除图片 $('.cancel').click(function(){ $(this).parents('.file-item').remove(); }) $('.file-item').on("mouseenter", function() { $('.cancel').stop().animate({ height: 25 }) }) $('.file-item').on("mouseleave", function() { $('.cancel').stop().animate({ height: 0 }) }) $('.del').click(function(){ $(this).parents('.file-item').remove(); }) $('body').on('click','.file-item img',function(){ layer.photos({ photos: '.file-item' ,anim: 5, closeBtn:1 }); }) }
import usersReducer from './usersReducer'; import initialState from '../initialState'; import types from '../../actions/actionTypes'; describe('user reducer', () => { it('should return the initial state', () => { expect(usersReducer(undefined, {})).toEqual( { instructors: [], users: [], searchKeyword: '', } ) }); it('should handle UPDATE_INSTRUCTORS', () => { const instructors = [{ firstName: 'Sylvia', lastName: 'Nguyen', email: 'sylvia@hackeryou.com', }]; const users = usersReducer({}, { type: types.UPDATE_INSTRUCTORS, instructors, }); expect(users.instructors).toEqual(users.instructors); }); });
import Product from '../../../models/ecommerse/product' import { tableColumnsByDomain } from '../../../scripts/utils/table-utils' import { img, price } from '../../../scripts/utils/table-renders' const width = App.options.styles.table.width const options = { image: { width: width.img, render(h, context) { const url = context.row.image return img.call(this, h, context, url) } }, name: { width: width.w_12, render(h, context) { return <span>{context.row.name}</span> } }, sn: { width: width.w_10 }, description: { width: width.w_12 }, brief: { width: width.w_16 }, brand: { width: width.w_12, title: '品牌', after: 'brief', render(h, context) { let name = '' if (context.row.brand) { name = context.row.brand.name } return <span>{name}</span> } }, categories: { width: width.w_12, title: '分类', after: 'brand', render(h, context) { let name = '' if (!_.isEmpty(context.row.categories)) { const categories = context.row.categories.map(it => { return it.name }) name = categories.join(',') } return <span>{name}</span> } }, marketPrice: { width: width.price, render(h, context) { return price.call(this, h, context, context.row.marketPrice) } }, price: { width: width.price, render(h, context) { return price.call(this, h, context, context.row.price) } }, tags: { width: width.w_12, render(h, context) { return <span>{context.row.tags.join(',')}</span> } }, ctime: { width: width.datetime, render(h, context) { return <span>{dateformat(context.row.ctime, "yyyy-mm-dd' 'HH:MM:ss")}</span> } } } export default tableColumnsByDomain(Product, options)
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ angular.module('appMain').controller('rgpdController',function($scope,$http){ //obter as leads que estão encriptadas function getData(){ $http({ url:'php/admin/listRGPD.php', method:'POST', data:sessionStorage.userId }).then(function(answer){ $scope.leadsList = answer.data; }); } getData(); //Re-ativar lead $scope.reativarLead = function(lead){ if(confirm("Atenção!\n Vai re-ativar a lead "+lead.lead+". \nPretende continuar? ")){ $http({ url:'php/admin/reativarLead.php', method:'POST', data:JSON.stringify({'lead':lead.lead, 'key':lead.rgpdkey}) }).then(function(answer){ alert(answer.data+'\n\nA lead '+lead.lead+' foi re-ativada!'); getData(); }); } } //Ver detalhes $scope.verDetalhes = function(lead){ alert('Ver detalhes. TO DO'); } });
// FileWraper : 将文件操作封装成 promise ,用于 async / await 操作 let fs = require('fs') export default class FileWraper { constructor () { // eslint-disable-line } static async dirExist (path) { return new Promise((resolve, reject) => { fs.stat(path, (exists) => { if (!exists) { // console.log(`Directory do NOT exist. ${path}`) // reject(new Error('NOT exist')) resolve(false) } else { // console.log(`Directory already exist. ${path}`) resolve(true) } }) }) } static async makeDir (path) { return new Promise((resolve, reject) => { fs.mkdir(path, (err) => { if (err) { // console.warn(`MakeDir FAILED: ${path}`) // reject(new Error(err)) resolve(false) } else { console.log(`MakeDir OK: ${path}`) resolve(true) } }) }) } static async readFile (uri) { return new Promise((resolve, reject) => { fs.readFile(uri, (err, data) => { if (err) { reject(new Error(err)) } else { resolve(data) } }) }) } static async writeFile (fd, data, position, encoding) { return new Promise((resolve, reject) => { fs.write(fd, data, position, encoding, (err, written) => { if (err) { reject(new Error(err)) } else { resolve(written) } }) }) } static async writeStream (path) { return new Promise((resolve, reject) => { fs.createWriteStream(path, (err, written) => { if (err) { reject(new Error(err)) } else { resolve(written) } }) }) } static async deleteFile (uri) { return new Promise((resolve, reject) => { fs.unlink(uri, (err) => { // ??? fs.unlink 的回调函数没有 err 参数!!! if (err) { reject(new Error(err)) } else { resolve() } }) }) } static async openFile (uri, flags, mode) { return new Promise((resolve, reject) => { fs.open(uri, flags, mode, (err, fd) => { if (err) { reject(new Error(err)) } else { resolve(fd) } }) }) } }
import { StyleSheet } from 'react-native'; export default StyleSheet.create({ 'a': { 'textDecoration': 'none' }, 'body': { 'margin': [{ 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }], 'padding': [{ 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }] }, 'li': { 'margin': [{ 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }], 'padding': [{ 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }] }, 'ul': { 'margin': [{ 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }], 'padding': [{ 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }] }, 'memenu navActive': { 'borderTop': [{ 'unit': 'px', 'value': 2 }, { 'unit': 'string', 'value': 'solid' }, { 'unit': 'string', 'value': '#6caf50' }], 'fontWeight': '700' }, 'navActive:hover': { 'borderTop': [{ 'unit': 'px', 'value': 2 }, { 'unit': 'string', 'value': 'solid' }, { 'unit': 'string', 'value': '#6caf50' }], 'fontWeight': '700' }, 'memenu': { 'float': 'left', 'display': 'inline-block', 'marginBottom': [{ 'unit': 'px', 'value': 0 }], 'marginLeft': [{ 'unit': 'px', 'value': 20 }], 'padding': [{ 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }], 'listStyle': 'none', 'verticalAlign': 'top' }, 'memenu': { 'height': [{ 'unit': 'px', 'value': 5 }], 'lineHeight': [{ 'unit': 'px', 'value': 5 }] }, 'subnav': { 'height': [{ 'unit': 'px', 'value': 5 }], 'lineHeight': [{ 'unit': 'px', 'value': 5 }] }, 'subnav': { 'position': 'absolute', 'top': [{ 'unit': 'px', 'value': 0 }], 'right': [{ 'unit': 'px', 'value': 0 }], 'maxWidth': [{ 'unit': 'px', 'value': 380 }], 'minWidth': [{ 'unit': 'px', 'value': 280 }] }, 'memenu li': { 'float': 'left', 'width': [{ 'unit': 'string', 'value': 'auto' }], 'height': [{ 'unit': 'px', 'value': 78 }], 'lineHeight': [{ 'unit': 'px', 'value': 78 }] }, 'input-wrap input-search:focus': { 'outline': '0' }, 'input-wrap a:focus': { 'outline': '0' }, 'input-wrap input:focus': { 'float': 'left', 'padding': [{ 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }], 'width': [{ 'unit': 'px', 'value': 164 }], 'height': [{ 'unit': 'px', 'value': 24 }], 'border': [{ 'unit': 'px', 'value': 1 }, { 'unit': 'string', 'value': 'solid' }, { 'unit': 'string', 'value': '#8bc34a' }], 'borderRadius': '0 15px 15px 0', 'color': '#888', 'textIndent': '10px', 'fontSize': [{ 'unit': 'px', 'value': 9 }], 'lineHeight': [{ 'unit': 'px', 'value': 78 }], 'lineHeight': [{ 'unit': 'px', 'value': 24 }], 'opacity': '1' }, '#LoginU': { 'width': [{ 'unit': 'px', 'value': 216 }] }, '#LoginA': { 'float': 'right', 'height': [{ 'unit': 'px', 'value': 5 }], 'lineHeight': [{ 'unit': 'px', 'value': 5 }] }, '#LoginU': { 'float': 'right', 'height': [{ 'unit': 'px', 'value': 5 }], 'lineHeight': [{ 'unit': 'px', 'value': 5 }] }, '#LoginA': { 'width': [{ 'unit': 'px', 'value': 306 }] }, '#search': { 'float': 'right', 'display': 'inline-block', 'margin': [{ 'unit': 'px', 'value': 3 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 2 }], 'padding': [{ 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 10 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }], 'width': [{ 'unit': 'px', 'value': 22 }], 'height': [{ 'unit': 'px', 'value': 20 }], 'borderRight': [{ 'unit': 'px', 'value': 1 }, { 'unit': 'string', 'value': 'solid' }, { 'unit': 'string', 'value': '#ddd' }], 'textAlign': 'right', 'lineHeight': [{ 'unit': 'px', 'value': 5 }] }, 'header_menu subnav nava': { 'float': 'left', 'marginRight': [{ 'unit': 'px', 'value': 5 }], 'padding': [{ 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 9 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 9 }], 'height': [{ 'unit': 'px', 'value': 26 }], 'border': [{ 'unit': 'px', 'value': 1 }, { 'unit': 'string', 'value': 'solid' }, { 'unit': 'string', 'value': '#8bc34a' }], 'borderRadius': '15px', 'background': '#8bc34a', 'color': '#fff', 'lineHeight': [{ 'unit': 'px', 'value': 24 }] }, 'header_menu subnav a': { 'padding': [{ 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 10 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 10 }], 'textTransform': 'capitalize' }, 'header_menu a': { 'float': 'left', 'color': '#6caf50', 'textDecoration': 'none', 'textTransform': 'uppercase', 'fontSize': [{ 'unit': 'px', 'value': 9 }], 'cursor': 'pointer' }, 'nava': { 'marginRight': [{ 'unit': 'px', 'value': 15 }], 'WebkitBorderRadius': '4px', 'background': '#8bc34a' }, 'header_menu subnav nava2': { 'marginRight': [{ 'unit': 'px', 'value': 15 }], 'marginLeft': [{ 'unit': 'px', 'value': 10 }], 'background': '#fff', 'color': '#8bc34a' }, 'header_menu subnav nava': { 'padding': [{ 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 1 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 1 }], 'height': [{ 'unit': 'px', 'value': 26 }], 'border': [{ 'unit': 'px', 'value': 1 }, { 'unit': 'string', 'value': 'solid' }, { 'unit': 'string', 'value': '#8bc34a' }], 'borderRadius': '15px', 'lineHeight': [{ 'unit': 'px', 'value': 24 }] }, 'header_menu subnav nava2': { 'padding': [{ 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 1 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 1 }], 'height': [{ 'unit': 'px', 'value': 26 }], 'border': [{ 'unit': 'px', 'value': 1 }, { 'unit': 'string', 'value': 'solid' }, { 'unit': 'string', 'value': '#8bc34a' }], 'borderRadius': '15px', 'lineHeight': [{ 'unit': 'px', 'value': 24 }] }, 'header_menu subnav nava': { 'float': 'left', 'marginTop': [{ 'unit': 'px', 'value': 24 }], 'marginRight': [{ 'unit': 'px', 'value': 5 }], 'width': [{ 'unit': 'px', 'value': 50 }], 'color': '#fff' }, 'header_menu subnav nava2': { 'marginTop': [{ 'unit': 'px', 'value': 24 }], 'marginRight': [{ 'unit': 'px', 'value': 15 }], 'padding': [{ 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 1 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 1 }], 'width': [{ 'unit': 'px', 'value': 50 }], 'height': [{ 'unit': 'px', 'value': 26 }], 'border': [{ 'unit': 'px', 'value': 1 }, { 'unit': 'string', 'value': 'solid' }, { 'unit': 'string', 'value': '#8bc34a' }], 'borderRadius': '15px', 'background': '#fff', 'color': '#8bc34a', 'lineHeight': [{ 'unit': 'px', 'value': 24 }] }, 'nava': { 'display': 'inline-block', 'borderRadius': '4px', 'background': '#8bc34a' }, 'search': { 'position': 'relative', 'margin': [{ 'unit': 'px', 'value': 0 }, { 'unit': 'string', 'value': 'auto' }, { 'unit': 'px', 'value': 0 }, { 'unit': 'string', 'value': 'auto' }], 'width': [{ 'unit': 'px', 'value': 526 }], 'height': [{ 'unit': 'px', 'value': 35 }], 'border': [{ 'unit': 'px', 'value': 1 }, { 'unit': 'string', 'value': 'solid' }, { 'unit': 'string', 'value': '#8bc34a' }], 'borderRight': [{ 'unit': 'string', 'value': 'none' }], 'borderRadius': '50px', 'background': '#fff' }, 'search select': { 'display': 'none' }, 'search select_box': { 'position': 'relative', 'float': 'left', 'width': [{ 'unit': 'px', 'value': 75 }], 'color': '#555', 'fontSize': [{ 'unit': 'px', 'value': 9 }], 'lineHeight': [{ 'unit': 'px', 'value': 35 }] }, 'search select_showbox': { 'height': [{ 'unit': 'px', 'value': 35 }], 'background': 'url(../images/search_ico.png) no-repeat 5pc center', 'textIndent': '1.5em' }, '#nav china': { 'display': 'inline-block', 'marginLeft': [{ 'unit': 'px', 'value': -40 }], 'width': [{ 'unit': 'px', 'value': 20 }], 'height': [{ 'unit': 'px', 'value': 20 }], 'border': [{ 'unit': 'px', 'value': 1 }, { 'unit': 'string', 'value': 'solid' }, { 'unit': 'string', 'value': '#8bc34a' }], 'borderRadius': '50%', 'lineHeight': [{ 'unit': 'px', 'value': 20 }] }, 'search select_option': { 'position': 'absolute', 'top': [{ 'unit': 'px', 'value': 35 }], 'left': [{ 'unit': 'px', 'value': -1 }], 'zIndex': '99', 'display': 'none', 'width': [{ 'unit': 'px', 'value': 75 }], 'border': [{ 'unit': 'px', 'value': 1 }, { 'unit': 'string', 'value': 'solid' }, { 'unit': 'string', 'value': '#8bc34a' }], 'borderRadius': '2px', 'background': '#fff' }, 'search select_option li': { 'width': [{ 'unit': '%H', 'value': 1 }], 'borderBottom': [{ 'unit': 'px', 'value': 1 }, { 'unit': 'string', 'value': 'dotted' }, { 'unit': 'string', 'value': '#bebebe' }], 'textIndent': '1.5em', 'cursor': 'pointer' }, 'search select_option liselected': { 'backgroundColor': '#f5f5f5', 'color': '#333' }, 'search inputbtn_srh': { 'float': 'left', 'height': [{ 'unit': 'px', 'value': 35 }], 'border': [{ 'unit': 'string', 'value': 'none' }], 'borderLeft': [{ 'unit': 'px', 'value': 1 }, { 'unit': 'string', 'value': 'solid' }, { 'unit': 'string', 'value': '#aaa' }], 'background': '0 0', 'lineHeight': [{ 'unit': 'px', 'value': 35 }], 'cursor': 'pointer' }, 'search inputinp_srh': { 'float': 'left', 'height': [{ 'unit': 'px', 'value': 35 }], 'border': [{ 'unit': 'string', 'value': 'none' }], 'borderLeft': [{ 'unit': 'px', 'value': 1 }, { 'unit': 'string', 'value': 'solid' }, { 'unit': 'string', 'value': '#aaa' }], 'background': '0 0', 'lineHeight': [{ 'unit': 'px', 'value': 35 }], 'cursor': 'pointer' }, 'search inputinp_srh': { 'paddingLeft': [{ 'unit': 'px', 'value': 10 }], 'width': [{ 'unit': 'px', 'value': 365 }], 'outline': '0', 'color': '#666', 'cursor': 'pointer' }, 'search inputbtn_srh': { 'top': [{ 'unit': 'px', 'value': 0 }], 'right': [{ 'unit': 'px', 'value': 0 }], 'zIndex': '99999999999', 'padding': [{ 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 14 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 14 }], 'width': [{ 'unit': 'px', 'value': 5 }], 'borderRadius': '0 50px 50px 0', 'background': '#8bc34a', 'color': '#fff', 'letterSpacing': [{ 'unit': 'px', 'value': 1 }] }, '#searchClose': { 'position': 'absolute', 'fontSize': [{ 'unit': 'px', 'value': 14 }], 'cursor': 'pointer' }, 'search inputbtn_srh': { 'position': 'absolute', 'fontSize': [{ 'unit': 'px', 'value': 14 }], 'cursor': 'pointer' }, '#searchClose': { 'top': [{ 'unit': 'px', 'value': 10 }], 'right': [{ 'unit': 'px', 'value': 10 }], 'width': [{ 'unit': 'px', 'value': 26 }], 'height': [{ 'unit': 'px', 'value': 26 }], 'borderRadius': '2px', 'color': '#fff', 'color': 'red', 'textAlign': 'center', 'letterSpacing': [{ 'unit': 'px', 'value': 2 }], 'lineHeight': [{ 'unit': 'px', 'value': 26 }] }, 'li': { 'listStyle': 'none' }, 'quickLink': { 'marginTop': [{ 'unit': 'px', 'value': 9 }], 'color': '#fff', 'fontSize': [{ 'unit': 'px', 'value': 9 }] }, 'quickLinkALl': { 'position': 'absolute', 'width': [{ 'unit': '%H', 'value': 1 }], 'height': [{ 'unit': 'px', 'value': 50 }], 'color': '#fff', 'textAlign': 'center', 'fontSize': [{ 'unit': 'px', 'value': 9 }], 'lineHeight': [{ 'unit': 'px', 'value': 50 }] }, 'quickLinkALl a': { 'margin': [{ 'unit': 'px', 'value': 10 }, { 'unit': 'string', 'value': 'auto' }, { 'unit': 'px', 'value': 10 }, { 'unit': 'string', 'value': 'auto' }], 'padding': [{ 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 10 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 10 }], 'color': '#666', 'textAlign': 'center', 'letterSpacing': [{ 'unit': 'px', 'value': 0.5 }] }, 'quickLinkALl span': { 'color': '#f58400', 'fontWeight': 'bolder' }, '#page': { 'position': 'absolute', 'top': [{ 'unit': 'px', 'value': 86 }], 'left': [{ 'unit': '%H', 'value': 0.5 }], 'zIndex': '9999', 'display': 'none', 'margin': [{ 'unit': 'px', 'value': 20 }, { 'unit': 'string', 'value': 'auto' }, { 'unit': 'px', 'value': 20 }, { 'unit': 'string', 'value': 'auto' }], 'marginLeft': [{ 'unit': 'px', 'value': -25 }], 'width': [{ 'unit': 'px', 'value': 50 }], 'height': [{ 'unit': 'px', 'value': 110 }], 'borderRadius': '4px', 'background': 'hsla(0,0%,100%,.9)', 'boxShadow': [{ 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 2 }, { 'unit': 'px', 'value': 10 }, { 'unit': 'string', 'value': 'rgba(0,0,0,.1)' }] }, 'open #page': { 'display': 'block' }, 'logo img': { 'height': [{ 'unit': 'px', 'value': 60 }], 'verticalAlign': 'top' }, 'header': { 'padding': [{ 'unit': 'px', 'value': 10 }, { 'unit': 'px', 'value': 10 }, { 'unit': 'px', 'value': 10 }, { 'unit': 'px', 'value': 10 }], 'width': [{ 'unit': '%H', 'value': 0.4 }], 'height': [{ 'unit': 'px', 'value': 44 }], 'WebkitTransition': 'background-color .2s ease', 'transition': 'background-color .2s ease' }, '#search': { 'float': 'left', 'border': [{ 'unit': 'string', 'value': 'none' }], 'borderRadius': '0' }, 'header': { 'float': 'left', 'border': [{ 'unit': 'string', 'value': 'none' }], 'borderRadius': '0' }, '#search': { 'marginRight': [{ 'unit': 'px', 'value': 2 }], 'height': [{ 'unit': 'px', 'value': 24 }], 'outline': '0', 'borderRight': [{ 'unit': 'px', 'value': 1 }, { 'unit': 'string', 'value': 'solid' }, { 'unit': 'string', 'value': '#e7eaf6' }], 'boxShadow': [{ 'unit': 'string', 'value': 'none' }, { 'unit': 'string', 'value': 'none' }, { 'unit': 'string', 'value': 'none' }, { 'unit': 'string', 'value': 'none' }], 'color': '#e7eaf6', 'WebkitTransition': 'width .2s ease', 'transition': 'width .2s ease' }, '#LoginA a': { 'padding': [{ 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 4 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 4 }], 'width': [{ 'unit': 'string', 'value': 'auto' }] }, '#LoginA a': { 'float': 'left', 'lineHeight': [{ 'unit': 'px', 'value': 78 }] }, '#LoginA span': { 'float': 'left', 'lineHeight': [{ 'unit': 'px', 'value': 78 }] }, '#LoginA span': { 'display': 'inline-block', 'overflow': 'hidden', 'width': [{ 'unit': 'px', 'value': 20 }], 'color': '#38ab74', 'verticalAlign': 'top' }, 'nav ul bg': { 'width': [{ 'unit': 'px', 'value': 10 }], 'height': [{ 'unit': 'px', 'value': 10 }], 'border': [{ 'unit': 'string', 'value': 'none' }], 'background': '#8bc34a' }, 'nav': { 'position': 'absolute', 'bottom': [{ 'unit': 'px', 'value': 44 }], 'left': [{ 'unit': '%H', 'value': 0.5 }], 'marginLeft': [{ 'unit': 'px', 'value': -40 }], 'width': [{ 'unit': 'px', 'value': 5 }], 'height': [{ 'unit': 'px', 'value': 14 }] }, 'title': { 'display': 'inline-block', 'marginTop': [{ 'unit': 'px', 'value': 40 }], 'padding': [{ 'unit': 'px', 'value': 20 }, { 'unit': 'px', 'value': 20 }, { 'unit': 'px', 'value': 20 }, { 'unit': 'px', 'value': 20 }], 'width': [{ 'unit': 'px', 'value': 50 }], 'height': [{ 'unit': 'px', 'value': 220 }], 'borderRadius': '2px', 'color': '#fff', 'textAlign': 'center', 'fontFamily': 'Open Sans,sans-serif', 'lineHeight': [{ 'unit': 'em', 'value': 1.5 }] }, 'title h2': { 'marginTop': [{ 'unit': 'px', 'value': 10 }], 'marginLeft': [{ 'unit': 'px', 'value': 10 }], 'color': '#8bc34a', 'textTransform': 'uppercase', 'fontWeight': '400', 'fontSize': [{ 'unit': 'px', 'value': 44 }], 'lineHeight': [{ 'unit': 'em', 'value': 1.3 }] }, 'title p': { 'margin': [{ 'unit': 'px', 'value': 10 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 10 }, { 'unit': 'px', 'value': 0 }], 'padding': [{ 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }], 'width': [{ 'unit': '%H', 'value': 1 }], 'color': '#333', 'textAlign': 'center', 'letterSpacing': [{ 'unit': 'px', 'value': 0.5 }], 'fontSize': [{ 'unit': 'px', 'value': 1 }], 'lineHeight': [{ 'unit': 'px', 'value': 20 }] }, 'header_menu': { 'position': 'relative', 'clear': 'both', 'margin': [{ 'unit': 'px', 'value': 0 }, { 'unit': 'string', 'value': 'auto' }, { 'unit': 'px', 'value': 0 }, { 'unit': 'string', 'value': 'auto' }], 'paddingRight': [{ 'unit': 'px', 'value': 280 }], 'paddingLeft': [{ 'unit': 'px', 'value': 220 }], 'height': [{ 'unit': 'px', 'value': 5 }], 'background': '#fff', 'boxShadow': [{ 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 2 }, { 'unit': 'px', 'value': 8 }, { 'unit': 'string', 'value': 'rgba(0,0,0,.1)' }], 'lineHeight': [{ 'unit': 'px', 'value': 5 }] }, 'header_menu a': { 'zIndex': '1', 'float': 'left', 'display': 'inline-block', 'padding': [{ 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 9 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 9 }], 'width': [{ 'unit': 'px', 'value': 90 }], 'height': [{ 'unit': 'px', 'value': 78 }], 'background': '#fff', 'color': '#6caf50', 'textAlign': 'center', 'textDecoration': 'none', 'textTransform': 'uppercase', 'letterSpacing': [{ 'unit': 'px', 'value': 0.6 }], 'fontWeight': '500', 'fontSize': [{ 'unit': 'px', 'value': 9 }], 'fontSize': [{ 'unit': 'px', 'value': 13 }], 'lineHeight': [{ 'unit': 'px', 'value': 78 }], 'cursor': 'pointer' }, 'header_menu subnav a': { 'height': [{ 'unit': 'px', 'value': 28 }], 'textTransform': 'capitalize', 'lineHeight': [{ 'unit': 'px', 'value': 28 }] }, '#nav img': { 'marginTop': [{ 'unit': 'px', 'value': 8 }] }, 'header_menu memenu': { 'margin': [{ 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }], 'padding': [{ 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }, { 'unit': 'px', 'value': 0 }], 'width': [{ 'unit': '%H', 'value': 1 }] }, '#nav logo': { 'position': 'absolute', 'top': [{ 'unit': 'px', 'value': 0 }], 'left': [{ 'unit': 'px', 'value': 10 }], 'marginRight': [{ 'unit': 'px', 'value': 20 }], 'marginLeft': [{ 'unit': 'px', 'value': 20 }], 'height': [{ 'unit': 'px', 'value': 5 }], 'lineHeight': [{ 'unit': 'px', 'value': 5 }] }, '#nav logo': { 'display': 'inline-block' }, '#search': { 'display': 'inline-block' }, '#search': { 'float': 'left', 'marginTop': [{ 'unit': 'px', 'value': 28 }], 'marginRight': [{ 'unit': 'px', 'value': 2 }], 'height': [{ 'unit': 'px', 'value': 24 }], 'outline': '0', 'border': [{ 'unit': 'string', 'value': 'none' }], 'borderRight': [{ 'unit': 'px', 'value': 1 }, { 'unit': 'string', 'value': 'solid' }, { 'unit': 'string', 'value': '#e7eaf6' }], 'borderRadius': '0', 'boxShadow': [{ 'unit': 'string', 'value': 'none' }, { 'unit': 'string', 'value': 'none' }, { 'unit': 'string', 'value': 'none' }, { 'unit': 'string', 'value': 'none' }], 'color': '#e7eaf6', 'lineHeight': [{ 'unit': 'px', 'value': 24 }], 'WebkitTransition': 'width .2s ease', 'transition': 'width .2s ease' }, '#search img': { 'display': 'inline', 'marginTop': [{ 'unit': 'px', 'value': 4 }], 'width': [{ 'unit': 'px', 'value': 1 }], 'height': [{ 'unit': 'px', 'value': 1 }] } });
const express = require("express"); const checkUserRoute = express.Router(); const checkUserCon = require("../controller/checkUserCon.js"); const orderManger = require("../controller/orderMangerCon.js") ; const customManger = require("../controller/customController.js"); const roleManger = require("../controller/roleMangerCon.js"); //user checkUserRoute.route("/checkUser.do").post(checkUserCon.checkUserExCon); checkUserRoute.route("/findUser.do").get(checkUserCon.finduserC); checkUserRoute.route("/getCheckNum.do").post(checkUserCon.getCheckNumC); checkUserRoute.route("/findPassword.do").post(checkUserCon.CheckNumC); // code 验证码 checkUserRoute.route("/getCode.do").get(checkUserCon.getCodeC); //order checkUserRoute.route("/getOrderMess.do").post(orderManger.getOrderMessC); checkUserRoute.route("/getTotalPage.do").get(orderManger.getTotalPageC); checkUserRoute.route("/searchOrder.do").post(orderManger.searchOrderC); checkUserRoute.route("/saveSendThing.do").get(orderManger.saveSendThingC); checkUserRoute.route("/getProImg.do").post(orderManger.getProImgC); //getUsername checkUserRoute.route("/getUserName.do").get(orderManger.getUserNameC); checkUserRoute.route("/orderNum.do").get(orderManger.orderNumC); checkUserRoute.route("/packMuil.do").get(orderManger.packMuilC); checkUserRoute.route("/packImg.do").get(orderManger.packImgC); //custom checkUserRoute.route("/getCustomMess.do").post(customManger.getCustomMessC); checkUserRoute.route("/getTotalPageCustom.do").get(customManger.getTotalPageCustomC); checkUserRoute.route("/searchCustom.do").post(customManger.searchCustomC); checkUserRoute.route("/searchMessC.do").post(customManger.searchMessC); //role checkUserRoute.route("/getRole.do").get(roleManger.getRoleC); checkUserRoute.route("/getAllPageRole.do").get(roleManger.getTotalPageC); checkUserRoute.route("/searchRole.do").get(roleManger.searchRoleC); checkUserRoute.route("/getRoleName.do").get(roleManger.getRoleNameC); checkUserRoute.route("/newRole.do").post(roleManger.newRoleC); checkUserRoute.route("/getNowMess.do").get(roleManger.getNowMessC); checkUserRoute.route("/updateRole.do").get(roleManger.updateRoleC); checkUserRoute.route("/deleteRole.do").get(roleManger.deleteRoleC); module.exports = checkUserRoute;
global.RESULT_200 = 200; global.MESSAGE_200 = 'SUCCESS';