text
stringlengths
7
3.69M
import Vue from 'vue' import Router from 'vue-router' import Home from '@/components/Home' import q1 from '@/components/q1' import q2 from '@/components/q2' import q4 from '@/components/q4' import q7 from '@/components/q7' Vue.use(Router) export default new Router({ routes: [ { path: '/', name: 'Home', component: Home }, { path: '/q1', name: 'q1', component: q1 }, { path: '/q2', name: 'q2', component: q2 }, { path: '/q4', name: 'q4', component: q4 }, { path: '/q7', name: 'q7', component: q7 } ] })
import React from 'react'; import Header from './Header'; import Grid from '@material-ui/core/Grid'; import Content from './Content'; import Box from '@material-ui/core/Box'; import ContactCard from './ContactCard'; import { makeStyles } from '@material-ui/core/styles'; const useStyles = makeStyles({ hero: { backgroundImage: 'url(https://images.unsplash.com/photo-1587563871167-1ee9c731aefb?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9)', height: '400px', backgroundSize: 'cover', backgroundPosition: 'center', backgroundRepeat: 'no-repeat', display: 'flex', marginTop: '60px', marginBottom: '30px' }, header: { fontSize: '4rem', width: '150px', }, content: { display: 'flex', justifyContent: 'center', marginTop: '20px', }, subHeader: { fontSize: '2rem', fontWeight: 'bold', marginBottom: '20px', }, demo: { backgroundImage: 'url(https://images.unsplash.com/photo-1523646745854-e018a9bcc73c?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9)', backgroundSize: 'cover', backgroundPosition: 'center', height: '350px', margin: '60px', marginTop: '100px', color: '#fff', display: 'flex', alignItems: 'flex-end', }, demoHeader: { margin: '25px', border: '1px solid #fff', padding: '25px', fontSize: '30px' }, contact: { height: '500px', }, }); function Home() { const classes = useStyles(); return ( <Grid container direction='column'> <Grid item> <Header /> </Grid> <Box className={classes.hero} id='home'> <Box className={classes.header}> Welcome to Kicks </Box> </Box> <Grid item container className={classes.content} align='center'> <Grid item xs={4} /> <Grid item xs={4} className={classes.subHeader}> Shop </Grid> <Grid item xs={4} /> <Grid item xs={1} sm={0}/> <Grid item xs={10} sm={12}> <Content /> </Grid> <Grid item xs={1} sm={0}/> </Grid> <Box className={classes.demo}> <Box className={classes.demoHeader}> The best deals anywhere. </Box> </Box> <Grid item container className={classes.content} align='center'> <Grid item xs={4} /> <Grid item xs={4} className={classes.subHeader}> Contact </Grid> <Grid item xs={4} /> <Grid item xs={1} sm={0} /> <Grid item xs={10} sm={12}> <ContactCard /> </Grid> <Grid item xs={1} sm={0}/> </Grid> </Grid> ); } export default Home;
import styled from 'styled-components/macro'; export const Button = styled.button` border: 1px solid var(--color-golden); border-radius: var(--size-xs); background-color: var(--color-green); box-shadow: 2px 2px 2px #222; font-family: 'EB Garamond', serif; padding: var(--size-xs); :disabled { background: none; } `;
import React from 'react' import {Carousel} from '3d-react-carousal'; let slides = [ <img src="https://www.junaidjamshed.com/media/weltpixel/owlcarouselslider/images/s/u/summer_gala_sale1.jpg" alt="1" />, <img src="https://cdn.shopify.com/s/files/1/0202/5884/8822/files/Men_85f7476a-0971-480f-a2ce-6b6f51e6e3c3_1024x.jpg?v=1621936735" alt="2" /> , <img src="https://cdn.shopify.com/s/files/1/2219/4051/files/KARACHI-WEB-BANNER-_1880-x-720.jpg?v=1604317458" alt="3" /> , <img src="https://edenrobe.com/pub/media/wysiwyg/21.4.20_Slider_ArtisanCollectionER_DSKTP.jpg" alt="4" /> , <img src="https://edenrobe.com/pub/media/wysiwyg/21.4.30_Slider_EscapeVelocityER_DSKTP.jpg" alt="5" /> ]; const slider = () => { return ( <div style={{marginTop:"10%"}} > <Carousel slides={slides} autoplay={true} interval={1000}/> </div> ) } export default slider
module.exports = { presets: [ [ "@babel/react", { "modules": false } ] ], plugins: [ "@babel/plugin-proposal-class-properties", "@babel/plugin-transform-classes", "@babel/plugin-transform-arrow-functions", "@babel/plugin-transform-template-literals", "@babel/plugin-syntax-dynamic-import", ], env: { production: { plugins: [ "transform-react-remove-prop-types", ] } } };
var fs = require('fs'); exports.writeLog = function(user,id,activity){ //create a file with appending function var logFile = fs.createWriteStream('./log/userActivities.txt', { flags: "a", encoding: "encoding", mode: 0744 }); logFile.write('User: '+user+" - id: "+id+' - '+ 'Activity: '+activity+' - '+'When: '+new Date() + "\n"); } //check on the connection status of other accounts //if all the other accounts are not connected, this will return "false" exports.checkAccountStatus = function(user){ //when the connection status of account is true, //then that account will be pushed into acct array. var acct =[]; var status = { 'local' :false, 'facebook' :false, 'twitter' :false, 'google' :false }; //check the connection status of each account if(user.local.email){ status.local = true; } if(user.facebook.token){ status.facebook = true; } if(user.twitter.token){ status.twitter = true; } if(user.google.token){ status.google = true; } var i = 0; //check how many accounts are connected. for(var key in status){ //if the status is true, then push the account into the acct array //this will show which accounts are connected if(status[key]){ i++; acct.push(key); } } if(i==1){ //if the number of connected accounts is only one, //return the connected account console.log("There is only "+acct[0]+" connected"); return acct[0]; }else{ //if there are multiple accounts connected, then return false console.log("There are multiple accounts connected"); return false; } } //remember me function for oAuthentication exports.rememberOauth = function(req,res){ //remember it for one year - 60 secounds * 60 mins * 24 hours * 365 days req.session.cookie.maxAge = 60000*60*24*365; } //remember me function for local login and signup exports.rememberMe = function(req,res){ if (req.body.remember_me) { //remember it for one year - 60 secounds * 60 mins * 24 hours * 365 days req.session.cookie.maxAge = 60000*60*24*365; }else{ req.session.cookie.expires = false; } } // route middleware to ensure user is logged in exports.isLoggedIn = function(req, res, next) { if (req.isAuthenticated()){ return next(); }else{ res.redirect('/'); } } exports.isInvited = function(req,res){ var isInvited = false; return isInvited=false; } // clean up the session after error shows up exports.cleanup = function (req,res){ req.session.signupMessage = ''; req.session.loginMessage = ''; req.session.errorMessage = ''; }
class Sorteio { constructor() { this.nome = document.querySelector('#names'); this.resultado = document.querySelector('#resultado'); this.listaNomes = []; } capturarNomes(event) { event.preventDefault(); if (this.nome.value != "" && this.listaNomes.indexOf(this.nome.value) == -1) { console.log(this.listaNomes.indexOf(this.nome.value)) this.listaNomes.push(this.nome.value.toUpperCase()); this.nome.focus(); this.resultado.innerHTML = `"${this.nome.value}" INSERIDO NA LISTA` this.nome.value = ""; } else { this.resultado.innerHTML = 'VOCÊ JA INSERIU ESSE ITEM' } console.log(this.listaNomes) } sorteiaNome() { let contador = this.listaNomes.length; if (contador > 0) { let index = Math.floor(Math.random() * contador); this.resultado.innerHTML = this.listaNomes[index]; this.eliminaNome(index); } else { this.resultado.innerHTML = 'ACABOU !!!'; } } eliminaNome(index) { this.listaNomes.splice(index, 1); } }
import Validator from "../helpers/validator"; export const FETCH_VENDORS = "FETCH_VENDORS"; export const FETCH_PRODUCTS = "FETCH_PRODUCTS"; export const FETCH_CATEGORIES = "FETCH_CATEGORIES"; export const FETCH_BRANDS = "FETCH_BRANDS"; export const FETCH_BLOGS = "FETCH_BLOGS"; export function loadFetchedVendors(vendors) { return { type: FETCH_VENDORS, payload: vendors, }; } export function fetchVendors(query) { return dispatch => fetch(`${process.env.REACT_APP_DEV_API_URL}/vendors/search/${query}&key=${process.env.REACT_APP_API_KEY}`, { method: "GET" }) .then(response => response.json()) .then((json) => { if (Validator.propertyExist(json, "error")) { throw json.error; } return dispatch(loadFetchedVendors(json)); }) .catch(error => ( dispatch(loadFetchedVendors({ success: false, message: error.message, })) )); } export function loadFetchedProducts(products) { return { type: FETCH_PRODUCTS, payload: products, }; } export function fetchProducts(query) { return dispatch => fetch(`${process.env.REACT_APP_DEV_API_URL}/products/search/${query}&key=${process.env.REACT_APP_API_KEY}`, { method: "GET" }) .then(response => response.json()) .then((json) => { if (Validator.propertyExist(json, "error")) { throw json.error; } return dispatch(loadFetchedProducts(json)); }) .catch(error => ( dispatch(loadFetchedProducts({ success: false, message: error.message, })) )); } export function loadFetchedCategories(categories) { return { type: FETCH_CATEGORIES, payload: categories, }; } export function fetchCategories(query) { return dispatch => fetch(`${process.env.REACT_APP_DEV_API_URL}/categories/search/${query}&key=${process.env.REACT_APP_API_KEY}`, { method: "GET" }) .then(response => response.json()) .then((json) => { if (Validator.propertyExist(json, "error")) { throw json.error; } return dispatch(loadFetchedCategories(json)); }) .catch(error => ( dispatch(loadFetchedCategories({ success: false, message: error.message, })) )); } export function loadFetchedBrands(brands) { return { type: FETCH_BRANDS, payload: brands, }; } export function fetchBrands(query) { return dispatch => fetch(`${process.env.REACT_APP_DEV_API_URL}/brands/search/${query}&key=${process.env.REACT_APP_API_KEY}`, { method: "GET" }) .then(response => response.json()) .then((json) => { if (Validator.propertyExist(json, "error")) { throw json.error; } return dispatch(loadFetchedBrands(json)); }) .catch(error => ( dispatch(loadFetchedBrands({ success: false, message: error.message, })) )); } export function loadFetchedBlogs(blogs) { return { type: FETCH_BLOGS, payload: blogs, }; } export function fetchBlogs(query) { return dispatch => fetch(`${process.env.REACT_APP_DEV_API_URL}/blogs/search/${query}&key=${process.env.REACT_APP_API_KEY}`, { method: "GET" }) .then(response => response.json()) .then((json) => { if (Validator.propertyExist(json, "error")) { throw json.error; } return dispatch(loadFetchedBlogs(json)); }) .catch(error => ( dispatch(loadFetchedBlogs({ success: false, message: error.message, })) )); }
exports.donasi = (id, KPIN BOT, corohelp, tampilTanggal, tampilWaktu, instagram, telegram, youtube, kapanbotaktif, grupch1, grupch2) => { return `〄{ *MENU DONASI ${KPIN BOT}* }〄 ᴛᴇʀɪᴍᴀ ᴋᴀsɪʜ *${id.split("@s.whatsapp.net")[0]}* ᴛᴇʟᴀʜ ᴍᴇᴍʙᴜᴋᴀ ᴍᴇɴᴜ ᴅᴏɴᴀsɪ 🐼🐼 🗓*${tampilTanggal}* 🐼 ⏰*${tampilWaktu}* 🐼 (Waktu Server) ᴋᴀʟɪᴀɴ ʙɪsᴀ ᴅᴏɴᴀsɪ ᴍᴇɴɢɢᴜɴᴀᴋᴀɴ 🛡 *ᴘᴜʟsᴀ*: 085774915506 🛡 *ᴏᴠᴏ*: 085774915506 🛡 *ᴅᴀɴᴀ* : 0857774915506 🛡 *ɢᴏᴘᴀʏ* : 085774915506 📺*IKLAN* *YOUTUBE Kevin Falih Muttaqin* ⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇⬇ ᴊᴀɴɢᴀɴ ʟᴜᴘᴀ ғᴏʟʟᴏᴡ ɪɴsᴛᴀɢʀᴀᴍ ${https://instagram.com/kev.infalih} ☞ᴛᴇʟᴇɢʀᴀᴍ : ${https://t.me/kepoon25} ╔═╗═════╔╗════╔╗═╔╦╦╗ ║║╠═╦═╦═╬╣╔╦╦╦╣╠╗║║║║ ║║║╬║╬║╬║║║║║║║═╣╠╬╬╣ ╚╩╬╗╠═╣╔╩╝╠╗╠═╩╩╝╚╩╩╝ ══╚═╝═╚╝══╚═╝ ᴄʀᴇᴀᴛᴏʀ ʙʏ ʏᴏᴜᴛᴜʙᴇ Kevin Falih Muttaqin ` }
// miniprogram/pages/placeQrcode/placeQrcode.js Page({ /** * 页面的初始数据 */ data: { imageurl: "" }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { this.getQrcode(options.id); }, // 获取二维码信息 getQrcode(queryId) { wx.showLoading({ title: '获取二维码中', }) var _this = this; // 请求云函数生成二维码,参数是当前用户的社区id wx.cloud.callFunction({ name: 'qrcode', data: { scene: queryId }, // 成功回调 success: function (res) { console.log(res.result.buffer); let imagebase64 = wx.arrayBufferToBase64(res.result.buffer); let imgUrl = 'data:image/jpg;base64,' + imagebase64; _this.setData({ imageurl: imgUrl }) wx.hideLoading(); }, }) }, /** * 保存图片到手机 */ saveQrcode: function () { var _this = this; wx.showLoading({ title: '保存二维码中', }) _this.base64src(this.data.imageurl, res => { wx.saveImageToPhotosAlbum({ filePath: res, success(res) { wx.showToast({ title: '保存成功', icon: 'success', duration: 2000 }) } }) wx.hideLoading(); }); }, /** * 将base64格式图片转为url地址 */ base64src: function (base64data, cb) { const [, format, bodyData] = /data:image\/(\w+);base64,(.*)/.exec(base64data) || []; if (!format) { return (new Error('ERROR_BASE64SRC_PARSE')); } const filePath = `${wx.env.USER_DATA_PATH}/${'wx_qrcode'}.${format}`; const buffer = wx.base64ToArrayBuffer(bodyData); wx.getFileSystemManager().writeFile({ filePath, data: buffer, encoding: 'binary', success() { cb(filePath); }, fail() { return (new Error('ERROR_BASE64SRC_WRITE')); }, }) }, })
import React, { useState } from "react"; import { generatePublicUrl } from "../../../urlConfig"; import "./CartItem.css"; import Image from "../../../FormElements/Image"; import { isAuthenticated } from "../../../auth"; /** * @author * @function CartItem **/ const CartItem = (props) => { const [qty, setQty] = useState(props.cartItem.qty); const { _id, name, price, imageUrl, sold, quantity } = props.cartItem; const { user, token } = isAuthenticated(); const onQuantityIncrement = () => { setQty(qty + 1); props.onQuantityInc(_id, qty + 1); }; const onQuantityDecrement = () => { if (qty <= 1) return; setQty(qty - 1); props.onQuantityDec(_id, qty - 1); }; return ( <div className="cartItemContainer"> <div className="flexRow"> <div className="cartProImgContainer"> <Image item={imageUrl} imageUrl={imageUrl} /> </div> <div className="cartItemDetails"> <div> <p>{name}</p> <p>Price. {price}</p> <p>Sold. {sold}</p> <p>Quantity. {quantity}</p> </div> <div>Delivery in 3 - 5 days</div> </div> </div> <div style={{ display: "flex", margin: "5px 0", }} > {/* quantity control */} <div className="quantityControl"> <button onClick={onQuantityDecrement}>-</button> <input value={qty} readOnly /> <button onClick={onQuantityIncrement}>+</button> </div> <button className="cartActionBtn">save for later</button> <button className="cartActionBtn" onClick={() => props.onRemoveCartItem(user._id, isAuthenticated().token, _id) } > Remove </button> </div> </div> ); }; export default CartItem;
var sharpmap = {}; sharpmap.queue = (function () { var queued = [], active = 0, size = 6; function init() { webdb.open(); webdb.createTable(); } function process() { if ((active >= size) || !queued.length) return; active++; queued.pop()(); } function dequeue(send) { for (var i = 0; i < queued.length; i++) { if (queued[i] == send) { queued.splice(i, 1); return true; } } return false; } function request(url, callback, mimeType) { var req; function send() { req = new XMLHttpRequest(); if (mimeType && req.overrideMimeType) { req.overrideMimeType(mimeType); } req.open("GET", url, true); req.onreadystatechange = function () { if (req.readyState == 4) { active--; if (req.status < 300) callback(req); process(); } }; req.send(null); } function abort(hard) { if (dequeue(send)) return true; if (hard && req) { req.abort(); return true; } return false; } queued.push(send); process(); return { abort: abort }; } function json(url, callback) { webdb.get(url, function (tx, r) { var item, parse; if (r.rows.length !== 0) { item = r.rows.item(0); parse = JSON.parse(item.json); console.log('retrieved from webdb ' + url); return callback(parse); } return request(url, function (req) { var text, data; if (req.responseText) { text = req.responseText; webdb.add(url, text); data = JSON.parse(text); console.log('added to webdb ' + url); callback(data); } }, "application/json"); }); } return { init: init, json: json }; })();
var svg = d3.select('svg') .append('g') .attr('transform','translate(100,100)'); /* Your code goes here */ d3.csv("./data.csv",function(dataIn){ console.log(dataIn); svg.selectAll('circles') .data(dataIn) .enter() .append('circle') .attr('cx',function (d) { return scaleX(d.x) }) .attr('cy',function (d) { return scaleY(d.y)}) .attr('r',25); svg.append('g') .attr('transform','translate(0,400)') .call(d3.axisBottom(scaleX)); svg.append('g') .call(d3.axisLeft(scaleY)); svg.append('text') .attr('x',300) .attr('y',0) .attr('font-size',25) .text('test'); svg.append('text') .attr('x',300) .attr('y',450) .attr('font-size',10) .text('x axis title'); svg.append('text') .attr('transform','rotate(270)') .attr('x',-200) .attr('y',-50) .attr('font-size',10) .text('y axis title'); }) var scaleX = d3.scaleLinear().domain([0, 400]).range([0, 600]); var scaleY = d3.scaleLinear().domain([0, 400]).range([400, 0]); function buttonClicked(){ console.log('here'); }
/* eslint-disable react-hooks/exhaustive-deps */ import React, { } from 'react'; import { useDispatch } from 'react-redux'; import { useSelector } from 'react-redux'; import { updateRole } from '../../../redux/userReducers'; import LoadingSpinner from '../../Helpers/LoadingSpinner'; const UsersPage = () => { const { allUsers, isUsersLoading } = useSelector(state => state.user) const dispatch = useDispatch() const toggleStatus = ({ user, index }) => { const userEdited = { username: user.username, email: user.email } user.status === "active" ? userEdited.status = "blocked" : userEdited.status = "active" dispatch(updateRole({ user: userEdited, index })) } const toggleRole = ({ user, index }) => { const userEdited = { username: user.username, email: user.email } user.role === "user" ? userEdited.role = "admin" : userEdited.role = "user" dispatch(updateRole({ user: userEdited, index })) } return ( <div className="container-fluid"> <div className="h4 mt-5">All Users</div> <div className="table-responsive mt-4"> <table className="table table-bordered table-sm"> <thead className="table-danger"> <tr className="text-center"> <th>S.no.</th> <th>Name</th> <th>Username</th> <th>E-Mail</th> <th>Phone</th> <th>Role</th> <th>Total Addresses</th> <th>Total Cards</th> <th>Created At</th> <th>Last Login</th> <th>Status</th> <th colSpan="2">Options</th> </tr> </thead> <tbody> { allUsers.map((user, index) => [ <tr key={index}> <td className="text-center">{index + 1}</td> <td>{user.name}</td> <td>{user.username}</td> <td>{user.email}</td> <td>{user.phone || "-"}</td> <td>{user.role}</td> <td>{user.addresses?.length || "-"}</td> <td>{user.cards?.length || "-"}</td> <td>{user.createdAt}</td> <td>{user.lastLogin}</td> <td>{user.status}</td> <td className="text-center"> <span className="text-danger fw-bold cursor-pointer" onClick={() => toggleStatus({ user, index })}>{user.status === "active" ? "Block" : "Unblock"}</span> </td> <td className="text-center"> <span className="text-danger fw-bold cursor-pointer" onClick={() => toggleRole({ user, index })}>{user.role === "user" ? "Make Admin" : "Make User"}</span> </td> </tr> ]) } { isUsersLoading ? <tr className="text-center"><td colSpan="12"><LoadingSpinner message="Loading Users..." /></td></tr> : !allUsers.length && <tr className="text-center"><td colSpan="12">No Records Found</td></tr> } </tbody> </table> </div> </div> ); } export default UsersPage;
import React from 'react'; import './style.scss'; import divider from '../image/Divider.png'; import cookImg from '../image/cook.png'; import dish from '../image/dish.png'; function About() { return ( <section id="about" className="wrapper"> <div className="section-about"> <div className="about-left"> <h1>Just the right food</h1> <img className="divider" src={divider} alt="divider" /> <p> If you’ve been to one of our restaurants, you’ve seen – and <br /> tasted – what keeps our customers coming back for more. <br /> Perfect materials and freshly baked food, delicious Lambda <br /> cakes, muffins, and gourmet coffees make us hard to resist! <br /> Stop in today and check us out! </p> <img className="cook" src={cookImg} alt="cook" /> </div> <div className="about-right"> <img className="mw-100" src={dish} alt="dish" /> </div> </div> </section> ); } export default About;
import { expect } from 'chai' import HeatMap from '../../' describe('heatmap', () => { it('should construct', () => { expect(new HeatMap()).to.be.not.undefined }) })
import { dbService, firebaseInstance } from "../fbInstance"; // Todo : DB 중복 제거하기 // init data on firebase export const firebaseAPI = async ({userObj}, dbCollection, defaultData) => { console.log(`Calling status API from ${dbCollection}`); return await dbService.collection(dbCollection) .where("uid", "==", userObj.uid) .get() .then((doc) => { const data = doc.empty ? undefined : doc.docs[0]; if (data === undefined ? false : data.exists) { return data.data(); } else { createData(userObj.uid, dbCollection, defaultData); } }).catch((error) => { console.log("Error getting documents: ", error); }); } // Create data on firebase With UID export const createData = async (uid, dbCollection, data) => { console.log(`Calling status API from ${dbCollection}`); return await dbService.collection(dbCollection).doc(uid).set(data); } // Create data on firebase without UID export const createDataWithoutUid = async (dbCollection, data) => { console.log(`Calling status API from ${dbCollection}`); await dbService.collection(dbCollection).add(data) .catch(error => { console.error("Error adding document: ", error); }); } // get twitter data export const getTwitterData = async (uid, dbCollection) => { console.log(`Calling status API from ${dbCollection}`); return await dbService.collection(dbCollection) .where("id_str", "==", uid) .get() .then((doc) => { const data = doc.empty ? undefined : doc.docs[0]; if (data === undefined ? false : data.exists) { return data.data(); } }).catch((error) => { console.log("Error getting documents: ", error); }); } export const getAllData = async (dbCollection) => { console.log(`Calling status API from ${dbCollection}`); return await dbService.collection(dbCollection).get(); } export const getMemberData = async (dbCollection, name) => { return await dbService.collection(dbCollection) .where("name", "==", name) .get(); } // update userInventoryData for memoryCardId export const updateData = async (uid, dbCollection, data) => { // uid(다큐먼트)가 존재할떄 아닐떄... 로 구별해서 작성하기 > 이럴필요없이 처음에 초기값 셋팅하는건/ const ref = dbService.collection(dbCollection).doc(uid); console.log(ref); ref.update({ // 중복 요소에 대해서 고민해보기(현재는 중복x) memoryCardId: firebaseInstance.firestore.FieldValue.arrayUnion(data) }).then(() => { console.log("Document successfully updated!"); }).catch(error => { console.log("document", error); }); } export const getUserItemInfo = async (uid, dbCollection) => { console.log(`Item Information! ${dbCollection}`); return await dbService.collection(dbCollection).doc(uid).get(); } // update equipment information export const updateEquipmentData = async (uid, dbCollection, data) => { const kinds = data.id.split("-")[2]; const updateData = (kinds === "W") ? { weapon: data } : (kinds === "A") ? { armor: data } : { accessory: data }; await dbService.collection(dbCollection).doc(uid).update(updateData).then(() => { console.log("Equipment Data successfully updated!"); }); } // update empty Equip infomation export const disarmEquipmentData = async (uid, dbCollection, key) => { const data = {}; data[key] = {} await dbService.collection(dbCollection).doc(uid).update(data).then(); } // random item export const getMemoryCardInfoForRandom = async (uid, dbCollection, grade) => { console.log(`Item Information! ${dbCollection}`); const result = await dbService.collection(dbCollection) .where("grade", "==", grade) .get().then(doc => { console.log(grade); if(doc.docs.length === 0) { return false; } const random = Math.floor(Math.random() * (doc.docs.length)); const data = doc.docs[random].data(); updateData(uid, process.env.REACT_APP_DB_USER_INVENTORY, data); return data; }) return result; }
import { Get_Tasks, Delete_Task } from './ActionTypes' import { getTasks, removeTask } from '../services/localStorage' import { createArray } from '../utils/utils' export const getAllTasks = () => { const tasks = getTasks() const taskArray = createArray(tasks) return { type: Get_Tasks, tasks: taskArray, } } const updateList = tasks => { return { type: Delete_Task, tasks, } } export const deleteTask = id => (dispatch, getState) => { removeTask(id) const tasks = getState().listState.tasks.filter(task => task.id !== id) dispatch(updateList(tasks)) }
import Vue from 'vue' import App from './App.vue' import('@/assets/styles/index.css'); import scroll from './common/scroll.directive'; Vue.directive('scroll', scroll); import Amplify from 'aws-amplify'; import aws_exports from './aws-exports'; Amplify.configure(aws_exports); Vue.config.productionTip = false new Vue({ render: h => h(App), }).$mount('#app')
// Get Current Date let today = new Date(); // new Date object // now concatenate formatted output let date = (today.getMonth()+1) + " / " + today.getDate() + " / " + today.getFullYear(); document.getElementById('currentdate').innerHTML = date; // Defining Table // INPUT: Get number of regular hours and the employee's gross salary // PROCESSING: Calculate the net salary after taxes // OUTPUT: Display employee’s after tax pay function getAfterTaxPay () { //INPUT let hours = parseFloat(document.getElementById("hours").value); let gain = parseFloat(document.getElementById("gain").value); //PROCESSING let netPay = hours * gain * 0.85; let netPayrounded = netPay.toFixed(2); //OUTPUT document.getElementById ("output").innerHTML = netPayrounded +" USD"; }
import React, { Component } from 'react'; import Cell from '../cell/cell.js'; import './grid.css'; const puzzle = { "puzzle": "080032001703080002500007030050001970600709008047200050020600009800090305300820010", "solution": "489532761713486592562917834258341976631759248947268153125673489876194325394825617" } class Grid extends Component { render() { const cells = puzzle.puzzle.split('').map((item, index) => { return (<Cell key={index} val={item}> {item} </Cell>) }) return ( <div className="grid"> {cells} </div> ) } } export default Grid;
var readlineSync = require('readline-sync'); var numeroVoo = readlineSync.questionInt('Qual o número do seu vôo? '); var fileira = readlineSync.question('Qual fileira o Sr. deseja sentar? A,B,C,D,E ou F? '); switch(fileira){ case 'A': console.log(`O número do seu vôo é ${numeroVoo} , fileira A.`); break; case 'B': console.log(`O número do seu vôo é ${numeroVoo} , fileira B.`); break; case 'C': console.log(`O número do seu vôo é ${numeroVoo} , fileira C.`); break; case 'D': console.log(`O número do seu vôo é ${numeroVoo} , fileira D.`); break; case 'E': console.log(`O número do seu vôo é ${numeroVoo} , fileira E.`); break; case 'F': console.log(`O número do seu vôo é ${numeroVoo} , fileira F.`); break; default: console.log('Opção inválida'); }
import React from 'react'; import TagList from 'molecules/tagList'; import { array } from '@storybook/addon-knobs'; import { withDesign } from 'storybook-addon-designs'; import mdx from './docs.mdx'; export default { title: 'Atoms|TagList', component: TagList, decorators: [ withDesign, ], parameters: { docs: { page: mdx, }, design: { name: 'tag', type: 'figma', url: 'https://www.figma.com/file/oY0oRyqDxQZMeMqG4BSwrf/30-seconds-web?node-id=193%3A0', }, jest: [ 'tagList', ], }, }; export const component = () => { const tags = array('tags', [ 'array', 'adapter', 'function' ]); return ( <TagList tags={ tags } /> ); };
// yy-renderer // by David Figatner // (c) YOPEY YOPEY LLC 2017 // MIT License // https://github.com/davidfig/update const PIXI = require('pixi.js') const FPS = require('yy-fps') const Loop = require('yy-loop') const exists = require('exists') class Renderer { /** * Wrapper for a pixi.js Renderer * @param {object} [options] * @param {boolean} [options.alwaysRender=false] update renderer every update tick * @param {number} [options.FPS=60] desired FPS for rendering (otherwise render on every tick) * * @param {HTMLCanvasElement} [options.canvas] place renderer in this canvas * @param {HTMLElement} [options.parent=document.body] if no canvas is provided, use parent to provide parent for generated canvas otherwise uses document.body * @param {object} [options.styles] apply these CSS styles to the div * * @param {number} [options.aspectRatio] resizing will maintain aspect ratio by ensuring that the smaller dimension fits * @param {boolean} [options.autoresize=false] automatically calls resize during resize events * @param {number} [options.color=0xffffff] background color in hex * * @param {boolean} [options.turnOffTicker] turn off PIXI.shared.ticker * @param {boolean} [options.turnOffInteraction] turn off PIXI.Interaction manager (saves cycles) * * @param {boolean} [options.noWebGL=false] use the PIXI.CanvasRenderer instead of PIXI.WebGLRenderer * @param {boolean} [options.antialias=true] turn on antialias if native antialias is not used, uses FXAA * @param {boolean} [options.forceFXAA=false] forces FXAA antialiasing to be used over native. FXAA is faster, but may not always look as great * @param {number} [options.resolution=window.devicePixelRatio] / device pixel ratio of the renderer (e.g., original retina is 2) * @param {boolean} [options.clearBeforeRender=true] sets if the CanvasRenderer will clear the canvas or before the render pass. If you wish to set this to false, you *must* set preserveDrawingBuffer to `true`. * @param {boolean} [options.preserveDrawingBuffer=false] enables drawing buffer preservation, enable this if you need to call toDataUrl on the webgl context. * @param {boolean} [options.roundPixels=false] if true PIXI will Math.floor() x/y values when rendering, stopping pixel interpolation * * @param {boolean|string} [options.debug] false, true, or some combination of 'fps', 'dirty', and 'count' (e.g., 'count-dirty' or 'dirty') * @param {object} [options.fpsOptions] options from yy-fps (https://github.com/davidfig/fps) * * @param {number} [options.maxFrameTime=1000/60] maximum time in milliseconds for a frame * @param {object} [options.pauseOnBlur] pause loop when app loses focus, start it when app regains focus * * @event each(elapsed, Loop, elapsedInLoop) * @event start(Loop) * @event stop(Loop) */ constructor(options) { options = options || {} this.options = options this.loop = new Loop({ pauseOnBlur: options.pauseOnBlur, maxFrameTime: options.maxFrameTime }) this.canvas = options.canvas this.autoResize = options.autoresize this.aspectRatio = options.aspectRatio this.FPS = exists(options.FPS) ? 1000 / options.FPS : 0 options.resolution = this.resolution = options.resolution || window.devicePixelRatio || 1 options.antialias = exists(options.antialias) ? options.antialias : true options.transparent = true if (!this.canvas) this.createCanvas(options) options.view = this.canvas if (options.turnoffTicker) { const ticker = PIXI.ticker.shared ticker.autoStart = false ticker.stop() } const noWebGL = options.noWebGL || false options.noWebGL = null options.autoresize = null const Renderer = noWebGL ? PIXI.CanvasRenderer : PIXI.WebGLRenderer this.renderer = new Renderer(options) if (options.turnOffInteraction) { this.renderer.plugins.interaction.destroy() } if (options.color) { this.canvas.style.backgroundColor = options.color } if (options.styles) { for (let style in options.styles) { this.canvas.style[style] = options.styles[style] } } if (options.debug) this.createDebug(options) if (this.autoResize) window.addEventListener('resize', () => this.resize()) this.time = 0 this.stage = new PIXI.Container() this.dirty = this.alwaysRender = options.alwaysRender || false this.resize(true) } /** * create canvas if one is not provided * @private */ createCanvas(options) { this.canvas = document.createElement('canvas') this.canvas.style.width = '100vw' this.canvas.style.height = '100vh' if (options.parent) { options.parent.appendChild(this.canvas) options.parent = null } else { document.body.appendChild(this.canvas) } var width = this.canvas.offsetWidth var height = this.canvas.offsetHeight this.canvas.style.position = 'absolute' this.canvas.width = width * this.resolution this.canvas.height = height * this.resolution this.canvas.style.left = this.canvas.style.top = '0px' this.canvas.style.overflow = 'auto' } /** * create FPS meter and render indicator * @param {object} options */ createDebug(options) { this.debug = options.debug const fpsOptions = options.fpsOptions || {} fpsOptions.FPS = options.FPS this.fpsMeter = new FPS(fpsOptions) const indicator = document.createElement('div') indicator.style.display = 'flex' indicator.style.justifyContent = 'space-between' this.fpsMeter.div.prepend(indicator) if (options.debug === true || options.debug === 1 || options.debug.toLowerCase().indexOf('dirty') !== -1) { this.dirtyIndicator = document.createElement('div') indicator.appendChild(this.dirtyIndicator) this.dirtyIndicator.innerHTML = '&#9624; ' } if (options.debug === true || options.debug === 1 || options.debug.toLowerCase().indexOf('count') !== -1) { this.countIndicator = document.createElement('div') indicator.appendChild(this.countIndicator) } } debugUpdate() { this.dirtyIndicator.color = this.dirty } /** * immediately render without checking dirty flag */ render() { this.renderer.render(this.stage) this.dirty = this.alwaysRender } /** * @private */ update() { if (this.fpsMeter) { this.fpsMeter.frame() if (this.dirtyIndicator && this.lastDirty !== this.dirty) { this.dirtyIndicator.style.color = this.dirty ? 'white' : 'black' this.lastDirty = this.dirty } if (this.countIndicator) { const count = this.countObjects() if (this.lastCount !== count) { this.countIndicator.innerText = count this.lastCount = count } } } if (this.dirty) { this.render() this.dirty = this.alwaysRender } } /** * counts visible objects */ countObjects() { function count(object) { if (!object.visible) { return } total++ for (let i = 0, _i = object.children.length; i < _i; i++) { count(object.children[i]) } } var total = 0 count(this.stage) return total } /** * sets the background color * @param {string} color in CSS format */ background(color) { this.canvas.style.backgroundColor = color } /** * adds object to stage * @param {PIXI.DisplayObject} object * @param {number} [to] index to add */ add(object, to) { if (typeof to === 'undefined') { to = this.stage.children.length } this.stage.addChildAt(object, to) return object } /** * alias for add * @param {PIXI.DisplayObject} object */ addChild(object) { return this.add(object) } /** * alias for add * @param {PIXI.DisplayObject} object * @param {number} to - index to add */ addChildTo(object, to) { return this.add(object, to) } /** * remove child from stage * @param {PIXI.DisplayObject} object */ removeChild(object) { this.stage.removeChild(object) } /** * clears the stage */ clear() { this.stage.removeChildren() } /** * resize * @param {boolean} [force] resize, even if cached width/height remain unchanged */ resize(force) { var width = this.canvas.offsetWidth var height = this.canvas.offsetHeight if (this.aspectRatio) { if (width > height) { width = height * this.aspectRatio } else { height = width / this.aspectRatio } } if (force || width !== this.width || height !== this.height) { this.width = width this.height = height this.canvas.width = width * this.resolution this.canvas.height = height * this.resolution this.renderer.resize(this.width, this.height) this.landscape = this.width > this.height this.dirty = true } } /** * returns the smaller of the width/height based * @return {number} */ dimensionSmall() { return (this.landscape ? this.height : this.width) } /** * returns the larger of the width/height based * @return {number} */ dimensionBig() { return (this.landscape ? this.width : this.height) } /** * getter/setter to change desired FPS of renderer */ get fps() { return this.FPS } set fps(value) { this.FPS = 1000 / value if (this.loop) { this.loop.remove(this.loopSave) this.loopSave = this.loop.add(() => this.update(), this.FPS) } if (this.fpsMeter) { this.fpsMeter.fps = value } } /** * Add a listener for a given event to yy-loop * @param {(String|Symbol)} event The event name. * @param {Function} fn The listener function. * @param {*} [context=this] The context to invoke the listener with. * @returns {EventEmitter} `this`. */ on() { this.loop.on(...arguments) } /** * Add a one-time listener for a given event to yy-loop * @param {(String|Symbol)} event The event name. * @param {Function} fn The listener function. * @param {*} [context=this] The context to invoke the listener with. * @returns {EventEmitter} `this`. * @public */ once() { this.loop.once(...arguments) } /** * start the internal loop * @returns {Renderer} this */ start() { this.loopSave = this.loop.add(() => this.update(), this.FPS) this.loop.start() return this } /** * stop the internal loop * @inherited from yy-loop * @returns {Renderer} this */ stop() { this.loop.stop() } } module.exports = Renderer
const fs = require('fs'); fs.readFile('./directions.txt', (err, data) => { floor = 0; directions = data.toString().split(""); directions.map(direction => { (direction === "(") ? floor++ : floor--; }) })
import { getValidationError, invalidUrlError, noTextError } from "../src/client/js/validation" const text1 = "" const text2 = "Definitely not a URL" const text3 = "http://google.com" const text4 = "https://www.google.com/en" const text5 = "http://www.google.com" const text6 = "http://www.google/en" const text7 = "htt://www.google.com" const text8 = "://www.google.com" const text9 = "www.google.com" describe("Testing the validation functionality", () => { test("Testing the getValidationError function exists", () => { expect(getValidationError).toBeDefined(); }) test(`Testing that "${text1}" fails validation with "${noTextError}"`, () => { expect(getValidationError(text1)).toBe(noTextError); }) test(`Testing that "${text2}" fails validation with "${invalidUrlError}"`, () => { expect(getValidationError(text2)).toBe(invalidUrlError); }) test(`Testing that "${text3}" passes validation`, () => { expect(getValidationError(text3)).toBe(false); }) test(`Testing that "${text4}" passes validation`, () => { expect(getValidationError(text4)).toBe(false); }) test(`Testing that "${text5}" passes validation`, () => { expect(getValidationError(text5)).toBe(false); }) test(`Testing that "${text6}" fails validation with "${invalidUrlError}"`, () => { expect(getValidationError(text6)).toBe(invalidUrlError); }) test(`Testing that "${text7}" fails validation with "${invalidUrlError}"`, () => { expect(getValidationError(text7)).toBe(invalidUrlError); }) test(`Testing that "${text8}" fails validation with "${invalidUrlError}"`, () => { expect(getValidationError(text8)).toBe(invalidUrlError); }) test(`Testing that "${text9}" passes validation`, () => { expect(getValidationError(text9)).toBe(false); }) })
'use strict'; window.raf = (function(){ return function(c){setTimeout(c,1000/10);}; })(); window.DigitalClock = (function() { //convert rgb to hsl var rgb2hsl = function(r,g,b){ r /= 255, g /= 255, b /= 255; var max = Math.max(r, g, b), min = Math.min(r, g, b); var h, s, l = (max + min) / 2; if(max == min){ h = s = 0; // achromatic }else{ var d = max - min; s = l > 0.5 ? d / (2 - max - min) : d / (max + min); switch(max){ case r: h = (g - b) / d ; break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; } } return [h*60, s*100, l*100]; } //get lighter or darker color var changeLuminance = function(rgba,scale){ var i1 = rgba.indexOf("("), i2 = rgba.indexOf(")"), arr = rgba.substring(i1+1,i2).split(","), hsl = (rgb2hsl(arr[0],arr[1],arr[2])); return "hsla("+hsl[0]+","+hsl[1]+"%,"+hsl[2]*scale+"%,"+arr[3]+")"; } var getLighter = function(rgba){ var o = /[^,]+(?=\))/g.exec(rgba)[0]*0.75; return rgba.replace(/[^,]+(?=\))/g,o); } var getStyle = function(selector,styleObj){ var isAttribute = false; var newStyle = selector+"{"; for(var attr in styleObj) { if (styleObj[attr]) { isAttribute = true; newStyle += attr+" : "+styleObj[attr]+";"; } } newStyle+="}"; return isAttribute ? newStyle : ""; } function DigitalClock(){ this.init = this.init.bind(this); this.animation = this.animation.bind(this); this.update = this.update.bind(this); this.pulse = this.pulse.bind(this); this.firstTime = true; this.default = { size : 50, stroke : 20, seperateSize : 28, color : 'rgba(121,181,210,1)', colorV : '', inactiveColor : 'rgba(230,230,230,1)', inactiveColorV : '', freeColor : true, space : 1, showSeconds : false, timeFormat : "24 hours",//"24 hours","AM/PM" } this.options = {}; this.count = 0; } DigitalClock.prototype.init = function(BannerFlow){ this.container = document.querySelector(".container"); for(var attr in this.default) { this.options[attr] = this.default[attr]; } if (BannerFlow) { var settings = BannerFlow.settings; this.options.size = settings.size>=0 ? settings.size : this.default.size; this.options.stroke = settings.stroke>=0 ? settings.stroke : this.default.size; this.options.color = settings.color ? settings.color : this.default.color; this.options.inactiveColor = settings.inactiveColor ? settings.inactiveColor : this.default.inactiveColor; this.options.freeColor= settings.freeColor; this.options.space = settings.space > this.default.space ? settings.space : this.default.space; this.options.showSeconds = settings.showSeconds; this.options.timeFormat = settings.timeFormat; } this.options.seperateSize = (this.options.size*2 + this.options.stroke*3)/5; console.log(this.options.space); this.options.colorV = changeLuminance(this.options.color,0.9); this.options.inactiveColorV = changeLuminance(this.options.inactiveColor,0.9); var settingStyle = ""; settingStyle += getStyle(".digital,.seperator,.period",{ "margin" : this.options.space/2+"px" }); settingStyle += getStyle(".digital",{ "border-radius" : this.options.stroke/2+"px", "border-color" : this.options.inactiveColor, "border-top-color" : this.options.inactiveColorV, "border-bottom-color" : this.options.inactiveColorV, }); settingStyle += getStyle(".digital:before,.digital:after",{ "width" : this.options.size+"px", "height" : this.options.size+"px", "border-width" : this.options.stroke+"px" }); settingStyle += getStyle(".digital:before",{ "border-bottom-width" : this.options.stroke/2+"px" }); settingStyle += getStyle(".digital:after",{ "border-top-width" : this.options.stroke/2+"px" }); settingStyle += getStyle("[class*='number']:before,[class*='number']:after,.seperator:before,.seperator:after",{ "border-color" : this.options.color, "border-top-color" : this.options.colorV, "border-bottom-color" : this.options.colorV }); settingStyle += getStyle(".seperator:before,.seperator:after",{ "margin-top" : this.options.seperateSize+"px", "width" : this.options.seperateSize/5+"px", "height" : this.options.seperateSize/5+"px", "border-width" : this.options.seperateSize*0.4+"px" }); settingStyle += getStyle(".period:before",{ "color" : this.options.color, "margin" : this.options.space/2+"px", "margin-top" : this.options.seperateSize+"px", "font-size" : this.options.seperateSize/0.6+"px", }); settingStyle += getStyle(".second",{ "display" : this.options.showSeconds ? "inline-block" : "none" }); document.querySelector("#setting").innerHTML = settingStyle; if(this.firstTime) { this.animation(); this.firstTime = false; } } DigitalClock.prototype.pulse = function(){ this.count+=2; var updateStyle = ""; if (this.options.freeColor) { updateStyle += getStyle("[class*='number']:before,[class*='number']:after,.seperator:before,.seperator:after",{ "border-color" : 'hsla('+this.count+',50%,50%,1)', "border-top-color" : 'hsla('+this.count+',60%,60%,1)', "border-bottom-color" : 'hsla('+this.count+',60%,60%,1)' }); updateStyle += getStyle(".period:before",{ "color" : 'hsla('+this.count+',50%,50%,1)' }); } document.querySelector("#update").innerHTML = updateStyle; } DigitalClock.prototype.update = function(arr){ var children = this.container.querySelectorAll("span"); //reset all data if (arr.length != children.length) { this.container.innerHTML = ""; children = []; } for(var i=0;i<arr.length;i++){ var span = children[i]; if (!span) { span = document.createElement("span"); this.container.appendChild(span); } span.className = arr[i]; } } DigitalClock.prototype.animation = function(){ var date = new Date(); var hour = date.getHours(); var minute = date.getMinutes(); var second = date.getSeconds(); var period = ""; if (this.options.timeFormat.toLowerCase() == "am/pm") { period = hour > 12 ? "pm" : "am"; hour %= 12; } this.update([ "hour digital number-"+(hour/10|0), "hour digital number-"+hour%10, "minute seperator", "minute digital number-"+(minute/10|0), "minute digital number-"+minute%10, "second seperator", "second digital number-"+(second/10|0), "second digital number-"+second%10, "period "+period ]); this.pulse(); raf(this.animation); } return DigitalClock; })(); var timer,widget = new DigitalClock(); if (typeof BannerFlow!='undefined') { BannerFlow.addEventListener(BannerFlow.SETTINGS_CHANGED, function() { clearTimeout(timer); timer = setTimeout(function(){ widget.init(BannerFlow); },500); }); } else { window.addEventListener("load",function(){ widget.init(); }) }
function isPrefersReducedMotion() { if (window.matchMedia) return window.matchMedia("(prefers-reduced-motion: reduce)").matches; return false; } function initProjectNav() { var projectList = document.querySelector("#projects ul"); var move = function (direction) { var rem = parseFloat(getComputedStyle(document.documentElement).fontSize); var scrollLeft = projectList.scrollLeft; var halfWidth = innerWidth / 2; var cardSize = rem * 17.5; var middlePosition = scrollLeft + halfWidth; var cardNearestToMiddle = Math.floor(middlePosition / cardSize); var cardToScrollTo = cardNearestToMiddle + direction; var whitespaceToCenterCard = halfWidth - cardSize / 2; var scrollTo = cardToScrollTo * cardSize - whitespaceToCenterCard; if (projectList.scrollTo && !isPrefersReducedMotion()) { projectList.scrollTo({ top: 0, left: scrollTo, behavior: "smooth", }); } else { projectList.scrollLeft = scrollTo; } }; var leftButton = document.querySelector("#projects .left-arrow"); var rightButton = document.querySelector("#projects .right-arrow"); leftButton.addEventListener("click", function () { move(-1); }); rightButton.addEventListener("click", function () { move(1); }); } function initFlowerSpin() { var flower = document.querySelector(".flower-1"); if (!flower || isPrefersReducedMotion()) return; flower.addEventListener("click", function () { if (flower.style.transform) flower.style.transform = ""; else flower.style.transform = "rotate(720deg)"; }); } function initThemeToggle() { var radioButtons = document.querySelectorAll(".theme-toggle-container input"); var systemDarkMode = null; if (window.matchMedia) systemDarkMode = window.matchMedia("(prefers-color-scheme: dark)"); var localStorageTheme = localStorage.getItem("theme"); var systemTheme = "light"; if (systemDarkMode && systemDarkMode.matches) systemTheme = "dark"; if (isValidTheme(localStorageTheme)) currentTheme = localStorageTheme; else currentTheme = systemTheme; for (var i = 0; i < radioButtons.length; i++) { if (radioButtons[i].value === currentTheme) radioButtons[i].checked = true; radioButtons[i].onchange = function (e) { var value = e.target.value; localStorage.setItem("theme", value); setTheme(value); }; } if (systemDarkMode && systemDarkMode.addEventListener) { systemDarkMode.addEventListener("change", function (e) { var localStorageTheme = localStorage.getItem("theme"); if (isValidTheme(localStorageTheme)) { setTheme(localStorageTheme); return; } if (e.matches) { document.querySelector("input[value='dark']").checked = true; setTheme("dark"); } else { document.querySelector("input[value='light']").checked = true; setTheme("light"); } }); } } function initFaqToggle() { var questions = document.querySelectorAll(".question"); for (var i = 0; i < questions.length; i++) { var action = function (e) { var key = e.key || e.keyCode; if (e.type === "keyup" && key !== "Enter" && key !== 13) return; var newState = "true"; if (e.target.getAttribute("aria-expanded") === "true") newState = "false"; e.target.setAttribute("aria-expanded", newState); }; var question = questions[i]; question.onclick = action; question.onkeyup = action; } var expandAll = document.querySelector(".expand"); var collapseAll = document.querySelector(".collapse"); expandAll.onclick = function () { for (var i = 0; i < questions.length; i++) questions[i].setAttribute("aria-expanded", "true"); }; collapseAll.onclick = function () { for (var i = 0; i < questions.length; i++) questions[i].setAttribute("aria-expanded", "false"); }; } initProjectNav(); initFlowerSpin(); initThemeToggle(); initFaqToggle(); window.addEventListener("load", function () { var lazyImages = document.querySelectorAll("img[loading=lazy]"); var i = 0; function loadImage() { var img = lazyImages[i]; i += 1; if (!img) return; if (img.naturalWidth === 0) { img.onload = loadImage; img.setAttribute("loading", ""); } else { img.setAttribute("loading", ""); loadImage(); } } loadImage(); });
(function(){ function Jeu() { var jeu = this; var arrierePlan = null; var balle = null; var terrain = null; var joueur1 = null; var joueur2 = null; var vitesseBalle; var ratioCanevasX; var ratioCanevasY; var canevas; var informationCanevas; var coordoneeJoueur1; //Vue var accueilVue = null; var jeuVue = null; var finVue = null; var vueActive = null; var serveur=null; var nomJoueur = ""; var nomAdversaire=""; var etatVictoire=""; var ignorerProchainImpactBalle=false; var numeroJoueur; var etat; var dernierRafraichissement= Date.now(); var proportionDelais=1; var initialiserCanevas = function() { var canevasDiv = document.getElementById('canevasDiv'); canevasDiv.innerHTML = "<canvas id='canevas' oncontextmenu='return false' width='" + Jeu.Configuration.largeur + "px' height='" + Jeu.Configuration.hauteur + "px'></canvas>"; canevas = document.getElementById('canevas'); //RecalculCanevas(null); canevas.style.width = "92%" canevas.style.marginLeft = "5%"; informationCanevas=canevas.getBoundingClientRect(); ratioCanevasX = canevas.width / informationCanevas.width; ratioCanevasY = canevas.height / informationCanevas.height; } var rafraichirAnimation = function(evenement) { arrierePlan.rafraichirAnimation(evenement); date = Date.now(); if(vitesseBalle!=0) proportionDelais=(date-dernierRafraichissement)/Jeu.Configuration.delais; balle.rafraichirAnimation(proportionDelais); dernierRafraichissement=date; coordoneeJoueur1=joueur1.getCoordonnees(); testerCollisions(balle.getCoordonnees(), coordoneeJoueur1); scene.update(evenement); } var lancer = function() { initialiserCanevas(); window.addEventListener("resize", interpreterEvenementsApplicatifs); window.addEventListener(window.Evenement.arrierePlanFinChargement.type, interpreterEvenementsApplicatifs); scene = new createjs.Stage(canevas); arrierePlan = new ArrierePlan(scene); createjs.Ticker.setFPS(Jeu.Configuration.FPS); } //Le contexte EST GÉRÉ par cette fonction var interpreterEvenementsApplicatifs = function(evenement) { switch(evenement.type) { case window.Evenement.joueur2EnAction.type: joueur2.recevoirCoordonneesServeur(serveur.getPositionAutreJoueur()); if(numeroJoueur==1 && vitesseBalle==0) { ignorerProchainImpactBalle=true; balle.commencerMouvement(); } break; case "mouseup": joueur1.retirerExplosion(); break; case "mousedown": joueur1.exploser(); break; case "mousemove": joueur1.bouger(((evenement.clientX - informationCanevas.left)*ratioCanevasX), ((evenement.clientY - informationCanevas.top)*ratioCanevasY)); break; case "resize": informationCanevas = canevas.getBoundingClientRect(); ratioCanevasX = canevas.width / informationCanevas.width; ratioCanevasY = canevas.height / informationCanevas.height; break; case window.Evenement.arrierePlanFinChargement.type: window.removeEventListener(window.Evenement.arrierePlanFinChargement.type,interpreterEvenementsApplicatifs); window.addEventListener(window.Evenement.balleFinChargement.type,interpreterEvenementsApplicatifs); window.addEventListener(window.Evenement.changementVitesse.type, interpreterEvenementsApplicatifs); balle = new Balle(scene); break; case window.Evenement.changementVitesse.type: vitesseBalle=balle.getVitesse(); jeuVue.modifierVitesse(vitesseBalle); arrierePlan.changerVitesse(vitesseBalle); break; case window.Evenement.mortJoueur.type: /*if(numeroJoueur==1) changerVariablesServeur("etat", "mort joueur 1"); else if(numeroJoueur==2) changerVariablesServeur("etat", "mort joueur 2");*/ balle.envoyerInformationsAuServeur(); break; case window.Evenement.mortJoueur2.type: if(numeroJoueur==1) etatVictoire="gagne"; else etatVictoire="perdu"; window.dispatchEvent(window.Evenement.navigationFinEnAction); break; case window.Evenement.mortJoueur1.type: if(numeroJoueur==2) etatVictoire="gagne"; else etatVictoire="perdu"; window.dispatchEvent(window.Evenement.navigationFinEnAction); break; case window.Evenement.explosionAvecJoueur.type: ignorerProchainImpactBalle=true; balle.exploser(coordoneeJoueur1.horizontal,coordoneeJoueur1.vertical); break; case window.Evenement.impactBalle.type: if(ignorerProchainImpactBalle); balle.recevoirCoordonneesServeur(serveur.getDeplacementBalle(), serveur.getPositionBalle()); ignorerProchainImpactBalle=false; break; case window.Evenement.balleFinChargement.type: window.removeEventListener(window.Evenement.balleFinChargement.type,interpreterEvenementsApplicatifs); joueur1 = new Joueur(scene, numeroJoueur); joueur2 = new Joueur(scene, (3-numeroJoueur)); coordoneeJoueur1=joueur1.getCoordonnees(); canevas.addEventListener("mouseup", interpreterEvenementsApplicatifs); canevas.addEventListener("mousedown", interpreterEvenementsApplicatifs); canevas.addEventListener("mousemove", interpreterEvenementsApplicatifs); window.addEventListener(window.Evenement.joueur2EnAction.type, interpreterEvenementsApplicatifs); window.addEventListener(window.Evenement.mortJoueur.type, interpreterEvenementsApplicatifs); window.addEventListener(window.Evenement.mortJoueur1.type, interpreterEvenementsApplicatifs); window.addEventListener(window.Evenement.mortJoueur2.type, interpreterEvenementsApplicatifs); window.addEventListener(window.Evenement.explosionAvecJoueur.type, interpreterEvenementsApplicatifs); window.addEventListener(window.Evenement.impactBalle.type, interpreterEvenementsApplicatifs); createjs.Ticker.addEventListener("tick", rafraichirAnimation); if(numeroJoueur==2) { changerVariablesServeur("etat","partie en cours") } break; case window.Evenement.changementEtatPartie.type: etat=serveur.getEtat(); if(etat=="mort joueur 2") window.dispatchEvent(window.Evenement.mortJoueur2); if(etat=="mort joueur 1") window.dispatchEvent(window.Evenement.mortJoueur1); if(etat=="partie en cours") { nomAdversaire=serveur.getNomAdversaire(); document.getElementById("nomAdversaire").innerHTML = "Adversaire: " + nomAdversaire; tracer("Adversaire: " + serveur.getNomAdversaire()); } break; //Gestion de la navigation entre les écrans case window.Evenement.navigationAccueilEnAction.type: if (vueActive instanceof JeuVue) { quitterScene(); } accueilVue.afficher(); vueActive = accueilVue; break; case window.Evenement.navigationJeuEnAction.type: window.addEventListener(window.Evenement.serveurPret.type, interpreterEvenementsApplicatifs); serveur.initialiserServeur(nomJoueur); break; case window.Evenement.serveurPret.type: window.removeEventListener(window.Evenement.serveurPret.type, interpreterEvenementsApplicatifs); window.addEventListener(window.Evenement.changementEtatPartie.type, interpreterEvenementsApplicatifs); nomJoueur = serveur.getNomJoueur(); numeroJoueur=serveur.getNumeroJoueur(); jeuVue.afficher(); vueActive = jeuVue; document.getElementById("nomJoueur").innerHTML = "Nom du Joueur: "+ nomJoueur; lancer(); break; case window.Evenement.navigationFinEnAction.type: if (vueActive instanceof JeuVue) { quitterScene(); } finVue.afficher(nomJoueur,nomAdversaire,etatVictoire, vitesseBalle); vueActive = finVue; break; //Gestion du nom du joueur dans la vue Accueil case window.Evenement.accueilVueEnregistrerNomJoueurEnAction.type: nomJoueur = accueilVue.getNomJoueur(); break; } } var interpreterEvenementsLocation = function(evenement) { //hash est la partie suivant le # dans l'url var ancre = window.location.hash; //Si l'ancre est vide ou qu'il ne débute pas par # if(!ancre || ancre.match(/^#$/)) { window.dispatchEvent(window.Evenement.navigationAccueilEnAction); //Fait le ménage dans l'URL pour ne pas voir # history.pushState("", document.title, window.location.pathname + window.location.search); } //Si l'ancre commence par #accueil else if(ancre.match(/^#accueil/)) { window.dispatchEvent(window.Evenement.navigationAccueilEnAction); //Fait le ménage dans l'URL pour ne pas voir #accueil history.pushState("", document.title, window.location.pathname + window.location.search); }//Si l'ancre commence par #jeu else if(ancre.match(/^#jeu/)) { window.dispatchEvent(window.Evenement.navigationJeuEnAction); //Fait le ménage dans l'URL pour ne pas voir #jeu history.pushState("", document.title, window.location.pathname + window.location.search); }//Si l'ancre commence par #fin- et qu'il est suivi de perdu ou gagne else if(succes = ancre.match(/^#fin-(perdu|gagne)/)) { //La seconde évaluation de l'expression régulière (perdu|gagne) est à la position 1 du tableau de résultat succes switch(succes[1]) { default: window.dispatchEvent(window.Evenement.navigationFinEnAction); break; } //Fait le ménage dans l'URL pour ne pas voir #fin-perdu ou #fin-gagne history.pushState("", document.title, window.location.pathname + window.location.search); } } var initialiser = function() { serveur= new ConnecterServeur(); accueilVue = new AccueilVue(); jeuVue = new JeuVue(); finVue = new FinVue(); //Enregistrer l'écoute des événements window.addEventListener("hashchange", interpreterEvenementsLocation); window.addEventListener(window.Evenement.navigationAccueilEnAction.type, interpreterEvenementsApplicatifs, false); window.addEventListener(window.Evenement.navigationJeuEnAction.type, interpreterEvenementsApplicatifs, false); window.addEventListener(window.Evenement.navigationFinEnAction.type, interpreterEvenementsApplicatifs, false); window.addEventListener(window.Evenement.accueilVueEnregistrerNomJoueurEnAction.type, interpreterEvenementsApplicatifs, false); //Première interaction possible avec le joueur accueilVue.afficher(); vueActive = accueilVue; } var quitterScene = function() { //Il faut faire du ménage pour ne pas surcharger le navigateur. serveur.quitterSeveur(); //Désenregistrer l'écoute des événements window.removeEventListener(window.Evenement.joueur2EnAction.type, interpreterEvenementsApplicatifs); window.removeEventListener(window.Evenement.mortJoueur1.type, interpreterEvenementsApplicatifs); window.removeEventListener(window.Evenement.mortJoueur2.type, interpreterEvenementsApplicatifs); window.removeEventListener(window.Evenement.explosionAvecJoueur.type, interpreterEvenementsApplicatifs); window.removeEventListener(window.Evenement.changementEtatPartie.type, interpreterEvenementsApplicatifs); createjs.Ticker.removeEventListener("tick", rafraichirAnimation); canevas.removeEventListener("mouseup", interpreterEvenementsApplicatifs); canevas.removeEventListener("mousedown", interpreterEvenementsApplicatifs); canevas.removeEventListener('mousemove', interpreterEvenementsApplicatifs); window.removeEventListener("resize", interpreterEvenementsApplicatifs); window.removeEventListener(window.Evenement.changementVitesse.type, interpreterEvenementsApplicatifs); } initialiser(); } Jeu.Evenement = { joueur2EnAction:document.createEvent('Event'), serveurPret:document.createEvent('Event'), changementEtatPartie:document.createEvent('Event'), impactBalle:document.createEvent('Event'), /*boutonSourisEnAction: document.createEvent('Event'), boutonSourisRelache: document.createEvent('Event'), bougeSouris: document.createEvent('Event'),*/ redimensionnementEcran: document.createEvent('Event'), arrierePlanFinChargement : document.createEvent('Event'), balleFinChargement : document.createEvent('Event'), changementVitesse: document.createEvent('Event'), mortJoueur : document.createEvent('Event'), mortJoueur1 : document.createEvent('Event'), mortJoueur2 : document.createEvent('Event'), explosionAvecJoueur : document.createEvent('Event'), navigationAccueilEnAction: document.createEvent('Event'), navigationJeuEnAction : document.createEvent('Event'), navigationFinEnAction : document.createEvent('Event'), accueilVueEnregistrerNomJoueurEnAction : document.createEvent('Event') } Jeu.Evenement.initialiser = function() { for(key in Jeu.Evenement) { if(Jeu.Evenement[key] instanceof Event) { Jeu.Evenement[key].initEvent(key, true, true); } } window['Evenement'] = Jeu.Evenement; }(); Jeu.Configuration = { largeur:2000, hauteur:1000, FPS:60, delais:(1000/60) } new Jeu(); })();
const ejsLib = require("ejs"); const TemplateEngine = require("./TemplateEngine"); class Ejs extends TemplateEngine { async compile(str) { let fn = ejsLib.compile(str, { root: "./" + super.getInputDir(), compileDebug: true, filename: "./" + super.getInputDir() }); return function(data) { return fn(data); }; } } module.exports = Ejs;
import { allCarsTemplate } from "./allCarsTemplate.js"; import carService from "./../../services/carService.js"; async function getView(context) { let allCars = await carService.getAll(); console.log(allCars) let templateResult = allCarsTemplate(allCars); context.renderView(templateResult); } export default { getView }
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose"; import _extends from "@babel/runtime/helpers/esm/extends"; var _excluded = ["children", "rtlEnabled"]; import { BaseInfernoComponent } from "@devextreme/vdom"; export var viewFunction = viewModel => viewModel.props.children; export var ConfigProviderProps = {}; export class ConfigProvider extends BaseInfernoComponent { constructor(props) { super(props); this.state = {}; } getChildContext() { return _extends({}, this.context, { ConfigContext: this.config }); } get config() { return { rtlEnabled: this.props.rtlEnabled }; } get restAttributes() { var _this$props = this.props, restProps = _objectWithoutPropertiesLoose(_this$props, _excluded); return restProps; } render() { var props = this.props; return viewFunction({ props: _extends({}, props), config: this.config, restAttributes: this.restAttributes }); } } ConfigProvider.defaultProps = _extends({}, ConfigProviderProps);
var ext = require('./ext.js'); var data = require('./data.json'); (function(e) { // Check for GET param 'lang' // codes from https://github.com/khanning/scratch-arduino-extension/blob/da1ab317a215a8c1c5cda1b9db756b9edc14ba68/arduino_extension.js#L533-L541 var paramString = window.location.search.replace(/^\?|\/$/g, ''); var vars = paramString.split("&"); var lang = 'en'; for (var i=0; i<vars.length; i++) { var pair = vars[i].split('='); if (pair.length > 1 && pair[0]=='lang') lang = pair[1]; } // merge objects for (var attrname in ext) { if (ext.hasOwnProperty(attrname)) { e[attrname] = ext[attrname]; } } // register exention ScratchExtensions.register(data.title, data.descriptor[lang], e); })({});
import React from 'react'; import * as AiIcons from 'react-icons/ai'; import * as IoIcons from 'react-icons/io'; import * as BiIcons from "react-icons/bi"; import * as TiIcons from "react-icons/ti"; import * as BsIcons from "react-icons/bs"; import * as FlatIcons from "react-icons/fc"; export const SidebarData = [ { title: 'Home', path: '/', icon: <AiIcons.AiFillHome />, cName: 'nav-text' }, { title: 'Add building', path: '/buildings', icon: <BiIcons.BiBuildingHouse />, cName: 'nav-text' }, { title: 'Add Hall', path: '/halls', icon: <IoIcons.IoIosAdd />, cName: 'nav-text' }, { title: 'Statistics per building', path: '/building-stats', icon: <FlatIcons.FcStatistics />, cName: 'nav-text' }, { title: 'Statistics per floor', path: '/floor-stats', icon: <FlatIcons.FcStatistics />, cName: 'nav-text' }, { title: 'Statistics per hall', path: '/hall-stats', icon: <FlatIcons.FcStatistics />, cName: 'nav-text' }, { title: 'Import', path: '/import', icon: <BsIcons.BsUpload/>, cName: 'nav-text' }, { title: 'Export', path: '/export', icon: <TiIcons.TiExport/>, cName: 'nav-text' } ];
/* global gapi */ const formValuesToPayload = formValues => { const headers = { To: formValues.email, Subject: formValues.subject }; const { message } = formValues; let payload = ""; for (const [key, value] of Object.entries(headers)) { payload += key + ": " + value + "\r\n"; } payload += "\r\n" + message; return payload; }; const sendMail = formValues => { return new Promise((resolve, reject) => { const payload = formValuesToPayload(formValues); const sendRequest = gapi.client.gmail.users.messages.send({ userId: "me", resource: { raw: window .btoa(payload) .replace(/\+/g, "-") .replace(/\//g, "_") } }); sendRequest.then(() => resolve()).catch(error => reject(error)); }); }; export default sendMail;
import React, { Component } from 'react'; import './App.css'; import CreateGist from './components/CreateGist/CreateGist'; import GistList from './components/GistList/GistList'; class App extends Component { render() { return ( <div className="App"> <header className="App-header"> <h1 className="App-title">Welcome to Gist Secret Code Base</h1> </header> <CreateGist /> <GistList /> </div> ); } } export default App;
var interface_c1_connector_response = [ [ "C1ConnectorResponseBlock", "interface_c1_connector_response.html#a0473fcb0c1f2e194004fda066a2ad61a", null ], [ "assignPublicClone:", "interface_c1_connector_response.html#a60a0cfa516fc72f39e2b5e3f4275c657", null ], [ "getResponsePublic", "interface_c1_connector_response.html#a13f499f72d02f927560903189f12c968", null ], [ "initWithResult:", "interface_c1_connector_response.html#a8e1680b43c4901f95245ce8bc592f15e", null ], [ "result", "interface_c1_connector_response.html#a7684edf72348da1f8573960d4a5ee099", null ], [ "success", "interface_c1_connector_response.html#af21d47b464a64e46cbb050dc9163c876", null ] ];
$(function() { let text=$("#myList").val(); let button = $("input[type=button]"); let list =$("ul"); button.on('click', function() { list.append(`<li>${text}</li>`); }) }) // //Geolocation var loc=document.getElementById('myloc'); function myLocation(){ if(navigator.geolocation){ navigator.geolocation.getCurrentPosition(position); }else{ loc.HTML="location Tracking not posible"; } } function showPosition(position){ loc.innerHTML="longitude: "+position.coords.longitude +"<br>latitude:" + position.coords.latitude + "<br>"; }
import {getChildren} from "../src/reactImpl/dom"; describe("dom", () => { const dom = document.createElement('dv'); dom.innerHTML = `<div><span><a>xx</a></span></div>`; test('set _webComponentTemp for every children', () => { const fragment = getChildren(dom); const div = fragment.querySelector('div'); expect(div._webComponentTemp).toBe(true); const span = div.querySelector('span'); expect(span._webComponentTemp).toBe(undefined); const a = span.querySelector('a'); expect(a._webComponentTemp).toBe(undefined); }); });
var urllib = require('url'); var Crawler = require('../../crawler.js').Crawler; describe('Crawler._processRedirect method', function () { 'use strict'; var pageInfo, finalURL, response; var crawler; var mockURLData; var onRedirectSpy; var urlParseSpy; beforeEach(function () { crawler = new Crawler(); pageInfo = { page: { url: 'http://www.google.com/', redirects: [] } }; finalURL = 'http://www.google.com/'; mockURLData = { href: 'http://www.google.com/' }; response = {}; urlParseSpy = spyOn(urllib, 'parse').andCallFake(function () { return mockURLData; }); onRedirectSpy = spyOn(crawler, 'onRedirect'); spyOn(crawler, '_wasCrawled'); }); it('parses the finalURL', function () { crawler._processRedirect(pageInfo, finalURL); expect(urlParseSpy).toHaveBeenCalledWith(finalURL); }); describe('- when crawler pages contain the parsed URL -', function () { var result; beforeEach(function () { crawler._wasCrawled.andReturn(true); result = crawler._processRedirect(pageInfo, finalURL); }); it('returns null', function () { expect(result).toBe(null); }); }); describe('- when crawler pages does not contain the parsed URL -', function () { beforeEach(function () { crawler._wasCrawled.andReturn(false); crawler._processRedirect(pageInfo, finalURL); }); it('returns pageInfo object', function () { crawler._pages = {}; var result = crawler._processRedirect(pageInfo, finalURL); expect(result).toEqual(pageInfo); }); it('returns updated pageInfo when a redirect occurs', function () { pageInfo.page.url = 'http://domain.com/redirected'; var result = crawler._processRedirect(pageInfo, finalURL); expect(result.page.url).toBe(finalURL); }); it('adds the parsed URL to the _urlsCrawled property', function () { mockURLData = { href: 'returned URL' }; crawler._urlsCrawled = []; crawler._processRedirect(pageInfo, finalURL); expect(crawler._urlsCrawled).toEqual(['returned URL']); }); it('sends onRedirect the pageInfo.page and response', function () { crawler._processRedirect(pageInfo, finalURL, response); expect(onRedirectSpy).toHaveBeenCalledWith(pageInfo.page, response, finalURL); }); it('preserves redirect\'s page url for onRedirect method', function (done) { pageInfo.page.url = 'http://domain.com/redirected'; onRedirectSpy.andCallFake(function (page) { setTimeout(function () { expect(page.url).toBe('http://domain.com/redirected'); done(); }); }); crawler._processRedirect(pageInfo, finalURL, response); }); }); });
import React, {useState, createContext} from "react"; export const AppContext = createContext(null); export const AppContextProvider = ({ children }) => { const [selectedTrack, setSelectedTrack] = useState(null) const [loading, setIsLoading] = useState(false) const [isPlaying, setIsPlaying] = useState(false) const [isMuted, setIsMuted] = useState(false) return ( <AppContext.Provider value={{ selectedTrack, setSelectedTrack, loading, setIsLoading, isPlaying, setIsPlaying, isMuted, setIsMuted }} > {children} </AppContext.Provider> ); }
import styled from 'styled-components' export const StyledHeader = styled.div` display: flex; flex-direction: row; justify-content: space-between; padding: 2em 0; ` export const StyledLayout = styled.div` max-width: 1560px; min-width: 500px; position: relative; margin: 10em; padding: 1em; border: 0.2em solid #ccc; ` export const StyledDateRange = styled.div` display: flex; flex-direction: row; justify-content: space-between; `
import React, { useEffect } from 'react' import { Text, StyleSheet } from 'react-native' function TodoDetail(props) { useEffect(() => { props.navigation.setOptions({ title: props.route.params.todo.title, }) }, []) return ( <Text>{JSON.stringify(props.route.params.todo)}</Text> ) } const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'center', }, todos: { // flex: 1 } }); export default TodoDetail
import React from 'react'; import './index.scss' class TypeBox extends React.Component { constructor() { super() this.state = { list: [ { link: "icon-banshidating", name: '多媒体数字展厅' }, { link: "icon-logo", name: '大型水幕秀' }, { link: "icon--", name: '大型灯光秀' }, { link: "icon-yingban", name: '影视宣传片' }, { link: "icon-shengchan", name: '三维产品动画' }, { link: "icon-shujujianmo", name: '建筑可视化漫游' } ] } } render() { return ( <div className='type-box'> <h2 className="type-title">核心产品与服务</h2> <span className="type-bar"></span> <div className='type-list'> {this.state.list.map(item => { return ( <div className='type-item' key={item.link}> <div className='type-icon'> <i className={['iconfont ', item.link].join(' ')}></i> </div> <div className='type-item-text'>{item.name}</div> </div> ) })} </div> </div> ) } componentDidMount() { console.log(this.props) } } export default TypeBox;
const mongoose = require('../connections/mongoose/instance'); const schema = require('../schema/topic'); module.exports = mongoose.model('topic', schema);
var searchData= [ ['objectlist',['ObjectList',['../de/df2/classBALL_1_1PersistenceManager.html#a17f2bfefff2e00bf012a7fa46bc017aa',1,'BALL::PersistenceManager']]], ['objectset',['ObjectSet',['../de/df2/classBALL_1_1PersistenceManager.html#a577529893993830d38c431e1b0d13a3e',1,'BALL::PersistenceManager']]], ['oneletteraasequence',['OneLetterAASequence',['../d8/df6/namespaceBALL_1_1Peptides.html#ad271ac1abf8bdbc4f45586bb2d73ecfd',1,'BALL::Peptides']]], ['openmode',['OpenMode',['../db/db5/classBALL_1_1File.html#a4fb423dfe14c17429117b4e38162ab64',1,'BALL::File']]], ['order',['Order',['../d8/d56/classBALL_1_1Bond.html#afbb461e17d3e1fe517234394025e4405',1,'BALL::Bond']]], ['orientationiterator',['OrientationIterator',['../df/dd7/classBALL_1_1SASFace.html#a5f5d6821ab8113395a2a7bc548a657d2',1,'BALL::SASFace']]] ];
/** * English translation for bootstrap-wysihtml5 */ (function (factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define('bootstrap.wysihtml5.en-US', ['jquery', 'bootstrap.wysihtml5'], factory); } else { // Browser globals factory(jQuery); } }(function ($) { $.fn.wysihtml5.locale.en = $.fn.wysihtml5.locale['en-US'] = { font_size: { x8: "8 pt", x9: "9 pt", x10: "10 pt", x11: "11 pt", x12: "12 pt", x13: "13 pt", x14: "14 pt", x15: "15 pt", x16: "16 pt", x17: "17 pt", x18: "18 pt", x19: "19 pt", x20: "20 pt", x21: "21 pt", x22: "22 pt", x23: "23 pt", x24: "24 pt" }, font_styles: { normal: 'Normal text', h1: 'Heading 1', h2: 'Heading 2', h3: 'Heading 3', h4: 'Heading 4', h5: 'Heading 5', h6: 'Heading 6' }, emphasis: { bold: 'Bold', italic: 'Italic', underline: 'Underline', small: 'Small' }, lists: { centerAlign: 'Centralizar', leftAlign: 'Alinhar à esquerda', rightAlign: 'Alinhar à direita', justifyAlign: 'Justificar', unordered: 'Unordered list', ordered: 'Ordered list', outdent: 'Outdent', indent: 'Indent' }, link: { insert: 'Insert link', cancel: 'Cancel', target: 'Open link in new window' }, image: { insert: 'Insert image', cancel: 'Cancel' }, html: { edit: 'Edit HTML' }, colours: { black: 'Black', silver: 'Silver', gray: 'Grey', maroon: 'Maroon', red: 'Red', purple: 'Purple', green: 'Green', olive: 'Olive', navy: 'Navy', blue: 'Blue', orange: 'Orange' } }; }));
export const nameInput = document.querySelector('#name'); export const jobInput = document.querySelector('#job'); export const addImageBtn = document.querySelector('.profile__button-add'); export const editProfileBtn = document.querySelector('.profile__button'); export const profileImgBtn = document.querySelector('.profile__image-btn'); export const formBtn = document.querySelector('.form__button'); export const newCardBtn = document.querySelector('#newCardSubmitBtn'); export const avatarBtn = document.querySelector('#avatar__btn'); export const elementsList = ".elements__list"; export const userData = { name: '.profile__name', job: '.profile__job', avatar:'.profile__image' }; export const props = { formSelector: '.form', inputSelector: '.form__input', submitButtonSelector: '.form__button', inactiveButtonClass: 'form__button_disabled', inputErrorClass: 'form__input_type_error', errorClass: 'form__input-error_active' };
'use strict' var appDir = __dirname + '/..' module.exports = { appRoot: appDir, swaggerFile: appDir + '/swagger.yaml' }
// Get Current Date let today = new Date(); // new Date object // now concatenate formatted output let date = (today.getMonth()+1) + " / " + today.getDate() + " / " + today.getFullYear(); document.getElementById('currentdate').innerHTML = date; // Defining Table // INPUT: Get an integer from the user // PROCESSING: sum of all the odd integers between 1 and then integer that the user inputted // OUTPUT: Display the sum of all the odd integers function oddSum() { let n = parseInt(document.getElementById("number").value); let sum = 0; for (let i = 1; i <= n; i += 2) { sum += i } document.getElementById("output").innerHTML = sum; }
// a key map of allowed keys var allowedKeys = { 37: 'left', 38: 'up', 39: 'right', 40: 'down', 65: 'a', 66: 'b' }; // the 'official' Konami Code sequence var konamiCode = ['up', 'up', 'down', 'down', 'left', 'right', 'left', 'right', 'b', 'a']; // a variable to remember the 'position' the user has reached so far. var konamiCodePosition = 0; // add keydown event listener document.addEventListener('keydown', function(e) { // get the value of the key code from the key map var key = allowedKeys[e.keyCode]; // get the value of the required key from the konami code var requiredKey = konamiCode[konamiCodePosition]; // compare the key with the required key if (key == requiredKey) { // move to the next key in the konami code sequence konamiCodePosition++; // if the last key is reached, activate cheats if (konamiCodePosition == konamiCode.length) { alert("Aber natürlich ist Hans nass, er steht unter dem Wasserfall."); emoji(); konamiCodePosition = 0; } } else { konamiCodePosition = 0; } }); function emoji(){ (function emojiCursor() { var possibleEmoji = ["😀", "😂", "😆", "😊"]; var width = window.innerWidth; var height = window.innerHeight; var cursor = {x: width/2, y: width/2}; var particles = []; function init() { bindEvents(); loop(); } // Bind events that are needed function bindEvents() { document.addEventListener('mousemove', onMouseMove); document.addEventListener('touchmove', onTouchMove); document.addEventListener('touchstart', onTouchMove); window.addEventListener('resize', onWindowResize); } function onWindowResize(e) { width = window.innerWidth; height = window.innerHeight; } function onTouchMove(e) { if( e.touches.length > 0 ) { for( var i = 0; i < e.touches.length; i++ ) { addParticle( e.touches[i].clientX, e.touches[i].clientY, possibleEmoji[Math.floor(Math.random()*possibleEmoji.length)]); } } } function onMouseMove(e) { cursor.x = e.clientX; cursor.y = e.clientY; addParticle( cursor.x, cursor.y, possibleEmoji[Math.floor(Math.random()*possibleEmoji.length)]); } function addParticle(x, y, character) { var particle = new Particle(); particle.init(x, y, character); particles.push(particle); } function updateParticles() { // Updated for( var i = 0; i < particles.length; i++ ) { particles[i].update(); } // Remove dead particles for( var i = particles.length -1; i >= 0; i-- ) { if( particles[i].lifeSpan < 0 ) { particles[i].die(); particles.splice(i, 1); } } } function loop() { requestAnimationFrame(loop); updateParticles(); } /** * Particles */ function Particle() { this.lifeSpan = 120; //ms this.initialStyles ={ "position": "fixed", "top": "0", "display": "block", "pointerEvents": "none", "z-index": "10000000", "fontSize": "24px", "will-change": "transform" }; // Init, and set properties this.init = function(x, y, character) { this.velocity = { x: (Math.random() < 0.5 ? -1 : 1) * (Math.random() / 2), y: 1 }; this.position = {x: x - 10, y: y - 20}; this.element = document.createElement('span'); this.element.innerHTML = character; applyProperties(this.element, this.initialStyles); this.update(); document.body.appendChild(this.element); }; this.update = function() { this.position.x += this.velocity.x; this.position.y += this.velocity.y; this.lifeSpan--; this.element.style.transform = "translate3d(" + this.position.x + "px," + this.position.y + "px,0) scale(" + (this.lifeSpan / 120) + ")"; } this.die = function() { this.element.parentNode.removeChild(this.element); } } /** * Utils */ // Applies css `properties` to an element. function applyProperties( target, properties ) { for( var key in properties ) { target.style[ key ] = properties[ key ]; } } init(); })(); }
/*! * maptalks.e3 v0.4.5 * LICENSE : MIT * (c) 2016-2017 maptalks.org */ /*! * requires maptalks@^0.25.0 */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('maptalks'), require('echarts')) : typeof define === 'function' && define.amd ? define(['exports', 'maptalks', 'echarts'], factory) : (factory((global.maptalks = global.maptalks || {}),global.maptalks,global.echarts)); }(this, (function (exports,maptalks,echarts) { 'use strict'; function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); } var options = { 'container': 'front', 'renderer': 'dom', 'hideOnZooming': false, 'hideOnMoving': false, 'hideOnRotating': false }; var E3Layer = function (_maptalks$Layer) { _inherits(E3Layer, _maptalks$Layer); function E3Layer(id, ecOptions, options) { _classCallCheck(this, E3Layer); var _this = _possibleConstructorReturn(this, _maptalks$Layer.call(this, id, options)); _this._ecOptions = ecOptions; return _this; } E3Layer.prototype.getEChartsOption = function getEChartsOption() { return this._ecOptions; }; E3Layer.prototype.setEChartsOption = function setEChartsOption(ecOption) { this._ecOptions = ecOption; if (this._getRenderer()) { this._getRenderer()._clearAndRedraw(); } return this; }; E3Layer.prototype.toJSON = function toJSON() { return { 'type': this.getJSONType(), 'id': this.getId(), 'ecOptions': this._ecOptions, 'options': this.config() }; }; E3Layer.fromJSON = function fromJSON(json) { if (!json || json['type'] !== 'E3Layer') { return null; } return new E3Layer(json['id'], json['ecOptions'], json['options']); }; return E3Layer; }(maptalks.Layer); E3Layer.mergeOptions(options); E3Layer.registerJSONType('E3Layer'); E3Layer.registerRenderer('dom', function () { function _class(layer) { _classCallCheck(this, _class); this.layer = layer; } _class.prototype.render = function render() { if (!this._container) { this._createLayerContainer(); } if (!this._ec) { this._ec = echarts.init(this._container); this._prepareECharts(); this._ec.setOption(this.layer._ecOptions, false); } else if (this._isVisible()) { this._ec.resize(); } this.layer.fire('layerload'); }; _class.prototype.drawOnInteracting = function drawOnInteracting() { if (this._isVisible()) { this._ec.resize(); } }; _class.prototype.needToRedraw = function needToRedraw() { var map = this.getMap(); var renderer = map._getRenderer(); return map.isInteracting() || renderer && (renderer.isStateChanged && renderer.isStateChanged() || renderer.isViewChanged && renderer.isViewChanged()); }; _class.prototype.getMap = function getMap() { return this.layer.getMap(); }; _class.prototype._isVisible = function _isVisible() { return this._container && this._container.style.display === ''; }; _class.prototype.show = function show() { if (this._container) { this._container.style.display = ''; } }; _class.prototype.hide = function hide() { if (this._container) { this._container.style.display = 'none'; } }; _class.prototype.remove = function remove() { this._ec.clear(); this._ec.dispose(); delete this._ec; this._removeLayerContainer(); }; _class.prototype.clear = function clear() { this._ec.clear(); }; _class.prototype.setZIndex = function setZIndex(z) { this._zIndex = z; if (this._container) { this._container.style.zIndex = z; } }; _class.prototype.isCanvasRender = function isCanvasRender() { return false; }; _class.prototype._prepareECharts = function _prepareECharts() { if (!this._registered) { this._coordSystemName = 'maptalks' + maptalks.Util.GUID(); echarts.registerCoordinateSystem(this._coordSystemName, this._getE3CoordinateSystem(this.getMap())); this._registered = true; } var series = this.layer._ecOptions.series; if (series) { for (var i = series.length - 1; i >= 0; i--) { series[i]['coordinateSystem'] = this._coordSystemName; series[i]['animation'] = false; } } }; _class.prototype._createLayerContainer = function _createLayerContainer() { var container = this._container = maptalks.DomUtil.createEl('div'); container.style.cssText = 'position:absolute;left:0px;top:0px;'; if (this._zIndex) { container.style.zIndex = this._zIndex; } this._resetContainer(); var parentContainer = this.layer.options['container'] === 'front' ? this.getMap()._panels['frontStatic'] : this.getMap()._panels['backStatic']; parentContainer.appendChild(container); }; _class.prototype._removeLayerContainer = function _removeLayerContainer() { if (this._container) { maptalks.DomUtil.removeDomNode(this._container); } delete this._levelContainers; }; _class.prototype._resetContainer = function _resetContainer() { var size = this.getMap().getSize(); this._container.style.width = size.width + 'px'; this._container.style.height = size.height + 'px'; }; _class.prototype._getE3CoordinateSystem = function _getE3CoordinateSystem(map) { var CoordSystem = function CoordSystem(map) { this.map = map; this._mapOffset = [0, 0]; }; var me = this; CoordSystem.create = function (ecModel) { ecModel.eachSeries(function (seriesModel) { if (seriesModel.get('coordinateSystem') === me._coordSystemName) { seriesModel.coordinateSystem = new CoordSystem(map); } }); }; CoordSystem.getDimensionsInfo = function () { return ['x', 'y']; }; CoordSystem.dimensions = ['x', 'y']; maptalks.Util.extend(CoordSystem.prototype, { dimensions: ['x', 'y'], setMapOffset: function setMapOffset(mapOffset) { this._mapOffset = mapOffset; }, dataToPoint: function dataToPoint(data) { var coord = new maptalks.Coordinate(data); var px = this.map.coordinateToContainerPoint(coord); var mapOffset = this._mapOffset; return [px.x - mapOffset[0], px.y - mapOffset[1]]; }, pointToData: function pointToData(pt) { var mapOffset = this._mapOffset; var data = this.map.containerPointToCoordinate({ x: pt[0] + mapOffset[0], y: pt[1] + mapOffset[1] }); return [data.x, data.y]; }, getViewRect: function getViewRect() { var size = this.map.getSize(); return new echarts.graphic.BoundingRect(0, 0, size.width, size.height); }, getRoamTransform: function getRoamTransform() { return echarts.matrix.create(); } }); return CoordSystem; }; _class.prototype.getEvents = function getEvents() { return { '_zoomstart': this.onZoomStart, '_zoomend': this.onZoomEnd, '_dragrotatestart': this.onDragRotateStart, '_dragrotateend': this.onDragRotateEnd, '_movestart': this.onMoveStart, '_moveend': this.onMoveEnd, '_resize': this._resetContainer }; }; _class.prototype._clearAndRedraw = function _clearAndRedraw() { if (this._container && this._container.style.display === 'none') { return; } this._ec.clear(); this._ec.resize(); this._prepareECharts(); this._ec.setOption(this.layer._ecOptions, false); }; _class.prototype.onZoomStart = function onZoomStart() { if (!this.layer.options['hideOnZooming']) { return; } this.hide(); }; _class.prototype.onZoomEnd = function onZoomEnd() { if (!this.layer.options['hideOnZooming']) { return; } this.show(); this._clearAndRedraw(); }; _class.prototype.onDragRotateStart = function onDragRotateStart() { if (!this.layer.options['hideOnRotating']) { return; } this.hide(); }; _class.prototype.onDragRotateEnd = function onDragRotateEnd() { if (!this.layer.options['hideOnRotating']) { return; } this.show(); this._clearAndRedraw(); }; _class.prototype.onMoveStart = function onMoveStart() { if (!this.layer.options['hideOnMoving']) { return; } this.hide(); }; _class.prototype.onMoveEnd = function onMoveEnd() { if (!this.layer.options['hideOnMoving']) { return; } this.show(); this._clearAndRedraw(); }; return _class; }()); exports.E3Layer = E3Layer; Object.defineProperty(exports, '__esModule', { value: true }); typeof console !== 'undefined' && console.log('maptalks.e3 v0.4.5, requires maptalks@^0.25.0.'); })));
import React from 'react'; import PropTypes from 'prop-types'; import { useQuery, useSubscription } from '@apollo/client'; import Tables from '../Tables'; import { GET_LAYER, SUBSCRIBE_LAYER_UPDATE } from './requests'; const LayerTablesWithData = ({ update }) => { const { ...initialResult } = useQuery(GET_LAYER, { variables: { id: '1' } }); const { ...updatedResult } = useSubscription(SUBSCRIBE_LAYER_UPDATE, { variables: { id: '1' } }); if (initialResult.loading || initialResult.error) return null; const { objects: loadedTables } = update && updatedResult.data ? updatedResult.data.layer : initialResult.data.layer; return <Tables objects={loadedTables} />; }; LayerTablesWithData.propTypes = { update: PropTypes.bool.isRequired }; export default LayerTablesWithData;
import RestfulDomainModel from '../../base/RestfulDomainModel' class Model extends RestfulDomainModel { } export default new Model([ { promotion_id: { name: 'ID' } }, { gid: { name: '商品id' } }, { image: { name: '图片' } }, { title: { name: '名称' } }, { price: { name: '价格' } }, { sales: { name: '全网销量' } }, { elastic_type: { name: 'elastic_type' } }, { promotion_source: { name: 'promotion_source' } }, { mtime: { name: '更新时间' } }, { ctime: { name: '创建时间' } } ], '/clouddata_douyin/promotion')
describe('Buttons - options - buttons.titleAttr', function() { let params; dt.libs({ js: ['jquery', 'datatables', 'buttons'], css: ['datatables', 'buttons'] }); describe('Functional tests', function() { dt.html('basic'); it('Empty if no title set', function() { $('#example').DataTable({ dom: 'Bfrtip', buttons: [ { name: 'first', text: 'button1' }, { name: 'second', text: 'button2', titleAttr: 'test2' }, { name: 'third', text: 'button3', titleAttr: function() { params = arguments; return 'test3'; } } ] }); expect($('button.dt-button:eq(0)').attr('title')).toBe(undefined); }); it('Can use string', function() { expect($('button.dt-button:eq(1)').attr('title')).toBe('test2'); }); it('Can use function', function() { expect($('button.dt-button:eq(2)').attr('title')).toBe('test3'); }); it('Function passed correct params', function() { expect(params.length).toBe(3); expect(params[0] instanceof $.fn.dataTable.Api).toBe(true); expect(params[1] instanceof $).toBe(true); expect(params[2].name).toBe('third'); }); }); });
let presidentArray = []; let president1 = { name: "Theodore Roosevelt", bio: "Theodore Roosevelt Jr. was an American statesman, author, explorer, soldier, naturalist, and reformer who served as the 26th President of the United States from 1901 to 1909.", img: "img/roosevelt.jpg", from: "From: 1901", to: "To: 1909" }; let president2 = { name: "Andrew Jackson", bio: "Andrew Jackson was an American soldier and statesman who served as the seventh President of the United States from 1829 to 1837. He is burried at his plantation in Hermitage, TN.", img: "img/jackson.jpg", from: "From: 1829", to: "To: 1837" }; let president3 = { name: "Ulysses S. Grant", bio: "Ulysses S. Grant, born Hiram Ulysses Grant, was the 18th President of the United States. Grant worked closely with President Abraham Lincoln to lead the Union Army to victory over the Confederacy in the American Civil War.", img: "img/grant.jpg", from: "From: 1869", to: "To: 1877" }; console.log(presidentArray) presidentArray.push(president1); presidentArray.push(president2); presidentArray.push(president3); let presidentContainer = document.getElementById("presidentContainer"); let textInput = document.getElementById("textInput"); function buildPresidentPage(president) { let presidentCard = ""; presidentCard += '<section class="president">'; presidentCard += '<div class="name">'; presidentCard += '<h2>' + president.name + '</h2>'; presidentCard += '</div>'; presidentCard += '<div class="bio">'; presidentCard += '<p>' + president.bio + '</p>'; presidentCard += '<div class="term">'; presidentCard += '<h6>' + president.from + '</h6>'; presidentCard += '<h6>' + president.to + '</h6>'; presidentCard += '</div>'; presidentCard += '<div>'; presidentCard += '<img src="' + president.img + '">'; presidentCard += '</div>' presidentCard += '</section>'; return presidentCard; }; function printPresidentArrayToDom(presidentArray) { for (var i = 0; i < presidentArray.length; i++ ) { let currentPresident = presidentArray[i]; let presidentDomString = buildPresidentPage(currentPresident); presidentContainer.innerHTML += presidentDomString; }; }; printPresidentArrayToDom(presidentArray); let presidentCardContainer = document.getElementById('presidentCardContainer'); let selectedPresident; //When you click on one of the person elements, a dotted border should appear around it. for (let i = 0; i < presidentContainer.childNodes.length; i++) { presidentContainer.childNodes[i].addEventListener("click", function(e) { changeBorder(e); replaceBio(); }); }; function changeBorder(e) { if (e.target.classList.contains('president')) { selectedPresident = e.target; } else if (e.target.parentNode.classList.contains('president')) { selectedPresident = e.target.parentNode; } else if (e.target.parentNode.parentNode.classList.contains('president')) { selectedPresident = e.target.parentNode.parentNode; } else if (e.target.parentNode.parentNode.parentNode.classList.contains('president')) { selectedPresident = e.target.parentNode.parentNode.parentNode; }; console.log("selectedPresident", selectedPresident); selectedPresident.classList.add('dottedBorder'); }; // When you press the enter/return key when typing in the input field, then the content of the input field should immediately be blank. function replaceBio() { textInput.focus(); textInput.addEventListener('keyup', function(e) { if (e.key === 'Enter') { textInput.value = ''; } else { var currentBio = selectedPresident.childNodes[1].childNodes[0]; console.log("currentBio", currentBio); currentBio.innerHTML = textInput.value; }; }); };
import React from 'react'; import { Button, Rate, Form, Input } from "antd"; import styles from './css/ReviewForm.module.css'; const FormComp = ({ onSubmit, form, isSaving, }) => { const onFinish = e => { e.preventDefault(); form.validateFields((err, values) => { if (!err) { onSubmit(values); return; } }); }; const { getFieldDecorator } = form; return ( <Form onSubmit={onFinish} name= 'review_form' colon="false" layout={'vertical'} className={styles.reviewForm} > <Form.Item label={ <div className={styles.reviewFormLabel}> Rating </div> } > {getFieldDecorator('rating', { initialValue: 4 })(<Rate allowHalf />)} </Form.Item> <Form.Item label={ <div className={styles.reviewFormLabel}> Review </div> } > {getFieldDecorator("note", { initialValue: '' })( <Input bordered='false' placeholder='Start typing...' /> )} </Form.Item> <Form.Item> <Button type="default" htmlType="submit" disabled={isSaving} className={styles.button}> Submit Review </Button> </Form.Item> </Form> ) }; const ReviewForm = Form.create({ name: "review_form" })(FormComp); export default ReviewForm;
import React, { useState, useRef, useContext } from 'react' import Axios from 'axios' import InputStatus from "./inputStatus" import FormConfirmationBanner from "./formConfirmationBanner" import greenCheckmarkIcon from "../images/icon-checkmark.svg" import invalidIcon from "../images/icon-invalid.svg" import playIcon from '../images/play.svg' import pauseIcon from '../images/pause.svg' import StateContext from '../context/stateContext' const ContactForm = () => { const {styleIncomplete, picIsComplete, baseDelay, delayAnimation} = useContext(StateContext) const [name, setName] = useState('') const [email, setEmail] = useState('') const [message, setMessage] = useState('') const [phone, setPhone] = useState('') const [address, setAddress] = useState('') const [nameIsValid, setNameIsValid] = useState(false) const [emailIsValid, setEmailIsValid] = useState(false) const [messageIsValid, setMessageIsValid] = useState(false) const [wasSent, setWasSent] = useState(false) const [bannerIsVisible, setBannerIsVisible] = useState(false) const [bannerIsLoading, setBannerIsLoading] = useState(false) const [isRobot, setIsRobot] = useState(false) const notabotCheckbox = useRef(); const messageField = useRef(); const nameField = useRef(); const emailField = useRef(); const phoneField = useRef(); const addressField = useRef(); const emailRegex = /(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/; function validateName(text) { if (text.replace(/\s/g, '').length) { return true } else { return false } } function validateEmail(email) { return emailRegex.test(email) } function validateMessage(text) { if (text.replace(/\s/g, '').length) { return true } else { return false } } async function handleSubmit(e) { e.preventDefault(); setNameIsValid(validateName(name)); setEmailIsValid(validateEmail(email)); setMessageIsValid(validateMessage(message)); if (nameIsValid && emailIsValid && messageIsValid && !phone && !address) { setBannerIsLoading(true); setBannerIsVisible(true); try { const response = await Axios.post(`/api/ses-send-email`, { name, email, message }); console.log(response) if (response.status === 200) { setWasSent(true); setBannerIsLoading(false); setTimeout(() => { setBannerIsVisible(false) }, 4000) } setName(""); setEmail(""); setMessage(""); setNameIsValid(false); setEmailIsValid(false); setMessageIsValid(false); } catch (error) { console.log(error); setWasSent(false); setBannerIsLoading(false); setTimeout(() => { setBannerIsVisible(false) }, 4000) } } else if (nameIsValid && emailIsValid && messageIsValid && (phone || address)) { setIsRobot(true); // setStatusIsVisible(true); } else { // setStatusIsVisible(true); } } async function handleChange() { if (isRobot && notabotCheckbox.current.checked) { if (nameIsValid && emailIsValid && messageIsValid) { document.getElementById("nab-container").classList.toggle("goodybag--is-visible") notabotCheckbox.current.checked = false setIsRobot(false) setBannerIsLoading(true); setBannerIsVisible(true); try { const response = await Axios.post("/api/ses-send-email", { name, email, message }); if (response.status === 200) { setWasSent(true); setBannerIsLoading(false); setTimeout(() => { setBannerIsVisible(false) }, 4000) } setName(""); setEmail(""); setMessage(""); setNameIsValid(false); setEmailIsValid(false); setMessageIsValid(false); } catch (error) { console.log(error); setWasSent(false); setBannerIsLoading(false); setTimeout(() => { setBannerIsVisible(false) }, 4000) } } else { // setStatusIsVisible(true); } } else { notabotCheckbox.current.disabled = true } } return ( <div className="form-container"> <form onSubmit={e => handleSubmit(e)} autoComplete="off" className="form"> <div id="nab-container" className={`goodybag${isRobot ? " goodybag--is-visible" : ""}`}> <div className="bg--orange-tr border-radius"> <input ref={notabotCheckbox} onChange={handleChange} type="checkbox" name="notabot" id="notabot" disabled={false}/> <label htmlFor="notabot">I am not a robot</label> </div> </div> <div className="form-group"> <label htmlFor="name-field" className="form-group__label color--red animation--slide-in" style={picIsComplete ? delayAnimation(baseDelay, 0) : styleIncomplete}>your name.</label> <div className={`form-group__input${nameIsValid ? " form-group__input--is-valid" : ""} animation--slide-in`} style={picIsComplete ? delayAnimation(baseDelay, 1) : styleIncomplete}> <input ref={nameField} onChange={e => { setName(e.target.value); setNameIsValid(validateName(e.target.value)); }} type="text" name="name" id="name-field" value={name} /> <InputStatus isValid={nameIsValid} /> </div> </div> <div className="form-group"> <label htmlFor="email-field" className="form-group__label color--red animation--slide-in" style={picIsComplete ? delayAnimation(baseDelay, 2) : styleIncomplete}>your email.</label> <div className={`form-group__input${emailIsValid ? " form-group__input--is-valid" : ""} animation--slide-in`} style={picIsComplete ? delayAnimation(baseDelay, 3) : styleIncomplete}> <input ref={emailField} onChange={e => { setEmail(e.target.value); setEmailIsValid(validateEmail(e.target.value)); }} type="email" name="email" id="email-field" value={email} autoComplete="new-password" /> <InputStatus isValid={emailIsValid} /> </div> </div> <div className="form-group"> <label htmlFor="message-field" className="form-group__label color--red animation--slide-in" style={picIsComplete ? delayAnimation(baseDelay, 4) : styleIncomplete}>your message.</label> <div className={`form-group__input${messageIsValid ? " form-group__input--is-valid" : ""} animation--slide-in`} style={picIsComplete ? delayAnimation(baseDelay, 5) : styleIncomplete}> <textarea ref={messageField} onChange={e => { setMessage(e.target.value); setMessageIsValid(validateMessage(e.target.value)); }} name="message" id="message-field" cols="33" rows="5" value={message} autoComplete="new-password" /> <InputStatus isValid={messageIsValid} isLast={true} /> </div> </div> <label htmlFor="phone-field" className="goodybag"></label> <input ref={phoneField} onChange={e => { setPhone(e.target.value); }} type="text" name="phone" id="phone-field" value={phone} autoComplete="new-password" className="goodybag"/> <label htmlFor="address-field" className="goodybag"></label> <input ref={addressField} onChange={e => { setAddress(e.target.value); }} type="text" name="address" id="address-field" value={address} autoComplete="new-password" className="goodybag"/> <div className="form__btn-group animation--slide-in" style={picIsComplete ? delayAnimation(baseDelay, 6) : styleIncomplete}> <button type="submit" className={`btn btn--red${bannerIsLoading ? " btn--loading" : ""}${nameIsValid && emailIsValid && messageIsValid ? "" : " btn--disabled"}`} disabled={bannerIsLoading} style={!bannerIsLoading && bannerIsVisible ? {backgroundColor: "red"} : {}}> { bannerIsLoading ? <div className="loading-icon"><div></div></div> : bannerIsVisible ? <img src={wasSent ? greenCheckmarkIcon : invalidIcon} alt={wasSent ? "valid" : "invalid"} style={wasSent ? {transform: "translateY(3px)"} : {}}/> : "send" } { !bannerIsLoading && !bannerIsVisible && nameIsValid && emailIsValid && messageIsValid ? <span className="animation--shake" style={{display: "inline-block"}}><img src={playIcon} alt="" className="icon-play"/></span> : !bannerIsLoading && !bannerIsVisible && !(nameIsValid && emailIsValid && messageIsValid) ? <span className="" style={{display: "inline-block"}}><img src={pauseIcon} alt="" className="icon-play"/></span> : "" } </button> <FormConfirmationBanner isLoading={bannerIsLoading} wasSent={wasSent} isVisible={bannerIsVisible} /> </div> </form> </div> ) } export default ContactForm
import React, {Component} from 'react'; class Message extends Component { constructor(props) { super(props); } componentWillMount(){ // this.setState({ // reactJson:['div',{className:'ez-led'},'Hello, React!',React.createElement("div",{className:"ez-led"},"Hello, React!")] // }) } render(){ return ( <div> 按钮 </div> ) } } export default Message;
/** * 1.创建一个元素 p,内容 glj * 2.将 p 插入 id 为 draft 的孩子末尾 * 3.再创建一个元素 p,内容 glj2 并插入 id 为 draft 的孩子头部 * 4.3s 后删除 glj2 所在的 p 元素 * 5.获取 glj 所在的 p 元素(两种方法) * 6.获取 glj 的标签名 * 7.设置 glj 的属性 name 为 glj * 8.获取 glj 的父节点 */ const draft = document.querySelector('#draft'); const p1 = document.createElement('p'); p1.innerText = 'glj'; draft.appendChild(p1); const p2 = document.createElement('p'); p2.innerText = 'glj2'; draft.insertBefore(p2, draft.childNodes[0]); setTimeout(function () { draft.removeChild(draft.firstChild) }, 3000); const a = document.querySelector('#draft').children[2]; const a1 = document.querySelector('#draft').lastElementChild; console.log(a.localName); a.setAttribute('name', 'glj'); console.log(a.parentNode);
$(function(){ //设置foot下的当前时间 var nowtime=new Date(); var nowyear=nowtime.getFullYear(); $(".nowtime").html(nowyear); $(".miaosha").click(function(){ $(".mask").show(); $(".tc1").show(); }) $(".close_tc").click(function(){ $(".mask").hide(); $(this).parent().hide(); }) // 弹幕 var num = 0; function suiji(){ num++, num>=$(".banposi p").length&&(num=0),$box.eq(num).css({top:Math.ceil(540*Math.random())}),$box.eq(num).animate({left:"-100%"},12e3,"linear",function(){$(this).removeAttr("style").css({top:Math.ceil(540*Math.random())})}) } var num=-1,$box=$(".banposi p"),looper=setInterval(suiji,2500); $(".guan_danmu").click(function(){ $(".banposi p").hide(); clearInterval(looper); }) });
import { isArray } from "util"; //import { Movie } from "./movie.model"; var Movie = require("./movie.model"); var Session = require("./session.model"); var Cinema = require("./cinema.model"); var bodyParser = require("body-parser"); var tmdb = require("./tmdb"); //Returns all movies irrespective of active sessions export async function getAllMovies(req, res) { // .select("+updated"); to included an excluded field const _limit = Number(req.query.limit) || 10; const _skip = _limit * Number(req.query.skip) || 0; try { let movies = await Movie.find() .limit(_limit) .skip(_skip); //TO DO: add some sort capability to increase relevance handleResponse({ reponse: res, status: "success", content: movies }); } catch (error) { handleResponse({ reponse: res, status: "error", message: error.message }); } } // TODO: determine how to determine whats and active session //Returns all movies with only active sessions export async function getMoviesWithActiveSessions(req, res) { // .select("+updated"); to included an excluded field const _limit = Number(req.query.limit) || 10; const _skip = _limit * Number(req.query.skip) || 0; var movieSessions = []; try { //refactor to return on movies with live sessions let movies = await Movie.find() .limit(_limit) .skip(_skip); //async for (const movie of movies){} for (const movie of movies) { const sessions = await Session.find({ movie: movie._id }).populate( "cinema" ); var { _id, title, language, rating, tags, genres, poster, trailer, duration, synopsis, crew, leadActors, cast, slug } = movie; const movieSession = { _id, title, language, rating, duration, sessions, tags, genres, poster, trailer, synopsis, crew, leadActors, cast, slug }; movieSessions.push(movieSession); } handleResponse({ reponse: res, status: "success", content: movieSessions }); } catch (error) { console.log("error"); handleResponse({ reponse: res, status: "error", message: error.message }); } } //Add one or more movies based on name/s passed in the request body export function createMovieByName(req, res) { let movieNames = req.body.movieNames; //If one movie is passed a string turn it into an array movieNames = isArray(movieNames) ? movieNames : [movieNames]; let promises = []; movieNames.forEach(movieName => { promises.push( Promise.resolve(async () => { let dbMovie = await tmdb.retrieveMovie({ movieName: movieName }); let modelMovie = new Movie({}); Object.assign(modelMovie, dbMovie); await modelMovie.save(); return modelMovie; }) ); }); Promise.all(promises) .then(movies => { console.log(`Succesfully created movie/s ${movieNames.join()}`); console.log(movies[0].title); handleResponse({ reponse: res, status: "success", message: `Succesfully created movie/s ${movieNames.join()}`, contentx: movies }); }) .catch(err => { console.log( `Error creating movie/s : ${movieNames.join()} Error : ${err}` ); handleResponse({ reponse: res, status: "error", message: `Error creating movie/s ${movieNames.join()} in database` }); }); } function handleResponse({ reponse, status, message = "", content = [] }) { console.log(content); //http Status let httpStatus = status == "success" ? 200 : 500; //Set override message if no message passed if (!message) { if (status == "success") { message = content.length > 0 ? "Successfully retrieved movies" : "No movies available for the specified criteria"; } else if (status == "error") { message = "Failure occured in retrieving movies"; } } const _status = { status, message }; const obj = { status: _status, content }; reponse.status(httpStatus).json(obj); }
/** * @class controllers.Novidade.PopUpNovidades * Popup contendo a lista dos módulos com descrição. * @alteracao 04/03/2015 180419 Projeto Carlos Eduardo Santos Alves Domingos * Criação. */ var args = arguments[0] || {}; /** * @method init * Construtor da classe. * @alteracao 04/03/2015 180419 Projeto Carlos Eduardo Santos Alves Domingos * Criação. */ $.init = function(parans){ Alloy.Globals.configPopUp($); }; /** * @event fechar * Fecha a popup. * @alteracao 04/03/2015 180419 Projeto Carlos Eduardo Santos Alves Domingos * Criação. */ function fechar(){ $.close(); } /** * @event listar * Mostra a lista de novidades para o módulo selecionado. * @alteracao 04/03/2015 180419 Projeto Carlos Eduardo Santos Alves Domingos * Criação. */ function listar(e){ var lstNovidades = Alloy.createController("Novidade/ListaNovidades", {descrModulo: e.source.desc, numModulo: e.source.numero}); Alloy.Globals.Transicao.proximo(lstNovidades, lstNovidades.init, {}); }
const db = require('../database/dbConfig.js'); module.exports = { getUsers, addUser, getUserBy, } function getUsers() { return db('users'); } function addUser(user) { return db('users') .insert(user) // .then(newProject => getProjectsByID(newProject[0].id)); } function getUserBy(value) { return db('users') .where(value) .first(); }
/*------------------------------------------- ForcedOscillatin2D.js 強制振動 --------------------------------------------*/ var canvas; //キャンバス要素 var ctx;//コンテキスト var dt, actTime, mass, constK, length0, disp0, amp, omega, forceE; var gamma ;//減衰率 var X0, Y0;//表示座標原点(ピクセル単位、canvas座標) var widthX, widthY;//データ表示幅(ピクセル単位) var numData; function main() { //canvas要素を取得する canvas = document.getElementById('myCanvas'); //描画コンテキストを取得 ctx = canvas.getContext("2d"); getData(); } function getData() {  dt = parseFloat(form1.dt.value);//計算時のタイムステップ[s]  actTime = parseFloat(form1.actTime.value);//計算時間[s]  mass = parseFloat(form1.mass.value);//質量[kg]  constK = parseFloat(form1.constK.value);//バネ定数[N/m]  length0 = parseFloat(form1.length0.value);//自然長[m]  disp0 = parseFloat(form1.disp0.value);//初期変位量[m] amp = parseFloat(form1.amp.value);//縦軸振幅[m] gamma = parseFloat(form1.gamma.value);//減衰率[1/s] omega = parseFloat(form1.omega.value);//強制信号角振動数[1/s] forceE = parseFloat(form1.forceE.value);//強制信号振幅[m] //共振角周波数 var omega0 = Math.sqrt(constK / mass); form1.omega0.value = omega0.toString(); drawCoordinates(); } function drawCoordinates() { //キャンバスを白でクリア clearCanvas("white"); //表示座標原点 var w0 = 50; X0 = w0; Y0 = canvas.height / 2; widthX = canvas.width - 2*w0;//横軸表示幅(ピクセル単位) widthY = canvas.height/2 - w0;//片側(ピクセル単位) //座標軸の表示 //x軸 drawLine(X0, Y0, X0 + widthX, Y0, "rgb(50, 50, 255)", 1); //y軸 drawLine(X0, w0, X0, canvas.height-w0, "rgb(50, 50, 255)", 1); //x軸目盛 drawLine(X0 + widthX/2, Y0, X0 + widthX/2 , Y0 - 20, "rgb(100, 100, 100)", 1); drawLine(X0 + widthX, Y0, X0 + widthX, Y0 - 40, "rgb(100, 100, 255)", 1); drawText(actTime+"[s]", X0 + widthX-5, Y0 + 20, "black", 2, 2); //y軸目盛 drawLine(X0, Y0 - widthY, X0 + 20, Y0 - widthY, "rgb(100, 100, 255)", 1); drawLine(X0, Y0 + widthY, X0 + 20, Y0 + widthY, "rgb(100, 100, 255)", 1); drawText("0", X0 - 20, Y0 + 5, "black", 2, 2); drawText(amp, X0 - 30, Y0 - widthY + 5, "black", 2, 2); drawText("-"+amp, X0 - 35, Y0 + widthY + 5, "black", 2, 2); drawText("変位量[m]", X0 -40, Y0 - widthY -15, "black", 2, 2); } function onClickStart() { var numData = parseFloat(form1.numData.value);//データ個数  var factorX = widthX / numData;//横軸表示倍率(1データ個数当たりピクセル数)  var factorY = widthY / amp ;//縦軸表示倍率(変位1[m]当たりのピクセル数 //データ取り込み間隔 var interval = Math.round((actTime / dt) / numData); var data0 = []; var length = length0 + disp0; var vel = 0.0; var pos = length;//一端は原点に固定 var time = 0.0;//経過時間 var count = 0;//データ個数のカウント var cnt = 0;//インターバルのカウント while (count < numData) { var disp = pos - length0; var acc = -constK * disp / mass - 2.0 * gamma * vel + forceE * Math.sin(omega * time); vel += acc * dt; pos += vel * dt;     time += dt; if (cnt == 0) {//interval回に1回保存 data0.push([X0 + count * factorX, Y0 - disp * factorY]) ;//変位量のデータ(2次元) count++; } cnt++; if (cnt == interval) cnt = 0; } drawLines(data0, "black", 1); } //------------------------------------------------------------- function onClickClear() { drawCoordinates(); } function onChangeData() { getData(); }
// harness.js contains definitions used for script testing try { include("harness.js"); } catch (ex) { // file might not exist, so don't get in a twist about it... } include("constants.js"); include("defaults.js"); include("string.js"); include("sleep.js"); function syncShell() { dialogue.expect(SHELL_PROMPT); dialogue.send(RETURN); dialogue.expect(SHELL_PROMPT); } function logout() { dialogue.send(LOGOUT_COMMAND + RETURN); dialogue.expect(LOGOUT_COMMAND); } function executeCommand(command) { dialogue.send(command + RETURN); dialogue.expect(LINE_OF_TEXT); // command echo-back var ctx = dialogue.expect(SHELL_PROMPT); return ctx.input; } function executeAndCollectLines(command) { dialogue.send(command + RETURN); dialogue.expect(LINE_OF_TEXT); // command echo-back var done = false; var lines = new Array(); while (!done) { dialogue.expect( SHELL_PROMPT, function(ctx) { done = true; }, LINE_OF_TEXT, function(ctx) { lines.push(ctx.matchResult.group(1)); } ); } return lines; } function priorityColor(priority) { if (priority == "CRITICAL") { return COLOR_CRITICAL; } else if (priority == "HIGH") { return COLOR_HIGH; } return COLOR_INFO; }
import axios from 'axios' const _baseUrl = 'http://localhost:3100/api/' export default { // 带参数的post haveParams(url,params){ return axios.post(_baseUrl+url,params) }, // 不带参数的get noParams(url){ return axios.get(_baseUrl+url) }, haveParamsGet(url,params){ return axios.get(_baseUrl+url,params) }, };
const http = require('http') const server = new http.Server(); // http.Server提供的事件有: // request:当客户端请求到来时,该事件被触发,提供两个参数req和res,表示请求和响应信息,是最常用的事件 // connection:当TCP连接建立时,该事件被触发,提供一个参数socket,是net.Socket的实例 // close:当服务器关闭时,触发事件(注意不是在用户断开连接时) server.on('request', function (req, res) { res.writeHead(200, { "content-type": "text/plain" }); res.write("hello nodejs"); res.end(); }) server.on('connection') server.listen(3001) console.log('http://localhost:3001')
import React from "react"; import "./Notifications.css"; import NotificationItem from "./NotificationItem"; import { getLatestNotification } from "../utils/utils"; import closeButton from "../assets/close-icon.png"; import PropTypes from "prop-types"; import NotificationItemShape from "./NotificationItemShape"; export default function Notifications({ displayDrawer, listNotifications }) { return ( <> <div className="menuItem">Your notifications</div> { displayDrawer ? (<div className="Notifications"> <button style={{ right: 45, border: "none", position: "absolute", background: "transparent", }} aria-label="close" onClick={() => console.log("Close button has been clicked")} > <img src={closeButton} alt="close button icon" /> </button> <p>Here is the list of notifications</p> <ul> {listNotifications.length === 0 ? (<NotificationItem value='No new notification for now' type='no-new' />) : <></>} {listNotifications.map((not) => (<NotificationItem key={not.id} type={not.type} value={not.value} html={not.html} />))} </ul> </div>) : <></> } </> ); } Notifications.defaultProps = { displayDrawer: false, listNotifications: [] }; Notifications.propTypes = { displayDrawer: PropTypes.bool, listNotifications: PropTypes.arrayOf(NotificationItemShape) };
import React, { Component,Fragment} from 'react'; import { FenleiWrap, FenleiNav, FenleiNavItem, FenleiContent, FenleiContentItem, Img, Loadcontainer } from './styledComponent' import Animates from 'components/highorder/animates.js' import BScroll from "better-scroll" import Loading from 'components/common/loading' class Fenlei extends Component { constructor(){ super() this.state={ fenleiList:[], fenleiContent:[], currentIndex:0, dis:false, } } render() { // console.log(this.state.dis) return ( <Fragment> <FenleiWrap> <div ref={el=>{ this.FenleiNavScroll=el }}> <FenleiNav> { this.state.fenleiList.map((v,i)=>{ return( <FenleiNavItem key={v.id} onTouchStart={(e)=>this.handleClick(v,i,e)} active={this.state.currentIndex===i} > <span>{v.name}</span> <p></p> </FenleiNavItem> ) }) } </FenleiNav> </div> <div ref={el => { this.FenleiContentScroll = el }}> <FenleiContent> { this.state.fenleiContent.map((val) => { return ( <FenleiContentItem key={val.id} > <Img> <img src={val.activePic} alt="" /> </Img> <span>{val.name}</span> </FenleiContentItem> ) }) } </FenleiContent> </div> </FenleiWrap> <Loadcontainer dis={this.state.dis}> <Loading></Loading> </Loadcontainer> </Fragment> ); } componentDidMount() { // console.log(this.state.dis) fetch('/api/navigation/listNew?param=%7B%22id%22%3A0%2C%22depth%22%3A0%2C%22type%22%3A1%7D',{ method:'get', headers: { 'appKey': 'ef1fc57c13007e33', "appVersion": "3.9.0" }, }) .then(response=>{ return response.json() }) .then(result=>{ // console.log(result.data) this.setState({ fenleiList:result.data||[], fenleiContent: result.data && result.data[0].subNavigations, dis:!!!this.state.dis }) }) // console.log(this.state.dis) this.FenleiScroll=new BScroll(this.FenleiNavScroll,{ click:true, // bounce:false, }) this.ContentScroll = new BScroll(this.FenleiContentScroll, { click: true, // bounce:false, }) } handleClick(v,i,e){ this.setState({ currentIndex:i }) this.getZero(e) //显示菜单 // console.log(v.id) this.setState({ fenleiContent:this.fillterContent(i) }) // console.log(this.fillterContent(i)) this.ContentScroll.scrollTo(0,0) } getZero(e){ let clientY = e.touches[0].clientY let isTopok = clientY-44 < 120 let isBottomok = clientY - 44 -(window.innerHeight - 94)> -120 // console.log(isTopok) if(isTopok){ this.FenleiScroll.scrollBy(0,200,300) this.FenleiScroll.refresh()//解决回弹问题 // console.log("ok") } if(isBottomok){ this.FenleiScroll.scrollBy(0, -200, 300) this.FenleiScroll.refresh()//解决回弹问题 } } fillterContent(i){ // console.log(this.state.fenleiList[i].subNavigations) return this.state.fenleiList[i].subNavigations } } export default Animates(Fenlei)
/** * @param {number[][]} grid * @return {number} */ var projectionArea = function(grid) { let top = 0, front = 0, side = 0; const frontPair = []; // TOP grid.forEach((elem) => { elem.forEach((val) => { if (val > 0) { top++; } }); }); // SIDE grid.forEach((elem) => { let current = 0; elem.forEach((val) => { if (current < val) { current = val; } }); // console.log(current); side += current; }); // FRONT grid.forEach((elem) => { elem.forEach((val, key) => { if (frontPair[key] === undefined) { frontPair[key] = val; } else if (val > frontPair[key]) { frontPair[key] = val; } }); }); front = frontPair.reduce((total, crr) => total + crr, 0); return top + side + front; };
const is = require('../lib/types'); describe('Types', () => { it('is true for arrays', () => { const isArray = is.array([]); expect(isArray).toEqual(true); }); it('is false for objects', () => { const isArray = is.array({}); expect(isArray).toEqual(false); }); it('is true for objects', () => { const isObject = is.object({}); expect(isObject).toEqual(true); }); it('is false for arrays', () => { const isObject = is.object([]); expect(isObject).toEqual(false); }); });
import api from './api' const resource = 'transactions' export default { placeOrder (payload) { return api().post(`${resource}/trade`, payload) } }
var app = require('express')(); var http = require('http').Server(app); var io = require("socket.io")(http); var clients = []; io.on("connection", (socket) => { console.log("Client connected"); clients.push(socket); socket.on('chat', message=>{ clients.forEach(client=>{ io.emit('chat', message); }); }); socket.on('disconnect', () =>{ clients.pop(socket); console.log('Client disconnected') }); }) setInterval(() => io.emit('time', new Date().toTimeString()), 1000); module.exports = {"app": app, "server":http, "socket":io}
import React from "react"; import { Link, Redirect } from "react-router-dom"; import { Container, Button, Header } from "semantic-ui-react"; import AuthService from "services/api/auth.js"; export default class Logout extends React.Component { render() { if (AuthService.isAuthenticated) { AuthService.logout(); return null; } else { return ( <Redirect to="/"></Redirect> ); } } }
const name = document.querySelector('#name'); const title = document.querySelector('#title'); const email = document.querySelector('#email'); const meassage = document.querySelector('#message'); const contactForm = document.querySelector('form'); const submitButton = document.querySelector('input[type=submit]'); submitButton.addEventListener('click', e => { e.preventDefault(); validateName(name); validateEmail(email); validateTitle(title); validateMessage(message) if(validateName(name) && validateEmail(email) && validateTitle(title) && validateMessage(message)) { window.alert("Form Submitted"); contactForm.reset(); } }) const flagIfInvalid = (field, isValid, errorMessage="error") => { let errorNode = field.previousElementSibling.lastChild if (isValid) { field.classList.remove('error'); errorNode.style.display = "none"; } else { field.classList.add('error'); errorNode.innerHTML = errorMessage; errorNode.style.display = "inline"; } } const validateName = (field) => { let errorMessage = "Error! - must contain only alphabets atleast 4 character long "; const regex = /^[A-z ]{4,}$/; let isValid = regex.test(field.value); flagIfInvalid(field, isValid, errorMessage); return isValid; } const validateEmail = (field) => { let errorMessage = "Error! - Invalid email address"; const regex = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/; let isValid = regex.test(field.value); flagIfInvalid(field, isValid, errorMessage); return isValid; } const validateTitle = (field) => { let errorMessage = "Error! - must contain only alphabet 2 to 10 character long"; const regex = /^[a-zA-Z.]{2,10}/; let isValid = regex.test(field.value); flagIfInvalid(field, isValid, errorMessage); return isValid; } const validateMessage = (field) => { let errorMessage = "Error! - must be atleast 20 character long" let isValid = message.value.length >= 20 ? true : false; flagIfInvalid(field, isValid, errorMessage); return isValid; }
class Point{ constructor(x,y,ratio){ this.ratio = ratio; this.startX = 0; this.startY = 0; this.textX = x*1; this.textY = -y; this.x = parseFloat(x)*this.ratio; this.y = parseFloat(y)*this.ratio; this.angle = atan2(this.y,this.x); } drawPoint(name){ strokeWeight(10); point(this.x, this.y); push(); translate(this.x,this.y); noStroke(); text(name + ": ("+this.textX+","+this.textY+")",10 ,0); pop(); } } class PointCollection{ constructor(ratio){ this.list = new Array(); this.ratio = ratio; } addPoint(x,y){ this.list.push(new Point(x,y,this.ratio)); } updatePoint(x,y,i){ this.list[i] = new Point(x,y,this.ratio); } } class PointController{ constructor(ratio){ this.ratio = ratio this.pointCol = new PointCollection(this.ratio); this.totalPoint = 0; } addPoint() { this.totalPoint +=1 var parent = select('#controller-container'); var temp = createDiv( '<h4> POINT '+ this.totalPoint + '</h4>'+ '<p>coordinate x</p>'+ '<input id="point-x-' + this.totalPoint + '" type="number" name="" value="" placeholder="Coordinate x">' + '<p>coordinate y</p>'+ '<input id="point-y-' + this.totalPoint + '" type="number" name="" value="" placeholder="Coordinate y">' ); temp.id('vector-card'); parent.child(temp); this.currX = select('#point-x-'+this.totalPoint).value(); this.currY = select('#point-y-'+this.totalPoint).value(); this.pointCol.addPoint(this.currX,this.currY); } drawResult(){ if(this.totalPoint == 0){ return; } else{ for(var i = 0; i < this.totalPoint; i++){ this.currX = select('#point-x-'+(i+1)).value(); this.currY = select('#point-y-'+(i+1)).value(); this.currX = this.currX; this.currY = -this.currY; this.pointCol.updatePoint(this.currX,this.currY,i); fill(255); this.pointCol.list[i].drawPoint("P" + parseInt(i+1)); } } } } class Shape{ constructor(object,ratio){ this.ratio = ratio; this.object = object; this.toogle = 0; } callShape(){ this.toogle++; } drawResult(){ if(this.object.totalPoint == 0){ return; } else{ if(this.toogle % 2 == 0){ return; } else{ fill(255,255,255,0); strokeWeight(2); beginShape(); for(var i = 0; i< this.object.totalPoint; i++){ this.currX = select('#point-x-'+(i+1)).value(); this.currY = select('#point-y-'+(i+1)).value(); this.currX = this.currX*ratio; this.currY = -this.currY*ratio; vertex(this.currX,this.currY); } vertex(select('#point-x-1').value()*ratio,-select('#point-y-1').value()*ratio); endShape(); } } } }
var searchData= [ ['window',['Window',['../classWindow.html#a2e2ce3cfbd3e468d389d8a9212e7b2ac',1,'Window']]] ];
import React from "react"; import cn from "../../utils/classnames"; import "./Grid.css"; export function Grid({ children, columns, columnsMobile, gap }) { const classes = cn({ grid: true, [`grid--columns-${columns}`]: columns, [`grid--columns-mobile-${columnsMobile}`]: columnsMobile, [`grid--gap-${gap}`]: gap, }); return <div className={classes}>{children}</div>; } export function GridItem({ children, style }) { const classes = cn({ grid__item: true, }); return ( <div className={classes} style={style}> {children} </div> ); }
import { Link, useHistory } from 'react-router-dom'; import { useDispatch, useSelector } from 'react-redux'; import { useFormik } from 'formik'; import * as Yup from 'yup'; import {roleChange, usernameChange} from "../../../store/actions/app"; const Sign = () => { const dispatch = useDispatch(); const history = useHistory(); let users = useSelector((state) => state.appReducer.users) const { handleChange, handleSubmit, values, touched, errors } = useFormik({ initialValues: { email: '', password: '', }, validationSchema: Yup.object({ email: Yup.string() .email('Invalid email address') .required('Required email'), password: Yup.string() .min(6, 'Password should be longer 6 characters') .required(), }), onSubmit: (values) => { const mail = values.email; const pass = values.password; users.forEach((el) => { if(el.email === mail && el.password === pass){ dispatch(roleChange(el.role)) dispatch(usernameChange(el.name)) history.push('/'); } }); }, }); return ( <div> <form onSubmit={handleSubmit}> <label htmlFor="email">Enter you email</label> <input id="email" name="email" type="email" placeholder="email" onChange={handleChange} value={values.email} /> {touched.email && errors.email ? <div>{errors.email}</div> : null} <label htmlFor="password">Enter you password</label> <input id="password" name="password" type="password" placeholder="Password" onChange={handleChange} /> {touched.password && errors.password ? ( <div>{errors.password}</div> ) : null} <button type="submit"> Sign </button> <Link to="/registration"> Registration </Link> </form> </div> ); }; export default Sign;
/** * ownCloud * * @author Vincent Petry * @copyright Copyright (c) 2014 Vincent Petry <pvince81@owncloud.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE * License as published by the Free Software Foundation; either * version 3 of the License, or any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU AFFERO GENERAL PUBLIC LICENSE for more details. * * You should have received a copy of the GNU Affero General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. * */ describe('OCA.Files.FileList tests', function() { var FileInfo = OC.Files.FileInfo; var testFiles, testRoot, notificationStub, fileList, pageSizeStub; var bcResizeStub; var filesClient; var filesConfig; var redirectStub; /** * Generate test file data */ function generateFiles(startIndex, endIndex) { var files = []; var name; for (var i = startIndex; i <= endIndex; i++) { name = 'File with index '; if (i < 10) { // do not rely on localeCompare here // and make the sorting predictable // cross-browser name += '0'; } name += i + '.txt'; files.push(new FileInfo({ id: i, type: 'file', name: name, mimetype: 'text/plain', size: i * 2, etag: 'abc' })); } return files; } beforeEach(function() { filesConfig = new OC.Backbone.Model({ showhidden: true }); filesClient = new OC.Files.Client({ host: 'localhost', port: 80, // FIXME: uncomment after fixing the test OC.webroot //root: OC.webroot + '/remote.php/webdav', root: '/remote.php/webdav', useHTTPS: false }); redirectStub = sinon.stub(OC, 'redirect'); notificationStub = sinon.stub(OC.Notification, 'show'); // prevent resize algo to mess up breadcrumb order while // testing bcResizeStub = sinon.stub(OCA.Files.BreadCrumb.prototype, '_resize'); // init parameters and test table elements $('#testArea').append( '<div id="app-content-files">' + // init horrible parameters '<input type="hidden" id="dir" value="/subdir"/>' + '<input type="hidden" id="permissions" value="31"/>' + // dummy controls '<div id="controls">' + ' <div class="actions creatable"></div>' + ' <div class="notCreatable"></div>' + '</div>' + // uploader '<input type="file" id="file_upload_start" name="files[]" multiple="multiple">' + // dummy table // TODO: at some point this will be rendered by the fileList class itself! '<table id="filestable">' + '<thead><tr>' + '<th id="headerName" class="hidden column-name">' + '<input type="checkbox" id="select_all_files" class="select-all checkbox">' + '<a class="name columntitle" data-sort="name"><span>Name</span><span class="sort-indicator"></span></a>' + '<span id="selectedActionsList" class="selectedActions hidden">' + '<a href class="download"><img/>Download</a>' + '<a href class="delete-selected">Delete</a></span>' + '</th>' + '<th class="hidden column-size"><a class="columntitle" data-sort="size"><span class="sort-indicator"></span></a></th>' + '<th class="hidden column-mtime"><a class="columntitle" data-sort="mtime"><span class="sort-indicator"></span></a></th>' + '</tr></thead>' + '<tbody id="fileList"></tbody>' + '<tfoot></tfoot>' + '</table>' + // TODO: move to handlebars template '<div id="emptycontent"><h2>Empty content message</h2><p class="uploadmessage">Upload message</p></div>' + '<div class="nofilterresults hidden"></div>' + '</div>' ); testRoot = new FileInfo({ // root entry id: 99, type: 'dir', name: '/subdir', mimetype: 'httpd/unix-directory', size: 1200000, etag: 'a0b0c0d0', permissions: OC.PERMISSION_ALL }); testFiles = [new FileInfo({ id: 1, type: 'file', name: 'One.txt', mimetype: 'text/plain', mtime: 123456789, size: 12, etag: 'abc', permissions: OC.PERMISSION_ALL }), new FileInfo({ id: 2, type: 'file', name: 'Two.jpg', mimetype: 'image/jpeg', mtime: 234567890, size: 12049, etag: 'def', permissions: OC.PERMISSION_ALL }), new FileInfo({ id: 3, type: 'file', name: 'Three.pdf', mimetype: 'application/pdf', mtime: 234560000, size: 58009, etag: '123', permissions: OC.PERMISSION_ALL }), new FileInfo({ id: 4, type: 'dir', name: 'somedir', mimetype: 'httpd/unix-directory', mtime: 134560000, size: 250, etag: '456', permissions: OC.PERMISSION_ALL })]; pageSizeStub = sinon.stub(OCA.Files.FileList.prototype, 'pageSize').returns(20); fileList = new OCA.Files.FileList($('#app-content-files'), { filesClient: filesClient, config: filesConfig, enableUpload: true }); }); afterEach(function() { testFiles = undefined; if (fileList) { fileList.destroy(); } fileList = undefined; notificationStub.restore(); bcResizeStub.restore(); pageSizeStub.restore(); redirectStub.restore(); }); describe('Getters', function() { it('Returns the current directory', function() { $('#dir').val('/one/two/three'); expect(fileList.getCurrentDirectory()).toEqual('/one/two/three'); }); it('Returns the directory permissions as int', function() { $('#permissions').val('23'); expect(fileList.getDirectoryPermissions()).toEqual(23); }); }); describe('Adding files', function() { var clock, now; beforeEach(function() { // to prevent date comparison issues clock = sinon.useFakeTimers(); now = new Date(); }); afterEach(function() { clock.restore(); }); it('generates file element with correct attributes when calling add() with file data', function() { var fileData = new FileInfo({ id: 18, name: 'testName.txt', mimetype: 'text/plain', size: 1234, etag: 'a01234c', mtime: 123456 }); var $tr = fileList.add(fileData); expect($tr).toBeDefined(); expect($tr[0].tagName.toLowerCase()).toEqual('tr'); expect($tr.attr('data-id')).toEqual('18'); expect($tr.attr('data-type')).toEqual('file'); expect($tr.attr('data-file')).toEqual('testName.txt'); expect($tr.attr('data-size')).toEqual('1234'); expect($tr.attr('data-etag')).toEqual('a01234c'); expect($tr.attr('data-permissions')).toEqual('31'); expect($tr.attr('data-mime')).toEqual('text/plain'); expect($tr.attr('data-mtime')).toEqual('123456'); expect($tr.find('a.name').attr('href')) .toEqual(OC.webroot + '/remote.php/webdav/subdir/testName.txt'); expect($tr.find('.nametext').text().trim()).toEqual('testName.txt'); expect($tr.find('.filesize').text()).toEqual('1 KB'); expect($tr.find('.date').text()).not.toEqual('?'); expect(fileList.findFileEl('testName.txt')[0]).toEqual($tr[0]); }); it('generates dir element with correct attributes when calling add() with dir data', function() { var fileData = new FileInfo({ id: 19, name: 'testFolder', mimetype: 'httpd/unix-directory', size: 1234, etag: 'a01234c', mtime: 123456 }); var $tr = fileList.add(fileData); expect($tr).toBeDefined(); expect($tr[0].tagName.toLowerCase()).toEqual('tr'); expect($tr.attr('data-id')).toEqual('19'); expect($tr.attr('data-type')).toEqual('dir'); expect($tr.attr('data-file')).toEqual('testFolder'); expect($tr.attr('data-size')).toEqual('1234'); expect($tr.attr('data-etag')).toEqual('a01234c'); expect($tr.attr('data-permissions')).toEqual('31'); expect($tr.attr('data-mime')).toEqual('httpd/unix-directory'); expect($tr.attr('data-mtime')).toEqual('123456'); expect($tr.find('.filesize').text()).toEqual('1 KB'); expect($tr.find('.date').text()).not.toEqual('?'); expect(fileList.findFileEl('testFolder')[0]).toEqual($tr[0]); }); it('generates file element with default attributes when calling add() with minimal data', function() { var fileData = { type: 'file', name: 'testFile.txt' }; clock.tick(123456); var $tr = fileList.add(fileData); expect($tr).toBeDefined(); expect($tr[0].tagName.toLowerCase()).toEqual('tr'); expect($tr.attr('data-id')).toBeUndefined(); expect($tr.attr('data-type')).toEqual('file'); expect($tr.attr('data-file')).toEqual('testFile.txt'); expect($tr.attr('data-size')).toBeUndefined(); expect($tr.attr('data-etag')).toBeUndefined(); expect($tr.attr('data-permissions')).toEqual('31'); expect($tr.attr('data-mime')).toBeUndefined(); expect($tr.attr('data-mtime')).toEqual('123456'); expect($tr.find('.filesize').text()).toEqual('Pending'); expect($tr.find('.date').text()).not.toEqual('?'); }); it('generates dir element with default attributes when calling add() with minimal data', function() { var fileData = { type: 'dir', name: 'testFolder' }; clock.tick(123456); var $tr = fileList.add(fileData); expect($tr).toBeDefined(); expect($tr[0].tagName.toLowerCase()).toEqual('tr'); expect($tr.attr('data-id')).toBeUndefined(); expect($tr.attr('data-type')).toEqual('dir'); expect($tr.attr('data-file')).toEqual('testFolder'); expect($tr.attr('data-size')).toBeUndefined(); expect($tr.attr('data-etag')).toBeUndefined(); expect($tr.attr('data-permissions')).toEqual('31'); expect($tr.attr('data-mime')).toEqual('httpd/unix-directory'); expect($tr.attr('data-mtime')).toEqual('123456'); expect($tr.find('.filesize').text()).toEqual('Pending'); expect($tr.find('.date').text()).not.toEqual('?'); }); it('generates file element with zero size when size is explicitly zero', function() { var fileData = { type: 'dir', name: 'testFolder', size: '0' }; var $tr = fileList.add(fileData); expect($tr.find('.filesize').text()).toEqual('0 KB'); }); it('generates file element with unknown date when mtime invalid', function() { var fileData = { type: 'dir', name: 'testFolder', mtime: -1 }; var $tr = fileList.add(fileData); expect($tr.find('.date .modified').text()).toEqual('?'); }); it('adds new file to the end of the list', function() { var $tr; var fileData = { type: 'file', name: 'ZZZ.txt' }; fileList.setFiles(testFiles); $tr = fileList.add(fileData); expect($tr.index()).toEqual(4); }); it('inserts files in a sorted manner when insert option is enabled', function() { for (var i = 0; i < testFiles.length; i++) { fileList.add(testFiles[i]); } expect(fileList.files[0].name).toEqual('somedir'); expect(fileList.files[1].name).toEqual('One.txt'); expect(fileList.files[2].name).toEqual('Three.pdf'); expect(fileList.files[3].name).toEqual('Two.jpg'); }); it('inserts new file at correct position', function() { var $tr; var fileData = { type: 'file', name: 'P comes after O.txt' }; for (var i = 0; i < testFiles.length; i++) { fileList.add(testFiles[i]); } $tr = fileList.add(fileData); // after "One.txt" expect($tr.index()).toEqual(2); expect(fileList.files[2]).toEqual(fileData); }); it('inserts new folder at correct position in insert mode', function() { var $tr; var fileData = { type: 'dir', name: 'somedir2 comes after somedir' }; for (var i = 0; i < testFiles.length; i++) { fileList.add(testFiles[i]); } $tr = fileList.add(fileData); expect($tr.index()).toEqual(1); expect(fileList.files[1]).toEqual(fileData); }); it('inserts new file at the end correctly', function() { var $tr; var fileData = { type: 'file', name: 'zzz.txt' }; for (var i = 0; i < testFiles.length; i++) { fileList.add(testFiles[i]); } $tr = fileList.add(fileData); expect($tr.index()).toEqual(4); expect(fileList.files[4]).toEqual(fileData); }); it('removes empty content message and shows summary when adding first file', function() { var $summary; var fileData = { type: 'file', name: 'first file.txt', size: 12 }; fileList.setFiles([]); expect(fileList.isEmpty).toEqual(true); fileList.add(fileData); $summary = $('#filestable .summary'); expect($summary.hasClass('hidden')).toEqual(false); // yes, ugly... expect($summary.find('.fileinfo').text()).toEqual('1 file'); expect($summary.find('.dirinfo').hasClass('hidden')).toEqual(true); expect($summary.find('.connector').hasClass('hidden')).toEqual(true); expect($summary.find('.fileinfo').hasClass('hidden')).toEqual(false); expect($summary.find('.filesize').text()).toEqual('12 B'); expect($('#filestable thead th').hasClass('hidden')).toEqual(false); expect($('#emptycontent').hasClass('hidden')).toEqual(true); expect(fileList.isEmpty).toEqual(false); }); it('correctly adds the extension markup and show hidden files completely in gray', function() { var $tr; var testDataAndExpectedResult = [ {file: {type: 'file', name: 'ZZZ.txt'}, extension: '.txt'}, {file: {type: 'file', name: 'ZZZ.tar.gz'}, extension: '.gz'}, {file: {type: 'file', name: 'test.with.some.dots.in.it.txt'}, extension: '.txt'}, // we render hidden files completely in gray {file: {type: 'file', name: '.test.with.some.dots.in.it.txt'}, extension: '.test.with.some.dots.in.it.txt'}, {file: {type: 'file', name: '.hidden'}, extension: '.hidden'}, ]; fileList.setFiles(testFiles); for(var i = 0; i < testDataAndExpectedResult.length; i++) { var testSet = testDataAndExpectedResult[i]; var fileData = testSet['file']; $tr = fileList.add(fileData); expect($tr.find('.nametext .extension').text()).toEqual(testSet['extension']); } }); }); describe('Hidden files', function() { it('sets the class hidden-file for hidden files', function() { var fileData = { type: 'dir', name: '.testFolder' }; var $tr = fileList.add(fileData); expect($tr).toBeDefined(); expect($tr.hasClass('hidden-file')).toEqual(true); }); it('does not set the class hidden-file for visible files', function() { var fileData = { type: 'dir', name: 'testFolder' }; var $tr = fileList.add(fileData); expect($tr).toBeDefined(); expect($tr.hasClass('hidden-file')).toEqual(false); }); it('toggles the list\'s class when toggling hidden files', function() { expect(fileList.$el.hasClass('hide-hidden-files')).toEqual(false); filesConfig.set('showhidden', false); expect(fileList.$el.hasClass('hide-hidden-files')).toEqual(true); filesConfig.set('showhidden', true); expect(fileList.$el.hasClass('hide-hidden-files')).toEqual(false); }); }); describe('Removing files from the list', function() { it('Removes file from list when calling remove() and updates summary', function() { var $summary; var $removedEl; fileList.setFiles(testFiles); $removedEl = fileList.remove('One.txt'); expect($removedEl).toBeDefined(); expect($removedEl.attr('data-file')).toEqual('One.txt'); expect($('#fileList tr').length).toEqual(3); expect(fileList.files.length).toEqual(3); expect(fileList.findFileEl('One.txt').length).toEqual(0); $summary = $('#filestable .summary'); expect($summary.hasClass('hidden')).toEqual(false); expect($summary.find('.dirinfo').text()).toEqual('1 folder'); expect($summary.find('.fileinfo').text()).toEqual('2 files'); expect($summary.find('.dirinfo').hasClass('hidden')).toEqual(false); expect($summary.find('.fileinfo').hasClass('hidden')).toEqual(false); expect($summary.find('.filesize').text()).toEqual('69 KB'); expect(fileList.isEmpty).toEqual(false); }); it('Shows empty content when removing last file', function() { var $summary; fileList.setFiles([testFiles[0]]); fileList.remove('One.txt'); expect($('#fileList tr').length).toEqual(0); expect(fileList.files.length).toEqual(0); expect(fileList.findFileEl('One.txt').length).toEqual(0); $summary = $('#filestable .summary'); expect($summary.hasClass('hidden')).toEqual(true); expect($('#filestable thead th').hasClass('hidden')).toEqual(true); expect($('#emptycontent').hasClass('hidden')).toEqual(false); expect(fileList.isEmpty).toEqual(true); }); }); describe('Deleting files', function() { var deferredDelete; var deleteStub; beforeEach(function() { deferredDelete = $.Deferred(); deleteStub = sinon.stub(filesClient, 'remove').returns(deferredDelete.promise()); }); afterEach(function() { deleteStub.restore(); }); function doDelete() { // note: normally called from FileActions fileList.do_delete(['One.txt', 'Two.jpg']); expect(deleteStub.calledTwice).toEqual(true); expect(deleteStub.getCall(0).args[0]).toEqual('/subdir/One.txt'); expect(deleteStub.getCall(1).args[0]).toEqual('/subdir/Two.jpg'); } it('calls delete.php, removes the deleted entries and updates summary', function() { var $summary; fileList.setFiles(testFiles); doDelete(); deferredDelete.resolve(200); expect(fileList.findFileEl('One.txt').length).toEqual(0); expect(fileList.findFileEl('Two.jpg').length).toEqual(0); expect(fileList.findFileEl('Three.pdf').length).toEqual(1); expect(fileList.$fileList.find('tr').length).toEqual(2); $summary = $('#filestable .summary'); expect($summary.hasClass('hidden')).toEqual(false); expect($summary.find('.dirinfo').text()).toEqual('1 folder'); expect($summary.find('.fileinfo').text()).toEqual('1 file'); expect($summary.find('.dirinfo').hasClass('hidden')).toEqual(false); expect($summary.find('.fileinfo').hasClass('hidden')).toEqual(false); expect($summary.find('.filesize').text()).toEqual('57 KB'); expect(fileList.isEmpty).toEqual(false); expect($('#filestable thead th').hasClass('hidden')).toEqual(false); expect($('#emptycontent').hasClass('hidden')).toEqual(true); expect(notificationStub.notCalled).toEqual(true); }); it('shows busy state on files to be deleted', function() { fileList.setFiles(testFiles); doDelete(); expect(fileList.findFileEl('One.txt').hasClass('busy')).toEqual(true); expect(fileList.findFileEl('Three.pdf').hasClass('busy')).toEqual(false); }); it('shows busy state on all files when deleting all', function() { fileList.setFiles(testFiles); fileList.do_delete(); expect(fileList.$fileList.find('tr.busy').length).toEqual(4); }); it('updates summary when deleting last file', function() { var $summary; fileList.setFiles([testFiles[0], testFiles[1]]); doDelete(); deferredDelete.resolve(200); expect(fileList.$fileList.find('tr').length).toEqual(0); $summary = $('#filestable .summary'); expect($summary.hasClass('hidden')).toEqual(true); expect(fileList.isEmpty).toEqual(true); expect(fileList.files.length).toEqual(0); expect($('#filestable thead th').hasClass('hidden')).toEqual(true); expect($('#emptycontent').hasClass('hidden')).toEqual(false); }); it('bring back deleted item when delete call failed', function() { fileList.setFiles(testFiles); doDelete(); deferredDelete.reject(403); // files are still in the list expect(fileList.findFileEl('One.txt').length).toEqual(1); expect(fileList.findFileEl('Two.jpg').length).toEqual(1); expect(fileList.$fileList.find('tr').length).toEqual(4); expect(notificationStub.calledTwice).toEqual(true); expect(notificationStub.getCall(0).args[0]).toEqual('Error deleting file "One.txt".'); expect(notificationStub.getCall(1).args[0]).toEqual('Error deleting file "Two.jpg".'); }); it('remove file from list if delete call returned 404 not found', function() { fileList.setFiles(testFiles); doDelete(); deferredDelete.reject(404); // files are removed from the list expect(fileList.findFileEl('One.txt').length).toEqual(0); expect(fileList.findFileEl('Two.jpg').length).toEqual(0); expect(fileList.$fileList.find('tr').length).toEqual(2); expect(notificationStub.notCalled).toEqual(true); }); it('shows notification about lock when file is locked', function() { fileList.setFiles(testFiles); doDelete(); deferredDelete.reject(423, {message: 'locked'}); // files are still in the list expect(fileList.findFileEl('One.txt').length).toEqual(1); expect(fileList.findFileEl('Two.jpg').length).toEqual(1); expect(fileList.$fileList.find('tr').length).toEqual(4); expect(notificationStub.calledTwice).toEqual(true); expect(notificationStub.getCall(0).args[0]).toEqual('The file "One.txt" is locked and cannot be deleted.'); expect(notificationStub.getCall(1).args[0]).toEqual('The file "Two.jpg" is locked and cannot be deleted.'); }); }); describe('Renaming files', function() { var deferredRename; var renameStub; beforeEach(function() { deferredRename = $.Deferred(); renameStub = sinon.stub(filesClient, 'move').returns(deferredRename.promise()); }); afterEach(function() { renameStub.restore(); }); function doCancelRename() { var $input; for (var i = 0; i < testFiles.length; i++) { fileList.add(testFiles[i]); } // trigger rename prompt fileList.rename('One.txt'); $input = fileList.$fileList.find('input.filename'); // keep same name $input.val('One.txt'); // trigger submit because triggering blur doesn't work in all browsers $input.closest('form').trigger('submit'); expect(renameStub.notCalled).toEqual(true); } function doRename() { var $input; for (var i = 0; i < testFiles.length; i++) { var file = testFiles[i]; file.path = '/some/subdir'; fileList.add(file, {silent: true}); } // trigger rename prompt fileList.rename('One.txt'); $input = fileList.$fileList.find('input.filename'); $input.val('Tu_after_three.txt'); // trigger submit because triggering blur doesn't work in all browsers $input.closest('form').trigger('submit'); expect(renameStub.calledOnce).toEqual(true); expect(renameStub.getCall(0).args[0]).toEqual('/some/subdir/One.txt'); expect(renameStub.getCall(0).args[1]).toEqual('/some/subdir/Tu_after_three.txt'); } it('Inserts renamed file entry at correct position if rename ajax call suceeded', function() { doRename(); deferredRename.resolve(201); // element stays renamed expect(fileList.findFileEl('One.txt').length).toEqual(0); expect(fileList.findFileEl('Tu_after_three.txt').length).toEqual(1); expect(fileList.findFileEl('Tu_after_three.txt').index()).toEqual(2); // after Two.jpg expect(notificationStub.notCalled).toEqual(true); }); it('Reverts file entry if rename ajax call failed', function() { doRename(); deferredRename.reject(403); // element was reverted expect(fileList.findFileEl('One.txt').length).toEqual(1); expect(fileList.findFileEl('One.txt').index()).toEqual(1); // after somedir expect(fileList.findFileEl('Tu_after_three.txt').length).toEqual(0); expect(notificationStub.calledOnce).toEqual(true); expect(notificationStub.getCall(0).args[0]).toEqual('Could not rename "One.txt"'); }); it('Shows notification in case file is locked', function() { doRename(); deferredRename.reject(423, {message: 'locked'}); // element was reverted expect(fileList.findFileEl('One.txt').length).toEqual(1); expect(fileList.findFileEl('One.txt').index()).toEqual(1); // after somedir expect(fileList.findFileEl('Tu_after_three.txt').length).toEqual(0); expect(notificationStub.calledOnce).toEqual(true); expect(notificationStub.getCall(0).args[0]).toEqual('The file "One.txt" is locked and can not be renamed.'); }); it('Correctly updates file link after rename', function() { var $tr; doRename(); deferredRename.resolve(201); $tr = fileList.findFileEl('Tu_after_three.txt'); expect($tr.find('a.name').attr('href')) .toEqual(OC.webroot + '/remote.php/webdav/some/subdir/Tu_after_three.txt'); }); it('Triggers "fileActionsReady" event after rename', function() { var handler = sinon.stub(); fileList.$fileList.on('fileActionsReady', handler); doRename(); expect(handler.notCalled).toEqual(true); deferredRename.resolve(201); expect(handler.calledOnce).toEqual(true); expect(fileList.$fileList.find('.test').length).toEqual(0); }); it('Leaves the summary alone when reinserting renamed element', function() { var $summary = $('#filestable .summary'); doRename(); deferredRename.resolve(201); expect($summary.find('.dirinfo').text()).toEqual('1 folder'); expect($summary.find('.fileinfo').text()).toEqual('3 files'); }); it('Leaves the summary alone when cancel renaming', function() { var $summary = $('#filestable .summary'); doCancelRename(); expect($summary.find('.dirinfo').text()).toEqual('1 folder'); expect($summary.find('.fileinfo').text()).toEqual('3 files'); }); it('Shows busy state while rename in progress', function() { var $tr; doRename(); // element is renamed before the request finishes $tr = fileList.findFileEl('Tu_after_three.txt'); expect($tr.length).toEqual(1); expect(fileList.findFileEl('One.txt').length).toEqual(0); // file actions are hidden expect($tr.hasClass('busy')).toEqual(true); expect($tr.find('a .nametext').text().trim()).toEqual('Tu_after_three.txt'); expect($tr.find('a.name').is(':visible')).toEqual(true); // input and form are gone expect(fileList.$fileList.find('input.filename').length).toEqual(0); expect(fileList.$fileList.find('form').length).toEqual(0); }); it('Validates the file name', function() { var $input, $tr; for (var i = 0; i < testFiles.length; i++) { fileList.add(testFiles[i], {silent: true}); } // trigger rename prompt fileList.rename('One.txt'); $input = fileList.$fileList.find('input.filename'); $input.val('Two.jpg'); // simulate key to trigger validation $input.trigger(new $.Event('keyup', {keyCode: 97})); // input is still there with error expect(fileList.$fileList.find('input.filename').length).toEqual(1); expect(fileList.$fileList.find('input.filename').hasClass('error')).toEqual(true); // trigger submit does not send server request $input.closest('form').trigger('submit'); expect(renameStub.notCalled).toEqual(true); // simulate escape key $input.trigger(new $.Event('keyup', {keyCode: 27})); // element is added back with the correct name $tr = fileList.findFileEl('One.txt'); expect($tr.length).toEqual(1); expect($tr.find('a .nametext').text().trim()).toEqual('One.txt'); expect($tr.find('a.name').is(':visible')).toEqual(true); $tr = fileList.findFileEl('Two.jpg'); expect($tr.length).toEqual(1); expect($tr.find('a .nametext').text().trim()).toEqual('Two.jpg'); expect($tr.find('a.name').is(':visible')).toEqual(true); // input and form are gone expect(fileList.$fileList.find('input.filename').length).toEqual(0); expect(fileList.$fileList.find('form').length).toEqual(0); }); it('Restores thumbnail when rename was cancelled', function() { doRename(); expect(OC.TestUtil.getImageUrl(fileList.findFileEl('Tu_after_three.txt').find('.thumbnail'))) .toEqual(OC.TestUtil.buildAbsoluteUrl(OC.imagePath('core', 'loading.gif'))); deferredRename.reject(409); expect(fileList.findFileEl('One.txt').length).toEqual(1); expect(OC.TestUtil.getImageUrl(fileList.findFileEl('One.txt').find('.thumbnail'))) .toEqual(OC.TestUtil.buildAbsoluteUrl(OC.imagePath('core', 'filetypes/text.svg'))); }); }); describe('Moving files', function() { var deferredMove; var moveStub; beforeEach(function() { deferredMove = $.Deferred(); moveStub = sinon.stub(filesClient, 'move').returns(deferredMove.promise()); fileList.setFiles(testFiles); }); afterEach(function() { moveStub.restore(); }); it('Moves single file to target folder', function() { fileList.move('One.txt', '/somedir'); expect(moveStub.calledOnce).toEqual(true); expect(moveStub.getCall(0).args[0]).toEqual('/subdir/One.txt'); expect(moveStub.getCall(0).args[1]).toEqual('/somedir/One.txt'); deferredMove.resolve(201); expect(fileList.findFileEl('One.txt').length).toEqual(0); // folder size has increased expect(fileList.findFileEl('somedir').data('size')).toEqual(262); expect(fileList.findFileEl('somedir').find('.filesize').text()).toEqual('262 B'); expect(notificationStub.notCalled).toEqual(true); }); it('Moves list of files to target folder', function() { var deferredMove1 = $.Deferred(); var deferredMove2 = $.Deferred(); moveStub.onCall(0).returns(deferredMove1.promise()); moveStub.onCall(1).returns(deferredMove2.promise()); fileList.move(['One.txt', 'Two.jpg'], '/somedir'); expect(moveStub.calledTwice).toEqual(true); expect(moveStub.getCall(0).args[0]).toEqual('/subdir/One.txt'); expect(moveStub.getCall(0).args[1]).toEqual('/somedir/One.txt'); expect(moveStub.getCall(1).args[0]).toEqual('/subdir/Two.jpg'); expect(moveStub.getCall(1).args[1]).toEqual('/somedir/Two.jpg'); deferredMove1.resolve(201); expect(fileList.findFileEl('One.txt').length).toEqual(0); // folder size has increased during move expect(fileList.findFileEl('somedir').data('size')).toEqual(262); expect(fileList.findFileEl('somedir').find('.filesize').text()).toEqual('262 B'); deferredMove2.resolve(201); expect(fileList.findFileEl('Two.jpg').length).toEqual(0); // folder size has increased expect(fileList.findFileEl('somedir').data('size')).toEqual(12311); expect(fileList.findFileEl('somedir').find('.filesize').text()).toEqual('12 KB'); expect(notificationStub.notCalled).toEqual(true); }); it('Shows notification if a file could not be moved', function() { fileList.move('One.txt', '/somedir'); expect(moveStub.calledOnce).toEqual(true); deferredMove.reject(409); expect(fileList.findFileEl('One.txt').length).toEqual(1); expect(notificationStub.calledOnce).toEqual(true); expect(notificationStub.getCall(0).args[0]).toEqual('Could not move "One.txt"'); }); it('Shows notification about lock if a file could not be moved due to lock', function() { fileList.move('One.txt', '/somedir'); expect(moveStub.calledOnce).toEqual(true); deferredMove.reject(423, {message: 'locked'}); expect(fileList.findFileEl('One.txt').length).toEqual(1); expect(notificationStub.calledOnce).toEqual(true); expect(notificationStub.getCall(0).args[0]).toEqual('Could not move "One.txt" because either the file or the target are locked.'); }); it('Restores thumbnail if a file could not be moved', function() { fileList.move('One.txt', '/somedir'); expect(OC.TestUtil.getImageUrl(fileList.findFileEl('One.txt').find('.thumbnail'))) .toEqual(OC.TestUtil.buildAbsoluteUrl(OC.imagePath('core', 'loading.gif'))); expect(moveStub.calledOnce).toEqual(true); deferredMove.reject(409); expect(fileList.findFileEl('One.txt').length).toEqual(1); expect(notificationStub.calledOnce).toEqual(true); expect(notificationStub.getCall(0).args[0]).toEqual('Could not move "One.txt"'); expect(OC.TestUtil.getImageUrl(fileList.findFileEl('One.txt').find('.thumbnail'))) .toEqual(OC.TestUtil.buildAbsoluteUrl(OC.imagePath('core', 'filetypes/text.svg'))); }); }); describe('Update file', function() { it('does not change summary', function() { var $summary = $('#filestable .summary'); var fileData = new FileInfo({ type: 'file', name: 'test file', }); var $tr = fileList.add(fileData); expect($summary.find('.dirinfo').hasClass('hidden')).toEqual(true); expect($summary.find('.fileinfo').text()).toEqual('1 file'); var model = fileList.getModelForFile('test file'); model.set({size: '100'}); expect($summary.find('.dirinfo').hasClass('hidden')).toEqual(true); expect($summary.find('.fileinfo').text()).toEqual('1 file'); }); }) describe('List rendering', function() { it('renders a list of files using add()', function() { expect(fileList.files.length).toEqual(0); expect(fileList.files).toEqual([]); fileList.setFiles(testFiles); expect($('#fileList tr').length).toEqual(4); expect(fileList.files.length).toEqual(4); expect(fileList.files).toEqual(testFiles); }); it('updates summary using the file sizes', function() { var $summary; fileList.setFiles(testFiles); $summary = $('#filestable .summary'); expect($summary.hasClass('hidden')).toEqual(false); expect($summary.find('.dirinfo').text()).toEqual('1 folder'); expect($summary.find('.fileinfo').text()).toEqual('3 files'); expect($summary.find('.filesize').text()).toEqual('69 KB'); }); it('shows headers, summary and hide empty content message after setting files', function(){ fileList.setFiles(testFiles); expect($('#filestable thead th').hasClass('hidden')).toEqual(false); expect($('#emptycontent').hasClass('hidden')).toEqual(true); expect(fileList.$el.find('.summary').hasClass('hidden')).toEqual(false); }); it('hides headers, summary and show empty content message after setting empty file list', function(){ fileList.setFiles([]); expect($('#filestable thead th').hasClass('hidden')).toEqual(true); expect($('#emptycontent').hasClass('hidden')).toEqual(false); expect($('#emptycontent .uploadmessage').hasClass('hidden')).toEqual(false); expect(fileList.$el.find('.summary').hasClass('hidden')).toEqual(true); }); it('hides headers, upload message, and summary when list is empty and user has no creation permission', function(){ $('#permissions').val(0); fileList.setFiles([]); expect($('#filestable thead th').hasClass('hidden')).toEqual(true); expect($('#emptycontent').hasClass('hidden')).toEqual(false); expect($('#emptycontent .uploadmessage').hasClass('hidden')).toEqual(true); expect(fileList.$el.find('.summary').hasClass('hidden')).toEqual(true); }); it('calling findFileEl() can find existing file element', function() { fileList.setFiles(testFiles); expect(fileList.findFileEl('Two.jpg').length).toEqual(1); }); it('calling findFileEl() returns empty when file not found in file', function() { fileList.setFiles(testFiles); expect(fileList.findFileEl('unexist.dat').length).toEqual(0); }); it('only add file if in same current directory', function() { $('#dir').val('/current dir'); var fileData = { type: 'file', name: 'testFile.txt', directory: '/current dir' }; fileList.add(fileData); expect(fileList.findFileEl('testFile.txt').length).toEqual(1); }); it('triggers "fileActionsReady" event after update', function() { var handler = sinon.stub(); fileList.$fileList.on('fileActionsReady', handler); fileList.setFiles(testFiles); expect(handler.calledOnce).toEqual(true); expect(handler.getCall(0).args[0].$files.length).toEqual(testFiles.length); }); it('triggers "fileActionsReady" event after single add', function() { var handler = sinon.stub(); var $tr; fileList.setFiles(testFiles); fileList.$fileList.on('fileActionsReady', handler); $tr = fileList.add({name: 'test.txt'}); expect(handler.calledOnce).toEqual(true); expect(handler.getCall(0).args[0].$files.is($tr)).toEqual(true); }); it('triggers "fileActionsReady" event after next page load with the newly appended files', function() { var handler = sinon.stub(); fileList.setFiles(generateFiles(0, 64)); fileList.$fileList.on('fileActionsReady', handler); fileList._nextPage(); expect(handler.calledOnce).toEqual(true); expect(handler.getCall(0).args[0].$files.length).toEqual(fileList.pageSize()); }); it('does not trigger "fileActionsReady" event after single add with silent argument', function() { var handler = sinon.stub(); fileList.setFiles(testFiles); fileList.$fileList.on('fileActionsReady', handler); fileList.add({name: 'test.txt'}, {silent: true}); expect(handler.notCalled).toEqual(true); }); it('triggers "updated" event after update', function() { var handler = sinon.stub(); fileList.$fileList.on('updated', handler); fileList.setFiles(testFiles); expect(handler.calledOnce).toEqual(true); }); it('does not update summary when removing non-existing files', function() { var $summary; // single file fileList.setFiles([testFiles[0]]); $summary = $('#filestable .summary'); expect($summary.hasClass('hidden')).toEqual(false); expect($summary.find('.dirinfo').hasClass('hidden')).toEqual(true); expect($summary.find('.fileinfo').text()).toEqual('1 file'); fileList.remove('unexist.txt'); expect($summary.hasClass('hidden')).toEqual(false); expect($summary.find('.dirinfo').hasClass('hidden')).toEqual(true); expect($summary.find('.fileinfo').text()).toEqual('1 file'); }); it('shows icon for shareTree items if parent is shared', function() { fileList._setShareTreeCache({ '/folder' : { name: "folder", shares : [{ share_type: 0, share_with_displayname: "Demo user", }] } }); fileList.setFiles(testFiles); expect($('#fileList tr:first-of-type td .sharetree-item').length).toEqual(1); }); it('does not show shareTree items if shareTree is empty', function() { fileList._purgeShareTreeCache(); fileList.setFiles(testFiles); expect($('#fileList tr td .sharetree-item').length).toEqual(0); }); }); describe('Filtered list rendering', function() { it('filters the list of files using filter()', function() { expect(fileList.files.length).toEqual(0); expect(fileList.files).toEqual([]); fileList.setFiles(testFiles); var $summary = $('#filestable .summary'); var $nofilterresults = fileList.$el.find(".nofilterresults"); expect($nofilterresults.length).toEqual(1); expect($summary.hasClass('hidden')).toEqual(false); expect($('#fileList tr:not(.hidden)').length).toEqual(4); expect(fileList.files.length).toEqual(4); expect($summary.hasClass('hidden')).toEqual(false); expect($nofilterresults.hasClass('hidden')).toEqual(true); fileList.setFilter('e'); expect($('#fileList tr:not(.hidden)').length).toEqual(3); expect(fileList.files.length).toEqual(4); expect($summary.hasClass('hidden')).toEqual(false); expect($summary.find('.dirinfo').text()).toEqual('1 folder'); expect($summary.find('.fileinfo').text()).toEqual('2 files'); expect($summary.find('.filter').text()).toEqual(" match 'e'"); expect($nofilterresults.hasClass('hidden')).toEqual(true); fileList.setFilter('ee'); expect($('#fileList tr:not(.hidden)').length).toEqual(1); expect(fileList.files.length).toEqual(4); expect($summary.hasClass('hidden')).toEqual(false); expect($summary.find('.dirinfo').hasClass('hidden')).toEqual(true); expect($summary.find('.fileinfo').text()).toEqual('1 file'); expect($summary.find('.filter').text()).toEqual(" matches 'ee'"); expect($nofilterresults.hasClass('hidden')).toEqual(true); fileList.setFilter('eee'); expect($('#fileList tr:not(.hidden)').length).toEqual(0); expect(fileList.files.length).toEqual(4); expect($summary.hasClass('hidden')).toEqual(true); expect($nofilterresults.hasClass('hidden')).toEqual(false); fileList.setFilter('ee'); expect($('#fileList tr:not(.hidden)').length).toEqual(1); expect(fileList.files.length).toEqual(4); expect($summary.hasClass('hidden')).toEqual(false); expect($summary.find('.dirinfo').hasClass('hidden')).toEqual(true); expect($summary.find('.fileinfo').text()).toEqual('1 file'); expect($summary.find('.filter').text()).toEqual(" matches 'ee'"); expect($nofilterresults.hasClass('hidden')).toEqual(true); fileList.setFilter('e'); expect($('#fileList tr:not(.hidden)').length).toEqual(3); expect(fileList.files.length).toEqual(4); expect($summary.hasClass('hidden')).toEqual(false); expect($summary.find('.dirinfo').text()).toEqual('1 folder'); expect($summary.find('.fileinfo').text()).toEqual('2 files'); expect($summary.find('.filter').text()).toEqual(" match 'e'"); expect($nofilterresults.hasClass('hidden')).toEqual(true); fileList.setFilter(''); expect($('#fileList tr:not(.hidden)').length).toEqual(4); expect(fileList.files.length).toEqual(4); expect($summary.hasClass('hidden')).toEqual(false); expect($summary.find('.dirinfo').text()).toEqual('1 folder'); expect($summary.find('.fileinfo').text()).toEqual('3 files'); expect($nofilterresults.hasClass('hidden')).toEqual(true); }); it('filters the list of non-rendered rows using filter()', function() { var $summary = $('#filestable .summary'); var $nofilterresults = fileList.$el.find(".nofilterresults"); fileList.setFiles(generateFiles(0, 64)); fileList.setFilter('63'); expect($('#fileList tr:not(.hidden)').length).toEqual(1); expect($summary.hasClass('hidden')).toEqual(false); expect($summary.find('.dirinfo').hasClass('hidden')).toEqual(true); expect($summary.find('.fileinfo').text()).toEqual('1 file'); expect($summary.find('.filter').text()).toEqual(" matches '63'"); expect($nofilterresults.hasClass('hidden')).toEqual(true); }); it('hides the emptyfiles notice when using filter()', function() { expect(fileList.files.length).toEqual(0); expect(fileList.files).toEqual([]); fileList.setFiles([]); var $summary = $('#filestable .summary'); var $emptycontent = fileList.$el.find("#emptycontent"); var $nofilterresults = fileList.$el.find(".nofilterresults"); expect($emptycontent.length).toEqual(1); expect($nofilterresults.length).toEqual(1); expect($('#fileList tr:not(.hidden)').length).toEqual(0); expect(fileList.files.length).toEqual(0); expect($summary.hasClass('hidden')).toEqual(true); expect($emptycontent.hasClass('hidden')).toEqual(false); expect($nofilterresults.hasClass('hidden')).toEqual(true); fileList.setFilter('e'); expect($('#fileList tr:not(.hidden)').length).toEqual(0); expect(fileList.files.length).toEqual(0); expect($summary.hasClass('hidden')).toEqual(true); expect($emptycontent.hasClass('hidden')).toEqual(true); expect($nofilterresults.hasClass('hidden')).toEqual(false); fileList.setFilter(''); expect($('#fileList tr:not(.hidden)').length).toEqual(0); expect(fileList.files.length).toEqual(0); expect($summary.hasClass('hidden')).toEqual(true); expect($emptycontent.hasClass('hidden')).toEqual(false); expect($nofilterresults.hasClass('hidden')).toEqual(true); }); it('does not show the emptyfiles or nofilterresults notice when the mask is active', function() { expect(fileList.files.length).toEqual(0); expect(fileList.files).toEqual([]); fileList.showMask(); fileList.setFiles(testFiles); var $emptycontent = fileList.$el.find("#emptycontent"); var $nofilterresults = fileList.$el.find(".nofilterresults"); expect($emptycontent.length).toEqual(1); expect($nofilterresults.length).toEqual(1); expect($emptycontent.hasClass('hidden')).toEqual(true); expect($nofilterresults.hasClass('hidden')).toEqual(true); /* fileList.setFilter('e'); expect($emptycontent.hasClass('hidden')).toEqual(true); expect($nofilterresults.hasClass('hidden')).toEqual(false); */ fileList.setFilter(''); expect($emptycontent.hasClass('hidden')).toEqual(true); expect($nofilterresults.hasClass('hidden')).toEqual(true); }); }); describe('Rendering next page on scroll', function() { beforeEach(function() { fileList.setFiles(generateFiles(0, 64)); }); it('renders only the first page', function() { expect(fileList.files.length).toEqual(65); expect($('#fileList tr').length).toEqual(20); }); it('renders the full first page despite hidden rows', function() { filesConfig.set('showhidden', false); var files = _.map(generateFiles(0, 23), function(data) { return _.extend(data, { name: '.' + data.name }); }); // only hidden files + one visible files.push(testFiles[0]); fileList.setFiles(files); expect(fileList.files.length).toEqual(25); // render 24 hidden elements + the visible one expect($('#fileList tr').length).toEqual(25); }); it('renders the full first page despite hidden rows', function() { filesConfig.set('showhidden', true); var files = _.map(generateFiles(0, 23), function(data) { return _.extend(data, { name: '.' + data.name }); }); // only hidden files + one visible files.push(testFiles[0]); fileList.setFiles(files); expect(fileList.files.length).toEqual(25); // render 20 first hidden elements as visible expect($('#fileList tr').length).toEqual(20); }); it('renders the second page when scrolling down (trigger nextPage)', function() { // TODO: can't simulate scrolling here, so calling nextPage directly fileList._nextPage(true); expect($('#fileList tr').length).toEqual(40); fileList._nextPage(true); expect($('#fileList tr').length).toEqual(60); fileList._nextPage(true); expect($('#fileList tr').length).toEqual(65); fileList._nextPage(true); // stays at 65 expect($('#fileList tr').length).toEqual(65); }); it('inserts into the DOM if insertion point is in the visible page ', function() { fileList.add({ id: 2000, type: 'file', name: 'File with index 15b.txt' }); expect($('#fileList tr').length).toEqual(21); expect(fileList.findFileEl('File with index 15b.txt').index()).toEqual(16); }); it('does not inserts into the DOM if insertion point is not the visible page ', function() { fileList.add({ id: 2000, type: 'file', name: 'File with index 28b.txt' }); expect($('#fileList tr').length).toEqual(20); expect(fileList.findFileEl('File with index 28b.txt').length).toEqual(0); fileList._nextPage(true); expect($('#fileList tr').length).toEqual(40); expect(fileList.findFileEl('File with index 28b.txt').index()).toEqual(29); }); it('appends into the DOM when inserting a file after the last visible element', function() { fileList.add({ id: 2000, type: 'file', name: 'File with index 19b.txt' }); expect($('#fileList tr').length).toEqual(21); fileList._nextPage(true); expect($('#fileList tr').length).toEqual(41); }); it('appends into the DOM when inserting a file on the last page when visible', function() { fileList._nextPage(true); expect($('#fileList tr').length).toEqual(40); fileList._nextPage(true); expect($('#fileList tr').length).toEqual(60); fileList._nextPage(true); expect($('#fileList tr').length).toEqual(65); fileList._nextPage(true); fileList.add({ id: 2000, type: 'file', name: 'File with index 88.txt' }); expect($('#fileList tr').length).toEqual(66); fileList._nextPage(true); expect($('#fileList tr').length).toEqual(66); }); it('shows additional page when appending a page of files and scrolling down', function() { var newFiles = generateFiles(66, 81); for (var i = 0; i < newFiles.length; i++) { fileList.add(newFiles[i]); } expect($('#fileList tr').length).toEqual(20); fileList._nextPage(true); expect($('#fileList tr').length).toEqual(40); fileList._nextPage(true); expect($('#fileList tr').length).toEqual(60); fileList._nextPage(true); expect($('#fileList tr').length).toEqual(80); fileList._nextPage(true); expect($('#fileList tr').length).toEqual(81); fileList._nextPage(true); expect($('#fileList tr').length).toEqual(81); }); it('automatically renders next page when there are not enough elements visible', function() { // delete the 15 first elements for (var i = 0; i < 15; i++) { fileList.remove(fileList.files[0].name); } // still makes sure that there are 20 elements visible, if any expect($('#fileList tr').length).toEqual(25); }); }); describe('file previews', function() { var previewLoadStub; beforeEach(function() { previewLoadStub = sinon.stub(OCA.Files.FileList.prototype, 'lazyLoadPreview'); }); afterEach(function() { previewLoadStub.restore(); }); it('renders default file icon when none provided and no mime type is set', function() { var fileData = { name: 'testFile.txt' }; var $tr = fileList.add(fileData); var $imgDiv = $tr.find('td.filename .thumbnail'); expect(OC.TestUtil.getImageUrl($imgDiv)).toEqual( OC.TestUtil.buildAbsoluteUrl(OC.webroot + '/core/img/filetypes/file.svg')); // tries to load preview expect(previewLoadStub.calledOnce).toEqual(true); }); it('renders default icon for folder when none provided', function() { var fileData = { name: 'test dir', mimetype: 'httpd/unix-directory' }; var $tr = fileList.add(fileData); var $imgDiv = $tr.find('td.filename .thumbnail'); expect(OC.TestUtil.getImageUrl($imgDiv)).toEqual( OC.TestUtil.buildAbsoluteUrl(OC.webroot + '/core/img/filetypes/folder.svg')); // no preview since it's a directory expect(previewLoadStub.notCalled).toEqual(true); }); it('renders provided icon for file when provided', function() { var fileData = new FileInfo({ type: 'file', name: 'test file', icon: OC.webroot + '/core/img/filetypes/application-pdf.svg', mimetype: 'application/pdf' }); var $tr = fileList.add(fileData); var $imgDiv = $tr.find('td.filename .thumbnail'); expect(OC.TestUtil.getImageUrl($imgDiv)).toEqual( OC.TestUtil.buildAbsoluteUrl(OC.webroot + '/core/img/filetypes/application-pdf.svg')); // try loading preview expect(previewLoadStub.calledOnce).toEqual(true); }); it('renders provided icon for file when provided', function() { var fileData = new FileInfo({ name: 'somefile.pdf', icon: OC.webroot + '/core/img/filetypes/application-pdf.svg' }); var $tr = fileList.add(fileData); var $imgDiv = $tr.find('td.filename .thumbnail'); expect(OC.TestUtil.getImageUrl($imgDiv)).toEqual( OC.TestUtil.buildAbsoluteUrl(OC.webroot + '/core/img/filetypes/application-pdf.svg')); // try loading preview expect(previewLoadStub.calledOnce).toEqual(true); }); it('renders provided icon for folder when provided', function() { var fileData = new FileInfo({ name: 'some folder', mimetype: 'httpd/unix-directory', icon: OC.webroot + '/core/img/filetypes/folder-alt.svg' }); var $tr = fileList.add(fileData); var $imgDiv = $tr.find('td.filename .thumbnail'); expect(OC.TestUtil.getImageUrl($imgDiv)).toEqual( OC.TestUtil.buildAbsoluteUrl(OC.webroot + '/core/img/filetypes/folder-alt.svg')); // do not load preview for folders expect(previewLoadStub.notCalled).toEqual(true); }); it('renders preview when no icon was provided', function() { var fileData = { type: 'file', name: 'test file' }; var $tr = fileList.add(fileData); var $td = $tr.find('td.filename'); expect(OC.TestUtil.getImageUrl($td.find('.thumbnail'))) .toEqual( OC.TestUtil.buildAbsoluteUrl(OC.webroot + '/core/img/filetypes/file.svg')); expect(previewLoadStub.calledOnce).toEqual(true); // third argument is callback previewLoadStub.getCall(0).args[0].callback(OC.webroot + '/somepath.png'); expect(OC.TestUtil.getImageUrl($td.find('.thumbnail'))).toEqual( OC.TestUtil.buildAbsoluteUrl(OC.webroot + '/somepath.png')); }); it('does not render preview for directories', function() { var fileData = { type: 'dir', mimetype: 'httpd/unix-directory', name: 'test dir' }; var $tr = fileList.add(fileData); var $td = $tr.find('td.filename'); expect(OC.TestUtil.getImageUrl($td.find('.thumbnail'))).toEqual( OC.TestUtil.buildAbsoluteUrl(OC.webroot + '/core/img/filetypes/folder.svg')); expect(previewLoadStub.notCalled).toEqual(true); }); it('render external storage icon for external storage root', function() { var fileData = { type: 'dir', mimetype: 'httpd/unix-directory', name: 'test dir', mountType: 'external-root' }; var $tr = fileList.add(fileData); var $td = $tr.find('td.filename'); expect(OC.TestUtil.getImageUrl($td.find('.thumbnail'))).toEqual( OC.TestUtil.buildAbsoluteUrl(OC.webroot + '/core/img/filetypes/folder-external.svg')); expect(previewLoadStub.notCalled).toEqual(true); }); it('render external storage icon for external storage subdir', function() { var fileData = { type: 'dir', mimetype: 'httpd/unix-directory', name: 'test dir', mountType: 'external' }; var $tr = fileList.add(fileData); var $td = $tr.find('td.filename'); expect(OC.TestUtil.getImageUrl($td.find('.thumbnail'))).toEqual( OC.TestUtil.buildAbsoluteUrl(OC.webroot + '/core/img/filetypes/folder-external.svg')); expect(previewLoadStub.notCalled).toEqual(true); // default icon override expect($tr.attr('data-icon')).toEqual(OC.webroot + '/core/img/filetypes/folder-external.svg'); }); }); describe('viewer mode', function() { it('enabling viewer mode hides files table and action buttons', function() { fileList.setViewerMode(true); expect($('#filestable').hasClass('hidden')).toEqual(true); expect($('.actions').hasClass('hidden')).toEqual(true); expect($('.notCreatable').hasClass('hidden')).toEqual(true); }); it('disabling viewer mode restores files table and action buttons', function() { fileList.setViewerMode(true); fileList.setViewerMode(false); expect($('#filestable').hasClass('hidden')).toEqual(false); expect($('.actions').hasClass('hidden')).toEqual(false); expect($('.notCreatable').hasClass('hidden')).toEqual(true); }); it('disabling viewer mode restores files table and action buttons with correct permissions', function() { $('#permissions').val(0); fileList.setViewerMode(true); fileList.setViewerMode(false); expect($('#filestable').hasClass('hidden')).toEqual(false); expect($('.actions').hasClass('hidden')).toEqual(true); expect($('.notCreatable').hasClass('hidden')).toEqual(false); }); it('toggling viewer mode triggers event', function() { var handler = sinon.stub(); fileList.$el.on('changeViewerMode', handler); fileList.setViewerMode(true); expect(handler.calledOnce).toEqual(true); expect(handler.getCall(0).args[0].viewerModeEnabled).toEqual(true); handler.reset(); fileList.setViewerMode(false); expect(handler.calledOnce).toEqual(true); expect(handler.getCall(0).args[0].viewerModeEnabled).toEqual(false); }); }); describe('loading file list', function() { var deferredList; var getFolderContentsStub; beforeEach(function() { deferredList = $.Deferred(); getFolderContentsStub = sinon.stub(filesClient, 'getFolderContents').returns(deferredList.promise()); }); afterEach(function() { getFolderContentsStub.restore(); }); it('fetches file list from server and renders it when reload() is called', function() { fileList.reload(); expect(getFolderContentsStub.calledOnce).toEqual(true); expect(getFolderContentsStub.calledWith('/subdir')).toEqual(true); deferredList.resolve(200, [testRoot].concat(testFiles)); expect($('#fileList tr').length).toEqual(4); expect(fileList.findFileEl('One.txt').length).toEqual(1); }); it('switches dir and fetches file list when calling changeDirectory()', function() { fileList.changeDirectory('/anothersubdir'); expect(fileList.getCurrentDirectory()).toEqual('/anothersubdir'); expect(getFolderContentsStub.calledOnce).toEqual(true); expect(getFolderContentsStub.calledWith('/anothersubdir')).toEqual(true); }); it('converts backslashes to slashes when calling changeDirectory()', function() { fileList.changeDirectory('/another\\subdir'); expect(fileList.getCurrentDirectory()).toEqual('/another/subdir'); }); it('switches to root dir when current directory is invalid', function() { _.each([ '..', '/..', '../', '/../', '/../abc', '/abc/..', '/abc/../', '/../abc/', '/zero' + decodeURIComponent('%00') + 'byte/', '/really who adds new' + decodeURIComponent('%0A') + 'lines in their paths/', ], function(path) { fileList.changeDirectory(path); expect(fileList.getCurrentDirectory()).toEqual('/'); }); }); it('allows paths with dotdot at the beginning or end', function() { _.each([ '/..abc', '/def..', '/...' ], function(path) { fileList.changeDirectory(path); expect(fileList.getCurrentDirectory()).toEqual(path); }); }); it('switches to root dir in case of bad request', function() { fileList.changeDirectory('/unexist'); // can happen in case of invalid chars in the URL deferredList.reject(400); expect(fileList.getCurrentDirectory()).toEqual('/'); }); it('switches to root dir when current directory does not exist', function() { fileList.changeDirectory('/unexist'); deferredList.reject(404); expect(fileList.getCurrentDirectory()).toEqual('/'); }); it('switches to root dir when current directory is forbidden', function() { fileList.changeDirectory('/unexist'); deferredList.reject(403); expect(fileList.getCurrentDirectory()).toEqual('/'); }); it('switches to root dir when current directory is unavailable', function() { fileList.changeDirectory('/unexist'); deferredList.reject(500); expect(fileList.getCurrentDirectory()).toEqual('/'); }); it('shows mask before loading file list then hides it at the end', function() { var showMaskStub = sinon.stub(fileList, 'showMask'); var hideMaskStub = sinon.stub(fileList, 'hideMask'); fileList.changeDirectory('/anothersubdir'); expect(showMaskStub.calledOnce).toEqual(true); expect(hideMaskStub.calledOnce).toEqual(false); deferredList.resolve(200, [testRoot].concat(testFiles)); expect(showMaskStub.calledOnce).toEqual(true); expect(hideMaskStub.calledOnce).toEqual(true); showMaskStub.restore(); hideMaskStub.restore(); }); it('triggers "changeDirectory" event when changing directory', function() { var handler = sinon.stub(); $('#app-content-files').on('changeDirectory', handler); fileList.changeDirectory('/somedir'); deferredList.resolve(200, [testRoot].concat(testFiles)); expect(handler.calledOnce).toEqual(true); expect(handler.getCall(0).args[0].dir).toEqual('/somedir'); }); it('triggers "afterChangeDirectory" event with fileid after changing directory', function() { var handler = sinon.stub(); $('#app-content-files').on('afterChangeDirectory', handler); fileList.changeDirectory('/somedir'); deferredList.resolve(200, [testRoot].concat(testFiles)); expect(handler.calledOnce).toEqual(true); expect(handler.getCall(0).args[0].dir).toEqual('/somedir'); expect(handler.getCall(0).args[0].fileId).toEqual(99); }); it('changes the directory when receiving "urlChanged" event', function() { $('#app-content-files').trigger(new $.Event('urlChanged', {view: 'files', dir: '/somedir'})); expect(fileList.getCurrentDirectory()).toEqual('/somedir'); }); it('refreshes breadcrumb after update', function() { var setDirSpy = sinon.spy(fileList.breadcrumb, 'setDirectory'); fileList.changeDirectory('/anothersubdir'); deferredList.resolve(200, [testRoot].concat(testFiles)); expect(fileList.breadcrumb.setDirectory.calledOnce).toEqual(true); expect(fileList.breadcrumb.setDirectory.calledWith('/anothersubdir')).toEqual(true); setDirSpy.restore(); getFolderContentsStub.restore(); }); it('prepends a slash to directory if none was given', function() { fileList.changeDirectory(''); expect(fileList.getCurrentDirectory()).toEqual('/'); fileList.changeDirectory('noslash'); expect(fileList.getCurrentDirectory()).toEqual('/noslash'); }); }); describe('breadcrumb events', function() { var deferredList; var getFolderContentsStub; beforeEach(function() { deferredList = $.Deferred(); getFolderContentsStub = sinon.stub(filesClient, 'getFolderContents').returns(deferredList.promise()); }); afterEach(function() { getFolderContentsStub.restore(); }); it('clicking on root breadcrumb changes directory to root', function() { fileList.changeDirectory('/subdir/two/three with space/four/five'); deferredList.resolve(200, [testRoot].concat(testFiles)); var changeDirStub = sinon.stub(fileList, 'changeDirectory'); fileList.breadcrumb.$el.find('.crumb:eq(0)').trigger({type: 'click', which: 1}); expect(changeDirStub.calledOnce).toEqual(true); expect(changeDirStub.getCall(0).args[0]).toEqual('/'); changeDirStub.restore(); }); it('clicking on breadcrumb changes directory', function() { fileList.changeDirectory('/subdir/two/three with space/four/five'); deferredList.resolve(200, [testRoot].concat(testFiles)); var changeDirStub = sinon.stub(fileList, 'changeDirectory'); fileList.breadcrumb.$el.find('.crumb:eq(3)').trigger({type: 'click', which: 1}); expect(changeDirStub.calledOnce).toEqual(true); expect(changeDirStub.getCall(0).args[0]).toEqual('/subdir/two/three with space'); changeDirStub.restore(); }); it('dropping files on breadcrumb calls move operation', function() { var testDir = '/subdir/two/three with space/four/five'; var moveStub = sinon.stub(filesClient, 'move').returns($.Deferred().promise()); fileList.changeDirectory(testDir); deferredList.resolve(200, [testRoot].concat(testFiles)); var $crumb = fileList.breadcrumb.$el.find('.crumb:eq(3)'); // no idea what this is but is required by the handler var ui = { helper: { find: sinon.stub() } }; // returns a list of tr that were dragged ui.helper.find.returns([ $('<tr data-file="One.txt" data-dir="' + testDir + '"></tr>'), $('<tr data-file="Two.jpg" data-dir="' + testDir + '"></tr>') ]); // simulate drop event fileList._onDropOnBreadCrumb(new $.Event('drop', {target: $crumb}), ui); expect(moveStub.callCount).toEqual(2); expect(moveStub.getCall(0).args[0]).toEqual(testDir + '/One.txt'); expect(moveStub.getCall(0).args[1]).toEqual('/subdir/two/three with space/One.txt'); expect(moveStub.getCall(1).args[0]).toEqual(testDir + '/Two.jpg'); expect(moveStub.getCall(1).args[1]).toEqual('/subdir/two/three with space/Two.jpg'); moveStub.restore(); }); it('dropping files on same dir breadcrumb does nothing', function() { var testDir = '/subdir/two/three with space/four/five'; var moveStub = sinon.stub(filesClient, 'move').returns($.Deferred().promise()); fileList.changeDirectory(testDir); deferredList.resolve(200, [testRoot].concat(testFiles)); var $crumb = fileList.breadcrumb.$el.find('.crumb:last'); // no idea what this is but is required by the handler var ui = { helper: { find: sinon.stub() } }; // returns a list of tr that were dragged ui.helper.find.returns([ $('<tr data-file="One.txt" data-dir="' + testDir + '"></tr>'), $('<tr data-file="Two.jpg" data-dir="' + testDir + '"></tr>') ]); // simulate drop event fileList._onDropOnBreadCrumb(new $.Event('drop', {target: $crumb}), ui); // no extra server request expect(moveStub.notCalled).toEqual(true); }); }); describe('Download Url', function() { it('returns correct download URL for single files', function() { expect(fileList.getDownloadUrl('some file.txt')) .toEqual(OC.webroot + '/remote.php/webdav/subdir/some%20file.txt'); expect(fileList.getDownloadUrl('some file.txt', '/anotherpath/abc')) .toEqual(OC.webroot + '/remote.php/webdav/anotherpath/abc/some%20file.txt'); $('#dir').val('/'); expect(fileList.getDownloadUrl('some file.txt')) .toEqual(OC.webroot + '/remote.php/webdav/some%20file.txt'); }); it('returns correct download URL for multiple files', function() { expect(fileList.getDownloadUrl(['a b c.txt', 'd e f.txt'])) .toEqual(OC.webroot + '/index.php/apps/files/ajax/download.php?dir=%2Fsubdir&files[]=a%20b%20c.txt&files[]=d%20e%20f.txt'); }); it('returns the correct ajax URL', function() { expect(fileList.getAjaxUrl('test', {a:1, b:'x y'})) .toEqual(OC.webroot + '/index.php/apps/files/ajax/test.php?a=1&b=x%20y'); }); }); describe('Upload Url', function() { var testPath; beforeEach(function() { currentUserStub = sinon.stub(OC, 'getCurrentUser').returns({uid: 'test@#?%test'}); testPath = 'path/to sp@ce/a@b#?%/x'; }); afterEach(function() { currentUserStub.restore(); }); it('returns correct upload URL for single files with provided dir', function() { expect(fileList.getUploadUrl('some file.txt', testPath)) .toEqual(OC.webroot + '/remote.php/dav/files/test%40%23%3F%25test/path/to%20sp%40ce/a%40b%23%3F%25/x/some%20file.txt'); }); it('returns correct upload URL with current list dir for single files when no dir argument was provided', function() { expect(fileList.getUploadUrl('some file.txt')) .toEqual(OC.webroot + '/remote.php/dav/files/test%40%23%3F%25test/subdir/some%20file.txt'); }); it('returns correct upload URL with current list dir when in root for single files when no dir argument was provided', function() { $('#dir').val('/'); expect(fileList.getUploadUrl('some file.txt')) .toEqual(OC.webroot + '/remote.php/dav/files/test%40%23%3F%25test/some%20file.txt'); }); }); describe('File selection', function() { beforeEach(function() { fileList.setFiles(testFiles); }); it('Selects a file when clicking its checkbox', function() { var $tr = fileList.findFileEl('One.txt'); expect($tr.find('input:checkbox').prop('checked')).toEqual(false); $tr.find('td.filename input:checkbox').click(); expect($tr.find('input:checkbox').prop('checked')).toEqual(true); }); it('Selects/deselect a file when clicking on the name while holding Ctrl', function() { var $tr = fileList.findFileEl('One.txt'); var $tr2 = fileList.findFileEl('Three.pdf'); var e; expect($tr.find('input:checkbox').prop('checked')).toEqual(false); expect($tr2.find('input:checkbox').prop('checked')).toEqual(false); e = new $.Event('click'); e.ctrlKey = true; $tr.find('td.filename .name').trigger(e); expect($tr.find('input:checkbox').prop('checked')).toEqual(true); expect($tr2.find('input:checkbox').prop('checked')).toEqual(false); // click on second entry, does not clear the selection e = new $.Event('click'); e.ctrlKey = true; $tr2.find('td.filename .name').trigger(e); expect($tr.find('input:checkbox').prop('checked')).toEqual(true); expect($tr2.find('input:checkbox').prop('checked')).toEqual(true); expect(_.pluck(fileList.getSelectedFiles(), 'name')).toEqual(['One.txt', 'Three.pdf']); // deselect now e = new $.Event('click'); e.ctrlKey = true; $tr2.find('td.filename .name').trigger(e); expect($tr.find('input:checkbox').prop('checked')).toEqual(true); expect($tr2.find('input:checkbox').prop('checked')).toEqual(false); expect(_.pluck(fileList.getSelectedFiles(), 'name')).toEqual(['One.txt']); }); it('Selects a range when clicking on one file then Shift clicking on another one', function() { var $tr = fileList.findFileEl('One.txt'); var $tr2 = fileList.findFileEl('Three.pdf'); var e; $tr.find('td.filename input:checkbox').click(); e = new $.Event('click'); e.shiftKey = true; $tr2.find('td.filename .name').trigger(e); expect($tr.find('input:checkbox').prop('checked')).toEqual(true); expect($tr2.find('input:checkbox').prop('checked')).toEqual(true); expect(fileList.findFileEl('Two.jpg').find('input:checkbox').prop('checked')).toEqual(true); var selection = _.pluck(fileList.getSelectedFiles(), 'name'); expect(selection.length).toEqual(3); expect(selection).toContain('One.txt'); expect(selection).toContain('Two.jpg'); expect(selection).toContain('Three.pdf'); }); it('Selects a range when clicking on one file then Shift clicking on another one that is above the first one', function() { var $tr = fileList.findFileEl('One.txt'); var $tr2 = fileList.findFileEl('Three.pdf'); var e; $tr2.find('td.filename input:checkbox').click(); e = new $.Event('click'); e.shiftKey = true; $tr.find('td.filename .name').trigger(e); expect($tr.find('input:checkbox').prop('checked')).toEqual(true); expect($tr2.find('input:checkbox').prop('checked')).toEqual(true); expect(fileList.findFileEl('Two.jpg').find('input:checkbox').prop('checked')).toEqual(true); var selection = _.pluck(fileList.getSelectedFiles(), 'name'); expect(selection.length).toEqual(3); expect(selection).toContain('One.txt'); expect(selection).toContain('Two.jpg'); expect(selection).toContain('Three.pdf'); }); it('Selecting all files will automatically check "select all" checkbox', function() { expect($('.select-all').prop('checked')).toEqual(false); $('#fileList tr td.filename input:checkbox').click(); expect($('.select-all').prop('checked')).toEqual(true); }); it('Selecting all files on the first visible page will not automatically check "select all" checkbox', function() { fileList.setFiles(generateFiles(0, 41)); expect($('.select-all').prop('checked')).toEqual(false); $('#fileList tr td.filename input:checkbox').click(); expect($('.select-all').prop('checked')).toEqual(false); }); it('Selecting all files also selects hidden files when invisible', function() { filesConfig.set('showhidden', false); var $tr = fileList.add(new FileInfo({ name: '.hidden', type: 'dir', mimetype: 'httpd/unix-directory', size: 150 })); $('.select-all').click(); expect($tr.find('td.filename input:checkbox').prop('checked')).toEqual(true); expect(_.pluck(fileList.getSelectedFiles(), 'name')).toContain('.hidden'); }); it('Clicking "select all" will select/deselect all files', function() { fileList.setFiles(generateFiles(0, 41)); $('.select-all').click(); expect($('.select-all').prop('checked')).toEqual(true); $('#fileList tr input:checkbox').each(function() { expect($(this).prop('checked')).toEqual(true); }); expect(_.pluck(fileList.getSelectedFiles(), 'name').length).toEqual(42); $('.select-all').click(); expect($('.select-all').prop('checked')).toEqual(false); $('#fileList tr input:checkbox').each(function() { expect($(this).prop('checked')).toEqual(false); }); expect(_.pluck(fileList.getSelectedFiles(), 'name').length).toEqual(0); }); it('Clicking "select all" then deselecting a file will uncheck "select all"', function() { $('.select-all').click(); expect($('.select-all').prop('checked')).toEqual(true); var $tr = fileList.findFileEl('One.txt'); $tr.find('input:checkbox').click(); expect($('.select-all').prop('checked')).toEqual(false); expect(_.pluck(fileList.getSelectedFiles(), 'name').length).toEqual(3); }); it('Updates the selection summary when doing a few manipulations with "Select all"', function() { $('.select-all').click(); expect($('.select-all').prop('checked')).toEqual(true); var $tr = fileList.findFileEl('One.txt'); // unselect one $tr.find('input:checkbox').click(); expect($('.select-all').prop('checked')).toEqual(false); expect(_.pluck(fileList.getSelectedFiles(), 'name').length).toEqual(3); // select all $('.select-all').click(); expect($('.select-all').prop('checked')).toEqual(true); expect(_.pluck(fileList.getSelectedFiles(), 'name').length).toEqual(4); // unselect one $tr.find('input:checkbox').click(); expect($('.select-all').prop('checked')).toEqual(false); expect(_.pluck(fileList.getSelectedFiles(), 'name').length).toEqual(3); // re-select it $tr.find('input:checkbox').click(); expect($('.select-all').prop('checked')).toEqual(true); expect(_.pluck(fileList.getSelectedFiles(), 'name').length).toEqual(4); }); it('Auto-selects files on next page when "select all" is checked', function() { fileList.setFiles(generateFiles(0, 41)); $('.select-all').click(); expect(fileList.$fileList.find('tr input:checkbox:checked').length).toEqual(20); fileList._nextPage(true); expect(fileList.$fileList.find('tr input:checkbox:checked').length).toEqual(40); fileList._nextPage(true); expect(fileList.$fileList.find('tr input:checkbox:checked').length).toEqual(42); expect(_.pluck(fileList.getSelectedFiles(), 'name').length).toEqual(42); }); it('Selecting files updates selection summary', function() { var $summary = $('#headerName a.name>span:first'); expect($summary.text()).toEqual('Name'); fileList.findFileEl('One.txt').find('input:checkbox').click(); fileList.findFileEl('Three.pdf').find('input:checkbox').click(); fileList.findFileEl('somedir').find('input:checkbox').click(); expect($summary.text()).toEqual('1 folder and 2 files'); }); it('Unselecting files hides selection summary', function() { var $summary = $('#headerName a.name>span:first'); fileList.findFileEl('One.txt').find('input:checkbox').click().click(); expect($summary.text()).toEqual('Name'); }); it('Displays the number of hidden files in selection summary if hidden files are invisible', function() { filesConfig.set('showhidden', false); var $tr = fileList.add(new FileInfo({ name: '.hidden', type: 'dir', mimetype: 'httpd/unix-directory', size: 150 })); $('.select-all').click(); var $summary = $('#headerName a.name>span:first'); expect($summary.text()).toEqual('2 folders and 3 files (including 1 hidden)'); }); it('Does not displays the number of hidden files in selection summary if hidden files are visible', function() { filesConfig.set('showhidden', true); var $tr = fileList.add(new FileInfo({ name: '.hidden', type: 'dir', mimetype: 'httpd/unix-directory', size: 150 })); $('.select-all').click(); var $summary = $('#headerName a.name>span:first'); expect($summary.text()).toEqual('2 folders and 3 files'); }); it('Toggling hidden file visibility updates selection summary', function() { filesConfig.set('showhidden', false); var $tr = fileList.add(new FileInfo({ name: '.hidden', type: 'dir', mimetype: 'httpd/unix-directory', size: 150 })); $('.select-all').click(); var $summary = $('#headerName a.name>span:first'); expect($summary.text()).toEqual('2 folders and 3 files (including 1 hidden)'); filesConfig.set('showhidden', true); expect($summary.text()).toEqual('2 folders and 3 files'); }); it('Select/deselect files shows/hides file actions', function() { var $actions = $('#headerName .selectedActions'); var $checkbox = fileList.findFileEl('One.txt').find('input:checkbox'); expect($actions.hasClass('hidden')).toEqual(true); $checkbox.click(); expect($actions.hasClass('hidden')).toEqual(false); $checkbox.click(); expect($actions.hasClass('hidden')).toEqual(true); }); it('Selection is cleared when switching dirs', function() { $('.select-all').click(); var deferredList = $.Deferred(); var getFolderContentsStub = sinon.stub(filesClient, 'getFolderContents').returns(deferredList.promise()); fileList.changeDirectory('/'); deferredList.resolve(200, [testRoot].concat(testFiles)); expect($('.select-all').prop('checked')).toEqual(false); expect(_.pluck(fileList.getSelectedFiles(), 'name')).toEqual([]); getFolderContentsStub.restore(); }); it('getSelectedFiles returns the selected files even when they are on the next page', function() { var selectedFiles; fileList.setFiles(generateFiles(0, 41)); $('.select-all').click(); // unselect one to not have the "allFiles" case fileList.$fileList.find('tr input:checkbox:first').click(); // only 20 files visible, must still return all the selected ones selectedFiles = _.pluck(fileList.getSelectedFiles(), 'name'); expect(selectedFiles.length).toEqual(41); }); describe('clearing the selection', function() { it('clears selected files selected individually calling setFiles()', function() { var selectedFiles; fileList.setFiles(generateFiles(0, 41)); fileList.$fileList.find('tr:eq(5) input:checkbox:first').click(); fileList.$fileList.find('tr:eq(7) input:checkbox:first').click(); selectedFiles = _.pluck(fileList.getSelectedFiles(), 'name'); expect(selectedFiles.length).toEqual(2); fileList.setFiles(generateFiles(0, 2)); selectedFiles = _.pluck(fileList.getSelectedFiles(), 'name'); expect(selectedFiles.length).toEqual(0); }); it('clears selected files selected with select all when calling setFiles()', function() { var selectedFiles; fileList.setFiles(generateFiles(0, 41)); $('.select-all').click(); selectedFiles = _.pluck(fileList.getSelectedFiles(), 'name'); expect(selectedFiles.length).toEqual(42); fileList.setFiles(generateFiles(0, 2)); selectedFiles = _.pluck(fileList.getSelectedFiles(), 'name'); expect(selectedFiles.length).toEqual(0); }); }); describe('Selection overlay', function() { it('show doesnt show the delete action if one or more files are not deletable', function () { fileList.setFiles(testFiles); $('#permissions').val(OC.PERMISSION_READ | OC.PERMISSION_DELETE); $('.select-all').click(); expect(fileList.$el.find('.delete-selected').hasClass('hidden')).toEqual(false); testFiles[0].permissions = OC.PERMISSION_READ; $('.select-all').click(); fileList.setFiles(testFiles); $('.select-all').click(); expect(fileList.$el.find('.delete-selected').hasClass('hidden')).toEqual(true); }); }); describe('Actions', function() { beforeEach(function() { fileList.findFileEl('One.txt').find('input:checkbox').click(); fileList.findFileEl('Three.pdf').find('input:checkbox').click(); fileList.findFileEl('somedir').find('input:checkbox').click(); }); it('getSelectedFiles returns the selected file data', function() { var files = fileList.getSelectedFiles(); expect(files.length).toEqual(3); expect(files[0]).toEqual({ id: 1, name: 'One.txt', mimetype: 'text/plain', mtime: 123456789, type: 'file', size: 12, etag: 'abc', permissions: OC.PERMISSION_ALL }); expect(files[1]).toEqual({ id: 3, type: 'file', name: 'Three.pdf', mimetype: 'application/pdf', mtime: 234560000, size: 58009, etag: '123', permissions: OC.PERMISSION_ALL }); expect(files[2]).toEqual({ id: 4, type: 'dir', name: 'somedir', mimetype: 'httpd/unix-directory', mtime: 134560000, size: 250, etag: '456', permissions: OC.PERMISSION_ALL }); expect(files[0].id).toEqual(1); expect(files[0].name).toEqual('One.txt'); expect(files[1].id).toEqual(3); expect(files[1].name).toEqual('Three.pdf'); expect(files[2].id).toEqual(4); expect(files[2].name).toEqual('somedir'); }); it('Removing a file removes it from the selection', function() { fileList.remove('Three.pdf'); var files = fileList.getSelectedFiles(); expect(files.length).toEqual(2); expect(files[0]).toEqual({ id: 1, name: 'One.txt', mimetype: 'text/plain', mtime: 123456789, type: 'file', size: 12, etag: 'abc', permissions: OC.PERMISSION_ALL }); expect(files[1]).toEqual({ id: 4, type: 'dir', name: 'somedir', mimetype: 'httpd/unix-directory', mtime: 134560000, size: 250, etag: '456', permissions: OC.PERMISSION_ALL }); }); describe('Download', function() { it('Opens download URL when clicking "Download"', function() { $('.selectedActions .download').click(); expect(redirectStub.calledOnce).toEqual(true); expect(redirectStub.getCall(0).args[0]).toContain(OC.webroot + '/index.php/apps/files/ajax/download.php?' + 'dir=%2Fsubdir&files[]=One.txt&files[]=Three.pdf&files[]=somedir'); redirectStub.restore(); }); it('Downloads root folder when all selected in root folder', function() { $('#dir').val('/'); $('.select-all').click(); $('.selectedActions .download').click(); expect(redirectStub.calledOnce).toEqual(true); expect(redirectStub.getCall(0).args[0]).toContain(OC.webroot + '/index.php/apps/files/ajax/download.php?dir=%2F&files='); }); it('Downloads parent folder when all selected in subfolder', function() { $('.select-all').click(); $('.selectedActions .download').click(); expect(redirectStub.calledOnce).toEqual(true); expect(redirectStub.getCall(0).args[0]).toContain(OC.webroot + '/index.php/apps/files/ajax/download.php?dir=%2F&files=subdir'); }); }); describe('Delete', function() { var deleteStub, deferredDelete; beforeEach(function() { deferredDelete = $.Deferred(); deleteStub = sinon.stub(filesClient, 'remove').returns(deferredDelete.promise()); }); afterEach(function() { deleteStub.restore(); }); it('Deletes selected files when "Delete" clicked', function() { $('.selectedActions .delete-selected').click(); expect(deleteStub.callCount).toEqual(3); expect(deleteStub.getCall(0).args[0]).toEqual('/subdir/One.txt'); expect(deleteStub.getCall(1).args[0]).toEqual('/subdir/Three.pdf'); expect(deleteStub.getCall(2).args[0]).toEqual('/subdir/somedir'); deferredDelete.resolve(204); expect(fileList.findFileEl('One.txt').length).toEqual(0); expect(fileList.findFileEl('Three.pdf').length).toEqual(0); expect(fileList.findFileEl('somedir').length).toEqual(0); expect(fileList.findFileEl('Two.jpg').length).toEqual(1); }); it('Deletes all files when all selected when "Delete" clicked', function() { $('.select-all').click(); $('.selectedActions .delete-selected').click(); expect(deleteStub.callCount).toEqual(4); expect(deleteStub.getCall(0).args[0]).toEqual('/subdir/One.txt'); expect(deleteStub.getCall(1).args[0]).toEqual('/subdir/Two.jpg'); expect(deleteStub.getCall(2).args[0]).toEqual('/subdir/Three.pdf'); expect(deleteStub.getCall(3).args[0]).toEqual('/subdir/somedir'); deferredDelete.resolve(204); expect(fileList.isEmpty).toEqual(true); }); }); }); it('resets the file selection on reload', function() { fileList.$el.find('.select-all').click(); fileList.reload(); expect(fileList.$el.find('.select-all').prop('checked')).toEqual(false); expect(fileList.getSelectedFiles()).toEqual([]); }); describe('Disabled selection', function() { beforeEach(function() { fileList._allowSelection = false; fileList.setFiles(testFiles); }); it('Does not render checkboxes', function() { expect(fileList.$fileList.find('.selectCheckBox').length).toEqual(0); }); it('Does not select a file with Ctrl or Shift if selection is not allowed', function() { var $tr = fileList.findFileEl('One.txt'); var $tr2 = fileList.findFileEl('Three.pdf'); var e; e = new $.Event('click'); e.ctrlKey = true; $tr.find('td.filename .name').trigger(e); // click on second entry, does not clear the selection e = new $.Event('click'); e.ctrlKey = true; $tr2.find('td.filename .name').trigger(e); expect(fileList.getSelectedFiles().length).toEqual(0); // deselect now e = new $.Event('click'); e.shiftKey = true; $tr2.find('td.filename .name').trigger(e); expect(fileList.getSelectedFiles().length).toEqual(0); }); }); }); describe('Details sidebar', function() { beforeEach(function() { fileList.setFiles(testFiles); fileList.showDetailsView('Two.jpg'); }); describe('registering', function() { var addTabStub; var addDetailStub; beforeEach(function() { addTabStub = sinon.stub(OCA.Files.DetailsView.prototype, 'addTabView'); addDetailStub = sinon.stub(OCA.Files.DetailsView.prototype, 'addDetailView'); }); afterEach(function() { addTabStub.restore(); addDetailStub.restore(); }); it('forward the registered views to the underlying DetailsView', function() { fileList.destroy(); fileList = new OCA.Files.FileList($('#app-content-files'), { detailsViewEnabled: true }); fileList.registerTabView(new OCA.Files.DetailTabView()); fileList.registerDetailView(new OCA.Files.DetailFileInfoView()); expect(addTabStub.calledOnce).toEqual(true); // twice because the filelist already registers one by default expect(addDetailStub.calledTwice).toEqual(true); }); it('does not error when registering panels when not details view configured', function() { fileList.destroy(); fileList = new OCA.Files.FileList($('#app-content-files'), { detailsViewEnabled: false }); fileList.registerTabView(new OCA.Files.DetailTabView()); fileList.registerDetailView(new OCA.Files.DetailFileInfoView()); expect(addTabStub.notCalled).toEqual(true); expect(addDetailStub.notCalled).toEqual(true); }); }); it('triggers file action when clicking on row if no details view configured', function() { fileList.destroy(); fileList = new OCA.Files.FileList($('#app-content-files'), { detailsViewEnabled: false }); var updateDetailsViewStub = sinon.stub(fileList, '_updateDetailsView'); var actionStub = sinon.stub(); fileList.setFiles(testFiles); fileList.fileActions.register( 'text/plain', 'Test', OC.PERMISSION_ALL, function() { // Specify icon for hitory button return OC.imagePath('core','actions/history'); }, actionStub ); fileList.fileActions.setDefault('text/plain', 'Test'); var $tr = fileList.findFileEl('One.txt'); $tr.find('td.filename>a.name').click(); expect(actionStub.calledOnce).toEqual(true); expect(updateDetailsViewStub.notCalled).toEqual(true); updateDetailsViewStub.restore(); }); it('highlights current file when clicked and updates sidebar', function() { fileList.fileActions.setDefault('text/plain', 'Test'); var $tr = fileList.findFileEl('One.txt'); $tr.find('td.filename>a.name').click(); expect($tr.hasClass('highlighted')).toEqual(true); expect(fileList._detailsView.getFileInfo().id).toEqual(1); }); it('keeps the last highlighted file when clicking outside', function() { var $tr = fileList.findFileEl('One.txt'); $tr.find('td.filename>a.name').click(); fileList.$el.find('tfoot').click(); expect($tr.hasClass('highlighted')).toEqual(true); expect(fileList._detailsView.getFileInfo().id).toEqual(1); }); it('removes last highlighted file when selecting via checkbox', function() { var $tr = fileList.findFileEl('One.txt'); // select $tr.find('td.filename>a.name').click(); $tr.find('input:checkbox').click(); expect($tr.hasClass('highlighted')).toEqual(false); // deselect $tr.find('td.filename>a.name').click(); $tr.find('input:checkbox').click(); expect($tr.hasClass('highlighted')).toEqual(false); expect(fileList._detailsView.getFileInfo()).toEqual(null); }); it('removes last highlighted file when selecting all files via checkbox', function() { var $tr = fileList.findFileEl('One.txt'); // select $tr.find('td.filename>a.name').click(); fileList.$el.find('.select-all.checkbox').click(); expect($tr.hasClass('highlighted')).toEqual(false); // deselect $tr.find('td.filename>a.name').click(); fileList.$el.find('.select-all.checkbox').click(); expect($tr.hasClass('highlighted')).toEqual(false); expect(fileList._detailsView.getFileInfo()).toEqual(null); }); it('closes sidebar whenever the currently highlighted file was removed from the list', function() { var $tr = fileList.findFileEl('One.txt'); $tr.find('td.filename>a.name').click(); expect($tr.hasClass('highlighted')).toEqual(true); expect(fileList._detailsView.getFileInfo().id).toEqual(1); expect($('#app-sidebar').hasClass('disappear')).toEqual(false); fileList.remove('One.txt'); expect($('#app-sidebar').hasClass('disappear')).toEqual(true); }); it('returns the currently selected model instance when calling getModelForFile', function() { var $tr = fileList.findFileEl('One.txt'); $tr.find('td.filename>a.name').click(); var model1 = fileList.getModelForFile('One.txt'); var model2 = fileList.getModelForFile('One.txt'); model1.set('test', true); // it's the same model expect(model2).toEqual(model1); var model3 = fileList.getModelForFile($tr); expect(model3).toEqual(model1); }); it('closes the sidebar when switching folders', function() { var $tr = fileList.findFileEl('One.txt'); $tr.find('td.filename>a.name').click(); expect($('#app-sidebar').hasClass('disappear')).toEqual(false); fileList.changeDirectory('/another'); expect($('#app-sidebar').hasClass('disappear')).toEqual(true); }); }); describe('File actions', function() { it('Clicking on a file name will trigger default action', function() { var actionStub = sinon.stub(); fileList.setFiles(testFiles); fileList.fileActions.registerAction({ mime: 'text/plain', name: 'Test', type: OCA.Files.FileActions.TYPE_INLINE, permissions: OC.PERMISSION_ALL, icon: function() { // Specify icon for hitory button return OC.imagePath('core','actions/history'); }, actionHandler: actionStub }); fileList.fileActions.setDefault('text/plain', 'Test'); var $tr = fileList.findFileEl('One.txt'); $tr.find('td.filename .nametext').click(); expect(actionStub.calledOnce).toEqual(true); expect(actionStub.getCall(0).args[0]).toEqual('One.txt'); var context = actionStub.getCall(0).args[1]; expect(context.$file.is($tr)).toEqual(true); expect(context.fileList).toBeDefined(); expect(context.fileActions).toBeDefined(); expect(context.dir).toEqual('/subdir'); }); it('redisplays actions when new actions have been registered', function() { var actionStub = sinon.stub(); var readyHandler = sinon.stub(); var clock = sinon.useFakeTimers(); var debounceStub = sinon.stub(_, 'debounce').callsFake(function(callback) { return function() { // defer instead of debounce, to make it work with clock _.defer(callback); }; }); // need to reinit the list to make the debounce call fileList.destroy(); fileList = new OCA.Files.FileList($('#app-content-files')); fileList.setFiles(testFiles); fileList.$fileList.on('fileActionsReady', readyHandler); fileList.fileActions.registerAction({ mime: 'text/plain', name: 'Test', type: OCA.Files.FileActions.TYPE_INLINE, permissions: OC.PERMISSION_ALL, icon: function() { // Specify icon for hitory button return OC.imagePath('core','actions/history'); }, actionHandler: actionStub }); var $tr = fileList.findFileEl('One.txt'); expect($tr.find('.action-test').length).toEqual(0); expect(readyHandler.notCalled).toEqual(true); // update is delayed clock.tick(100); expect($tr.find('.action-test').length).toEqual(1); expect(readyHandler.calledOnce).toEqual(true); clock.restore(); debounceStub.restore(); }); }); describe('Sorting files', function() { var currentUserStub; beforeEach(function() { currentUserStub = sinon.stub(OC, 'getCurrentUser').returns({uid: 'user1'}); }); afterEach(function() { currentUserStub.restore(); }); it('Toggles the sort indicator when clicking on a column header', function() { var ASC_CLASS = fileList.SORT_INDICATOR_ASC_CLASS; var DESC_CLASS = fileList.SORT_INDICATOR_DESC_CLASS; var request; var sortingUrl = OC.generateUrl('/apps/files/api/v1/sorting'); fileList.$el.find('.column-size .columntitle').click(); // moves triangle to size column, check indicator on name is hidden expect( fileList.$el.find('.column-name .sort-indicator').hasClass('hidden') ).toEqual(true); // check indicator on size is visible and defaults to descending expect( fileList.$el.find('.column-size .sort-indicator').hasClass('hidden') ).toEqual(false); expect( fileList.$el.find('.column-size .sort-indicator').hasClass(DESC_CLASS) ).toEqual(true); // check if changes are persisted expect(fakeServer.requests.length).toEqual(1); request = fakeServer.requests[0]; expect(request.url).toEqual(sortingUrl); // click again on size column, reverses direction fileList.$el.find('.column-size .columntitle').click(); expect( fileList.$el.find('.column-size .sort-indicator').hasClass('hidden') ).toEqual(false); expect( fileList.$el.find('.column-size .sort-indicator').hasClass(ASC_CLASS) ).toEqual(true); // check if changes are persisted expect(fakeServer.requests.length).toEqual(2); request = fakeServer.requests[1]; expect(request.url).toEqual(sortingUrl); // click again on size column, reverses direction fileList.$el.find('.column-size .columntitle').click(); expect( fileList.$el.find('.column-size .sort-indicator').hasClass('hidden') ).toEqual(false); expect( fileList.$el.find('.column-size .sort-indicator').hasClass(DESC_CLASS) ).toEqual(true); expect(fakeServer.requests.length).toEqual(3); request = fakeServer.requests[2]; expect(request.url).toEqual(sortingUrl); // click on mtime column, moves indicator there fileList.$el.find('.column-mtime .columntitle').click(); expect( fileList.$el.find('.column-size .sort-indicator').hasClass('hidden') ).toEqual(true); expect( fileList.$el.find('.column-mtime .sort-indicator').hasClass('hidden') ).toEqual(false); expect( fileList.$el.find('.column-mtime .sort-indicator').hasClass(DESC_CLASS) ).toEqual(true); expect(fakeServer.requests.length).toEqual(4); request = fakeServer.requests[3]; expect(request.url).toEqual(sortingUrl); }); it('Uses correct sort comparator when inserting files', function() { testFiles.sort(OCA.Files.FileList.Comparators.size); testFiles.reverse(); //default is descending fileList.setFiles(testFiles); fileList.$el.find('.column-size .columntitle').click(); var newFileData = new FileInfo({ id: 999, name: 'new file.txt', mimetype: 'text/plain', size: 40001, etag: '999' }); fileList.add(newFileData); expect(fileList.findFileEl('Three.pdf').index()).toEqual(0); expect(fileList.findFileEl('new file.txt').index()).toEqual(1); expect(fileList.findFileEl('Two.jpg').index()).toEqual(2); expect(fileList.findFileEl('somedir').index()).toEqual(3); expect(fileList.findFileEl('One.txt').index()).toEqual(4); expect(fileList.files.length).toEqual(5); expect(fileList.$fileList.find('tr').length).toEqual(5); }); it('Uses correct reversed sort comparator when inserting files', function() { testFiles.sort(OCA.Files.FileList.Comparators.size); fileList.setFiles(testFiles); fileList.$el.find('.column-size .columntitle').click(); // reverse sort fileList.$el.find('.column-size .columntitle').click(); var newFileData = new FileInfo({ id: 999, name: 'new file.txt', mimetype: 'text/plain', size: 40001, etag: '999' }); fileList.add(newFileData); expect(fileList.findFileEl('One.txt').index()).toEqual(0); expect(fileList.findFileEl('somedir').index()).toEqual(1); expect(fileList.findFileEl('Two.jpg').index()).toEqual(2); expect(fileList.findFileEl('new file.txt').index()).toEqual(3); expect(fileList.findFileEl('Three.pdf').index()).toEqual(4); expect(fileList.files.length).toEqual(5); expect(fileList.$fileList.find('tr').length).toEqual(5); }); it('does not sort when clicking on header whenever multiselect is enabled', function() { var sortStub = sinon.stub(OCA.Files.FileList.prototype, 'setSort'); fileList.setFiles(testFiles); fileList.findFileEl('One.txt').find('input:checkbox:first').click(); fileList.$el.find('.column-size .columntitle').click(); expect(sortStub.notCalled).toEqual(true); // can sort again after deselecting fileList.findFileEl('One.txt').find('input:checkbox:first').click(); fileList.$el.find('.column-size .columntitle').click(); expect(sortStub.calledOnce).toEqual(true); sortStub.restore(); }); }); describe('create file', function() { var deferredCreate; var deferredInfo; var createStub; var getFileInfoStub; beforeEach(function() { deferredCreate = $.Deferred(); deferredInfo = $.Deferred(); createStub = sinon.stub(filesClient, 'putFileContents') .returns(deferredCreate.promise()); getFileInfoStub = sinon.stub(filesClient, 'getFileInfo') .returns(deferredInfo.promise()); }); afterEach(function() { createStub.restore(); getFileInfoStub.restore(); }); it('creates file with given name and adds it to the list', function() { fileList.createFile('test.txt'); expect(createStub.calledOnce).toEqual(true); expect(createStub.getCall(0).args[0]).toEqual('/subdir/test.txt'); expect(createStub.getCall(0).args[2]).toEqual({ contentType: 'text/plain', overwrite: true }); deferredCreate.resolve(200); expect(getFileInfoStub.calledOnce).toEqual(true); expect(getFileInfoStub.getCall(0).args[0]).toEqual('/subdir/test.txt'); deferredInfo.resolve( 200, new FileInfo({ path: '/subdir', name: 'test.txt', mimetype: 'text/plain' }) ); var $tr = fileList.findFileEl('test.txt'); expect($tr.length).toEqual(1); expect($tr.attr('data-mime')).toEqual('text/plain'); }); // TODO: error cases // TODO: unique name cases }); describe('create folder', function() { var deferredCreate; var deferredInfo; var createStub; var getFileInfoStub; beforeEach(function() { deferredCreate = $.Deferred(); deferredInfo = $.Deferred(); createStub = sinon.stub(filesClient, 'createDirectory') .returns(deferredCreate.promise()); getFileInfoStub = sinon.stub(filesClient, 'getFileInfo') .returns(deferredInfo.promise()); }); afterEach(function() { createStub.restore(); getFileInfoStub.restore(); }); it('creates folder with given name and adds it to the list', function() { fileList.createDirectory('sub dir'); expect(createStub.calledOnce).toEqual(true); expect(createStub.getCall(0).args[0]).toEqual('/subdir/sub dir'); deferredCreate.resolve(200); expect(getFileInfoStub.calledOnce).toEqual(true); expect(getFileInfoStub.getCall(0).args[0]).toEqual('/subdir/sub dir'); deferredInfo.resolve( 200, new FileInfo({ path: '/subdir', name: 'sub dir', mimetype: 'httpd/unix-directory' }) ); var $tr = fileList.findFileEl('sub dir'); expect($tr.length).toEqual(1); expect($tr.attr('data-mime')).toEqual('httpd/unix-directory'); }); // TODO: error cases // TODO: unique name cases }); describe('addAndFetchFileInfo', function() { var getFileInfoStub; var getFileInfoDeferred; beforeEach(function() { getFileInfoDeferred = $.Deferred(); getFileInfoStub = sinon.stub(OC.Files.Client.prototype, 'getFileInfo'); getFileInfoStub.returns(getFileInfoDeferred.promise()); }); afterEach(function() { getFileInfoStub.restore(); }); it('does not fetch if the given folder is not the current one', function() { var promise = fileList.addAndFetchFileInfo('testfile.txt', '/another'); expect(getFileInfoStub.notCalled).toEqual(true); expect(promise.state()).toEqual('resolved'); }); it('fetches info when folder is the current one', function() { fileList.addAndFetchFileInfo('testfile.txt', '/subdir'); expect(getFileInfoStub.calledOnce).toEqual(true); expect(getFileInfoStub.getCall(0).args[0]).toEqual('/subdir/testfile.txt'); }); it('adds file data to list when fetching is done', function() { fileList.addAndFetchFileInfo('testfile.txt', '/subdir'); getFileInfoDeferred.resolve(200, { name: 'testfile.txt', size: 100 }); expect(fileList.findFileEl('testfile.txt').attr('data-size')).toEqual('100'); }); it('replaces file data to list when fetching is done', function() { fileList.addAndFetchFileInfo('testfile.txt', '/subdir', {replace: true}); fileList.add({ name: 'testfile.txt', size: 95 }); getFileInfoDeferred.resolve(200, { name: 'testfile.txt', size: 100 }); expect(fileList.findFileEl('testfile.txt').attr('data-size')).toEqual('100'); }); it('resolves promise with file data when fetching is done', function() { var promise = fileList.addAndFetchFileInfo('testfile.txt', '/subdir', {replace: true}); getFileInfoDeferred.resolve(200, { name: 'testfile.txt', size: 100 }); expect(promise.state()).toEqual('resolved'); promise.then(function(status, data) { expect(status).toEqual(200); expect(data.name).toEqual('testfile.txt'); expect(data.size).toEqual(100); }); }); }); /** * Test upload mostly by testing the code inside the event handlers * that were registered on the magic upload object */ describe('file upload', function() { var uploadData; var uploader; beforeEach(function() { fileList.setFiles(testFiles); uploader = fileList._uploader; // simulate data structure from jquery.upload uploadData = { files: [{ name: 'upload.txt' }] }; }); afterEach(function() { uploader = null; uploadData = null; }); describe('enableupload', function() { it('sets up uploader when enableUpload is true', function() { expect(fileList._uploader).toBeDefined(); }); it('does not sets up uploader when enableUpload is false', function() { fileList.destroy(); fileList = new OCA.Files.FileList($('#app-content-files'), { filesClient: filesClient }); expect(fileList._uploader).toBeFalsy(); }); }); describe('adding files for upload', function() { /** * Simulate add event on the given target * * @return event object including the result */ function addFile(data) { uploader.trigger('add', {}, data || {}); } it('sets target dir to the current directory', function() { addFile(uploadData); expect(uploadData.targetDir).toEqual('/subdir'); }); }); describe('dropping external files', function() { /** * Simulate drop event on the given target * * @param $target target element to drop on * @return event object including the result */ function dropOn($target, data) { var eventData = { originalEvent: { delegatedEvent: { target: $target } } }; uploader.trigger('drop', eventData, data || {}); return !!data.targetDir; } it('drop on a tr or crumb outside file list does not trigger upload', function() { var $anotherTable = $('<table><tbody><tr><td>outside<div class="crumb">crumb</div></td></tr></table>'); var ev; $('#testArea').append($anotherTable); ev = dropOn($anotherTable.find('tr'), uploadData); expect(ev).toEqual(false); ev = dropOn($anotherTable.find('.crumb'), uploadData); expect(ev).toEqual(false); }); it('drop on an element outside file list container does not trigger upload', function() { var $anotherEl = $('<div>outside</div>'); var ev; $('#testArea').append($anotherEl); ev = dropOn($anotherEl, uploadData); expect(ev).toEqual(false); }); it('drop on an element inside the table triggers upload', function() { var ev; ev = dropOn(fileList.$fileList.find('th:first'), uploadData); expect(ev).not.toEqual(false); expect(uploadData.targetDir).toEqual('/subdir'); }); it('drop on an element on the table container triggers upload', function() { var ev; ev = dropOn($('#app-content-files'), uploadData); expect(ev).not.toEqual(false); expect(uploadData.targetDir).toEqual('/subdir'); }); it('drop on an element inside the table does not trigger upload if no upload permission', function() { $('#permissions').val(0); var ev; ev = dropOn(fileList.$fileList.find('th:first'), uploadData); expect(ev).toEqual(false); expect(notificationStub.calledOnce).toEqual(true); }); it('drop on an folder does not trigger upload if no upload permission on that folder', function() { var $tr = fileList.findFileEl('somedir'); var ev; $tr.data('permissions', OC.PERMISSION_READ); ev = dropOn($tr, uploadData); expect(ev).toEqual(false); expect(notificationStub.calledOnce).toEqual(true); }); it('drop on a file row inside the table triggers upload to current folder', function() { var ev; ev = dropOn(fileList.findFileEl('One.txt').find('td:first'), uploadData); expect(ev).not.toEqual(false); expect(uploadData.targetDir).toEqual('/subdir'); }); it('drop on a folder row inside the table triggers upload to target folder', function() { var ev; ev = dropOn(fileList.findFileEl('somedir').find('td:eq(2)'), uploadData); expect(ev).not.toEqual(false); expect(uploadData.targetDir).toEqual('/subdir/somedir'); }); it('drop on a breadcrumb inside the table triggers upload to target folder', function() { var ev; fileList.changeDirectory('a/b/c/d'); ev = dropOn(fileList.$el.find('.crumb:eq(2)'), uploadData); expect(ev).not.toEqual(false); expect(uploadData.targetDir).toEqual('/a/b'); }); it('renders upload indicator element for folders only', function() { fileList.add({ name: 'afolder', type: 'dir', mime: 'httpd/unix-directory' }); fileList.add({ name: 'afile.txt', type: 'file', mime: 'text/plain' }); expect(fileList.findFileEl('afolder').find('.uploadtext').length).toEqual(1); expect(fileList.findFileEl('afile.txt').find('.uploadtext').length).toEqual(0); }); }); describe('after folder creation due to folder upload', function() { it('fetches folder info', function() { var fetchInfoStub = sinon.stub(fileList, 'addAndFetchFileInfo'); uploader.trigger('createdfolder', '/subdir/newfolder'); expect(fetchInfoStub.calledOnce).toEqual(true); expect(fetchInfoStub.getCall(0).args[0]).toEqual('newfolder'); expect(fetchInfoStub.getCall(0).args[1]).toEqual('/subdir'); fetchInfoStub.restore(); }); }); describe('after upload', function() { var fetchInfoStub; beforeEach(function() { fetchInfoStub = sinon.stub(fileList, 'addAndFetchFileInfo'); }); afterEach(function() { fetchInfoStub.restore(); }); function createUpload(name, dir) { var jqXHR = { status: 200 }; return { getFileName: sinon.stub().returns(name), getFullPath: sinon.stub().returns(dir), data: { jqXHR: jqXHR } }; } /** * Simulate add event on the given target * * @return event object including the result */ function addFile(data) { var ev = new $.Event('done', { jqXHR: {status: 200} }); var deferred = $.Deferred(); fetchInfoStub.returns(deferred.promise()); uploader.trigger('done', ev, data || {}); return deferred; } it('fetches file info', function() { addFile(createUpload('upload.txt', '/subdir')); expect(fetchInfoStub.calledOnce).toEqual(true); expect(fetchInfoStub.getCall(0).args[0]).toEqual('upload.txt'); expect(fetchInfoStub.getCall(0).args[1]).toEqual('/subdir'); }); it('highlights all uploaded files after all fetches are done', function() { var highlightStub = sinon.stub(fileList, 'highlightFiles'); var def1 = addFile(createUpload('upload.txt', '/subdir')); var def2 = addFile(createUpload('upload2.txt', '/subdir')); var def3 = addFile(createUpload('upload3.txt', '/another')); uploader.trigger('stop', {}); expect(highlightStub.notCalled).toEqual(true); def1.resolve(); expect(highlightStub.notCalled).toEqual(true); def2.resolve(); def3.resolve(); expect(highlightStub.calledOnce).toEqual(true); expect(highlightStub.getCall(0).args[0]).toEqual(['upload.txt', 'upload2.txt']); highlightStub.restore(); }); it('queries storage stats after all fetches are done', function() { var statStub = sinon.stub(fileList, 'updateStorageStatistics'); var highlightStub = sinon.stub(fileList, 'highlightFiles'); var def1 = addFile(createUpload('upload.txt', '/subdir')); var def2 = addFile(createUpload('upload2.txt', '/subdir')); var def3 = addFile(createUpload('upload3.txt', '/another')); uploader.trigger('stop', {}); expect(statStub.notCalled).toEqual(true); def1.resolve(); expect(statStub.notCalled).toEqual(true); def2.resolve(); def3.resolve(); expect(statStub.calledOnce).toEqual(true); highlightStub.restore(); }); }); }); describe('Handling errors', function () { var deferredList; var getFolderContentsStub; beforeEach(function() { deferredList = $.Deferred(); getFolderContentsStub = sinon.stub(filesClient, 'getFolderContents'); getFolderContentsStub.onCall(0).returns(deferredList.promise()); getFolderContentsStub.onCall(1).returns($.Deferred().promise()); fileList.reload(); }); afterEach(function() { getFolderContentsStub.restore(); fileList = undefined; }); it('redirects to root folder in case of forbidden access', function () { deferredList.reject(403); expect(fileList.getCurrentDirectory()).toEqual('/'); expect(getFolderContentsStub.calledTwice).toEqual(true); }); it('redirects to root folder and shows notification in case of internal server error', function () { expect(notificationStub.notCalled).toEqual(true); deferredList.reject(500); expect(fileList.getCurrentDirectory()).toEqual('/'); expect(getFolderContentsStub.calledTwice).toEqual(true); expect(notificationStub.calledOnce).toEqual(true); }); it('redirects to root folder and shows notification in case of storage not available', function () { expect(notificationStub.notCalled).toEqual(true); deferredList.reject(503, 'Storage is temporarily not available'); expect(fileList.getCurrentDirectory()).toEqual('/'); expect(getFolderContentsStub.calledTwice).toEqual(true); expect(notificationStub.calledOnce).toEqual(true); }); }); describe('showFileBusyState', function() { var $tr; beforeEach(function() { fileList.setFiles(testFiles); $tr = fileList.findFileEl('Two.jpg'); }); it('shows spinner on busy rows', function() { fileList.showFileBusyState('Two.jpg', true); expect($tr.hasClass('busy')).toEqual(true); expect(OC.TestUtil.getImageUrl($tr.find('.thumbnail'))) .toEqual( OC.TestUtil.buildAbsoluteUrl(OC.imagePath('core', 'loading.gif'))); fileList.showFileBusyState('Two.jpg', false); expect($tr.hasClass('busy')).toEqual(false); expect(OC.TestUtil.getImageUrl($tr.find('.thumbnail'))) .toEqual( OC.TestUtil.buildAbsoluteUrl(OC.imagePath('core', 'filetypes/image.svg'))); }); it('accepts multiple input formats', function() { _.each([ 'Two.jpg', ['Two.jpg'], $tr, [$tr] ], function(testCase) { fileList.showFileBusyState(testCase, true); expect($tr.hasClass('busy')).toEqual(true); fileList.showFileBusyState(testCase, false); expect($tr.hasClass('busy')).toEqual(false); }); }); }); describe('elementToFile', function() { var $tr; beforeEach(function() { fileList.setFiles(testFiles); $tr = fileList.findFileEl('One.txt'); }); it('converts data attributes to file info structure', function() { var fileInfo = fileList.elementToFile($tr); expect(fileInfo.id).toEqual(1); expect(fileInfo.name).toEqual('One.txt'); expect(fileInfo.mtime).toEqual(123456789); expect(fileInfo.etag).toEqual('abc'); expect(fileInfo.permissions).toEqual(OC.PERMISSION_ALL); expect(fileInfo.size).toEqual(12); expect(fileInfo.mimetype).toEqual('text/plain'); expect(fileInfo.type).toEqual('file'); expect(fileInfo.path).not.toBeDefined(); }); it('adds path attribute if available', function() { $tr.attr('data-path', '/subdir'); var fileInfo = fileList.elementToFile($tr); expect(fileInfo.path).toEqual('/subdir'); }); }); describe('new file menu', function() { var newFileMenuStub; beforeEach(function() { newFileMenuStub = sinon.stub(OCA.Files.NewFileMenu.prototype, 'showAt'); }); afterEach(function() { newFileMenuStub.restore(); }) it('renders new button when no legacy upload button exists', function() { expect(fileList.$el.find('.button.upload').length).toEqual(0); expect(fileList.$el.find('.button.new').length).toEqual(1); }); it('does not render new button when no legacy upload button exists (public page)', function() { fileList.destroy(); $('#controls').append('<input type="button" class="button upload" />'); fileList = new OCA.Files.FileList($('#app-content-files')); expect(fileList.$el.find('.button.upload').length).toEqual(1); expect(fileList.$el.find('.button.new').length).toEqual(0); }); it('opens the new file menu when clicking on the "New" button', function() { var $button = fileList.$el.find('.button.new'); $button.click(); expect(newFileMenuStub.calledOnce).toEqual(true); }); it('does not open the new file menu when button is disabled', function() { var $button = fileList.$el.find('.button.new'); $button.addClass('disabled'); $button.click(); expect(newFileMenuStub.notCalled).toEqual(true); }); }); describe('mount type detection', function() { function testMountType(dirInfoId, dirInfoMountType, inputMountType, expectedMountType) { var $tr; fileList.dirInfo.id = dirInfoId; fileList.dirInfo.mountType = dirInfoMountType; $tr = fileList.add({ type: 'dir', mimetype: 'httpd/unix-directory', name: 'test dir', mountType: inputMountType }); expect($tr.attr('data-mounttype')).toEqual(expectedMountType); } it('leaves mount type as is if no parent exists', function() { testMountType(null, null, 'external', 'external'); testMountType(null, null, 'shared', 'shared'); }); it('detects share root if parent exists', function() { testMountType(123, null, 'shared', 'shared-root'); testMountType(123, 'shared', 'shared', 'shared'); testMountType(123, 'shared-root', 'shared', 'shared'); }); it('detects external storage root if parent exists', function() { testMountType(123, null, 'external', 'external-root'); testMountType(123, 'external', 'external', 'external'); testMountType(123, 'external-root', 'external', 'external'); }); }); describe('file list should not refresh if url does not change', function() { var fileListStub; beforeEach(function() { fileListStub = sinon.stub(OCA.Files.FileList.prototype, 'changeDirectory'); }); afterEach(function() { fileListStub.restore(); }); it('File list must not be refreshed', function() { $('#app-content-files').trigger(new $.Event('urlChanged', {dir: '/subdir'})); expect(fileListStub.notCalled).toEqual(true); }); it('File list must be refreshed', function() { $('#app-content-files').trigger(new $.Event('urlChanged', {dir: '/'})); expect(fileListStub.notCalled).toEqual(false); }); }); });
import streams from "../apis/streams"; import {FETCH_STREAM} from "./types"; export default (id) =>{ return async(dispatch, getState)=>{ const response = await streams.get(`/streams/${id}`); dispatch({type: FETCH_STREAM, payload: response.data}) } }
// api key for twitter go here for easier access and cleaner code // twitter api key info exports.twitterKeys = { consumer_key: 'LXSloFXv2dUydjxaaX66Dxye1', consumer_secret: 'q2MJbYSCcSsDMyMYZr5U0mnP2EfasxJqLj1MTBdoF819VpS2TT', access_token_key: '906230281-b3owan8cdn9ggA8k4apMEESrXHgnBthAfvepsUDy', access_token_secret: '69dh7tCq9DfGea3k92SKJoYlcS9ZqDQ0wojub2bK730pU' };
import React, { useState, useEffect } from 'react'; import styled from 'styled-components'; const SearchBox = styled.div` display: flex; justify-content: center; align-items: center; width: 250px; height: 70px; ` const SearchBoxContent = styled.div` margin-top: 20px; input { padding: 1rem 2rem; border-radius: 25px; border: none; background-color: #ffe694; color: black; } ` const SearchBar = ({handleQueryChange, handleSearchValueChange}) => { const [searchValue, setSearchValue] = useState(''); const handleInputChange = (event) => { setSearchValue(event.currentTarget.value); } useEffect(() => { if(searchValue !== '') { handleQueryChange(`search/movie`) handleSearchValueChange(`query=${searchValue}`) } else { handleQueryChange(`movie/popular`) handleSearchValueChange('') } }, [searchValue]) return ( <SearchBox> <SearchBoxContent> <input type="text" placeholder="Search.." onChange={handleInputChange} value={searchValue} /> </SearchBoxContent> </SearchBox> ); } export default SearchBar;
/** * @author Raoul Harel * @license The MIT license (LICENSE.txt) * @copyright 2015 Raoul Harel * @url https://github.com/rharel/webgl-dm-voronoi */ /** * The main class of the library. Responsible for initializing a drawing canvas * (from scratch or from an existing one) and exposes an interface for creating * voronoi sites. * * Currently we support the following sites: point, and line (segment). * * @param options * An object with the following optional properties: * canvas: * If present, will render into this element. Otherwise, will create * a new canvas. The library user needs to add it to the DOM him/herself. * * width, height: * Desired size of the canvas, ignored if the canvas option is available. * * precision: * Positive integer which controls diagram refinement. The higher, the more * detailed will the distance-meshes be, and thus the more correct * the rendering becomes. * * markers: * Boolean. Indicates whether the site markers are initially visible. * * @constructor */ function Diagram(options) { options = _parseOptions(options); if (options.canvas === null) { this._canvas = _createCanvas(options.width, options.height); } else { this._canvas = options.canvas; } this._3d = new Context3D(this._canvas); this._precision = options.precision; this._sites = {}; this._id = 0; this._nSites = 0; this._maxDistance = Math.max(this._canvas.width, this._canvas.height); this._pointDistanceGeometry = PointSite.distanceGeometry(this._precision); this._lineDistancGeometry = { edge: LineSite.edgeDistanceGeometry(), endpoint: LineSite.endpointDistanceGeometry(this._precision) }; this._markerLayer = new MarkerLayer(); this._markerLayer.visible = options.markers; this._3d.add(this._markerLayer.origin); function _parseOptions(options) { var defaultOptions = { canvas: null, width: 500, height: 500, precision: 16, markers: true }; if (typeof options === 'undefined') { return defaultOptions; } else { options.canvas = options.canvas || null; options.width = +options.width || defaultOptions.width; options.height = +options.height || defaultOptions.height; options.precision = +options.precision || defaultOptions.precision; options.markers = !!options.markers; return options; } } function _createCanvas(width, height) { var canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height; return canvas; } } Diagram.prototype = { constructor: Diagram, _parseColor: function(color) { if (typeof color === 'string') { return new THREE.Color(color); } else { return new THREE.Color(color.r, color.g, color.b); } }, /** * Creates a new point site. * @returns {PointSite} * The object returned is a reference to the created site. * Changing the reference properties will have immediate effect on the * diagram. */ point: function(x, y, color) { color = this._parseColor(color); var site = new PointSite( this._id++, x, y, this._maxDistance, this._pointDistanceGeometry, this._3d.material(color) ); this._add(site); return site; }, /** * Creates a new line site. * * @param a Object with {x: y:} * @param b Object with {x: y:} * @param color * Either a css style string, or an object with {r:[0-1] g:[0-1] b:[0-1]}. * * @returns {LineSite} * The object returned is a reference to the created site. * Changing the reference properties will have immediate effect on the * diagram. */ line: function(a, b, color) { color = this._parseColor(color); var site = new LineSite( this._id++, a, b, this._maxDistance, this._lineDistancGeometry, this._3d.material(color) ); this._add(site); return site; }, _add: function(site) { this._sites[site.id] = site; this._nSites++; this._3d.add(site.origin); this._markerLayer.add(site); }, /** * Removes a site from the diagram. * * @param id_or_site * Either the site.id or the site object itself. * * @returns {boolean} True if the site was removed. */ remove: function(id_or_site) { var id = (typeof id_or_site === 'number') ? id_or_site : id_or_site.id; if (this._sites.hasOwnProperty(id)) { var site = this._sites[id]; this._markerLayer.remove(site); this._3d.remove(site.origin); delete this._sites[id]; this._nSites--; return true; } else { return false; } }, /** * Renders the diagram onto the canvas. */ render: function() { if (this._markerLayer.visible) { this._markerLayer.update(); } this._3d.render(); }, /** * Resizes the diagram. * * Call this when the canvas' dimensions have changed. */ resize: function() { this._maxDistance = Math.max(this._canvas.width, this._canvas.height); this._3d.resize(); for (var id in this._sites) { this._sites[id].radius = this._maxDistance; } }, /** * Gets the canvas tied to this. */ get canvas() { return this._canvas; }, /** * Gets the precision of this. */ get precision() { return this._precision; }, /** * Gets the number of sites (of all types together). * * @returns {number} */ get nSites() { return this._nSites; }, /** * Gets the marker layer object of this. * * @returns {MarkerLayer} */ get markers() { return this._markerLayer; } };
import React, {Component} from 'react'; class Header extends Component { render() { return ( <header className="header"> <div className="container"> <div className="header-left"> <a className="header-item" href="#"> React </a> </div> <span className="header-toggle"> <span></span> <span></span> <span></span> </span> <div className="header-right header-menu"> <span className="header-item"> <a className="button" href="#">Login</a> </span> </div> </div> </header> ); } } ; export default Header;
module.exports = { states: [ { "bounds_max_lat": 35.02499, "bounds_max_long": -84.92153, "bounds_min_lat": 30.23092, "bounds_min_long": -88.4862, "code": "USA-AL", "full_name": "Alabama", "short_name": "AL" }, { "bounds_max_lat": 71.40768, "bounds_max_long": -130.01407, "bounds_min_lat": 51.60367, "bounds_min_long": -178.19452, "code": "USA-AK", "full_name": "Alaska", "short_name": "AK" }, { "bounds_max_lat": 60, "bounds_max_long": -109.98324, "bounds_min_lat": 48.9931, "bounds_min_long": -120, "code": "CAN-AB", "full_name": "Alberta", "short_name": "AB" }, { "bounds_max_lat": 37.00415, "bounds_max_long": -109.04667, "bounds_min_lat": 31.32421, "bounds_min_long": -114.83596, "code": "USA-AZ", "full_name": "Arizona", "short_name": "AZ" }, { "bounds_max_lat": 36.50087, "bounds_max_long": -89.68891, "bounds_min_lat": 33.01199, "bounds_min_long": -94.61838, "code": "USA-AR", "full_name": "Arkansas", "short_name": "AR" }, { "bounds_max_lat": -35.13944, "bounds_max_long": 149.40692, "bounds_min_lat": -35.92084, "bounds_min_long": 148.76721, "code": "AUS-ACT", "full_name": "Australian Capital Territory", "short_name": "ACT" }, { "bounds_max_lat": 60.03069, "bounds_max_long": -114.08384, "bounds_min_lat": 48.34609, "bounds_min_long": -139.0378, "code": "CAN-BC", "full_name": "British Columbia", "short_name": "BC" }, { "bounds_max_lat": 42.00077, "bounds_max_long": -114.12502, "bounds_min_lat": 32.53336, "bounds_min_long": -124.37165, "code": "USA-CA", "full_name": "California", "short_name": "CA" }, { "bounds_max_lat": 41.00086, "bounds_max_long": -102.01279, "bounds_min_lat": 37.00084, "bounds_min_long": -109.04667, "code": "USA-CO", "full_name": "Colorado", "short_name": "CO" }, { "bounds_max_lat": 42.05557, "bounds_max_long": -71.79579, "bounds_min_lat": 40.99187, "bounds_min_long": -73.72301, "code": "USA-CT", "full_name": "Connecticut", "short_name": "CT" }, { "bounds_max_lat": 39.84343, "bounds_max_long": -75.03588, "bounds_min_lat": 38.45486, "bounds_min_long": -75.78472, "code": "USA-DE", "full_name": "Delaware", "short_name": "DE" }, { "bounds_max_lat": 39.01178, "bounds_max_long": -76.93124, "bounds_min_lat": 38.80652, "bounds_min_long": -77.12206, "code": "USA-DC", "full_name": "District of Columbia", "short_name": "DC" }, { "bounds_max_lat": 31.00167, "bounds_max_long": -80.04131, "bounds_min_lat": 24.54235, "bounds_min_long": -87.60744, "code": "USA-FL", "full_name": "Florida", "short_name": "FL" }, { "bounds_max_lat": 35.00148, "bounds_max_long": -80.87234, "bounds_min_lat": 30.37135, "bounds_min_long": -85.62361, "code": "USA-GA", "full_name": "Georgia", "short_name": "GA" }, { "bounds_max_lat": 28.22117, "bounds_max_long": -154.80419, "bounds_min_lat": 18.96391, "bounds_min_long": -177.39048, "code": "USA-HI", "full_name": "Hawaii", "short_name": "HI" }, { "bounds_max_lat": 48.99308, "bounds_max_long": -111.0503, "bounds_min_lat": 42.00056, "bounds_min_long": -117.2017, "code": "USA-ID", "full_name": "Idaho", "short_name": "ID" }, { "bounds_max_lat": 42.51299, "bounds_max_long": -87.03913, "bounds_min_lat": 36.99211, "bounds_min_long": -91.50164, "code": "USA-IL", "full_name": "Illinois", "short_name": "IL" }, { "bounds_max_lat": 41.76076, "bounds_max_long": -84.78963, "bounds_min_lat": 37.78803, "bounds_min_long": -88.09531, "code": "USA-IN", "full_name": "Indiana", "short_name": "IN" }, { "bounds_max_lat": 43.50241, "bounds_max_long": -90.14943, "bounds_min_lat": 40.37945, "bounds_min_long": -96.62684, "code": "USA-IA", "full_name": "Iowa", "short_name": "IA" }, { "bounds_max_lat": 40.00149, "bounds_max_long": -94.61807, "bounds_min_lat": 37.00084, "bounds_min_long": -102.02449, "code": "USA-KS", "full_name": "Kansas", "short_name": "KS" }, { "bounds_max_lat": 39.1289, "bounds_max_long": -81.96528, "bounds_min_lat": 36.49968, "bounds_min_long": -89.56003, "code": "USA-KY", "full_name": "Kentucky", "short_name": "KY" }, { "bounds_max_lat": 33.01592, "bounds_max_long": -88.81258, "bounds_min_lat": 28.98133, "bounds_min_long": -94.0433, "code": "USA-LA", "full_name": "Louisiana", "short_name": "LA" }, { "bounds_max_lat": 47.46299, "bounds_max_long": -66.98702, "bounds_min_lat": 43.07003, "bounds_min_long": -71.08454, "code": "USA-ME", "full_name": "Maine", "short_name": "ME" }, { "bounds_max_lat": 60.0087, "bounds_max_long": -88.96088, "bounds_min_lat": 48.99624, "bounds_min_long": -102, "code": "CAN-MB", "full_name": "Manitoba", "short_name": "MB" }, { "bounds_max_lat": 39.7228, "bounds_max_long": -75.03766, "bounds_min_lat": 37.95396, "bounds_min_long": -79.48798, "code": "USA-MD", "full_name": "Maryland", "short_name": "MD" }, { "bounds_max_lat": 42.88157, "bounds_max_long": -69.93384, "bounds_min_lat": 41.24947, "bounds_min_long": -73.50729, "code": "USA-MA", "full_name": "Massachusetts", "short_name": "MA" }, { "bounds_max_lat": 48.3031, "bounds_max_long": -82.13785, "bounds_min_lat": 41.70143, "bounds_min_long": -90.41259, "code": "USA-MI", "full_name": "Michigan", "short_name": "MI" }, { "bounds_max_lat": 49.36967, "bounds_max_long": -89.49838, "bounds_min_lat": 43.50117, "bounds_min_long": -97.22574, "code": "USA-MN", "full_name": "Minnesota", "short_name": "MN" }, { "bounds_max_lat": 35.00112, "bounds_max_long": -88.08477, "bounds_min_lat": 30.19263, "bounds_min_long": -91.65644, "code": "USA-MS", "full_name": "Mississippi", "short_name": "MS" }, { "bounds_max_lat": 40.62465, "bounds_max_long": -89.12249, "bounds_min_lat": 35.99274, "bounds_min_long": -95.76503, "code": "USA-MO", "full_name": "Missouri", "short_name": "MO" }, { "bounds_max_lat": 48.99313, "bounds_max_long": -104.00478, "bounds_min_lat": 44.39662, "bounds_min_long": -116.04901, "code": "USA-MT", "full_name": "Montana", "short_name": "MT" }, { "bounds_max_lat": 43.00141, "bounds_max_long": -95.34668, "bounds_min_lat": 40.00112, "bounds_min_long": -104.02886, "code": "USA-NE", "full_name": "Nebraska", "short_name": "NE" }, { "bounds_max_lat": 42.00111, "bounds_max_long": -114.04027, "bounds_min_lat": 34.99112, "bounds_min_long": -120.00081, "code": "USA-NV", "full_name": "Nevada", "short_name": "NV" }, { "bounds_max_lat": 48.05031, "bounds_max_long": -63.86091, "bounds_min_lat": 45.03891, "bounds_min_long": -69.0457, "code": "CAN-NB", "full_name": "New Brunswick", "short_name": "NB" }, { "bounds_max_lat": 60.41152, "bounds_max_long": -52.54375, "bounds_min_lat": 46.61466, "bounds_min_long": -67.80453, "code": "CAN-NL", "full_name": "Newfoundland and Labrador", "short_name": "NL" }, { "bounds_max_lat": 45.29401, "bounds_max_long": -70.73309, "bounds_min_lat": 42.70248, "bounds_min_long": -72.5528, "code": "USA-NH", "full_name": "New Hampshire", "short_name": "NH" }, { "bounds_max_lat": 41.3573, "bounds_max_long": -73.91008, "bounds_min_lat": 38.94114, "bounds_min_long": -75.52425, "code": "USA-NJ", "full_name": "New Jersey", "short_name": "NJ" }, { "bounds_max_lat": 37.00084, "bounds_max_long": -103.0003, "bounds_min_lat": 31.32788, "bounds_min_long": -109.04781, "code": "USA-NM", "full_name": "New Mexico", "short_name": "NM" }, { "bounds_max_lat": -28.15011, "bounds_max_long": 159.1019, "bounds_min_lat": -37.51267, "bounds_min_long": 140.99786, "code": "AUS-NSW", "full_name": "New South Wales", "short_name": "NSW" }, { "bounds_max_lat": 46.18721, "bounds_max_long": -71.9032, "bounds_min_lat": 40.51872, "bounds_min_long": -79.76303, "code": "USA-NY", "full_name": "New York", "short_name": "NY" }, { "bounds_max_lat": 36.61058, "bounds_max_long": -75.45647, "bounds_min_lat": 33.87667, "bounds_min_long": -84.32469, "code": "USA-NC", "full_name": "North Carolina", "short_name": "NC" }, { "bounds_max_lat": 48.99319, "bounds_max_long": -96.5564, "bounds_min_lat": 45.94278, "bounds_min_long": -104.03393, "code": "USA-ND", "full_name": "North Dakota", "short_name": "ND" }, { "bounds_max_lat": -11.01139, "bounds_max_long": 138.00082, "bounds_min_lat": -26.0049, "bounds_min_long": 128.99997, "code": "AUS-NT", "full_name": "Northern Territory", "short_name": "NT" }, { "bounds_max_lat": 78.73526, "bounds_max_long": -102, "bounds_min_lat": 59.9881, "bounds_min_long": -136.4512, "code": "CAN-NT", "full_name": "Northwest Territories", "short_name": "NT" }, { "bounds_max_lat": 47.05282, "bounds_max_long": -59.7525, "bounds_min_lat": 43.45679, "bounds_min_long": -66.20085, "code": "CAN-NS", "full_name": "Nova Scotia", "short_name": "NS" }, { "bounds_max_lat": 83.14809, "bounds_max_long": -61.02131, "bounds_min_lat": 55.65507, "bounds_min_long": -120.67909, "code": "CAN-NU", "full_name": "Nunavut", "short_name": "NU" }, { "bounds_max_lat": 42.32439, "bounds_max_long": -80.51908, "bounds_min_lat": 38.41497, "bounds_min_long": -84.82172, "code": "USA-OH", "full_name": "Ohio", "short_name": "OH" }, { "bounds_max_lat": 37.00084, "bounds_max_long": -94.43914, "bounds_min_lat": 33.64844, "bounds_min_long": -103.00084, "code": "USA-OK", "full_name": "Oklahoma", "short_name": "OK" }, { "bounds_max_lat": 56.89806, "bounds_max_long": -74.35808, "bounds_min_lat": 41.9715, "bounds_min_long": -95.15772, "code": "CAN-ON", "full_name": "Ontario", "short_name": "ON" }, { "bounds_max_lat": 46.22545, "bounds_max_long": -116.47705, "bounds_min_lat": 42.00056, "bounds_min_long": -124.53963, "code": "USA-OR", "full_name": "Oregon", "short_name": "OR" }, { "bounds_max_lat": 42.53898, "bounds_max_long": -74.69905, "bounds_min_lat": 39.72236, "bounds_min_long": -80.52076, "code": "USA-PA", "full_name": "Pennsylvania", "short_name": "PA" }, { "bounds_max_lat": 47.04936, "bounds_max_long": -62.0666, "bounds_min_lat": 45.97394, "bounds_min_long": -64.46341, "code": "CAN-PE", "full_name": "Prince Edward Island", "short_name": "PE" }, { "bounds_max_lat": 62.7889, "bounds_max_long": -57.1134, "bounds_min_lat": 44.9836, "bounds_min_long": -81.12309, "code": "CAN-QC", "full_name": "Quebec", "short_name": "QC" }, { "bounds_max_lat": -10.05139, "bounds_max_long": 153.5433, "bounds_min_lat": -29.17056, "bounds_min_long": 138, "code": "AUS-QLD", "full_name": "Queensland", "short_name": "QLD" }, { "bounds_max_lat": 42.01687, "bounds_max_long": -71.23205, "bounds_min_lat": 41.33091, "bounds_min_long": -71.84235, "code": "USA-RI", "full_name": "Rhode Island", "short_name": "RI" }, { "bounds_max_lat": 60, "bounds_max_long": -101.34937, "bounds_min_lat": 49, "bounds_min_long": -110, "code": "CAN-SK", "full_name": "Saskatchewan", "short_name": "SK" }, { "bounds_max_lat": -25.99944, "bounds_max_long": 141.00266, "bounds_min_lat": -38.07389, "bounds_min_long": 129, "code": "AUS-SA", "full_name": "South Australia", "short_name": "SA" }, { "bounds_max_lat": 35.21093, "bounds_max_long": -78.56427, "bounds_min_lat": 32.02957, "bounds_min_long": -83.35558, "code": "USA-SC", "full_name": "South Carolina", "short_name": "SC" }, { "bounds_max_lat": 45.94306, "bounds_max_long": -96.45362, "bounds_min_lat": 42.51126, "bounds_min_long": -104.03721, "code": "USA-SD", "full_name": "South Dakota", "short_name": "SD" }, { "bounds_max_lat": -39.43195, "bounds_max_long": 158.96329, "bounds_min_lat": -54.75389, "bounds_min_long": 143.83469, "code": "AUS-TAS", "full_name": "Tasmania", "short_name": "TAS" }, { "bounds_max_lat": 36.69301, "bounds_max_long": -81.65889, "bounds_min_lat": 34.9881, "bounds_min_long": -90.29376, "code": "USA-TN", "full_name": "Tennessee", "short_name": "TN" }, { "bounds_max_lat": 36.50123, "bounds_max_long": -93.53059, "bounds_min_lat": 25.87051, "bounds_min_long": -106.66826, "code": "USA-TX", "full_name": "Texas", "short_name": "TX" }, { "bounds_max_lat": 42.00111, "bounds_max_long": -109.04639, "bounds_min_lat": 37.00084, "bounds_min_long": -114.04259, "code": "USA-UT", "full_name": "Utah", "short_name": "UT" }, { "bounds_max_lat": 45.00756, "bounds_max_long": -71.51023, "bounds_min_lat": 42.73031, "bounds_min_long": -73.42613, "code": "USA-VT", "full_name": "Vermont", "short_name": "VT" }, { "bounds_max_lat": -33.98779, "bounds_max_long": 149.97775, "bounds_min_lat": -39.14722, "bounds_min_long": 140.96664, "code": "AUS-VIC", "full_name": "Victoria", "short_name": "VIC" }, { "bounds_max_lat": 39.45186, "bounds_max_long": -75.22579, "bounds_min_lat": 36.55051, "bounds_min_long": -83.66752, "code": "USA-VA", "full_name": "Virginia", "short_name": "VA" }, { "bounds_max_lat": 48.99308, "bounds_max_long": -116.89648, "bounds_min_lat": 45.59107, "bounds_min_long": -124.70998, "code": "USA-WA", "full_name": "Washington", "short_name": "WA" }, { "bounds_max_lat": -13.72669, "bounds_max_long": 129.00589, "bounds_min_lat": -35.13834, "bounds_min_long": 112.90721, "code": "AUS-WA", "full_name": "Western Australia", "short_name": "WA" }, { "bounds_max_lat": 40.64695, "bounds_max_long": -77.72665, "bounds_min_lat": 37.20807, "bounds_min_long": -82.61955, "code": "USA-WV", "full_name": "West Virginia", "short_name": "WV" }, { "bounds_max_lat": 47.3091, "bounds_max_long": -86.26452, "bounds_min_lat": 42.49281, "bounds_min_long": -92.89652, "code": "USA-WI", "full_name": "Wisconsin", "short_name": "WI" }, { "bounds_max_lat": 45.00113, "bounds_max_long": -104.02166, "bounds_min_lat": 41.00086, "bounds_min_long": -111.05143, "code": "USA-WY", "full_name": "Wyoming", "short_name": "WY" }, { "bounds_max_lat": 69.64713, "bounds_max_long": -123.9109, "bounds_min_lat": 59.99609, "bounds_min_long": -141.00286, "code": "CAN-YU", "full_name": "Yukon", "short_name": "YT" } ], "success": true }
import { db } from './FirebaseConfig' export function enableModeOffline() { db.enablePersistence().catch(function (err) { if (err.code == 'failed-precondition') { console.log( 'Múltiples TABS abiertas, solo se puede habilitar la persistencia un TAB a la vez' ) } else if (err.code == 'unimplemented') { console.log( 'Este navegador no soporta todas las características que se requiere para habilitar la persistencia' ) } }) console.log('Persistencia habilitada') }
const expect =require('expect'); const { generateMessage, generateLocationMessage } = require('./messages') describe('generateMessage', () => { it('Should generate correct message object', () => { let from = 'senderName'; let text = 'some text body' let res = generateMessage(from, text); expect(res.from).toBe(from) expect(res.text).toBe(text) expect(typeof res.createdAt).toBe('number'); }) }); describe('generateLocationMessage', () => { it('Should generate correct location object', () => { let from = 'SomeName'; let latitude = 2; let longitude = 1; let url = `https://www.google.com/maps?q=${latitude},${longitude}`; let res = generateLocationMessage(from, latitude, longitude); expect(res.from).toBe(from); expect(res.url).toBe(url); expect(res.createdAt).toBeTruthy(); }) })
const cron = require('node-cron'); cron.schedule('*/5 * * * *', () => { // parse lamoda });
import React, { Component } from 'react'; import { Platform, StyleSheet, Text, View, Linking, Button } from 'react-native'; window.navigator.userAgent = 'react-native'; var io = require('socket.io-client/dist/socket.io'); const instructions = Platform.select({ ios: 'Press Cmd+R to reload,\n' + 'Cmd+D or shake for dev menu', android: 'Double tap R on your keyboard to reload,\n' + 'Shake or press menu button for dev menu', }); var logSocket = io('https://logdataingest.riverway.in/astro/logs?app=' + 'location' + '&user=Maya' ); // logSocket.emit('log.info', { errorCode: 8024, errorMessage:'Map init function is initialized' }); // OR // logSocket.emit('log.error', { errorCode: 403, errorMessage: 'Error Message Text', data: { pseudoName: currentUser.pseudoName,sessionid: sessID } }); type Props = {}; // let logSocket = ""; export default class App extends Component<Props> { state = { lat: "", long: "", counter: 0 } constructor() { super(); } componentDidMount() { let success = (position) => { this.setState({ lat: position.coords.latitude, long: position.coords.longitude }) logSocket.emit('log.info', { errorCode: 9898, errorMessage:'Map init function is initialized' }); } let error = (errors) => { logSocket.emit('log.error', { errorCode: 9989, errorMessage: 'Error Message Text', data: { pseudoName: "maya",sessionid:0 } }); } setInterval(() => { navigator.geolocation.getCurrentPosition(success, error) this.setState((prestate) => { return { counter: prestate.counter + 1 } }) }, 1000) } openMap(lat, lng) { const scheme = Platform.select({ ios: 'maps:0,0?q=', android: 'geo:0,0?q=' }); const latLng = `${lat},${lng}`; const label = 'Your Current Location'; const url = Platform.select({ ios: `${scheme}${label}@${latLng}`, android: `${scheme}${latLng}(${label})` }); Linking.openURL(url); } render() { return ( <View style={styles.container}> <Text style={styles.welcome}>counter: {this.state.counter}</Text> <Text style={styles.welcome}>Current Coordinates</Text> <Text style={styles.welcome}>Latitude: {this.state.lat}</Text> <Text style={styles.welcome}>Longitude: {this.state.long}</Text> <Button onPress={() => { this.openMap(this.state.lat, this.state.long) }} title="Open Maps" color="#841584" accessibilityLabel="Learn more about this purple button" /> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, });
E = "101100000111011000000110101110011101100000001010111110010101101111101011110111010111001110101001011101001100001011000000010101111101101011111011010011000010100101110101001101001010010111010101111110101011011111011000000110110000001101100001011010111110110110000000101011100101010100101110100110000101011101111010111000110110000010101011101001011000100110101110110101001111101010111111010101000001101011011011010100010110101110110101011011111010100010110101101101101100001011010110111110101000011101011111001010100010110101101101101100000101010011111010100111110101011011011010111000010101000010101011100101011000101110100110000" A = "10101101111" // a // original function that create the token function createToken(text) { let encrypted = ""; for (let i = 0; i < text.length; i++) { encrypted += ((text[i].charCodeAt(0)-43+1337) >> 0).toString(2) } return encrypted } // try to reverse the function function createTokenReverse(text) { let encrypted = ""; for (let i = 0; i < text.length; i++) { encrypted += ((text[i].charCodeAt(0)-43+1337) >> 0) } return encrypted } // decode one character (binary) to char function decode(text) { let decrypted = ""; decrypted += (String.fromCharCode(parseInt(text, 2)+43-1337)) return decrypted } // decode all the text function decodeAll(text) { let tt = text.match(/.{1,11}/g); let decrypted = ""; for (const t of tt) { decrypted += decode(t) } return decrypted } console.log(createToken("a")) console.log(createTokenReverse("a")) console.log(decode(A)) console.log(decodeAll(E))
//时间轴的 滚动事件 var h = $("#timeline").height(); //1.1滚动通知 var num = 0; function goLeft() { //750是根据你给的尺寸,可变的 // if (num == -750) { if (num == -180) { num = 0; } num -= 1; $("#timeline").css({ top: num }) } //设置滚动速度 var timer = setInterval(goLeft, 25);
const less = require('rollup-plugin-less'); module.exports = { rollup(config, options) { config.plugins.push( less({ insert: true, output: 'dist/style.css', }) ); return config; }, };
module.exports = function (data) { data = data.replace(/\r/g, ''); var regex = /(\d+)\n(\d{2}:\d{2}:\d{2},\d{3}) --> (\d{2}:\d{2}:\d{2},\d{3})/g; data = data.split(regex); data.shift(); var items = []; for (var i = 0; i < data.length; i += 4) { var posText = data[i + 3].trim().replace('\n',' ').replace('\-',''); if(posText.includes("*") || posText.includes("<") || posText.includes(">") || posText.includes("=") || posText.includes("#")) continue; //taking this out because their found in some sort of meta data attrs in srt files. Suck it. items.push({ id: data[i].trim(), text: posText }); } return items; }
// gulp const gulp = require('gulp'); // import tasks const styles = require('./tasks/styles'); const scripts = require('./tasks/scripts'); const icons = require('./tasks/icons'); const images = require('./tasks/images'); const copy = require('./tasks/copy'); const clean = require('./tasks/clean'); const server = require('./tasks/browserSync'); const paths = require('./tasks/paths'); // Watch files const watchFiles = () => { // watch style files gulp.watch( paths.watch.sass, gulp.series(styles.build, server.reload) ); // watch script files gulp.watch( paths.watch.js, gulp.series(scripts.lint, scripts.build, server.reload) ); // watch icon files gulp.watch( paths.watch.svg, gulp.series(clean.icons, icons.build, server.reload) ); // watch image files gulp.watch( paths.watch.img, gulp.series(clean.img, images.optimise, server.reload) ); // watch font files gulp.watch( paths.watch.font, gulp.series(clean.font, copy.fonts, server.reload) ); }; // define tasks const build = gulp.series( clean.dist, gulp.parallel( styles.build, gulp.series(scripts.lint, scripts.build), icons.build, images.optimise, copy.fonts ), gulp.parallel(watchFiles, server.init) ); // expose tasks to CLI exports.default = build;
#! /usr/bin/env node const fs = require('fs'); const path = require('path'); const { execSync } = require('child_process'); const { generate } = require('../dist/index.cjs'); const cloneUrl = 'https://github.com/danielsogl/awesome-cordova-plugins.git'; const clonePath = 'tmp/awesome-cordova-plugins'; const rootPluginsDirectoryPath = path.resolve(path.join(clonePath, 'src/@awesome-cordova-plugins/plugins')); const failures = []; let runCount = 0; function exec(cmd) { console.log('> ' + cmd); execSync(cmd, { stdio: 'inherit' }); } function cleanCloneDirectory() { if (fs.existsSync(clonePath)) { fs.rmSync(clonePath, { recursive: true }); } } function getDirectoryNamesIn(rootDirectory) { return fs.readdirSync(rootDirectory, { withFileTypes: true }) .filter(dirent => dirent.isDirectory()) .map(dirent => dirent.name); } function generatePluginGuard(dirName) { console.log('generatePluginGuard() -> ' + dirName); runCount++; const dirPath = path.resolve(path.join(rootPluginsDirectoryPath, dirName)); const inputFilePath = path.join(dirPath, 'index.ts'); const outputFilePath = path.join(dirPath, 'guard.ts'); const inputFileText = fs.readFileSync(inputFilePath, 'utf8'); const targetClassRegex = new RegExp('export class (' + dirName.replace(/-/g, '') + ') extends', 'gmi'); try { const inputFileTargetClass = targetClassRegex.exec(inputFileText)[1]; const outputFileText = generate({ inputFileText, inputFileTargetClass }); fs.writeFileSync(outputFilePath, outputFileText, 'utf8'); } catch (e) { console.warn('guard generate failed for ' + dirName + ' -> ' + e); failures.push({ path: inputFilePath, plugin: dirName, error: (e + '') }); } } function performStressTest() { cleanCloneDirectory(); exec('git clone ' + cloneUrl + ' ' + clonePath); const pluginDirectories = getDirectoryNamesIn(rootPluginsDirectoryPath); pluginDirectories.forEach(dirName => generatePluginGuard(dirName)); } performStressTest(); if (failures.length > 0) { console.warn('caught ' + failures.length + ' errors (out of ' + runCount + ' runs):'); console.warn(failures); }
import styled from 'styled-components'; export const HeaderTitle = styled.Text` text-align: left; font-size: 34px; font-weight: 600; padding-horizontal: 15px; padding-top: 5px; padding-bottom: 8px; color: #454f63; `;
import { Router } from 'express'; import cadastroRoutes from './cadastro.routes'; import loginRoutes from './login.routes'; import profileRoutes from './profile.routes'; import avatarRoutes from './avatar.routes'; const router = Router(); router.use('/cadastro', cadastroRoutes); router.use('/log', loginRoutes); router.use('/profile', profileRoutes); router.use('/avatar', avatarRoutes); export default router;
import React from "react"; import { createMaterialBottomTabNavigator } from "react-navigation-material-bottom-tabs"; import { createStackNavigator } from "react-navigation"; import { Image } from "react-native"; import { Text, HeaderDetail } from "@app/components"; import Icon from "react-native-vector-icons/FontAwesome"; import Color from "@app/assets/colors"; import Images from "@app/assets/images"; import { HistoryScreen, ProfileScreen } from "@app/screens"; import MainStack from "./MainStack"; const Label = ({ text }) => ( <Text style={{ fontSize: 12, color: Color.textColor, textAlign: "center", fontWeight: "bold" }}> {text} </Text> ); const TabIcon = ({ name }) => ({ focused }) => { if (name == "home") { if (focused) { icon = Images.icon.home_active } else { icon = Images.icon.home } } else if (name == "archive") { if (focused) { icon = Images.icon.archive_active } else { icon = Images.icon.archive } } else if (name == "person") { if (focused) { icon = Images.icon.person_active } else { icon = Images.icon.person } } return ( <Image source={icon} style={{ width: 24, height: 24, resizeMode: "cover" }} /> ) }; const HistoryStack = createStackNavigator({ History: { screen: HistoryScreen, navigationOptions: { headerTitle: <HeaderDetail>Riwayat</HeaderDetail>, headerStyle: { backgroundColor: Color.white, headerTintColor: Color.textColor, } } } }); const ProfileStack = createStackNavigator({ Profile: { screen: ProfileScreen, navigationOptions: { headerTitle: <HeaderDetail>Profil</HeaderDetail>, headerStyle: { backgroundColor: Color.white, headerTintColor: Color.textColor, } } }, }) export default createMaterialBottomTabNavigator( { Home: { screen: MainStack, navigationOptions: { tabBarLabel: <Label text={"Beranda"} />, tabBarIcon: TabIcon({ name: "home" }) } }, History: { screen: HistoryStack, navigationOptions: { tabBarLabel: <Label text={"Riwayat"} />, tabBarIcon: TabIcon({ name: "archive" }) } }, Profile: { screen: ProfileStack, navigationOptions: { tabBarLabel: <Label text={"Profil"} />, tabBarIcon: TabIcon({ name: "person" }) } }, }, { shifting: true, barStyle: { backgroundColor: Color.white }, } );