text
stringlengths
7
3.69M
const storage_path = () => { return 'storage'; } const storage_logs_path = () => { return 'storage/logs'; } const ups_locked_file = () => { return 'storage/instagram_login.locked' } module.exports = { storage_path, ups_locked_file }
const jquery = require('jquery'); const cheerio = require('cheerio'); const request = require('request'); const Nightmare = require('nightmare'); const async = require('async'); nightmare = Nightmare({show:true}); nightmare .goto('https://www.draisbeachclub.com/calendar/') .wait(5000) .evaluate(()=>{ var results = []; $('.uvc-overevent').each(function() { var dataId = $(this).attr('data-id'); var dataDate = $(this).attr('data-date'); results.push('http://www.draisbeachclub.com/uvtix/index.html?id='+dataId+'&date='+dataDate); }); return results; }) .end() .then((data)=>{ async.forEachLimit(data,1,function(data){ nightmare .goto(data) .wait(5000) .end() }) })
// Description of you application // Explain your project's features // Include a short demo video // Tutorial on how to use or interact with your application // Obvious and clear button to link to your live application // "Meet the Engineers" that shows a photo of the you and your team plus links to your LinkedIn, Twitter, and Github // add([ // text(` // Space Invaders was created using // Kaboom.JS JavaScript Library and Replit // `), // origin('topleft'), // // pos(width() / 2) // ]) // const leftArrow = // add([ // sprite('leftArrow'), // scale(.5), // pos(15, height()/2), // origin('center') // ]) // if (mouseIsClicked('leftArrow')) { // go('howToPlay'); // } add([ text("SPACE INVADERS", 20), pos(width() / 2, height() / 20), origin('center') ]); add([ text(`The objective of Space Invaders is to pan across a screen and shoot descending swarms of aliens, preventing them from reaching the bottom of the screen. Best played on full screen. `, 5), pos(width() / 2, height() / 6), origin('center'), ]); add([ sprite('space-invader'), scale(1), pos(width() / 2 - 35, height() / 2), origin('center') ]) add([ sprite('space-ship'), scale(1), pos(width() / 2, height() / 2), origin('center') ]) add([ sprite('space-invader2'), scale(1), pos(width() / 2 + 35, height() / 2), origin('center') ]) add([ text(`Press Space to Play Press 'A' to learn how to play Press 'D' to meet the developer` , 8), origin('center'), pos(width() / 2, height() / 1.1) ]); // Press " i " to learn more // Press " h " to learn how to play // keyDown("a", () => { // go("howToPlay") // }); keyPress("space", () => { go("battle") }); keyPress("d", () => { go("theCreator") }); keyPress("a", () => { go("howToPlay") });
const searchByTitleOrGenre = (item, search) => search .toLowerCase() .split(' ') .every(v => item.title.toLowerCase().includes(v) || item.genre.toLowerCase().includes(v)); const searchPlaylists = (playlists, search) => { const searchResults = []; if (search) { for (const [playlistName, playlistItems] of Object.entries(playlists)) { // Search for the item that matches the search by the single playlist title const matchingPlaylistItems = playlistItems.filter(item => searchByTitleOrGenre(item, search)); // Set the first matching playlist as the search result if (matchingPlaylistItems.length !== 0) { searchResults.push(matchingPlaylistItems); } } } return searchResults; }; var app = new Vue({ el: '#app', data: { searchQuery: null, playlists: { curated: [ { title: "Metal Essentials", color: "red", description: "description", genre: "metal", list: "PLGFMsDB0B5xxoM4NvsnpcCVgyOytis74P", }, { title: "Title2", color: "blue", description: "description", genre: "rock", list: "PLGFMsDB0B5xyqR0LgYHa79ZsWDxBSE_Kq", }, ], recommended: [ { title: "Title 3", color: "blue", description: "description", genre: "indie", list: "PLGFMsDB0B5xyqR0LgYHa79ZsWDxBSE_Kq", }, ], }, }, computed: { resultQuery() { return searchPlaylists(this.playlists, this.searchQuery); } }, }); $('a[action="#dialog"]').click(function() { $('#dialog').addClass('open') $('body').addClass('remove-scrollbar') }) $('a[action="#closedialog"]').click(function() { $('#dialog').removeClass('open') $('body').removeClass('remove-scrollbar') }) // 2. This code loads the IFrame Player API code asynchronously. var tag = document.createElement('script'); tag.src = "https://www.youtube.com/iframe_api"; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); // 3. This function creates an <iframe> (and YouTube player) // after the API code downloads. var player; function onYouTubeIframeAPIReady() { player = new YT.Player('player', { playerVars: { 'playsinline': 1 }, events: { 'onReady': onPlayerReady, 'onStateChange': onPlayerStateChange } }); } function onPlayerReady(event) { event.target.playVideo(); } function changePlayIcon(playerStatus) { if (playerStatus == -1) { document.querySelector('[play]').textContent = 'check_circle'; } else if (playerStatus == 1) { document.querySelector('[play]').textContent = 'pause'; document.querySelector('[play_mini]').textContent = 'pause'; $( ".line-1" ).addClass( "hidden" ); $( ".now_playing" ).removeClass( "hidden" ); var url = player.getVideoUrl(); var match = url.match(/[?&]v=([^&]+)/); videoId = match[1]; $.getJSON('https://noembed.com/embed', {format: 'json', url: url}, function (data) { document.querySelector('.song_title').textContent = data.title.replace(/\(OFFICIAL|MUSIC|VIDEO\)/g,''); }); var thumby = "https://i1.ytimg.com/vi/" + videoId + "/mqdefault.jpg"; document.querySelector('.current_thumbnail').setAttribute("src", thumby); function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); }; function seekBar() { var rangeslider = document.getElementById("sliderRange"); var current = document.getElementById("current_time"); var songLength = document.getElementById("current_length"); rangeslider.max = player.getDuration(); rangeslider.value = player.getCurrentTime(); var s = Math.trunc(player.getCurrentTime()); var minutes = Math.floor(s / 60); var seconds = s - minutes * 60; var s_len = Math.trunc(player.getDuration()); var minutes_len = Math.floor(s_len / 60); var seconds_len = s_len - minutes_len * 60; sleep(0).then(() => { rangeslider.oninput = function() { player.seekTo(this.value); }; current.innerHTML = minutes + ':' + seconds; songLength.innerHTML = minutes_len + ':' + seconds_len; }); }; setInterval(seekBar, 1000); } else if (playerStatus == 2) { document.querySelector('[play]').textContent = 'play_arrow'; document.querySelector('[play_mini]').textContent = 'play_arrow'; } else if (playerStatus == 3) { document.querySelector('[play]').textContent = 'hourglass_empty'; } } function onPlayerStateChange(event) { changePlayIcon(event.data); } function play() { player.playVideo() $(this).one("click", pause); } function pause() { player.pauseVideo() $(this).one("click", play); } document.getElementById("volumeRange").oninput = function() { player.setVolume(this.value); }; $("[play]").one("mousedown", play); $("[play_mini]").one("mousedown", play); $("[skip-next]").on("mousedown", function() { player.nextVideo(); }); $("[skip-prev]").on("mousedown", function() { player.previousVideo(); }); function mute() { player.mute() $(this).one("click", unmute); document.querySelector('[mute]').textContent = 'volume_off'; } function unmute() { player.unMute() $(this).one("click", mute); document.querySelector('[mute]').textContent = 'volume_up'; } $("[mute]").one("click", mute); $("[dropdown].custom").on("mouseover", ".activator", function() { $('[dropdown].custom').removeClass('open'); $(this).parent().toggleClass('open'); }); $(document).on("mouseout", function(event) { var $trigger = $("[dropdown].custom"); if ($trigger !== event.target && !$trigger.has(event.target).length) { $("[dropdown].custom").removeClass("open"); } });
import React, { useRef } from 'react'; import BindedInput from '../BindedInput/BindedInput'; import useForm from './useForm' export default function Form(props) { const formRef = useRef(null); const [state, updateField] = useForm(props.fields); function _onSubmit(e) { e.preventDefault(); formRef.current.checkValidity(); props.onSubmit(state); } return ( <form ref={formRef} onSubmit={_onSubmit} className="Form"> {props.fields.map(field => <BindedInput key={field.id} state={state} updateField={updateField} {...field} />)} <section className="action-btn"> <input type="submit" value={props.buttonText} className="button"></input> </section> </form> ); }
function newOrder() { var checkin = $("#checkin").val(); var checkout = $("#checkout").val(); var year1=checkin.substr(0,4); var year2=checkout.substr(0,4); var month1=checkin.substr(5,2); var month2=checkout.substr(5,2); var day1=checkin.substr(8,2); var day2=checkout.substr(8,2); if (checkin == "") { $("#date_info").html("入住时间不能为空"); return; } if (checkout == "") { $("#date_info").html("退房时间不能为空"); return; } if (checkin == checkout) { $("#date_info").html("入住时间不能与退房时间相同"); return; } if(year1>year2){ $("#date_info").html("入住时间不能晚于退房时间"); return; } else{ if(month1>month2&&year1==year2){ $("#date_info").html("入住时间不能晚于退房时间"); return; }else{ if(day1>day2&&month1==month2){ $("#date_info").html("入住时间不能晚于退房时间"); return; } } } $.ajax({ cache : true, type : "POST", url : "addOrder.action", data:$('#orderForm').serialize(), async : false, error : function(request) { $("#date_info").html("链接错误"); }, success : function(data) { $("#date_info").html(data); // if (data==="下单成功") { alert(data); // } // if (data) { // $("#date_info").html("下单成功"); // } else if (data) { // $("#date_info").html("该段时间已出租"); // } // else if(data){ // $("#date_info").html("您的入住时间不足最小天数"); // } // else if(data){ // $("#date_info").html("您的入住时间超出最大天数"); // } // // else { // $("#date_info").html("输入日期不正确"); // } } }); }
import React from 'react' const Shoes = ({ shoes }) => { return ( <div className="App"> <div className="App-list"> <ul className="App-list__container"> {shoes.map((shoe) => ( <li className="App-list__box"> <div className="App-list__content"> <ul className="App-list__content-card"> <li className="App-list__content-informations"> <span className="App-list__title">Marca:</span> <span className="App-list__data">{shoe.brand}</span> </li> <li className="App-list__content-informations"> <span className="App-list__title">Model:</span> <span className="App-list__data">{shoe.model}</span> </li> <li className="App-list__content-informations"> <span className="App-list__title">Preço:</span> <span className="App-list__data">R$: {shoe.price}</span> </li> <li className="App-list__content-informations"> <span className="App-list__title">Stock:</span> <span className="App-list__data">{shoe.stock}</span> </li> </ul> </div> </li> ))} </ul> </div> </div> ) }; export default Shoes
import React from "react"; import styled, { keyframes } from "react-emotion"; const Shade = ({ onClick, children, className }) => { const fadeIn = keyframes` from { opacity: 0; } to { opacity: 1; } `; const Shade = styled("div")` height: 100vh; width: 100%; position: fixed; top: 0; left: 0; z-index: 99; background-color: rgba(255, 255, 255, 0.5); animation: ${fadeIn} 300ms ease-in; transition: all 0.5s ease-in; `; return ( <Shade className={className} onClick={onClick}> {children} </Shade> ); }; export default Shade;
const express = require('express'); const router = express.Router(); const authMiddleware = require('../middleware/auth-middleware'); const quizController = require('../controllers/quiz-controller'); router.get('/', quizController.getQuizzes); router.get('/quiz/:id', quizController.getQuizByID); router.get('/post/:id', quizController.getQuizByPostID); router.post('/', authMiddleware.verifyToken, quizController.addQuiz); router.put('/', authMiddleware.verifyToken, quizController.updateQuiz); router.delete('/post/:id', authMiddleware.verifyToken, quizController.deleteQuiz); module.exports = router;
const router = require("express").Router(); const withAuth = require("../../middleware/authentication"); const { newPost, getUserPosts, deleteUserPost, updateUserPost } = require("../../controllers/post") router .route("/") .get(withAuth, getUserPosts) .post(withAuth, newPost); router .route("/delete/:id") .delete(withAuth, deleteUserPost); router .route("/update/:id") .put(withAuth, updateUserPost); module.exports = router;
var FeatTrainer = (function () { function FeatTrainer() { this.patternSize = 640; this.levels = 4; this.keyPointsPerlevel = 400; this.blurSize = 5; this.matchThreshold = 48; this._imgU8Smooth = new jsfeat.matrix_t(1, 1, jsfeat.U8_t | jsfeat.C1_t); this._screenCorners = []; } FeatTrainer.prototype._configParameters = function () { jsfeat.yape06.laplacian_threshold = 30; jsfeat.yape06.min_eigen_value_threshold = 25; }; FeatTrainer.prototype.findTransform = function (matches, screenKeyPoints, patternKeyPoints) { var mm_kernel = new jsfeat.motion_model.affine2d(); // ransac params var num_model_points = 4; var reproj_threshold = 3; var ransac_param = new jsfeat.ransac_params_t(num_model_points, reproj_threshold, 0.5, 0.99); var pattern_xy = []; var screen_xy = []; var count = matches.length; // construct correspondences for (var i = 0; i < count; ++i) { var m = matches[i]; var s_kp = screenKeyPoints[m.screen_idx]; var p_kp = patternKeyPoints[m.pattern_lev][m.pattern_idx]; pattern_xy[i] = { x: p_kp.x, y: p_kp.y }; screen_xy[i] = { x: s_kp.x, y: s_kp.y }; } // estimate motion var homo3x3 = new jsfeat.matrix_t(3, 3, jsfeat.F32C1_t); var match_mask = new jsfeat.matrix_t(this.keyPointsPerlevel, 1, jsfeat.U8C1_t); var ok = jsfeat.motion_estimator.ransac(ransac_param, mm_kernel, pattern_xy, screen_xy, count, homo3x3, match_mask, 1000); // extract good matches and re-estimate var good_cnt = 0; if (ok) { for (var i = 0; i < count; ++i) { if (match_mask.data[i]) { pattern_xy[good_cnt].x = pattern_xy[i].x; pattern_xy[good_cnt].y = pattern_xy[i].y; screen_xy[good_cnt].x = screen_xy[i].x; screen_xy[good_cnt].y = screen_xy[i].y; good_cnt++; } } // run kernel directly with inliers only mm_kernel.run(pattern_xy, screen_xy, homo3x3, good_cnt); return { transform: homo3x3, goodMatch: good_cnt }; } }; FeatTrainer.prototype.getGrayScaleMat = function (img) { var width, height, imageData; if (img instanceof Image || img instanceof HTMLImageElement) { width = img.naturalWidth; height = img.naturalHeight; var ctx = getCanvasContext(width, height); ctx.drawImage(img, 0, 0, width, height); imageData = ctx.getImageData(0, 0, width, height).data; } else { width = img.width; height = img.height; imageData = img.data; } var target; if (imageData.length === width * height * 4) { target = new jsfeat.matrix_t(width, height, jsfeat.U8_t | jsfeat.C1_t); jsfeat.imgproc.grayscale(imageData, width, height, target); } else if (imageData.length === width * height) { target = new jsfeat.matrix_t(width, height, jsfeat.U8_t | jsfeat.C1_t, { u8: imageData }); } return target; }; FeatTrainer.prototype.createMatFromUint8Array = function (width, height, bytes) { return new jsfeat.matrix_t(width, height, jsfeat.U8_t | jsfeat.C1_t, { u8: bytes }); }; FeatTrainer.prototype.matchPattern = function (screen_descriptors, pattern_descriptors) { var q_cnt = screen_descriptors.rows; var query_u32 = screen_descriptors.buffer.i32; var qd_off = 0; var qidx = 0, lev = 0, pidx = 0, k = 0; var match_threshold = this.matchThreshold; var num_train_levels = this.levels; var matches = []; for (qidx = 0; qidx < q_cnt; ++qidx) { var best_dist = 256; var best_dist2 = 256; var best_idx = -1; var best_lev = -1; for (lev = 0; lev < num_train_levels; ++lev) { var lev_descr = pattern_descriptors[lev]; var ld_cnt = lev_descr.rows; var ld_i32 = lev_descr.buffer.i32; // cast to integer buffer var ld_off = 0; for (pidx = 0; pidx < ld_cnt; ++pidx) { var curr_d = 0; // our descriptor is 32 bytes so we have 8 Integers for (k = 0; k < 8; ++k) { curr_d += popcnt32(query_u32[qd_off + k] ^ ld_i32[ld_off + k]); } if (curr_d < best_dist) { best_dist2 = best_dist; best_dist = curr_d; best_lev = lev; best_idx = pidx; } else if (curr_d < best_dist2) { best_dist2 = curr_d; } ld_off += 8; // next descriptor } } // filter out by some threshold if (best_dist < match_threshold) { matches.push({ screen_idx: qidx, pattern_lev: best_lev, pattern_idx: best_idx }); } qd_off += 8; // next query descriptor } return matches; }; FeatTrainer.prototype.describeFeatures = function (img_u8) { var img_u8_smooth = this._imgU8Smooth; var screen_corners = this._screenCorners; if (img_u8_smooth.cols !== img_u8.cols || img_u8_smooth.rows !== img_u8.rows) { img_u8_smooth.resize(img_u8.cols, img_u8.rows, img_u8.channel); var i = img_u8.cols * img_u8.rows; while (i-- > 0) { screen_corners[i] = {}; } } jsfeat.imgproc.gaussian_blur(img_u8, img_u8_smooth, this.blurSize); var max_per_level = this.keyPointsPerlevel; var num_corners = this.detectKeyPoints(img_u8_smooth, screen_corners, max_per_level); var descriptors = new jsfeat.matrix_t(32, max_per_level, jsfeat.U8_t | jsfeat.C1_t); jsfeat.orb.describe(img_u8_smooth, screen_corners, num_corners, descriptors); return { keyPoints: screen_corners.slice(0, num_corners), descriptors: descriptors }; }; FeatTrainer.prototype.trainPattern = function (img_u8) { var max_pattern_size = this.patternSize; var num_train_levels = this.levels; var sc0 = Math.min(max_pattern_size / img_u8.cols, max_pattern_size / img_u8.rows, 1); var new_width = (img_u8.cols * sc0); var new_height = (img_u8.rows * sc0); var lev0_img = new jsfeat.matrix_t(img_u8.cols, img_u8.rows, jsfeat.U8_t | jsfeat.C1_t); var lev_img = new jsfeat.matrix_t(img_u8.cols, img_u8.rows, jsfeat.U8_t | jsfeat.C1_t); var pattern_corners = [], pattern_descriptors = []; var sc_inc = Math.sqrt(2.0); var sc = 1; var levels = []; this.resample(img_u8, lev0_img, new_width, new_height); for (var lev = 0; lev < num_train_levels; ++lev) { new_width = (lev0_img.cols * sc); new_height = (lev0_img.rows * sc); this.resample(lev0_img, lev_img, new_width, new_height); var result = this.describeFeatures(lev_img); result.keyPoints.forEach(function (k) { k.x /= sc; k.y /= sc; }); pattern_corners[lev] = result.keyPoints; pattern_descriptors[lev] = result.descriptors; levels.push([new_width, new_height]); sc /= sc_inc; } return { keyPoints: pattern_corners, descriptors: pattern_descriptors, levels: levels }; }; FeatTrainer.prototype.resample = function (src, target, nw, nh) { nw = Math.round(nw); nh = Math.round(nh); var h = src.rows, w = src.cols; if (!target) { target = new jsfeat.matrix_t(nw, nh, jsfeat.U8_t | jsfeat.C1_t); } if (h > nh && w > nw) { jsfeat.imgproc.resample(src, target, nw, nh); } else { target.resize(nw, nh, src.channel); target.data.set(src.data); } return target; }; FeatTrainer.prototype.detectKeyPoints = function (img, corners, max_allowed) { this._configParameters(); var count = jsfeat.yape06.detect(img, corners, 17); // sort by score and reduce the count if needed if (count > max_allowed) { jsfeat.math.qsort(corners, 0, count - 1, function (a, b) { return (b.score < a.score); }); count = max_allowed; } for (var i = 0; i < count; ++i) { corners[i].angle = ic_angle(img, corners[i].x, corners[i].y); } return count; }; return FeatTrainer; }()); var cvs; function getCanvasContext(width, height) { if (!cvs) { cvs = document.createElement('canvas'); } if (width && height) { cvs.width = width; cvs.height = height; } return cvs.getContext('2d'); } function popcnt32(n) { n -= ((n >> 1) & 0x55555555); n = (n & 0x33333333) + ((n >> 2) & 0x33333333); return (((n + (n >> 4)) & 0xF0F0F0F) * 0x1010101) >> 24; } function ic_angle(img, px, py) { var half_k = 15; // half patch size var m_01 = 0, m_10 = 0; var src = img.data, step = img.cols; var u = 0, v = 0, center_off = (py * step + px) | 0; var v_sum = 0, d = 0, val_plus = 0, val_minus = 0; // Treat the center line differently, v=0 for (u = -half_k; u <= half_k; ++u) m_10 += u * src[center_off + u]; // Go line by line in the circular patch for (v = 1; v <= half_k; ++v) { // Proceed over the two lines v_sum = 0; d = u_max[v]; for (u = -d; u <= d; ++u) { val_plus = src[center_off + u + v * step]; val_minus = src[center_off + u - v * step]; v_sum += (val_plus - val_minus); m_10 += u * (val_plus + val_minus); } m_01 += v * v_sum; } return Math.atan2(m_01, m_10); } var u_max = new Int32Array([15, 15, 15, 15, 14, 14, 14, 13, 13, 12, 11, 10, 9, 8, 6, 3, 0]);
function solve() { document.querySelector('#btnSend').addEventListener('click', onClick); function onClick () { let restaurantOutputElement=document.querySelector('#outputs #bestRestaurant p'); let workersOutputElement=document.querySelector('#outputs #workers p'); let textElement=document.querySelector('textarea'); let restaurantsInput=JSON.parse(textElement.value); let restaurants={}; for (const r of restaurantsInput) { let [currRestName, workersStr] = r.split(' - '); if (!restaurants[currRestName]) { restaurants[currRestName]={ name: currRestName, workers: [], bestSalary: 0, averageSalary: 0 }; } let currentRestaurant=restaurants[currRestName]; let workersInfo=workersStr.split(', '); for (const w of workersInfo) { let [workerName, workerSalary]=w.split(' '); workerSalary=Number(workerSalary); let worker={ name: workerName, workerSalary: workerSalary }; currentRestaurant['workers'].push(worker); } } let restaurantObjs=Object.values(restaurants); for (let r of restaurantObjs) { let currentWorkers=r['workers']; let currAvSalary=(currentWorkers .reduce((acc, x)=>acc+=x.workerSalary,0)/currentWorkers.length) .toFixed(2); let currBestSalary=(currentWorkers .sort((a,b)=>b.workerSalary-a.workerSalary)[0].workerSalary) .toFixed(2); r['averageSalary']=currAvSalary; r['bestSalary']=currBestSalary; } let bestRestaurant=Object.values(restaurants) .sort((a, b)=>b.averageSalary-a.averageSalary)[0]; bestRestaurant .workers .sort((a, b)=>b.workerSalary-a.workerSalary); let bestRestaurantOutput=`Name: ${bestRestaurant.name} Average Salary: ${bestRestaurant.averageSalary} Best Salary: ${bestRestaurant.bestSalary}`; restaurantOutputElement.textContent=bestRestaurantOutput; let workersOutput=''; for (const w of bestRestaurant.workers) { workersOutput+=`Name: ${w.name} With Salary: ${w.workerSalary} ` } workersOutputElement.textContent=workersOutput.trimEnd(); } }
import React, { Component } from 'react'; import { List, Input, Button } from 'antd'; import axios from 'axios'; export default class BasicPage extends Component { state = { inputValue: '', todos: [], } componentDidMount() { axios.get('/todolist').then(res => { this.setState({ todos: res.data, }); }); } clickAddBtn = () => { const { inputValue } = this.state; if (!inputValue) return; axios.post('/todolist/add', inputValue).then(res => { this.setState({ inputValue: '', todos: res.data, }); }); } inputValueChang = event => { this.setState({ inputValue: event.target.value }); } deleteTask = index => { axios.delete('/todolist/remove', { data: index }).then(res => { this.setState({ todos: res.data, }); }); } HeaderInput = () => ( <Input value={this.state.inputValue} onChange={this.inputValueChang} placeholder="请输入你要添加的任务" suffix={ <Button onClick={this.clickAddBtn} type="primary">添加</Button> } /> ) render() { return ( <List style={{width: 500}} header={this.HeaderInput()} bordered dataSource={this.state.todos} renderItem={(item, index) => ( <List.Item key={item.task + index} extra={<Button onClick={() => this.deleteTask(index)}>删除</Button>} > {item.task} </List.Item> )} /> ); } }
import React from "react"; import GridList from "@material-ui/core/GridList"; import GridListTile from "@material-ui/core/GridListTile"; import GridListTileBar from "@material-ui/core/GridListTileBar"; import IconButton from "@material-ui/core/IconButton"; import CloudDownload from "@material-ui/icons/CloudDownload"; import { Container, Spinner } from "reactstrap"; import "../App.css"; import { connect } from "react-redux"; import { getPhotoByTag } from "../actions/tagActions"; import { withStyles } from "@material-ui/core/styles"; const styles = (theme => ({ root: { display: "flex", flexWrap: "wrap", justifyContent: "space-around", overflow: "hidden", backgroundColor: theme.palette.background.paper, }, gridList: { width: 500, height: 450, }, icon: { color: "rgba(255, 255, 255, 0.54)", }, })); class SearchResultPage extends React.Component { state = { pathName: "" } componentDidMount() { this.getPathName(); } getPathName = () => { const { pathname } = this.props.location; const currentPath = pathname.substring(pathname.lastIndexOf("/") + 1); this.props.getPhotoByTag(currentPath); this.setState({ pathName: currentPath }); } render() { const { photosByTag } = this.props.tags; const classes = this.props.classes; return ( <React.Fragment> <h1>Photos for {this.state.pathName}</h1> <Container style={{ display: "flex", alignContent: "center", justifyContent: "center", marginTop: "50px", marginBottom: "10px" }}> {photosByTag ? <GridList cellHeight={180} className={classes.gridList} style={{ width: "90%" }}> {photosByTag.map((tile, index) => { return ( <GridListTile key={index}> <img src={tile.photo.data} alt={tile.title} /> <GridListTileBar title={tile.title} subtitle={<span>Uploaded on: {tile.uploadDate}</span>} actionIcon={ <IconButton aria-label={`info about ${tile.title}`} className={classes.icon} onClick={() => window.open(tile.fileURL)}> <CloudDownload /> </IconButton> } /> </GridListTile> ); })} </GridList> : <Spinner animation="border" />} </Container> </React.Fragment> ); } } const mapStateToProps = (state) => ({ tags: state.tags //TODO: need to get this userid from backend first }); export default connect( mapStateToProps, { getPhotoByTag } )(withStyles(styles)(SearchResultPage));
import React from "react" import Layout from "../components/Layout" const Contact = () => { return ( <Layout> <main className="page"> <section className="contact-page"> <article className="contact-info"> <h3>Whant to get in touch</h3> <p> I'm baby iPhone kickstarter pinterest fam tofu subway tile blue bottle tbh messenger bag adaptogen 90's sartorial small batch artisan hexagon. Authentic kombucha everyday carry four loko, food truck austin occupy. Kinfolk subway tile green juice pinterest everyday carry migas asymmetrical franzen art party slow-carb pour-over, paleo biodiesel. Vice salvia health goth microdosing </p> <p> Ramps helvetica 3 wolf moon, shabby chic cronut offal four dollar toast you probably haven't heard of them pour-over irony taiyaki. Lumbersexual seitan distillery, crucifix venmo drinking vinegar waistcoat. Adaptogen fashion axe distillery kickstarter etsy subway tile yuccie, tumblr lomo heirloom post-ironic forage chia chartreuse. Iceland unicorn everyday carry tumblr. </p> </article> <article> <form className="form contact-form"> <div className="form-row"> <label htmlFor="name"> Votre nom</label> <input type="text" name="name" id="name" /> </div> <div className="form-row"> <label htmlFor="email"> Votre email</label> <input type="text" name="email" id="email" /> </div> <div className="form-row"> <label htmlFor="message"> Votre message </label> <textarea type="message" name="email" id="message"></textarea> <button type="submit" className="btn block"> {" "} envoyer </button> </div> </form> </article> </section> </main> </Layout> ) } export default Contact
var fruit = []; var price = []; var totalPrice = 0; function display(){ for(var i = 0; i < fruit.length; i++){ document.write(fruit[i] + "<br>") } } function total(){ for (var i = 0; i < price.length; i++){ totalPrice += price[i] } document.write("Total is: $" + totalPrice) } function priceC(){ fruit.push('Cherries'); price.push(3); } function priceB(){ fruit.push('Bananas'); price.push(2.50); } function priceA(){ fruit.push('Apples'); price.push(5.25); } function priceS(){ fruit.push('Strawberries'); price.push(5); } function priceO(){ fruit.push('Oranges'); price.push(2.25) } function totalFruit(){ display(); total(); }
import Vuex from 'vuex'; import Vue from 'vue'; import addresses from './modules/addresses.js'; Vue.use(Vuex); export default new Vuex.Store({ modules: { addresses } });
import { TOGGLE_UNIT } from "./settingType"; const initialState = { unit: true, }; export const settingReducer = (state = initialState, action) => { switch (action.type) { case TOGGLE_UNIT: return { ...state, unit: action.payload }; default: return state; } };
import { css } from '@emotion/core' import styled from '@emotion/styled' import { navItem } from '../../../macros' const NavItemUnderline = styled.a(...navItem.styles(), ({ current }) => { return ( current && css` text-decoration: underline !important; ` ) }) NavItemUnderline.propTypes = { ...navItem.propTypes() } NavItemUnderline.defaultProps = { ...navItem.defaultProps() } export default NavItemUnderline
/* Simple JavaScript Inheritance * By John Resig http://ejohn.org/ * MIT Licensed. */ // Inspired by base2 and Prototype (function () { var initializing = false, fnTest = /xyz/.test(function () { xyz; }) ? /\b_super\b/ : /.*/; // The base Class implementation (does nothing) this.Class = function () { }; // Create a new Class that inherits from this class Class.extend = function (prop) { var _super = this.prototype; // Instantiate a base class (but only create the instance, // don't run the init constructor) initializing = true; var prototype = new this(); initializing = false; // Copy the properties over onto the new prototype for (var name in prop) { // Check if we're overwriting an existing function prototype[name] = typeof prop[name] == "function" && typeof _super[name] == "function" && fnTest.test(prop[name]) ? (function (name, fn) { return function () { var tmp = this._super; // Add a new ._super() method that is the same method // but on the super-class this._super = _super[name]; // The method only need to be bound temporarily, so we // remove it when we're done executing var ret = fn.apply(this, arguments); this._super = tmp; return ret; }; })(name, prop[name]) : prop[name]; } // The dummy class constructor function Class() { // All construction is actually done in the init method if (!initializing && this.init) this.init.apply(this, arguments); } // Populate our constructed prototype object Class.prototype = prototype; // Enforce the constructor to be what we expect Class.prototype.constructor = Class; // And make this class extendable Class.extend = arguments.callee; return Class; }; })(); (function () { module("Template tests"); function HoistedFunctionViewModel() { } window.MyApp = { MyViewModel: function () { } } MyApp.MyViewModel.prototype = { constructor: MyApp.MyViewModel, test: function () { } }; MyApp.OOExtendedViewModel = Class.extend({ init: function(){ } }); MyApp.OOExtendedSubViewModel = MyApp.OOExtendedViewModel.extend({ init: function(){ } }); MyApp.NestedNameSpace = {}; MyApp.NestedNameSpace.NestedViewModel = MyApp.OOExtendedViewModel.extend({ init: function(){ } }); var templateTest = function (model, name, convention, assert, prepElement, template) { var template = template || $("<script id='" + name + "' type='text/html'>Bound</script>"); $("body").append(template); var test = function (element) { assert ? assert(element) : equal(element.html(), "Bound", "It should be able to bind template to model"); template.remove(); }; ko.test("div", convention || "$data", model, test, prepElement); }; test("When binding a template against a Hoisted function ViewModel", function () { templateTest(new HoistedFunctionViewModel(), "HoistedFunctionView"); }); test("When binding a template against a local variabel ViewModel", function () { templateTest(new MyApp.MyViewModel(), "MyView"); }); test("When binding a template against a null data", function () { templateTest({ nullModel: ko.observable(null) }, "MyView", "nullModel", function () { ok(true, "It should not crash due to null value"); }); }); test("When binding a template against a undefined data and then setting model", function () { var model = { nullModel: ko.observable() }; templateTest(model, "MyView", "nullModel", function (element) { equal("", element.text(), "The view should reflect null value"); model.nullModel(new MyApp.MyViewModel()); equal(element.text(), "Bound", "The view should reflect bound value"); }); }); test("When binding a template against null data when a ViewModel is allready bound", function () { var model = { model: ko.observable(new MyApp.MyViewModel()) }; templateTest(model, "MyView", "model", function (element) { equal("Bound", element.text(), "The view should reflect bound value"); model.model(null); equal(element.text(), "", "The view should reflect null value"); }); }); test("When binding a template against a null data and then setting model", function () { var model = { nullModel: ko.observable(null) }; templateTest(model, "MyView", "nullModel", function (element) { equal("", element.text(), "The view should reflect undefined value"); model.nullModel(new MyApp.MyViewModel()); equal(element.text(), "Bound", "The view should reflect bound value"); }); }); test("When binding a template against a local variabel ViewModel when root is set", function () { ko.bindingConventions.init({ roots: [MyApp] }); templateTest(new MyApp.MyViewModel(), "MyView"); ko.bindingConventions.init({ roots: [window] }); }); test("When binding a template against a array of models", function () { var model = { items: ko.observableArray([new MyApp.MyViewModel(), new MyApp.MyViewModel()]) }; templateTest(model, "MyView", "items", function (element) { equal(element.text(), "BoundBound", "It should bind all items"); }); }); test("When binding a template against an empty array of models", function () { var model = { items: ko.observableArray() }; templateTest(model, "MyView", "items", function (element) { model.items.push(new MyApp.MyViewModel()); equal(element.text(), "Bound", "It should bind all items"); }); }); test("When binding a template against a OO extended ViewModel", function () { ko.bindingConventions.init({ roots: [MyApp] }); templateTest(new MyApp.OOExtendedViewModel(), "OOExtendedView"); ko.bindingConventions.init({ roots: [window] }); }); test("When binding a template against a OO extended ViewModel", function () { ko.bindingConventions.init({ roots: [MyApp] }); templateTest(new MyApp.OOExtendedSubViewModel(), "OOExtendedSubView"); ko.bindingConventions.init({ roots: [window] }); }); test("When prechecking constructor names with a nested namespace",function() { ko.bindingConventions.init({ roots: [MyApp] }); ko.testBase({}, $("<div></div>"), function() { equal(MyApp.NestedNameSpace.NestedViewModel.__fcnName, "NestedViewModel", "It should add the constuctor name to the object"); ko.bindingConventions.init({ roots: [window] }); }); }); test("When binding a template to a empty element but with newline and whitespace", function() { templateTest(new MyApp.MyViewModel(), "MyView", undefined, undefined, function(element) { element.html(" \r\n"); }); }); test("When binding a template to a model and then to a new model of different type", function () { var templates = $('<div><script id="MyView" type="text/html">MyView</script><script id="OOExtendedView" type="text/html">OOExtendedViewModel</script></div>'); var model = { test: ko.observable(new MyApp.MyViewModel()) }; ko.bindingConventions.init({ roots: [MyApp] }); templateTest(model, undefined, "test", function (element) { model.test(new MyApp.OOExtendedViewModel()); equal(element.html(), "OOExtendedViewModel", "It should update the view with latest model"); }, undefined, templates); }); })();
/** * The Render Engine * Engine Class * * @fileoverview The main engine class * * @author: Brett Fattori (brettf@renderengine.com) * @author: $Author$ * @version: $Revision$ * * Copyright (c) 2010 Brett Fattori (brettf@renderengine.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ /** * @class The main engine class which is responsible for keeping the world up to date. * Additionally, the Engine will track and display metrics for optimizing a game. Finally, * the Engine is responsible for maintaining the local client's <tt>worldTime</tt>. * <p/> * The engine includes methods to load scripts and stylesheets in a serialized fashion * and report on the sound engine status. Since objects are tracked by the engine, a list * of all game objects can be obtained from the engine. The engine also contains the root * rendering context, or "default" context. For anything to be rendered, or updated by the * engine, it will need to be added to a child of the default context. * <p/> * Other methods allow for starting or shutting down then engine, toggling metric display, * setting of the base "frames per second", toggling of the debug mode, and processing of * the script and function queue. * <p/> * Since JavaScript is a single-threaded environment, frames are generated serially. One * frame must complete before another can be rendered. By default, if frames are missed, * the engine will wait until the next logical frame can be rendered. The engine can also * run where it doesn't skip frames, and instead runs a constant frame clock. This * doesn't guarantee that the engine will run at a fixed frame rate. * * @static */ var Engine = Base.extend(/** @scope Engine.prototype */{ version: "@ENGINE_VERSION", constructor: null, // Default configuration options defaultOptions: { skipFrames: true, // Skip missed frames billboards: true, // Use billboards to speed up rendering hardwareAccel: false,// Hardware acceleration is not available pointAsArc: true, // Draw points are arcs transientMathObject: false // MathObject is not transient (pooled) }, // Global engine options options: {}, /* * Engine objects */ idRef: 0, // Object reference Id gameObjects: {}, // Live objects cache timerPool: {}, // Pool of running timers livingObjects: 0, // Count of live objects /* * Engine info */ fpsClock: 33, // The clock rate (ms) frameTime: 0, // Amount of time taken to render a frame engineLocation: null, // URI of engine defaultContext: null, // The default rendering context debugMode: false, // Global debug flag localMode: false, // Local run flag started: false, // Engine started flag running: false, // Engine running flag shuttingDown: false, // Engine is shutting down upTime: 0, // The startup time downTime: 0, // The shutdown time skipFrames: true, // Skip missed frames /* * Sound engine info */ soundsEnabled: false, // Sound engine enabled flag /** * The current time of the world on the client. This time is updated * for each frame generated by the Engine. * @type Number * @memberOf Engine */ worldTime: 0, // The world time /** * The number of milliseconds the engine has been running. This time is updated * for each frame generated by the Engine. * @type Number * @memberOf Engine */ liveTime: 0, // The "alive" time (worldTime-upTime) shutdownCallbacks: [], // Methods to call when the engine is shutting down // Issue #18 - Intrinsic loading dialog loadingCSS: "<style type='text/css'>div.loadbox {width:325px;height:30px;padding:10px;font:10px Arial;border:1px outset gray;-moz-border-radius:10px;-webkit-border-radius:10px} #engine-load-progress { position:relative;border:1px inset gray;width:300px;height:5px} #engine-load-progress .bar {background:silver;}</style>", //==================================================================================================== //==================================================================================================== // ENGINE PROPERTIES //==================================================================================================== //==================================================================================================== /** * Set/override the engine options. * @param opts {Object} Configuration options for the engine */ setOptions: function(opts) { // Check for a "defaults" key var configOpts; if (opts.defaults) { configOpts = opts.defaults; } // See if the OS has a key var osOpts, platformDefaults, versionDefaults, platformVersions; if (opts["platforms"] && opts["platforms"][EngineSupport.sysInfo().OS]) { // Yep, extract that one osOpts = opts["platforms"][EngineSupport.sysInfo().OS]; // Check for platform defaults if (osOpts && osOpts["defaults"]) { platformDefaults = osOpts["defaults"]; } } // Check for general version specific options if (opts["versions"]) { for (var v in opts["versions"]) { if (parseFloat(EngineSupport.sysInfo().version) >= parseFloat(v)) { // Add the version options versionDefaults = opts["versions"][v]; } } } // Finally, check the OS for version specific options if (osOpts && osOpts["versions"]) { for (var v in osOpts["versions"]) { if (parseFloat(EngineSupport.sysInfo().version) >= parseFloat(v)) { // Add the version options platformVersions = osOpts["versions"][v]; } } } $.extend(Engine.options, configOpts, platformDefaults, versionDefaults, platformVersions); }, /** * Set the debug mode of the engine. Affects message ouput and * can be queried for additional debugging operations. * * @param mode {Boolean} <tt>true</tt> to set debugging mode * @memberOf Engine */ setDebugMode: function(mode) { this.debugMode = mode; }, /** * Query the debugging mode of the engine. * * @return {Boolean} <tt>true</tt> if the engine is in debug mode * @memberOf Engine */ getDebugMode: function() { return this.debugMode; }, /** * Returns <tt>true</tt> if SoundManager2 is loaded and initialized * properly. The resource loader and play manager will use this * value to execute properly. * @return {Boolean} <tt>true</tt> if the sound engine was loaded properly * @memberOf Engine */ isSoundEnabled: function() { return this.soundsEnabled; }, /** * Set the FPS (frames per second) the engine runs at. This value * is mainly a suggestion to the engine as to how fast you want to * redraw frames. If frame execution time is long, frames will be * processed as time is available. See the metrics to understand * available time versus render time. * * @param fps {Number} The number of frames per second to refresh * Engine objects. * @memberOf Engine */ setFPS: function(fps) { Assert((fps != 0), "You cannot have a framerate of zero!"); this.fpsClock = Math.floor(1000 / fps); }, /** * Get the FPS (frames per second) the engine is set to run at. * @return {Number} * @memberOf Engine */ getFPS: function() { return Math.floor((1 / this.fpsClock) * 1000) }, /** * Get the actual FPS (frames per second) the engine is running at. * This value will vary as load increases or decreases due to the * number of objects being rendered. A faster machine will be able * to handle a higher FPS setting. * @return {Number} * @memberOf Engine */ getActualFPS: function() { return Math.floor((1 / Engine.frameTime) * 1000); }, /** * Get the amount of time allocated to draw a single frame. * @return {Number} Milliseconds allocated to draw a frame * @memberOf Engine */ getFrameTime: function() { return this.fpsClock; }, /** * Get the amount of time it took to draw the last frame. This value * varies per frame drawn, based on visible objects, number of operations * performed, and other factors. The draw time can be used to optimize * your game for performance. * @return {Number} Milliseconds required to draw the frame * @memberOf Engine */ getDrawTime: function() { return Engine.frameTime; }, /** * Get the load the currently rendered frame is putting on the engine. * The load represents the amount of * work the engine is doing to render a frame. A value less * than one indicates the the engine can render a frame within * the amount of time available. Higher than one indicates the * engine cannot render the frame in the time available. * <p/> * Faster machines will be able to handle more load. You can use * this value to gauge how well your game is performing. * @return {Number} * @memberOf Engine */ getEngineLoad: function () { return (Engine.frameTime / this.fpsClock); }, /** * Get the default rendering context for the Engine. This * is the <tt>document.body</tt> element in the browser. * * @return {RenderContext} The default rendering context * @memberOf Engine */ getDefaultContext: function() { if (this.defaultContext == null) { this.defaultContext = DocumentContext.create(); } return this.defaultContext; }, /** * Get the path to the engine. Uses the location of the <tt>engine.js</tt> * file that was loaded. * @return {String} The path/URL where the engine is located * @memberOf Engine */ getEnginePath: function() { if (this.engineLocation == null) { // Determine the path of the "engine.js" file var head = document.getElementsByTagName("head")[0]; var scripts = head.getElementsByTagName("script"); for (var x = 0; x < scripts.length; x++) { var src = scripts[x].src; if (src != null && src.match(/(.*)\/engine\/(.*?)engine\.js/)) { // Get the path this.engineLocation = src.match(/(.*)\/engine\/(.*?)engine\.js/)[1]; break; } } } return this.engineLocation; }, //==================================================================================================== //==================================================================================================== // GLOBAL OBJECT MANAGEMENT //==================================================================================================== //==================================================================================================== /** * Track an instance of an object managed by the Engine. This is called * by any object that extends from {@link PooledObject}. * * @param obj {PooledObject} A managed object within the engine * @return {String} The global Id of the object * @memberOf Engine */ create: function(obj) { if(this.shuttingDown === true) { Console.warn("Engine shutting down, '" + obj + "' destroyed because it would create an orphaned reference"); obj.destroy(); return; }; Assert((this.started === true), "Creating an object when the engine is stopped!", obj); this.idRef++; var objId = obj.getName() + this.idRef; Console.log("CREATED Object ", objId, "[", obj, "]"); this.livingObjects++; return objId; }, /** * Removes an object instance managed by the Engine. * * @param obj {PooledObject} The object, managed by the engine, to destroy * @memberOf Engine */ destroy: function(obj) { if (obj == null) { Console.warn("NULL reference passed to Engine.destroy()! Ignored."); return; } var objId = obj.getId(); Console.log("DESTROYED Object ", objId, "[", obj, "]"); this.livingObjects--; }, /** * Add a timer to the pool so it can be cleaned up when * the engine is shutdown, or paused when the engine is * paused. * @param timerName {String} The timer name * @param timer {Timer} The timer to add */ addTimer: function(timerName, timer) { Engine.timerPool[timerName] = timer; }, /** * Remove a timer from the pool when it is destroyed. * @param timerName {String} The timer name */ removeTimer: function(timerName) { Engine.timerPool[timerName] = null; delete Engine.timerPool[timerName]; }, /** * Get an object by the Id that was assigned during the call to {@link #create}. * * @param id {String} The global Id of the object to locate * @return {PooledObject} The object * @memberOf Engine * @deprecated This method no longer returns an object */ getObject: function(id) { return null; }, //==================================================================================================== //==================================================================================================== // ENGINE PROCESS CONTROL //==================================================================================================== //==================================================================================================== /** * Load the minimal scripts required for the engine to run. * @private * @memberOf Engine */ loadEngineScripts: function() { // Engine stylesheet this.loadStylesheet("/css/engine.css"); // The basics needed by the engine to get started this.loadNow("/engine/engine.game.js"); this.loadNow("/engine/engine.rendercontext.js"); this.loadNow("/engine/engine.pooledobject.js"); this.loadNow("/rendercontexts/context.render2d.js"); this.loadNow("/rendercontexts/context.htmlelement.js"); this.loadNow("/rendercontexts/context.documentcontext.js"); }, /** * Starts the engine and loads the basic engine scripts. When all scripts required * by the engine have been loaded the {@link #run} method will be called. * * @param debugMode {Boolean} <tt>true</tt> to set the engine into debug mode * which allows the output of messages to the console. * @memberOf Engine */ startup: function(debugMode) { Assert((this.running == false), "An attempt was made to restart the engine!"); // Check for supported browser if (!this.browserSupportCheck()) { return; }; this.upTime = new Date().getTime(); this.debugMode = debugMode ? true : false; this.started = true; // Load the required scripts this.loadEngineScripts(); }, /** * Runs the engine. This will be called after all scripts have been loaded. * You will also need to call this if you pause the engine. * @memberOf Engine */ run: function() { if (Engine.shuttingDown || Engine.running) { return; } // Restart all of the timers for (var tm in Engine.timerPool) { Engine.timerPool[tm].restart(); } var mode = "["; mode += (this.debugMode ? "DEBUG" : ""); mode += (this.localMode ? (mode.length > 0 ? " LOCAL" : "LOCAL") : ""); mode += "]" Console.warn(">>> Engine started. " + (mode != "[]" ? mode : "")); this.running = true; this.shuttingDown = false; Console.debug(">>> sysinfo: ", EngineSupport.sysInfo()); // Start world timer Engine.globalTimer = window.setTimeout(function() { Engine.engineTimer(); }, this.fpsClock); }, /** * Pauses the engine. * @memberOf Engine */ pause: function() { if (Engine.shuttingDown) { return; } // Pause all of the timers Console.debug("Pausing all timers"); for (var tm in Engine.timerPool) { Engine.timerPool[tm].pause(); } Console.warn(">>> Engine paused <<<"); window.clearTimeout(Engine.globalTimer); this.running = false; }, /** * Add a method to be called when the engine is being shutdown. Use this * method to allow an object, which is not referenced to by the engine, to * perform cleanup actions. * * @param fn {Function} The callback function */ onShutdown: function(fn) { if (Engine.shuttingDown === true) { return; } Engine.shutdownCallbacks.push(fn); }, /** * Shutdown the engine. Stops the global timer and cleans up (destroys) all * objects that have been created and added to the world. * @memberOf Engine */ shutdown: function() { if (Engine.shuttingDown) { // Prevent another shutdown return; } Engine.shuttingDown = true; if (!this.running && this.started) { // If the engine is not currently running (i.e. paused) // restart it and then re-perform the shutdown this.running = true; setTimeout(function() { Engine.shutdown(); }, (this.fpsClock * 2)); return; } this.started = false; window.clearTimeout(Engine.dependencyProcessor); Console.warn(">>> Engine shutting down..."); // Stop world timer window.clearTimeout(Engine.globalTimer); // Run through shutdown callbacks to allow objects not tracked by Engine // to clean up references, etc. while (Engine.shutdownCallbacks.length > 0) { Engine.shutdownCallbacks.shift()(); }; if (this.metricDisplay) { this.metricDisplay.remove(); this.metricDisplay = null; } // Cancel all of the timers Console.debug("Cancelling all timers"); for (var tm in Engine.timerPool) { Engine.timerPool[tm].cancel(); } Engine.timerPool = {}; this.downTime = new Date().getTime(); Console.warn(">>> Engine stopped. Runtime: " + (this.downTime - this.upTime) + "ms"); this.running = false; // Kill off the default context and anything // that's attached to it. We'll alert the // developer if there's an issue with orphaned objects this.getDefaultContext().destroy(); // Dump the object pool if (typeof PooledObject != "undefined") { PooledObject.objectPool = null; } AssertWarn((this.livingObjects == 0), "Object references not cleaned up!"); this.loadedScripts = {}; this.scriptLoadCount = 0; this.scriptsProcessed = 0; this.defaultContext = null; // Perform final cleanup if (!Engine.UNIT_TESTING /* Is this a hack? */) { this.cleanup(); } }, /** * After a successful shutdown, the Engine needs to clean up * all of the objects that were created on the window object by the engine. * @memberOf Engine * @private */ cleanup: function() { // Protect the HTML console, if visible var hdc = $("#debug-console").remove(); // Remove the body contents $(document.body).empty(); if (hdc.length != 0) { $(document.body).append(hdc); } // Remove all scripts from the <head> $("head script", document).remove(); // Final cleanup Linker.cleanup(); // Shutdown complete Engine.shuttingDown = false; }, /** * Initializes an object for use in the engine. Calling this method is required to make sure * that all dependencies are resolved before actually instantiating an object of the specified * class. This uses the {@link Linker} class to handle dependency processing and resolution. * * @param objectName {String} The name of the object class * @param primaryDependency {String} The name of the class for which the <tt>objectName</tt> class is * dependent upon. Specifying <tt>null</tt> will assume the <tt>Base</tt> class. * @param fn {Function} The function to run when the object can be initialized. */ initObject: function(objectName, primaryDependency, fn) { Linker.initObject(objectName, primaryDependency, fn); }, /** * Check the current browser to see if it is supported by the * engine. If it isn't, there's no reason to load the remainder of * the engine. This check can be disabled with the <tt>disableBrowserCheck</tt> * query parameter set to <tt>true</tt>. * <p/> * If the browser isn't supported, the engine is shutdown and a message is * displayed. */ browserSupportCheck: function() { if (EngineSupport.checkBooleanParam("disableBrowserCheck")) { return true; } var sInfo = EngineSupport.sysInfo(); var msg = "This browser is not currently supported by <i>The Render Engine</i>.<br/><br/>"; msg += "Please see <a href='http://www.renderengine.com/browsers.php' target='_blank'>the list of "; msg += "supported browsers</a> for more information."; switch (sInfo.browser) { case "iPhone": case "android": case "msie": Engine.options.billboards = false; return true; case "chrome": case "Wii": case "safari": case "mozilla": case "firefox": case "opera": return true; case "unknown": $(document).ready(function() { Engine.shutdown(); $("body", document).append($("<div class='unsupported'>") .html(msg)); }); } return false; }, /** * Prints the version of the engine. * @memberOf Engine */ toString: function() { return "The Render Engine " + this.version; }, //==================================================================================================== //==================================================================================================== // THE WORLD TIMER //==================================================================================================== //==================================================================================================== /** * This is the process which updates the world. It starts with the default * context, telling it to update itself. Since each context is a container, * all of the objects in the container will be called to update, and then * render themselves. * * @private * @memberOf Engine */ engineTimer: function() { if (Engine.shuttingDown) { return; } /* pragma:DEBUG_START */ try { Profiler.enter("Engine.engineTimer()"); /* pragma:DEBUG_END */ var nextFrame = Engine.fpsClock; // Update the world if (Engine.running && Engine.getDefaultContext() != null) { Engine.vObj = 0; // Render a frame Engine.worldTime = new Date().getTime(); Engine.getDefaultContext().update(null, Engine.worldTime); Engine.frameTime = new Date().getTime() - Engine.worldTime; Engine.liveTime = Engine.worldTime - Engine.upTime; // Determine when the next frame should draw // If we've gone over the allotted time, wait until the next available frame var f = nextFrame - Engine.frameTime; nextFrame = (Engine.skipFrames ? (f > 0 ? f : nextFrame) : Engine.fpsClock); Engine.droppedFrames += (f <= 0 ? Math.round((f * -1) / Engine.fpsClock) : 0); // Update the metrics display Engine.doMetrics(); } // When the process is done, start all over again Engine.globalTimer = setTimeout(function _engineTimer() { Engine.engineTimer(); }, nextFrame); /* pragma:DEBUG_START */ } finally { Profiler.exit(); } /* pragma:DEBUG_END */ } }, { // Interface globalTimer: null });
/// reduced to ~ 410 LOCs (parser only 300 vs. 1400+) with (some, needed) BSON classes "inlined". /// Compare ~ 4,300 (22KB vs. 157KB) in browser build at: https://github.com/mongodb/js-bson/blob/master/browser_build/bson.js var Long = require('./long'), ObjectID = require('./objectid'), MinKey = require('./min_key'), MaxKey = require('./max_key'), Binary = require('./binary'), Code = require('./code'), BSONRegExp = require('./regexp'), Timestamp = require('./timestamp'); // JS MAX PRECISE VALUES var JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. var JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. // BSON Types var BSON_DATA_NUMBER = 1; var BSON_DATA_STRING = 2; var BSON_DATA_OBJECT = 3; var BSON_DATA_ARRAY = 4; var BSON_DATA_BINARY = 5; var BSON_DATA_UNDEFINED = 6; var BSON_DATA_OID = 7; var BSON_DATA_BOOLEAN = 8; var BSON_DATA_DATE = 9; var BSON_DATA_NULL = 10; var BSON_REGEXP = 11; var BSON_DATA_CODE = 13; var BSON_DATA_SYMBOL = 14; var BSON_DATA_CODE_W_SCOPE = 15; var BSON_DATA_INT = 16; var BSON_DATA_TIMESTAMP = 17; var BSON_DATA_LONG = 18; var BSON_DATA_MIN_KEY = 127; var BSON_DATA_MAX_KEY = 255; var readIEEE754 = function(buffer, offset, endian, mLen, nBytes) { var e, m, bBE = (endian === 'big'), eLen = nBytes * 8 - mLen - 1, eMax = (1 << eLen) - 1, eBias = eMax >> 1, nBits = -7, i = bBE ? 0 : (nBytes - 1), d = bBE ? 1 : -1, s = buffer[offset + i]; i += d; e = s & ((1 << (-nBits)) - 1); s >>= (-nBits); nBits += eLen; for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); m = e & ((1 << (-nBits)) - 1); e >>= (-nBits); nBits += mLen; for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); if (e === 0) { e = 1 - eBias; } else if (e === eMax) { return m ? NaN : ((s ? -1 : 1) * Infinity); } else { m = m + Math.pow(2, mLen); e = e - eBias; } return (s ? -1 : 1) * m * Math.pow(2, e - mLen); }; // http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt /* utf.js - UTF-8 <=> UTF-16 convertion * * Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp> * Version: 1.0 * LastModified: Dec 25 1999 * This library is free. You can redistribute it and/or modify it. */ function Utf8ArrayToStr(array) { var out, i, len, c; var char2, char3; out = ""; len = array.length; i = 0; while(i < len) { c = array[i++]; switch(c >> 4) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: // 0xxxxxxx out += String.fromCharCode(c); break; case 12: case 13: // 110x xxxx 10xx xxxx char2 = array[i++]; out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F)); break; case 14: // 1110 xxxx 10xx xxxx 10xx xxxx char2 = array[i++]; char3 = array[i++]; out += String.fromCharCode(((c & 0x0F) << 12) | ((char2 & 0x3F) << 6) | ((char3 & 0x3F) << 0)); break; } } return out; } function deserializeFast(buffer, i, isArray){ if (buffer.length < 5) { return new Error('Corrupt bson message < 5 bytes long'); } var elementType, tempindex = 0, name; var string, low, high; // = lowBits / highBits // using 'i' as the index to keep the lines shorter: i || ( i = 0 ); // for parseResponse it's 0; set to running index in deserialize(object/array) recursion var object = isArray ? [] : {}; /// needed for type ARRAY recursion later! var size = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; if(size < 5 || size > buffer.length) { return new Error('Corrupt BSON message'); } /// 'size' var was not used by anything after this, so we can reuse it while(true) { // While we have more left data left keep parsing elementType = buffer[i++]; // Read the type if (elementType === 0) { break; // If we get a zero it's the last byte, exit } tempindex = i; /// inlined readCStyleString & removed extra i<buffer.length check slowing EACH loop! while( buffer[tempindex] !== 0x00 ) { tempindex++; /// read ahead w/out changing main 'i' index } if (tempindex >= buffer.length) { return new Error('Corrupt BSON document: illegal CString') } name = Utf8ArrayToStr(buffer.slice(i, tempindex)); i = tempindex + 1; /// Update index position to after the string + '0' termination if(elementType === BSON_DATA_OID) { var array = new Array(12); for(var j = 0; j < 12; j++) { array[j] = String.fromCharCode(buffer[i+j]); } i = i + 12; object[name] = new ObjectID(array.join('')); } else if(elementType === BSON_DATA_STRING) { size = buffer[i++] | buffer[i++] <<8 | buffer[i++] <<16 | buffer[i++] <<24; object[name] = Utf8ArrayToStr(buffer.slice(i, i += size -1 )); i++; } else if(elementType === BSON_DATA_INT) { object[name] = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; } else if(elementType === BSON_DATA_NUMBER) { object[name] = readIEEE754(buffer, i, 'little', 52, 8); i += 8; } else if(elementType === BSON_DATA_BOOLEAN) { object[name] = buffer[i++] == 1; } else if(elementType === BSON_DATA_UNDEFINED || elementType === BSON_DATA_NULL) { object[name] = null; } else if(elementType === BSON_DATA_ARRAY) { size = buffer[i] | buffer[i+1] <<8 | buffer[i+2] <<16 | buffer[i+3] <<24; object[name] = deserializeFast(buffer, i, true ); i += size; } else if(elementType === BSON_DATA_OBJECT) { size = buffer[i] | buffer[i+1] <<8 | buffer[i+2] <<16 | buffer[i+3] <<24; object[name] = deserializeFast(buffer, i, false ); i += size; } else if(elementType === BSON_DATA_BINARY) { size = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; var subType = buffer[i++]; object[name] = new Binary(buffer.slice(i, i += size), subType) } else if(elementType === BSON_DATA_DATE) { low = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; high = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; object[name] = new Date( high * 4294967296 + (low < 0 ? low + 4294967296 : low) ); } else if(elementType === BSON_DATA_LONG) { low = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; high = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; object[name] = new Long(low, high); } else if(elementType === BSON_DATA_MIN_KEY) { object[name] = new MinKey(); } else if(elementType === BSON_DATA_MAX_KEY) { object[name] = new MaxKey(); } else if(elementType === BSON_DATA_TIMESTAMP) { low = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; high = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; object[name] = new Timestamp(low, high); } else if(elementType === BSON_DATA_SYMBOL) { size = buffer[i++] | buffer[i++] <<8 | buffer[i++] <<16 | buffer[i++] <<24; object[name] = Utf8ArrayToStr(buffer.slice(i, i += size -1 )); i++; } else if(elementType === BSON_DATA_CODE) { size = buffer[i++] | buffer[i++] <<8 | buffer[i++] <<16 | buffer[i++] <<24; var code = Utf8ArrayToStr(buffer.slice(i, i += size -1 )); object[name] = new Code(code, {}); i++; } else if(elementType === BSON_REGEXP) { var index = i; // Locate the end of the c string while(buffer[index] !== 0x00 && index < buffer.length) { index++ } // If are at the end of the buffer there is a problem with the document if(index >= buffer.length) throw new Error("Bad BSON Document: illegal CString") // Return the C string var source = Utf8ArrayToStr(buffer.slice(i, index)); i = index + 1; // Get the start search index var index = i; // Locate the end of the c string while(buffer[index] !== 0x00 && index < buffer.length) { index++ } // If are at the end of the buffer there is a problem with the document if(index >= buffer.length) throw new Error("Bad BSON Document: illegal CString") // Return the C string var regExpOptions = Utf8ArrayToStr(buffer.slice(i, index)); i = index + 1; // Set the object object[name] = new BSONRegExp(source, regExpOptions); } else if(elementType === BSON_DATA_CODE_W_SCOPE) { // Decode the sizes var total = buffer[i++] | buffer[i++] <<8 | buffer[i++] <<16 | buffer[i++] <<24; size = buffer[i++] | buffer[i++] <<8 | buffer[i++] <<16 | buffer[i++] <<24; var code = Utf8ArrayToStr(buffer.slice(i, i += size -1 )); i++; // Decode the scope var objectSize = buffer[i] | buffer[i + 1] <<8 | buffer[i + 2] <<16 | buffer[i + 3] <<24; var scope = deserializeFast(buffer, i, false ); i+=objectSize; object[name] = new Code(code, scope); } else { throw new Error("BSON type " + elementType + " is not supported"); } } return object; } module.exports.deserializeFast = deserializeFast;
export { default } from './CandidatesToolbar';
/** csrf token */ /** Admin Another Case Module */ const UserTests = require('./user/user.spec'); module.exports = (request, should, app) => { /** Method Admin Main Tests */ describe("GET Admin Main Test", () => { /** Test Case (One) */ it("1) Admin Main Url Tests", (done) => { request(app) .get('/admin') .expect(302) .end((err, res) => { if (err) { console.log("Admin Main Tests Error Code ::: ", err.code); console.log("Admin Main Tests Error ::: ", err); throw err; } return done(); }); }); /** Test Case (Two) */ }); UserTests(request, should, app); };
const Telnet = require('telnet-client') const _ = require('lodash') const chalk = require('chalk') const emoji = require('./lib/emoji') const logger = require('./lib/logger') const validator = require('./lib/validator') const exchange = require('./lib/exchange') const navigation = require('./lib/navigation') const score = require('./lib/score') // Load in our .env file require('dotenv').config() // What is the maximum cutoff to determine current commodity deficits? const DEFICIT_MAX = -500 // What is the minimum cutoff to determine current commodity surpluses? const SURPLUS_MIN = 19500 // How many minutes to sleep between each cycle? const SLEEP_MINUTES = 5 // How low should stamina go before we buy food? const STAMINA_MIN = 25 // Information for connection to Fed2's servers const connectionParams = { host: process.env.FED_HOST || 'play.federation2.com', port: process.env.FED_PORT || 30003, negotiationMandatory: false } // Useful regexes for pulling out data from game output let commodRegex = new RegExp("([A-Z,a-z]*): value ([0-9]*)ig/ton Spread: ([0-9]*)% Stock: current ([-0-9]*)") let staminaRegex = new RegExp("Stamina max: ([0-9]*) current: ([0-9]*)") let cargoSpaceRegex = new RegExp("Cargo space: ([0-9]*)/([0-9]*)") let currentPlanetRegex = new RegExp("You are currently on ([A-Z,a-z,0-9]*) in the") // Import our planet and step configuration const planets = require("./planets") const steps = require("./steps") // Holds our Telnet connection into the Fed2 server const connection = new Telnet() // Info we want to track as we go along let lastBankBalance = 0 let cargoBays = 0 let cycleNum = 1 /** * Easily lets us wait for a specified period of time with await */ function sleep(ms) { return new Promise((resolve) => { setTimeout(resolve, ms) }) } /** * The main function that starts up everything else */ async function run() { logger.output("Validating step & planet data for errors...") const planetValid = validator.validatePlanets(planets) let stepsValid = true for(let stepSet of steps) { stepsValid = validator.validateSteps(stepSet) && stepsValid } if(!planetValid || !stepsValid) { logger.output(chalk.red("Please fix the errors with your configuration and run again.")) process.exit(0) } logger.output(chalk.green("No issues found!")) logger.output("Connecting to Federation 2 servers...") try { await connection.connect(connectionParams) } catch(error) { logger.output(chalk.red("ERROR! Could not connect to Fed2.")) process.exit(0) } // Authenticate the user await connection.send(process.env.FED_USERNAME) await connection.send(process.env.FED_PASSWORD) await sleep(2000) logger.output("HaulBot is powering up. BEEP-BOOP! 🤖") await calculateCargoBays() while(true) { await runCycle() logger.output(`Bot is sleeping for ${SLEEP_MINUTES} minutes. 😴`) // Sleep until we need to repeat the cycle again await sleep(1000 * 60 * SLEEP_MINUTES) } } /** * Determine how many cargo bays the player's ship has */ async function calculateCargoBays() { let status = await connection.send("st") let match = cargoSpaceRegex.exec(status) let tonnage = parseInt(match[2]) // Save this info for use elsewhere cargoBays = Math.trunc(tonnage/75) logger.output(`Your ship has ${cargoBays} cargo bays. 📦`) } /** * Ensure we don't have anything in our cargo hold */ async function checkCargoHold() { let status = await connection.send("st") let match = cargoSpaceRegex.exec(status) if(match[1] !== match[2]) { logger.output(chalk.red("ERROR! Cargo detected in hold.")) process.exit(0) } } /** * Ensures the player is on this planet at its exchange * * @param {String} planet */ async function verifyAtPlanetExchange(planet) { let score = await connection.send("sc") let match = currentPlanetRegex.exec(score) if(match[1] !== planet) { logger.output(chalk.red(`ERROR! You're not on the right starting planet, ${planet}. Cannot run.`)); process.exit(0) } let priceTest = await connection.send("c price arts") if(priceTest.indexOf("need to be in an exchange") > -1) { logger.output(chalk.red(`ERROR! You're not at ${planet}'s exchange. Cannot run.`)); process.exit(0) } } /** * Run a single cycle of our hauling steps defined in steps.js */ async function runCycle() { await logger.balances(connection) logger.output(`Cycle #${cycleNum} starting.`) let startingPlanet = steps[0].from await verifyAtPlanetExchange(startingPlanet) for(let step of steps) { await runStep(step) } logger.output(`Cycle #${cycleNum} finished all steps.`) cycleNum++ } /** * Runs a single of the steps defined in steps.js * * @param {Object} step */ async function runStep(step) { if(step.type === "TRADE") { await tradeBetween(step.from, step.to) } else if(step.type === "MOVE") { await navigation.navigateBetweenExchanges(connection, step.from, step.to) } else if(step.type === "WALK_UP") { await exchange.walkUpStockpiles(connection) } else if(step.type === "HAUL_OUT") { await haulOut(step.from) } else if(step.type === "HAUL_IN") { //await exchange.setProtectiveStockpiles(connection) await haulIn(step.from) } else { logger.output(chalk.red(`Invalid step type: ${step.type}. Skipping.`)) } } async function haulIn(planet) { if(planets[planet].toRestaurant) { await checkStamina(planet) } logger.output(chalk.blue(`Hauling in deficits on: ${planet}`)) logger.output(`Scanning ${planet} exchange.`) let exc = await connection.send("di exchange") let planetImpEx = parseExData(exc) for(let imp of planetImpEx.imp) { if(planet === "Sakura") { if(imp === "Vidicasters") { console.log("Skipping Vidicasters because of factories on Sakura") return } } await connection.send("buy fuel") logger.output("Hauling in " + emoji.formatCommod(imp)) let bestSeller = await exchange.findBestSeller(connection, imp) await navigation.navigateBetweenExchanges(connection, planet, bestSeller) for(let i=0; i < 6; i++) { await connection.send("buy " + imp) } await navigation.navigateBetweenExchanges(connection, bestSeller, planet) for(let i=0; i < 6; i++) { await connection.send("sell " + imp) } } } async function haulOut(planet) { if(planets[planet].toRestaurant) { await checkStamina(planet) } logger.output(chalk.blue(`Hauling out surpluses on: ${planet}`)) logger.output(`Scanning ${planet} exchange.`) let exc = await connection.send("di exchange") let planetImpEx = parseExData(exc) for(let exp of planetImpEx.exp) { await connection.send("buy fuel") // TODO - not make this hardcoded if(exp === "LanzariK" || exp === "Lasers" || exp === "Munitions" || exp === "Monopoles" || exp === "LubOils" || exp === "Xmetals" || exp === "Synths" || exp === "Nickel" || exp === "Radioactives" || exp === "Electros" || exp === "Musiks") { logger.output("Skipping " + exp + " due to a lack of reliable buyers in cartel.") continue } logger.output("Hauling out " + emoji.formatCommod(exp)) let bestBuyer = await exchange.findBestBuyer(connection, exp) for(let i=0; i < 6; i++) { await connection.send("buy " + exp) } await navigation.navigateBetweenExchanges(connection, planet, bestBuyer) for(let i=0; i < 6; i++) { await connection.send("sell " + exp) } let status = await connection.send("st") let match = cargoSpaceRegex.exec(status) if(match[1] !== match[2]) { logger.output("Cargo still in hold, looking for 2nd buyer") let secondBestBuyer = await exchange.findBestBuyer(connection, exp) await navigation.navigateBetweenExchanges(connection, bestBuyer, secondBestBuyer) for(let i=0; i < 6; i++) { await connection.send("sell " + exp) } bestBuyer = secondBestBuyer } await navigation.navigateBetweenExchanges(connection, bestBuyer, planet) } } /** * Determines two planets available imports & exports and runs any possible * routes between them. * * @param {String} planetA Name of the first planet * @param {String} planetB Name of the second plent */ async function tradeBetween(planetA, planetB) { // If planet A has a restaurant defined, we should check our stamina if(planets[planetA].toRestaurant) { await checkStamina(planetA) } logger.output(chalk.blue(`Auto-trading: ${planetA} <=> ${planetB}.`)) await connection.send("buy fuel") // Gather info about planet A logger.output(`Scanning ${planetA} exchange.`) let planetAExc = await connection.send("di exchange") let planetAImpEx = parseExData(planetAExc) await navigation.navigateBetweenExchanges(connection, planetA, planetB) // Gather info about planet B logger.output(`Scanning ${planetB} exchange.`) let planetBExc = await connection.send("di exchange") let planetBImpEx = parseExData(planetBExc) // Determine available trade routes let routesAtoB = _.intersection(planetAImpEx.exp, planetBImpEx.imp) let routesBtoA = _.intersection(planetBImpEx.exp, planetAImpEx.imp) if(routesAtoB.length > 0) { logger.output(`Routes from ${planetA} => ${planetB} (${routesAtoB.length}): ${routesAtoB.join(", ")}`) } else { logger.output(`No available routes from ${planetA} => ${planetB}`) } if(routesBtoA.length > 0) { logger.output(`Routes from ${planetB} => ${planetA} (${routesBtoA.length}): ${routesBtoA.join(", ")}`) } else { logger.output(`No available routes from ${planetB} => ${planetA}`) } await navigation.navigateBetweenExchanges(connection, planetB, planetA) while(routesAtoB.length > 0) { let commod = routesAtoB[0] await buyCommod(commod) await navigation.navigateBetweenExchanges(connection, planetA, planetB) await sellCommod(commod) // Remove this from our list routesAtoB = routesAtoB.slice(1) let returnLoad = routesBtoA.length > 0 let returnCommod = returnLoad ? routesBtoA[0] : "" if(returnLoad) await buyCommod(returnCommod) await navigation.navigateBetweenExchanges(connection, planetB, planetA) if(returnLoad) { await sellCommod(returnCommod) routesBtoA = routesBtoA.slice(1) } await connection.send("buy fuel") } if(routesBtoA.length > 0) { while(routesBtoA.length > 0) { navigation.navigateBetweenExchanges(connection, planetA, planetB) let commod = routesBtoA[0] await buyCommod(commod) await navigation.navigateBetweenExchanges(connection, planetB, planetA) await sellCommod(commod) routesBtoA = routesBtoA.slice(1) await connection.send("buy fuel") } } } /** * Ensure the player is staying well-fed * * @param {String} planet The planet the player is currently on */ async function checkStamina(planet) { let score = await connection.send("sc") let match = staminaRegex.exec(score) if(!match) { logger.output(chalk.red("ERROR! Unable to get stamina info.")) process.exit(0) } else { logger.output("Current stamina: " + chalk.bold.white(match[2])) let stamina = parseInt(match[2]) if(stamina < STAMINA_MIN) { logger.output(chalk.yellow(`Stamina less than ${STAMINA_MIN}. Buying food from the planet's restaurant.`)) const planetInfo = planets[planet] for(let cmd of planetInfo.fromExchange) { await connection.send(cmd) } for(let cmd of planetInfo.toRestaurant) { await connection.send(cmd) } await connection.send("buy food") logger.output("Food purchased. Itadakimasu! 🍕") for(let cmd of planetInfo.fromRestaurant) { await connection.send(cmd) } for(let cmd of planetInfo.toExchange) { await connection.send(cmd) } } } } /** * Fills our cargo bay with the specified commodity * * @param {String} commod */ async function buyCommod(commod) { lastBankBalance = await score.getBankBalance(connection) logger.output("Buying " + cargoBays + " bays of " + emoji.formatCommod(commod)) for(i = 0; i < cargoBays; i++) { await connection.send("buy " + commod) } } /** * Sells off all of the commodity we are hauling * * @param {String} commod */ async function sellCommod(commod) { logger.output("Selling " + cargoBays + " bays of " + emoji.formatCommod(commod)) for(i = 0; i < cargoBays; i++) { await connection.send("sell " + commod) } const newBankBalance = await score.getBankBalance(connection) const profit = newBankBalance - lastBankBalance if(profit < 0) { logger.output(chalk.yellow("WARN! Money loss detected.")) logger.output(chalk.yellow("Balance before: " + lastBankBalance)) logger.output(chalk.yellow("Balnce after: " + newBankBalance)) } logger.output(`Personal profit of ${chalk.bold.white(profit)}ig made from the sale. 🤑`) // Ensure everything sold properly await checkCargoHold() } /** * Parses exchange data in order to determine current surpluses and deficits * * @param {String} commod Output from command: di exchange */ function parseExData(data) { let commods = data.split("\n") let exp = [] let imp = [] for(let c of commods) { let match = commodRegex.exec(c) if(match) { let stock = parseInt(match[4]) if(stock >= SURPLUS_MIN) { exp.push(match[1]) } else if(stock <= DEFICIT_MAX) { imp.push(match[1]) } } } logger.output("Exchange has " + exp.length + " surpluses and " + imp.length + " deficits.") return { exp: exp, imp: imp } } run()
import React, { Component } from 'react'; import { FormGroup, FormControl, Row, Button } from 'react-bootstrap'; import axios from 'axios'; export default class Login extends Component{ constructor(props) { super(props); this.state = { email: '', password: '', }; this.setNewLoginInfo = props.setNewLoginInfo; } handlePass(password) { this.setState({ password, }); } handleEmail(email) { this.setState({ email, }); } sendDataLogin() { const data = { email: this.state.email, password: this.state.password, }; axios({ method: 'post', url: '/api/auth/sign_in', data, headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, transformRequest: [(data) => { const newData = []; for (const prop in data) { if (data.hasOwnProperty(prop)) { newData.push(`${prop}=${data[prop]}`); } } return newData.join('&'); }], }) .then(res => { console.log(this.setNewLoginInfo); this.setNewLoginInfo({ 'access-token': res.headers['access-token'], client: res.headers.client, expiry: res.headers.expiry, uid: res.headers.uid, }); }) .catch(err => console.error(err)); } render() { return ( <div> <h2>Введите данные учётной записи</h2> <FormGroup> <Row> <FormControl onChange={(e) => { this.handleEmail(e.target.value);}} type="email" placeholder="Введите email" /> </Row> <Row> <FormControl onChange={(e) => { this.handlePass(e.target.value);}} type="password" placeholder="Введите пароль" /> </Row> <Row> <Button onClick={() => { this.sendDataLogin(); }}>Войти</Button> </Row> </FormGroup> </div> ); } }
import React from 'react' import ReactDOM from 'react-dom'; import GuestIncrementer from './GuestIncrementer.jsx' import PopDownWrapper from '../styles/BookItForm/PopDownWrapper.js' class GuestList extends React.Component { constructor(props) { super(props) } render() { return ( <PopDownWrapper> <GuestIncrementer guestsBooked = {this.props.guestsBooked} guestsAllowed = {this.props.guestsAllowed} current = 'adult' changeGuests = {this.props.changeGuests}/> <GuestIncrementer guestsBooked = {this.props.guestsBooked} guestsAllowed = {this.props.guestsAllowed} current = 'child' changeGuests = {this.props.changeGuests}/> <GuestIncrementer guestsBooked = {this.props.guestsBooked} guestsAllowed = {this.props.guestsAllowed} current = 'infant' changeGuests = {this.props.changeGuests}/> </PopDownWrapper> )} } export default GuestList
import React, { useState, useEffect } from "react"; import Back from "./Back"; import SummaryCard from "./SummaryCard"; import "../styles/orderSummary.css"; import PriceCard from "./PriceCard"; import { connect } from "react-redux"; function OrderSummary({ selectedCards }) { const [numOfItems, setNumOfItems] = useState(0); useEffect(() => { setNumOfItems(selectedCards.length); }, [selectedCards]); return ( <> <div className="row mb-4"> <div className="col-12"> <Back /> </div> </div> <div className="row mb-3"> <div className="col-6"> <p className="summary-title">Order Summary ( {numOfItems} items )</p> </div> </div> <div className="row"> <div className="col-7 d-flex align-items-stretch"> <SummaryCard items={selectedCards} /> </div> <div className="col-5"> <PriceCard items={selectedCards} /> </div> </div> </> ); } const mapStateToProps = state => ({ selectedCards: state.cardListReducer.selectedCards }); export default connect(mapStateToProps)(OrderSummary);
'use strict'; ApplicationConfiguration.registerModule('templates', []);
! function(e, t) { var i = function(e) { var t = {}; function i(s) { if (t[s]) return t[s].exports; var n = t[s] = { i: s, l: !1, exports: {} }; return e[s].call(n.exports, n, n.exports, i), n.l = !0, n.exports } return i.m = e, i.c = t, i.d = function(e, t, s) { i.o(e, t) || Object.defineProperty(e, t, { configurable: !1, enumerable: !0, get: s }) }, i.r = function(e) { Object.defineProperty(e, "__esModule", { value: !0 }) }, i.n = function(e) { var t = e && e.__esModule ? function() { return e. default }: function() { return e }; return i.d(t, "a", t), t }, i.o = function(e, t) { return Object.prototype.hasOwnProperty.call(e, t) }, i.p = "", i(i.s = 268) } ({ 162 : function(e, t, i) { (function(e) { var i; /** * @license MIT */ /** * @license MIT */ ! function(s, n, r) { "use strict"; var o = s.navigator.msPointerEnabled; function a(e) { if (this.support = !("undefined" == typeof File || "undefined" == typeof Blob || "undefined" == typeof FileList || !Blob.prototype.slice && !Blob.prototype.webkitSlice && !Blob.prototype.mozSlice), this.support) { this.supportDirectory = /Chrome/.test(s.navigator.userAgent) || /Firefox/.test(s.navigator.userAgent) || /Edge/.test(s.navigator.userAgent), this.files = [], this.defaults = { chunkSize: 1048576, forceChunkSize: !1, simultaneousUploads: 3, singleFile: !1, fileParameterName: "file", progressCallbacksInterval: 500, speedSmoothingFactor: .1, query: {}, headers: {}, withCredentials: !1, preprocess: null, method: "multipart", testMethod: "GET", uploadMethod: "POST", prioritizeFirstAndLastChunk: !1, allowDuplicateUploads: !1, target: "/", testChunks: !0, generateUniqueIdentifier: null, maxChunkRetries: 0, chunkRetryInterval: null, permanentErrors: [404, 413, 415, 500, 501], successStatuses: [200, 201, 202], onDropStopPropagation: !1, initFileFn: null, readFileFn: l }, this.opts = {}, this.events = {}; var t = this; this.onDrop = function(e) { t.opts.onDropStopPropagation && e.stopPropagation(), e.preventDefault(); var i = e.dataTransfer; i.items && i.items[0] && i.items[0].webkitGetAsEntry ? t.webkitReadDataTransfer(e) : t.addFiles(i.files, e) }, this.preventEvent = function(e) { e.preventDefault() }, this.opts = a.extend({}, this.defaults, e || {}) } } function h(e, t, i) { this.flowObj = e, this.bytes = null, this.file = t, this.name = t.fileName || t.name, this.size = t.size, this.relativePath = t.relativePath || t.webkitRelativePath || this.name, this.uniqueIdentifier = i === r ? e.generateUniqueIdentifier(t) : i, this.chunks = [], this.paused = !1, this.error = !1, this.averageSpeed = 0, this.currentSpeed = 0, this._lastProgressCallback = Date.now(), this._prevUploadedSize = 0, this._prevProgress = 0, this.bootstrap() } function l(e, t, i, s, n) { var r = "slice"; e.file.slice ? r = "slice": e.file.mozSlice ? r = "mozSlice": e.file.webkitSlice && (r = "webkitSlice"), n.readFinished(e.file[r](t, i, s)) } function u(e, t, i) { this.flowObj = e, this.fileObj = t, this.offset = i, this.tested = !1, this.retries = 0, this.pendingRetry = !1, this.preprocessState = 0, this.readState = 0, this.loaded = 0, this.total = 0, this.chunkSize = this.flowObj.opts.chunkSize, this.startByte = this.offset * this.chunkSize, this.computeEndByte = function() { var e = Math.min(this.fileObj.size, (this.offset + 1) * this.chunkSize); return this.fileObj.size - e < this.chunkSize && !this.flowObj.opts.forceChunkSize && (e = this.fileObj.size), e }, this.endByte = this.computeEndByte(), this.xhr = null; var s = this; this.event = function(e, t) { (t = Array.prototype.slice.call(arguments)).unshift(s), s.fileObj.chunkEvent.apply(s.fileObj, t) }, this.progressHandler = function(e) { e.lengthComputable && (s.loaded = e.loaded, s.total = e.total), s.event("progress", e) }, this.testHandler = function(e) { var t = s.status(!0); "error" === t ? (s.event(t, s.message()), s.flowObj.uploadNextChunk()) : "success" === t ? (s.tested = !0, s.event(t, s.message()), s.flowObj.uploadNextChunk()) : s.fileObj.paused || (s.tested = !0, s.send()) }, this.doneHandler = function(e) { var t = s.status(); if ("success" === t || "error" === t) delete this.data, s.event(t, s.message()), s.flowObj.uploadNextChunk(); else { s.event("retry", s.message()), s.pendingRetry = !0, s.abort(), s.retries++; var i = s.flowObj.opts.chunkRetryInterval; null !== i ? setTimeout(function() { s.send() }, i) : s.send() } } } function f(e, t) { return "function" == typeof e && (t = Array.prototype.slice.call(arguments), e = e.apply(null, t.slice(1))), e } function p(e, t) { setTimeout(e.bind(t), 0) } function c(e, t) { return d(arguments, function(t) { t !== e && d(t, function(t, i) { e[i] = t }) }), e } function d(e, t, i) { var s; if (e) if (void 0 !== e.length) { for (s = 0; s < e.length; s++) if (!1 === t.call(i, e[s], s)) return } else for (s in e) if (e.hasOwnProperty(s) && !1 === t.call(i, e[s], s)) return } a.prototype = { on: function(e, t) { e = e.toLowerCase(), this.events.hasOwnProperty(e) || (this.events[e] = []), this.events[e].push(t) }, off: function(e, t) { var i, s, n; e !== r ? (e = e.toLowerCase(), t !== r ? this.events.hasOwnProperty(e) && (i = this.events[e], s = t, (n = i.indexOf(s)) > -1 && i.splice(n, 1)) : delete this.events[e]) : this.events = {} }, fire: function(e, t) { t = Array.prototype.slice.call(arguments), e = e.toLowerCase(); var i = !1; return this.events.hasOwnProperty(e) && d(this.events[e], function(e) { i = !1 === e.apply(this, t.slice(1)) || i }, this), "catchall" != e && (t.unshift("catchAll"), i = !1 === this.fire.apply(this, t) || i), !i }, webkitReadDataTransfer: function(e) { var t = this, i = e.dataTransfer.items.length, s = []; function n(e, t) { e.relativePath = t.substring(1), s.push(e), o() } function r(e) { throw e } function o() { 0 == --i && t.addFiles(s, e) } d(e.dataTransfer.items, function(e) { var t = e.webkitGetAsEntry(); t ? t.isFile ? n(e.getAsFile(), t.fullPath) : function e(t) { t.readEntries(function(s) { s.length ? (i += s.length, d(s, function(t) { if (t.isFile) { var i = t.fullPath; t.file(function(e) { n(e, i) }, r) } else t.isDirectory && e(t.createReader()) }), e(t)) : o() }, r) } (t.createReader()) : o() }) }, generateUniqueIdentifier: function(e) { var t = this.opts.generateUniqueIdentifier; if ("function" == typeof t) return t(e); var i = e.relativePath || e.webkitRelativePath || e.fileName || e.name; return e.size + "-" + i.replace(/[^0-9a-zA-Z_-]/gim, "") }, uploadNextChunk: function(e) { var t = !1; if (this.opts.prioritizeFirstAndLastChunk && (d(this.files, function(e) { return ! e.paused && e.chunks.length && "pending" === e.chunks[0].status() ? (e.chunks[0].send(), t = !0, !1) : !e.paused && e.chunks.length > 1 && "pending" === e.chunks[e.chunks.length - 1].status() ? (e.chunks[e.chunks.length - 1].send(), t = !0, !1) : void 0 }), t)) return t; if (d(this.files, function(e) { if (e.paused || d(e.chunks, function(e) { if ("pending" === e.status()) return e.send(), t = !0, !1 }), t) return ! 1 }), t) return ! 0; var i = !1; return d(this.files, function(e) { if (!e.isComplete()) return i = !0, !1 }), i || e || p(function() { this.fire("complete") }, this), !1 }, assignBrowse: function(e, t, i, s) { e instanceof Element && (e = [e]), d(e, function(e) { var r; "INPUT" === e.tagName && "file" === e.type ? r = e: ((r = n.createElement("input")).setAttribute("type", "file"), c(r.style, { visibility: "hidden", position: "absolute", width: "1px", height: "1px" }), e.appendChild(r), e.addEventListener("click", function() { r.click() }, !1)), this.opts.singleFile || i || r.setAttribute("multiple", "multiple"), t && r.setAttribute("webkitdirectory", "webkitdirectory"), d(s, function(e, t) { r.setAttribute(t, e) }); var o = this; r.addEventListener("change", function(e) { e.target.value && (o.addFiles(e.target.files, e), e.target.value = "") }, !1) }, this) }, assignDrop: function(e) { d(e, function(e) { e.addEventListener("dragover", this.preventEvent, !1), e.addEventListener("dragenter", this.preventEvent, !1), e.addEventListener("drop", this.onDrop, !1) }, this) }, unAssignDrop: function(e) { void 0 === e.length && (e = [e]), d(e, function(e) { e.removeEventListener("dragover", this.preventEvent), e.removeEventListener("dragenter", this.preventEvent), e.removeEventListener("drop", this.onDrop) }, this) }, isUploading: function() { var e = !1; return d(this.files, function(t) { if (t.isUploading()) return e = !0, !1 }), e }, _shouldUploadNext: function() { var e = 0, t = !0, i = this.opts.simultaneousUploads; return d(this.files, function(s) { d(s.chunks, function(s) { if ("uploading" === s.status() && ++e >= i) return t = !1, !1 }) }), t && e }, upload: function() { var e = this._shouldUploadNext(); if (!1 !== e) { this.fire("uploadStart"); for (var t = !1, i = 1; i <= this.opts.simultaneousUploads - e; i++) t = this.uploadNextChunk(!0) || t; t || p(function() { this.fire("complete") }, this) } }, resume: function() { d(this.files, function(e) { e.isComplete() || e.resume() }) }, pause: function() { d(this.files, function(e) { e.pause() }) }, cancel: function() { for (var e = this.files.length - 1; e >= 0; e--) this.files[e].cancel() }, progress: function() { var e = 0, t = 0; return d(this.files, function(i) { e += i.progress() * i.size, t += i.size }), t > 0 ? e / t: 0 }, addFile: function(e, t) { this.addFiles([e], t) }, addFiles: function(e, t) { var i = []; d(e, function(e) { if ((!o || o && e.size > 0) && (e.size % 4096 != 0 || "." !== e.name && "." !== e.fileName)) { var s = this.generateUniqueIdentifier(e); if (this.opts.allowDuplicateUploads || !this.getFromUniqueIdentifier(s)) { var n = new h(this, e, s); this.fire("fileAdded", n, t) && i.push(n) } } }, this), this.fire("filesAdded", i, t) && (d(i, function(e) { this.opts.singleFile && this.files.length > 0 && this.removeFile(this.files[0]), this.files.push(e) }, this), this.fire("filesSubmitted", i, t)) }, removeFile: function(e) { for (var t = this.files.length - 1; t >= 0; t--) this.files[t] === e && (this.files.splice(t, 1), e.abort(), this.fire("fileRemoved", e)) }, getFromUniqueIdentifier: function(e) { var t = !1; return d(this.files, function(i) { i.uniqueIdentifier === e && (t = i) }), t }, getSize: function() { var e = 0; return d(this.files, function(t) { e += t.size }), e }, sizeUploaded: function() { var e = 0; return d(this.files, function(t) { e += t.sizeUploaded() }), e }, timeRemaining: function() { var e = 0, t = 0; return d(this.files, function(i) { i.paused || i.error || (e += i.size - i.sizeUploaded(), t += i.averageSpeed) }), e && !t ? Number.POSITIVE_INFINITY: e || t ? Math.floor(e / t) : 0 } }, h.prototype = { measureSpeed: function() { var e = Date.now() - this._lastProgressCallback; if (e) { var t = this.flowObj.opts.speedSmoothingFactor, i = this.sizeUploaded(); this.currentSpeed = Math.max((i - this._prevUploadedSize) / e * 1e3, 0), this.averageSpeed = t * this.currentSpeed + (1 - t) * this.averageSpeed, this._prevUploadedSize = i } }, chunkEvent: function(e, t, i) { switch (t) { case "progress": if (Date.now() - this._lastProgressCallback < this.flowObj.opts.progressCallbacksInterval) break; this.measureSpeed(), this.flowObj.fire("fileProgress", this, e), this.flowObj.fire("progress"), this._lastProgressCallback = Date.now(); break; case "error": this.error = !0, this.abort(!0), this.flowObj.fire("fileError", this, i, e), this.flowObj.fire("error", i, this, e); break; case "success": if (this.error) return; this.measureSpeed(), this.flowObj.fire("fileProgress", this, e), this.flowObj.fire("progress"), this._lastProgressCallback = Date.now(), this.isComplete() && (this.currentSpeed = 0, this.averageSpeed = 0, this.flowObj.fire("fileSuccess", this, i, e)); break; case "retry": this.flowObj.fire("fileRetry", this, e) } }, pause: function() { this.paused = !0, this.abort() }, resume: function() { this.paused = !1, this.flowObj.upload() }, abort: function(e) { this.currentSpeed = 0, this.averageSpeed = 0; var t = this.chunks; e && (this.chunks = []), d(t, function(e) { "uploading" === e.status() && (e.abort(), this.flowObj.uploadNextChunk()) }, this) }, cancel: function() { this.flowObj.removeFile(this) }, retry: function() { this.bootstrap(), this.flowObj.upload() }, bootstrap: function() { "function" == typeof this.flowObj.opts.initFileFn && this.flowObj.opts.initFileFn(this), this.abort(!0), this.error = !1, this._prevProgress = 0; for (var e = this.flowObj.opts.forceChunkSize ? Math.ceil: Math.floor, t = Math.max(e(this.size / this.flowObj.opts.chunkSize), 1), i = 0; i < t; i++) this.chunks.push(new u(this.flowObj, this, i)) }, progress: function() { if (this.error) return 1; if (1 === this.chunks.length) return this._prevProgress = Math.max(this._prevProgress, this.chunks[0].progress()), this._prevProgress; var e = 0; d(this.chunks, function(t) { e += t.progress() * (t.endByte - t.startByte) }); var t = e / this.size; return this._prevProgress = Math.max(this._prevProgress, t > .9999 ? 1 : t), this._prevProgress }, isUploading: function() { var e = !1; return d(this.chunks, function(t) { if ("uploading" === t.status()) return e = !0, !1 }), e }, isComplete: function() { var e = !1; return d(this.chunks, function(t) { var i = t.status(); if ("pending" === i || "uploading" === i || "reading" === i || 1 === t.preprocessState || 1 === t.readState) return e = !0, !1 }), !e }, sizeUploaded: function() { var e = 0; return d(this.chunks, function(t) { e += t.sizeUploaded() }), e }, timeRemaining: function() { if (this.paused || this.error) return 0; var e = this.size - this.sizeUploaded(); return e && !this.averageSpeed ? Number.POSITIVE_INFINITY: e || this.averageSpeed ? Math.floor(e / this.averageSpeed) : 0 }, getType: function() { return this.file.type && this.file.type.split("/")[1] }, getExtension: function() { return this.name.substr(2 + (~ - this.name.lastIndexOf(".") >>> 0)).toLowerCase() } }, u.prototype = { getParams: function() { return { flowChunkNumber: this.offset + 1, flowChunkSize: this.flowObj.opts.chunkSize, flowCurrentChunkSize: this.endByte - this.startByte, flowTotalSize: this.fileObj.size, flowIdentifier: this.fileObj.uniqueIdentifier, flowFilename: this.fileObj.name, flowRelativePath: this.fileObj.relativePath, flowTotalChunks: this.fileObj.chunks.length } }, getTarget: function(e, t) { return e.indexOf("?") < 0 ? e += "?": e += "&", e + t.join("&") }, test: function() { this.xhr = new XMLHttpRequest, this.xhr.addEventListener("load", this.testHandler, !1), this.xhr.addEventListener("error", this.testHandler, !1); var e = f(this.flowObj.opts.testMethod, this.fileObj, this), t = this.prepareXhrRequest(e, !0); this.xhr.send(t) }, preprocessFinished: function() { this.endByte = this.computeEndByte(), this.preprocessState = 2, this.send() }, readFinished: function(e) { this.readState = 2, this.bytes = e, this.send() }, send: function() { var e = this.flowObj.opts.preprocess, t = this.flowObj.opts.readFileFn; if ("function" == typeof e) switch (this.preprocessState) { case 0: return this.preprocessState = 1, void e(this); case 1: return } switch (this.readState) { case 0: return this.readState = 1, void t(this.fileObj, this.startByte, this.endByte, this.fileObj.file.type, this); case 1: return } if (!this.flowObj.opts.testChunks || this.tested) { this.loaded = 0, this.total = 0, this.pendingRetry = !1, this.xhr = new XMLHttpRequest, this.xhr.upload.addEventListener("progress", this.progressHandler, !1), this.xhr.addEventListener("load", this.doneHandler, !1), this.xhr.addEventListener("error", this.doneHandler, !1); var i = f(this.flowObj.opts.uploadMethod, this.fileObj, this), s = this.prepareXhrRequest(i, !1, this.flowObj.opts.method, this.bytes); this.xhr.send(s) } else this.test() }, abort: function() { var e = this.xhr; this.xhr = null, e && e.abort() }, status: function(e) { return 1 === this.readState ? "reading": this.pendingRetry || 1 === this.preprocessState ? "uploading": this.xhr ? this.xhr.readyState < 4 ? "uploading": this.flowObj.opts.successStatuses.indexOf(this.xhr.status) > -1 ? "success": this.flowObj.opts.permanentErrors.indexOf(this.xhr.status) > -1 || !e && this.retries >= this.flowObj.opts.maxChunkRetries ? "error": (this.abort(), "pending") : "pending" }, message: function() { return this.xhr ? this.xhr.responseText: "" }, progress: function() { if (this.pendingRetry) return 0; var e = this.status(); return "success" === e || "error" === e ? 1 : "pending" === e ? 0 : this.total > 0 ? this.loaded / this.total: 0 }, sizeUploaded: function() { var e = this.endByte - this.startByte; return "success" !== this.status() && (e = this.progress() * e), e }, prepareXhrRequest: function(e, t, i, s) { var n = f(this.flowObj.opts.query, this.fileObj, this, t); n = c(n, this.getParams()); var r = f(this.flowObj.opts.target, this.fileObj, this, t), o = null; if ("GET" === e || "octet" === i) { var a = []; d(n, function(e, t) { a.push([encodeURIComponent(t), encodeURIComponent(e)].join("=")) }), r = this.getTarget(r, a), o = s || null } else o = new FormData, d(n, function(e, t) { o.append(t, e) }), void 0 !== s && o.append(this.flowObj.opts.fileParameterName, s, this.fileObj.file.name); return this.xhr.open(e, r, !0), this.xhr.withCredentials = this.flowObj.opts.withCredentials, d(f(this.flowObj.opts.headers, this.fileObj, this, t), function(e, t) { this.xhr.setRequestHeader(t, e) }, this), o } }, a.evalOpts = f, a.extend = c, a.each = d, a.FlowFile = h, a.FlowChunk = u, a.version = "<%= version %>", "object" == typeof e && e && "object" == typeof e.exports ? e.exports = a: (s.Flow = a, (i = function() { return a }.apply(t, [])) === r || (e.exports = i)) } (window, document) }).call(this, i(5)(e)) }, 268 : function(e, t, i) { "use strict"; i.r(t); var s = i(162); i.n(s), i.d(t, "Flow", function() { return s }) }, 5 : function(e, t) { e.exports = function(e) { return e.webpackPolyfill || (e.deprecate = function() {}, e.paths = [], e.children || (e.children = []), Object.defineProperty(e, "loaded", { enumerable: !0, get: function() { return e.l } }), Object.defineProperty(e, "id", { enumerable: !0, get: function() { return e.i } }), e.webpackPolyfill = 1), e } } }); if ("object" == typeof i) { var s = ["object" == typeof module && "object" == typeof module.exports ? module.exports: null, "undefined" != typeof window ? window: null, e && e !== window ? e: null]; for (var n in i) s[0] && (s[0][n] = i[n]), s[1] && "__esModule" !== n && (s[1][n] = i[n]), s[2] && (s[2][n] = i[n]) } } (this);
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); 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) : subClass.__proto__ = superClass; } var url="https://spreadsheets.google.com/feeds/list/1lz79dMIx0s5ItD0ooRqHsncQcxcwsS7YQQ5Xk1iNzSk/od6/public/values?alt=json"; $.getJSON(url, function req(json) { try{ display(json.feed.entry.reverse()); } catch{ location.reload(); } }); var types = [{ category: "All" }, { category: "Free" }, { category: "Arts" }, { category: "Business" }, { category: "City Government" }, { category: "Culture" }, { category: "Environment" }, { category: "Fairs" }, { category: "Family" }, { category: "General" }, { category: "Holiday" }, { category: "Parks" }, { category: "Shows" }, { category: "Tours" }, { category: "Training" }]; function filter(data, filterKeys) { var arr = []; if (filterKeys === "All") { for (i = 0; i < data.length; i++) { var current = data[i]; arr.push(current); } } else if(filterKeys === "Free"){ for (i = 0; i < data.length; i++) { var current = data[i]; if (current.gsx$eventfee.$t === "No") { arr.push(current); } } } else { for (i = 0; i < data.length; i++) { var current = data[i]; if (current.gsx$eventtypes.$t.indexOf(filterKeys) >= 0) { arr.push(current); } } } return arr; } function display(json) { var arrButtons = []; var buttonStyle = { margin: '10px 10px 10px 0' }; var ButtonClicks = function (_React$Component) { _inherits(ButtonClicks, _React$Component); function ButtonClicks(props) { _classCallCheck(this, ButtonClicks); var _this = _possibleConstructorReturn(this, (ButtonClicks.__proto__ || Object.getPrototypeOf(ButtonClicks)).call(this, props)); _this.onClick = _this.onClick.bind(_this); return _this; } _createClass(ButtonClicks, [{ key: 'onClick', value: function onClick(i) { var data = filter(json, i); var arr = []; if(data.length > 0){ for (j = 0; j < data.length; j++) { const title = data[j].gsx$rawtitle.$t; const date = data[j]["gsx$event-date"].$t; const startTime = data[j].gsx$eventtime.$t; const street = data[j].gsx$street.$t; const city = data[j].gsx$city.$t; const zip = data[j].gsx$zipcode.$t; const pic = data[j].gsx$eventimage.$t; const link = data[j].gsx$url.$t; if(pic === ""){ //default image //data[j].gsx$eventimage.$t = "" } arr.push(React.createElement('div', {key: title + j,className: 'box'}, React.createElement('div', {className: 'date'}, date), React.createElement('div', {className: 'time'}, startTime), React.createElement('div', {className: 'title'}, he.decode(title)), React.createElement('div', {className: 'address'}, street), React.createElement('div', {className: 'cityZip'}, city + ' ' + zip), React.createElement('br'), React.createElement('img', {className: 'eventImg', src: pic, alt: he.decode(title) + ' picture' }), React.createElement('a', {className: 'calLink', href: link}, 'Link') )); } draw(React.createElement( 'div', null, arr ), results); } else{ arr.push(React.createElement( 'p', { key: 'empty' }, 'No events to display for this category.' )); } draw(React.createElement( 'div', {className: "flex-container"}, arr ), results); } }, { key: 'render', value: function render() { var _this2 = this; var _loop = function _loop(_i) { arrButtons.push(React.createElement( 'button', { style: buttonStyle, key: types[_i].category, id: types[_i].category, onClick: function onClick() { return _this2.onClick(types[_i].category); } }, types[_i].category )); }; for (var _i = 0; _i < types.length; _i++) { _loop(_i); } return React.createElement( 'div', null, arrButtons ); } }]); return ButtonClicks; }(React.Component); var buttonDiv = document.getElementById("test"); var results = document.getElementById("test2"); draw(React.createElement(ButtonClicks, null), buttonDiv); document.getElementById("All").click(); showPage(); } function draw(element, id) { ReactDOM.render(element, id); } function showPage() { document.getElementById("loader").style.display = "none"; document.getElementById("content").style.display = "block"; } function showLoader() { document.getElementById("loader").style.display = "block"; document.getElementById("content").style.display = "none"; }
fs = require('fs') const Discord = require("discord.js"); const client = new Discord.Client(); client.on('ready', function () { console.log('ready') }) client.on('error', function (e) { console.log("error", e) }) try { let data = fs.readFileSync("./creds.json"); let creds = JSON.parse(data); client.login(creds.token); } catch (e) { console.log("error reading ./creds.json", e); } client.on('message', (m) => { //must be from me and be in form <effect> <args>~<msg> try { if (m.author.id != client.user.id || m.content.match(/[^\s]+(\s[^\s]+)*~.*/).length == 0) return; let parts = m.content.split("~"); let effect_parts = parts[0].split(" "); //get effect and args let content = parts[1]; effects[effect_parts.shift()](m, content, ...effect_parts); } catch (e) { console.log("error while parsing command, please check your syntax"); } }); let effects = { rotate: function (m, content, count) { var interval; var a = ("" + content + ""); function hi() { if (count-- < 0) { clearInterval(interval); } var out = a.substring(1); out = out + a.substring(0, 1); a = out; m.edit(out).then(() => { }); } interval = setInterval(hi, 1000); }, hungry(m, content) { var interval; var strmsg = (content); var a = true; var n = 1; function hi() { if (n++ > strmsg.length) { clearInterval(interval); m.delete(); return;} if (a) { n--; } var out = ' .'.repeat(n - 1) + ((a) ? '<' : '-'); a = !a; out += strmsg.substring(n); m.edit(out); } interval = setInterval(hi, 1000); }, reveal: function (m, content) { var interval; var strmsg = ""; m.edit(""); var a = true; var n = 0; function hi() { if (n++ > content.length+1) { clearInterval(interval); } var out = strmsg; out += content.substring(0, n) m.edit(out.length <= 0 ? "." : out) } interval = setInterval(hi, 1000); }, wrap: function (m, content, count, wrap_a, wrap_b) { var interval; var strmsg = content; var isa = true; function hi() { if (count-- < 0) { clearInterval(interval); } var out = ""; if (isa) { out = wrap_a + strmsg + wrap_a; } else { out = wrap_b + strmsg + wrap_b; } isa = !isa; m.edit(out) } interval = setInterval(hi, 1000); }, wof: function (m) { var wheel = ":three: :broken_heart: :broken_heart: :broken_heart: :zero: :one: :two: :two: :one: :zero: :zero: :zero: :zero: :star: :zero: :zero: :zero: :zero: :zero: :one: :two: :two: :one: :zero: :broken_heart: :broken_heart: :broken_heart: :three:" var vel = 10; var x = 1; absolutex = 1; function hi() { if (vel < 0) { clearInterval(interval); } var out = wheel + '\n'; out += ' :heavy_minus_sign: '.repeat(27 - x); out += ' :arrow_up_small: '; out += ' :heavy_minus_sign: '.repeat(x); vel -= Math.floor(Math.random() * 2);; x += vel; if (x >= 28) { x %= 28; } //absolutex += vel; //x = absolutex%8; m.edit(out); } interval = setInterval(hi, 1000); } }
import Modal from 'modal_dialog'; import ModalView from './view/ModalView'; describe('Modal dialog', () => { describe('Main', () => { var obj; beforeEach(() => { obj = new Modal().init(); }); afterEach(() => { obj = null; }); test('Object exists', () => { expect(obj).toBeTruthy(); }); test('Is close by default', () => { expect(obj.isOpen()).toEqual(false); }); test('Title is empty', () => { expect(obj.getTitle()).toEqual(''); }); test('Content is empty', () => { expect(obj.getContent()).toEqual(''); }); test('Set title', () => { obj.setTitle('Test'); expect(obj.getTitle()).toEqual('Test'); }); test('Set content', () => { obj.setContent('Test'); expect(obj.getContent()).toEqual('Test'); }); test('Set HTML content', () => { obj.setContent('<h1>Test</h1>'); expect(obj.getContent()).toEqual('<h1>Test</h1>'); }); test('Open modal', () => { obj.open(); expect(obj.isOpen()).toEqual(true); }); test('Close modal', () => { obj.open(); obj.close(); expect(obj.isOpen()).toEqual(false); }); }); });
var CaseManager = require('../pageObjects/common/CaseManager'); var { defineSupportCode } = require('cucumber'); let caseManager = new CaseManager(); When('I Add Comment to the case', async function () { await caseManager.startNextStep('Add Comment'); await caseManager.clickSubmit(); }); Then('I see the event with the current timestamp', async function () { let currentDate = new Date(); expect(await caseManager.getTimestampDisplayed()).to.be.contain(currentDate.toLocaleTimeString()); });
import axios from 'axios'; const TODO_API_BASE_URL = "http://localhost:8081/todo"; class TodoService { getTodos() { return axios.get(TODO_API_BASE_URL); } } export default new TodoService();
import React from 'react'; import { Link } from 'react-router-dom'; import styles from './style.module.scss'; export default function Header() { return ( <header className={styles.header}> <div className={styles.headerContent}> {/* eslint-disable-next-line jsx-a11y/anchor-is-valid */} <Link to="/"> <span>MY HEROES</span> </Link> <nav> <Link to="/favorite"> <span>Favorite</span> </Link> </nav> </div> </header> ); }
import React from 'react' import {shallow} from 'enzyme' import SalesTool from './index' import configureStore from 'redux-mock-store' //not working const setup = () => { const props = { store: configureStore()({}), sales: [], dispatch: jest.fn(), season: '', dimensions: [ {value: 'some', title: 'Some'}, {value: 'mock', title: 'Mock'}, {value: 'dims', title: 'Dims'} ], reduce: () => {}, calculations: [{ title: 'Calculated Field', value: 'calculatedField' }], activeDimensions: ['some'], numPaginateRows: 1000 } //todo convert to static render so we can test components are called with correct props const enzymeWrapper = shallow(<SalesTool {...props} />) return { props, enzymeWrapper } } describe('sales-tool', () => { describe('Page', () => { it('should render correctly', () => { const {enzymeWrapper} = setup() expect(enzymeWrapper.find('h1')).toHaveLength(1) }) //ToDo renders grid //grid has expected number of cols //sends the correct params to grid }) })
/* eslint-disable dot-notation */ import chai from 'chai'; import chaiHttp from 'chai-http'; import app from '../../index'; import { User, } from '../../models'; const deleteUsers = async () => { await User.deleteMany({ isSubscribed: true }); }; deleteUsers(); chai.use(chaiHttp); const { expect } = chai; let token; before('login with an existing user details to get token', async () => { it('should create a user and verify the user', async () => { const userDetails = { username: 'JthnDmkloes', password: 'password', email: 'chris90@wemail.com', firstName: 'John', lastName: 'Doe', }; const response = await chai.request(app).post('/api/v1/auth/signup') .send(userDetails); expect(response.status).to.equal(200); await User.updateOne({ email: 'chris90@wemail.com' }, { $set: { isVerified: true } }); }); it('should login the user to get token', async () => { const response = await chai.request(app).post('/api/v1/auth/login') .send({ email: 'chris90@wemail.com', password: 'password', }); token = response.body.data.userDetails.token; }); }); describe('Integration tests for answer controller', () => { it('should answer a question', async () => { const createQuestion = await chai.request(app).post('/api/v1/question') .set('x-access-token', token) .send({ title: 'this title is for the integration test', description: 'this description is also for integration test', labels: 'express, mongoDB', }); const id = createQuestion.body.data.question['_id']; const response = await chai.request(app) .post(`/api/v1/answer/${id}`) .set('x-access-token', token) .send({ response: 'this is a response from the integration test to a question', }); const { data } = response.body; expect(data.success).to.equal(true); expect(data).to.have.property('answer'); expect(data.answer).to.be.an('object'); expect(data.answer['_id']).to.be.a('string'); }); it('should return an error is the question ID is invalid', async () => { const response = await chai.request(app) .post('/api/v1/answer/invalid_Question_Id') .set('x-access-token', token) .send({ response: 'this is a response from the integration test to a question', }); expect(response.body.success).to.equal(false); expect(response.body.message).to.equal('A valid id is required'); }); });
function attachEventsListeners() { let buttonElement=document.querySelector('#convert'); buttonElement.addEventListener('click', ()=>{ let fromElement=document.querySelector('#inputUnits'); let toElement=document.querySelector('#outputUnits'); let inputElement=document.querySelector('#inputDistance'); let outputElement=document.querySelector('#outputDistance') let inputMeters=inputElement.value; if (fromElement.value=='km') { inputMeters*=1000; } else if (fromElement.value=='cm'){ inputMeters/=100; } else if (fromElement.value=='mm'){ inputMeters/=1000; } else if (fromElement.value=='mi'){ inputMeters*=1609.34; } else if (fromElement.value=='in'){ inputMeters*=0.0254; } else if (fromElement.value=='yrd'){ inputMeters*=0.9144; } else if (fromElement.value=='ft'){ inputMeters*=0.3048; } if (toElement.value=='km') { inputMeters/=1000; } else if (toElement.value=='cm') { inputMeters*=100; } else if (toElement.value=='mm') { inputMeters*=1000; } else if (toElement.value=='mi') { inputMeters/=1609.34; } else if (toElement.value=='in') { inputMeters/=0.0254; } else if (toElement.value=='yrd') { inputMeters/=0.9144; } else if (toElement.value=='ft') { inputMeters/=0.3048; } outputElement.value=inputMeters; }); }
dojo.provide('dojox.grid.compat._grid.scroller'); dojo.declare('dojox.grid.scroller.base', null, { // summary: // virtual scrollbox, abstract class // Content must in /rows/ // Rows are managed in contiguous sets called /pages/ // There are a fixed # of rows per page // The minimum rendered unit is a page constructor: function(){ this.pageHeights = []; this.stack = []; }, // specified rowCount: 0, // total number of rows to manage defaultRowHeight: 10, // default height of a row keepRows: 100, // maximum number of rows that should exist at one time contentNode: null, // node to contain pages scrollboxNode: null, // node that controls scrolling // calculated defaultPageHeight: 0, // default height of a page keepPages: 10, // maximum number of pages that should exists at one time pageCount: 0, windowHeight: 0, firstVisibleRow: 0, lastVisibleRow: 0, // private page: 0, pageTop: 0, // init init: function(inRowCount, inKeepRows, inRowsPerPage){ switch(arguments.length){ case 3: this.rowsPerPage = inRowsPerPage; case 2: this.keepRows = inKeepRows; case 1: this.rowCount = inRowCount; } this.defaultPageHeight = this.defaultRowHeight * this.rowsPerPage; //this.defaultPageHeight = this.defaultRowHeight * Math.min(this.rowsPerPage, this.rowCount); this.pageCount = Math.ceil(this.rowCount / this.rowsPerPage); this.setKeepInfo(this.keepRows); this.invalidate(); if(this.scrollboxNode){ this.scrollboxNode.scrollTop = 0; this.scroll(0); this.scrollboxNode.onscroll = dojo.hitch(this, 'onscroll'); } }, setKeepInfo: function(inKeepRows){ this.keepRows = inKeepRows; this.keepPages = !this.keepRows ? this.keepRows : Math.max(Math.ceil(this.keepRows / this.rowsPerPage), 2); }, // updating invalidate: function(){ this.invalidateNodes(); this.pageHeights = []; this.height = (this.pageCount ? (this.pageCount - 1)* this.defaultPageHeight + this.calcLastPageHeight() : 0); this.resize(); }, updateRowCount: function(inRowCount){ this.invalidateNodes(); this.rowCount = inRowCount; // update page count, adjust document height oldPageCount = this.pageCount; this.pageCount = Math.ceil(this.rowCount / this.rowsPerPage); if(this.pageCount < oldPageCount){ for(var i=oldPageCount-1; i>=this.pageCount; i--){ this.height -= this.getPageHeight(i); delete this.pageHeights[i] } }else if(this.pageCount > oldPageCount){ this.height += this.defaultPageHeight * (this.pageCount - oldPageCount - 1) + this.calcLastPageHeight(); } this.resize(); }, // abstract interface pageExists: function(inPageIndex){ }, measurePage: function(inPageIndex){ }, positionPage: function(inPageIndex, inPos){ }, repositionPages: function(inPageIndex){ }, installPage: function(inPageIndex){ }, preparePage: function(inPageIndex, inPos, inReuseNode){ }, renderPage: function(inPageIndex){ }, removePage: function(inPageIndex){ }, pacify: function(inShouldPacify){ }, // pacification pacifying: false, pacifyTicks: 200, setPacifying: function(inPacifying){ if(this.pacifying != inPacifying){ this.pacifying = inPacifying; this.pacify(this.pacifying); } }, startPacify: function(){ this.startPacifyTicks = new Date().getTime(); }, doPacify: function(){ var result = (new Date().getTime() - this.startPacifyTicks) > this.pacifyTicks; this.setPacifying(true); this.startPacify(); return result; }, endPacify: function(){ this.setPacifying(false); }, // default sizing implementation resize: function(){ if(this.scrollboxNode){ this.windowHeight = this.scrollboxNode.clientHeight; } dojox.grid.setStyleHeightPx(this.contentNode, this.height); }, calcLastPageHeight: function(){ if(!this.pageCount){ return 0; } var lastPage = this.pageCount - 1; var lastPageHeight = ((this.rowCount % this.rowsPerPage)||(this.rowsPerPage)) * this.defaultRowHeight; this.pageHeights[lastPage] = lastPageHeight; return lastPageHeight; }, updateContentHeight: function(inDh){ this.height += inDh; this.resize(); }, updatePageHeight: function(inPageIndex){ if(this.pageExists(inPageIndex)){ var oh = this.getPageHeight(inPageIndex); var h = (this.measurePage(inPageIndex))||(oh); this.pageHeights[inPageIndex] = h; if((h)&&(oh != h)){ this.updateContentHeight(h - oh) this.repositionPages(inPageIndex); } } }, rowHeightChanged: function(inRowIndex){ this.updatePageHeight(Math.floor(inRowIndex / this.rowsPerPage)); }, // scroller core invalidateNodes: function(){ while(this.stack.length){ this.destroyPage(this.popPage()); } }, createPageNode: function(){ var p = document.createElement('div'); p.style.position = 'absolute'; //p.style.width = '100%'; p.style[dojo._isBodyLtr() ? "left" : "right"] = '0'; return p; }, getPageHeight: function(inPageIndex){ var ph = this.pageHeights[inPageIndex]; return (ph !== undefined ? ph : this.defaultPageHeight); }, // FIXME: this is not a stack, it's a FIFO list pushPage: function(inPageIndex){ return this.stack.push(inPageIndex); }, popPage: function(){ return this.stack.shift(); }, findPage: function(inTop){ var i = 0, h = 0; for(var ph = 0; i<this.pageCount; i++, h += ph){ ph = this.getPageHeight(i); if(h + ph >= inTop){ break; } } this.page = i; this.pageTop = h; }, buildPage: function(inPageIndex, inReuseNode, inPos){ this.preparePage(inPageIndex, inReuseNode); this.positionPage(inPageIndex, inPos); // order of operations is key below this.installPage(inPageIndex); this.renderPage(inPageIndex); // order of operations is key above this.pushPage(inPageIndex); }, needPage: function(inPageIndex, inPos){ var h = this.getPageHeight(inPageIndex), oh = h; if(!this.pageExists(inPageIndex)){ this.buildPage(inPageIndex, this.keepPages&&(this.stack.length >= this.keepPages), inPos); h = this.measurePage(inPageIndex) || h; this.pageHeights[inPageIndex] = h; if(h && (oh != h)){ this.updateContentHeight(h - oh) } }else{ this.positionPage(inPageIndex, inPos); } return h; }, onscroll: function(){ this.scroll(this.scrollboxNode.scrollTop); }, scroll: function(inTop){ this.startPacify(); this.findPage(inTop); var h = this.height; var b = this.getScrollBottom(inTop); for(var p=this.page, y=this.pageTop; (p<this.pageCount)&&((b<0)||(y<b)); p++){ y += this.needPage(p, y); } this.firstVisibleRow = this.getFirstVisibleRow(this.page, this.pageTop, inTop); this.lastVisibleRow = this.getLastVisibleRow(p - 1, y, b); // indicates some page size has been updated if(h != this.height){ this.repositionPages(p-1); } this.endPacify(); }, getScrollBottom: function(inTop){ return (this.windowHeight >= 0 ? inTop + this.windowHeight : -1); }, // events processNodeEvent: function(e, inNode){ var t = e.target; while(t && (t != inNode) && t.parentNode && (t.parentNode.parentNode != inNode)){ t = t.parentNode; } if(!t || !t.parentNode || (t.parentNode.parentNode != inNode)){ return false; } var page = t.parentNode; e.topRowIndex = page.pageIndex * this.rowsPerPage; e.rowIndex = e.topRowIndex + dojox.grid.indexInParent(t); e.rowTarget = t; return true; }, processEvent: function(e){ return this.processNodeEvent(e, this.contentNode); }, dummy: 0 }); dojo.declare('dojox.grid.scroller', dojox.grid.scroller.base, { // summary: // virtual scroller class, makes no assumption about shape of items being scrolled constructor: function(){ this.pageNodes = []; }, // virtual rendering interface renderRow: function(inRowIndex, inPageNode){ }, removeRow: function(inRowIndex){ }, // page node operations getDefaultNodes: function(){ return this.pageNodes; }, getDefaultPageNode: function(inPageIndex){ return this.getDefaultNodes()[inPageIndex]; }, positionPageNode: function(inNode, inPos){ inNode.style.top = inPos + 'px'; }, getPageNodePosition: function(inNode){ return inNode.offsetTop; }, repositionPageNodes: function(inPageIndex, inNodes){ var last = 0; for(var i=0; i<this.stack.length; i++){ last = Math.max(this.stack[i], last); } // var n = inNodes[inPageIndex]; var y = (n ? this.getPageNodePosition(n) + this.getPageHeight(inPageIndex) : 0); //console.log('detected height change, repositioning from #%d (%d) @ %d ', inPageIndex + 1, last, y, this.pageHeights[0]); // for(var p=inPageIndex+1; p<=last; p++){ n = inNodes[p]; if(n){ //console.log('#%d @ %d', inPageIndex, y, this.getPageNodePosition(n)); if(this.getPageNodePosition(n) == y){ return; } //console.log('placing page %d at %d', p, y); this.positionPage(p, y); } y += this.getPageHeight(p); } }, invalidatePageNode: function(inPageIndex, inNodes){ var p = inNodes[inPageIndex]; if(p){ delete inNodes[inPageIndex]; this.removePage(inPageIndex, p); dojox.grid.cleanNode(p); p.innerHTML = ''; } return p; }, preparePageNode: function(inPageIndex, inReusePageIndex, inNodes){ var p = (inReusePageIndex === null ? this.createPageNode() : this.invalidatePageNode(inReusePageIndex, inNodes)); p.pageIndex = inPageIndex; p.id = (this._pageIdPrefix || "") + 'page-' + inPageIndex; inNodes[inPageIndex] = p; }, // implementation for page manager pageExists: function(inPageIndex){ return Boolean(this.getDefaultPageNode(inPageIndex)); }, measurePage: function(inPageIndex){ var p = this.getDefaultPageNode(inPageIndex); var h = p.offsetHeight; if(!this._defaultRowHeight){ //The default sizes tend to vary, particularly on IE, so we //need to calculate a basic default size for a row. Putting //a text character and using it to calculate a default row padding //in the div seems to handle this okay. It keeps IE //from loading too much data. if(p){ this._defaultRowHeight = 8; var fr = p.firstChild; if(fr){ var text = dojo.doc.createTextNode("T"); fr.appendChild(text); this._defaultRowHeight = fr.offsetHeight; fr.removeChild(text); } } } //If page height isn't very accurate (empty rows because data hasn't //been populated yet and the size is far too small) we need to adjust //it via the _defaultRowSize. return (this.rowsPerPage == h)?(h*this._defaultRowHeight):h; }, positionPage: function(inPageIndex, inPos){ this.positionPageNode(this.getDefaultPageNode(inPageIndex), inPos); }, repositionPages: function(inPageIndex){ this.repositionPageNodes(inPageIndex, this.getDefaultNodes()); }, preparePage: function(inPageIndex, inReuseNode){ this.preparePageNode(inPageIndex, (inReuseNode ? this.popPage() : null), this.getDefaultNodes()); }, installPage: function(inPageIndex){ this.contentNode.appendChild(this.getDefaultPageNode(inPageIndex)); }, destroyPage: function(inPageIndex){ var p = this.invalidatePageNode(inPageIndex, this.getDefaultNodes()); dojox.grid.removeNode(p); }, // rendering implementation renderPage: function(inPageIndex){ var node = this.pageNodes[inPageIndex]; for(var i=0, j=inPageIndex*this.rowsPerPage; (i<this.rowsPerPage)&&(j<this.rowCount); i++, j++){ this.renderRow(j, node); } }, removePage: function(inPageIndex){ for(var i=0, j=inPageIndex*this.rowsPerPage; i<this.rowsPerPage; i++, j++){ this.removeRow(j); } }, // scroll control getPageRow: function(inPage){ return inPage * this.rowsPerPage; }, getLastPageRow: function(inPage){ return Math.min(this.rowCount, this.getPageRow(inPage + 1)) - 1; }, getFirstVisibleRowNodes: function(inPage, inPageTop, inScrollTop, inNodes){ var row = this.getPageRow(inPage); var rows = dojox.grid.divkids(inNodes[inPage]); for(var i=0,l=rows.length; i<l && inPageTop<inScrollTop; i++, row++){ inPageTop += rows[i].offsetHeight; } return (row ? row - 1 : row); }, getFirstVisibleRow: function(inPage, inPageTop, inScrollTop){ if(!this.pageExists(inPage)){ return 0; } return this.getFirstVisibleRowNodes(inPage, inPageTop, inScrollTop, this.getDefaultNodes()); }, getLastVisibleRowNodes: function(inPage, inBottom, inScrollBottom, inNodes){ var row = this.getLastPageRow(inPage); var rows = dojox.grid.divkids(inNodes[inPage]); for(var i=rows.length-1; i>=0 && inBottom>inScrollBottom; i--, row--){ inBottom -= rows[i].offsetHeight; } return row + 1; }, getLastVisibleRow: function(inPage, inBottom, inScrollBottom){ if(!this.pageExists(inPage)){ return 0; } return this.getLastVisibleRowNodes(inPage, inBottom, inScrollBottom, this.getDefaultNodes()); }, findTopRowForNodes: function(inScrollTop, inNodes){ var rows = dojox.grid.divkids(inNodes[this.page]); for(var i=0,l=rows.length,t=this.pageTop,h; i<l; i++){ h = rows[i].offsetHeight; t += h; if(t >= inScrollTop){ this.offset = h - (t - inScrollTop); return i + this.page * this.rowsPerPage; } } return -1; }, findScrollTopForNodes: function(inRow, inNodes){ var rowPage = Math.floor(inRow / this.rowsPerPage); var t = 0; for(var i=0; i<rowPage; i++){ t += this.getPageHeight(i); } this.pageTop = t; this.needPage(rowPage, this.pageTop); var rows = dojox.grid.divkids(inNodes[rowPage]); var r = inRow - this.rowsPerPage * rowPage; for(var i=0,l=rows.length; i<l && i<r; i++){ t += rows[i].offsetHeight; } return t; }, findTopRow: function(inScrollTop){ return this.findTopRowForNodes(inScrollTop, this.getDefaultNodes()); }, findScrollTop: function(inRow){ return this.findScrollTopForNodes(inRow, this.getDefaultNodes()); }, dummy: 0 }); dojo.declare('dojox.grid.scroller.columns', dojox.grid.scroller, { // summary: // Virtual scroller class that scrolls list of columns. Owned by grid and used internally // for virtual scrolling. constructor: function(inContentNodes){ this.setContentNodes(inContentNodes); }, // nodes setContentNodes: function(inNodes){ this.contentNodes = inNodes; this.colCount = (this.contentNodes ? this.contentNodes.length : 0); this.pageNodes = []; for(var i=0; i<this.colCount; i++){ this.pageNodes[i] = []; } }, getDefaultNodes: function(){ return this.pageNodes[0] || []; }, scroll: function(inTop) { if(this.colCount){ dojox.grid.scroller.prototype.scroll.call(this, inTop); } }, // resize resize: function(){ if(this.scrollboxNode){ this.windowHeight = this.scrollboxNode.clientHeight; } for(var i=0; i<this.colCount; i++){ dojox.grid.setStyleHeightPx(this.contentNodes[i], this.height); } }, // implementation for page manager positionPage: function(inPageIndex, inPos){ for(var i=0; i<this.colCount; i++){ this.positionPageNode(this.pageNodes[i][inPageIndex], inPos); } }, preparePage: function(inPageIndex, inReuseNode){ var p = (inReuseNode ? this.popPage() : null); for(var i=0; i<this.colCount; i++){ this.preparePageNode(inPageIndex, p, this.pageNodes[i]); } }, installPage: function(inPageIndex){ for(var i=0; i<this.colCount; i++){ this.contentNodes[i].appendChild(this.pageNodes[i][inPageIndex]); } }, destroyPage: function(inPageIndex){ for(var i=0; i<this.colCount; i++){ dojox.grid.removeNode(this.invalidatePageNode(inPageIndex, this.pageNodes[i])); } }, // rendering implementation renderPage: function(inPageIndex){ var nodes = []; for(var i=0; i<this.colCount; i++){ nodes[i] = this.pageNodes[i][inPageIndex]; } //this.renderRows(inPageIndex*this.rowsPerPage, this.rowsPerPage, nodes); for(var i=0, j=inPageIndex*this.rowsPerPage; (i<this.rowsPerPage)&&(j<this.rowCount); i++, j++){ this.renderRow(j, nodes); } } });
import Validator from "../helpers/validator"; export const POST_PRODUCT_DETAILS = "POST_PRODUCT_DETAILS"; export const FETCH_PRODUCTS = "FETCH_PRODUCTS"; export const FETCH_APPROVED_PRODUCTS = "FETCH_APPROVED_PRODUCTS"; export const UPDATE_PRODUCT_DETAILS = "UPDATE_PRODUCT_DETAILS"; export const APPROVED_PRODUCT = "APPROVED_PRODUCT"; export const DELETE_PRODUCT = "DELETE_PRODUCT"; export function loadProducts(result) { return { type: FETCH_PRODUCTS, payload: result, }; } export function fetchProducts(kind = "normal") { return dispatch => fetch(`${process.env.REACT_APP_DEV_API_URL}/products/vendor/${JSON.parse(localStorage["bezop-login:vendor"]).profile.domainName}/${kind}/?key=${process.env.REACT_APP_API_KEY}`, { method: "GET", headers: { authorization: `Bearer ${JSON.parse(localStorage["bezop-login:vendor"]).accessToken}`, }, }) .then(response => response.json()) .then((json) => { if (Validator.propertyExist(json, "error")) { throw json.error; } return dispatch(loadProducts(json)); }) .catch(error => ( dispatch(loadProducts({ success: false, message: error.message, })) )); } export function loadApprovedProducts(result) { return { type: FETCH_APPROVED_PRODUCTS, payload: result, }; } export function fetchApprovedProducts() { return dispatch => fetch(`${process.env.REACT_APP_DEV_API_URL}/approvals/vendor/${JSON.parse(localStorage["bezop-login:vendor"]).profile.id}/?key=${process.env.REACT_APP_API_KEY}`, { method: "GET", headers: { authorization: `Bearer ${JSON.parse(localStorage["bezop-login:vendor"]).accessToken}`, }, }) .then(response => response.json()) .then((json) => { if (Validator.propertyExist(json, "error")) { throw json.error; } return dispatch(loadApprovedProducts(json)); }) .catch(error => ( dispatch(loadApprovedProducts({ success: false, message: error.message, })) )); } export function loadProductDetail(results) { return { type: POST_PRODUCT_DETAILS, payload: results, }; } export function postProductDetails(productDetails) { return dispatch => fetch(`${process.env.REACT_APP_DEV_API_URL}/products/?key=${process.env.REACT_APP_API_KEY}`, { method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json", authorization: `Bearer ${JSON.parse(localStorage["bezop-login:vendor"]).accessToken}`, }, body: JSON.stringify(productDetails), }) .then(response => response.json()) .then((json) => { if (Validator.propertyExist(json, "error")) { throw json.error; } return dispatch(loadProductDetail(json)); }) .catch(error => ( dispatch(loadProductDetail({ success: false, message: error.message, })) )); } export function loadUpdatedProductDetails(results) { return { type: UPDATE_PRODUCT_DETAILS, payload: results, }; } export function putProductDetails(productDetails, productID) { return dispatch => fetch(`${process.env.REACT_APP_DEV_API_URL}/products/${productID}/?key=${process.env.REACT_APP_API_KEY}`, { method: "PUT", headers: { Accept: "application/json", "Content-Type": "application/json", authorization: `Bearer ${JSON.parse(localStorage["bezop-login:vendor"]).accessToken}`, }, body: JSON.stringify(productDetails), }) .then(response => response.json()) .then((json) => { if (Validator.propertyExist(json, "error")) { throw json.error; } return dispatch(loadUpdatedProductDetails(json)); }) .catch(error => ( dispatch(loadUpdatedProductDetails({ success: false, message: error.message, })) )); } export function loadApprovedProduct(results) { return { type: APPROVED_PRODUCT, payload: results, }; } export function approveProduct(productDetails) { return dispatch => fetch(`${process.env.REACT_APP_DEV_API_URL}/approvals/?key=${process.env.REACT_APP_API_KEY}`, { method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json", authorization: `Bearer ${JSON.parse(localStorage["bezop-login:vendor"]).accessToken}`, }, body: JSON.stringify(productDetails), }) .then(response => response.json()) .then((json) => { if (Validator.propertyExist(json, "error")) { throw json.error; } return dispatch(loadApprovedProduct(json)); }) .catch(error => ( dispatch(loadApprovedProduct({ success: false, message: error.message, })) )); } export function loadDeleteProduct(results) { return { type: DELETE_PRODUCT, payload: results, }; } export function deleteProduct(productID) { return dispatch => fetch(`${process.env.REACT_APP_DEV_API_URL}/products/vendor/${productID}/?key=${process.env.REACT_APP_API_KEY}`, { method: "DELETE", headers: { Accept: "application/json", "Content-Type": "application/json", authorization: `Bearer ${JSON.parse(localStorage["bezop-login:vendor"]).accessToken}`, }, }) .then(response => response.json()) .then((json) => { if (Validator.propertyExist(json, "error")) { throw json.error; } return dispatch(loadDeleteProduct(json)); }) .catch(error => ( dispatch(loadDeleteProduct({ success: false, message: error.message, })) )); }
var _ = require('lodash'); var EventProxy = require('eventproxy'); var saidan_pictures = function(server) { return { find_saidans: function(comments_ids, callback) { var query = `select product_comments_id, location FROM interaction_saidan_pictures where product_comments_id in (?) and flag =0`; server.plugins['mysql'].pool.getConnection(function(err, connection) { connection.query(query, [comments_ids], function(err, results) { if (err) { throw err; } connection.release(); callback(results); }); }); }, }; }; module.exports = saidan_pictures;
let bullet = { x: 100, // Starting coordinate for the x-axis y: 326.5, // Starting coordinate for the y-axis diamX: 15, // Diameter of the width diamY: 8, // Diameter of the height speed: 3.5, // The rate of speed the bullet will travel shootButton: false, // Shoot key pressed value // Function will display the bullet on the screen display: function() { strokeWeight(3); // Outline's the thickness of the bullet fill("yellow"); // The color the shape will be ellipse(this.x, this.y, this.diamX, this.diamY); // Ellipse's x, y, width, and height based on the values stored in the bullet object's attributes this.moveBullet(); // Uses the method stored in bullet object to cause the bullet to move }, // This will cause the bullet to move once it's been shot moveBullet: function() { this.x += this.speed; this.resetBullet(); // Will reset the position of the bullet once it goes out of bounds }, // Resets the position of the bullet if out of bounds resetBullet: function() { // if (this.x > width) { this.x = megaman.megamanX; this.speed = 0; } } }
import React from 'react' import { NavLink } from 'react-router-dom' import { HeadWrapper, Nav, StepList, Step } from './style' function Header() { return ( <HeadWrapper> <Nav> <StepList> <Step> <NavLink className="nav-item" activeClassName="active" to="/cart"> Sacola </NavLink> </Step> <Step> <NavLink className="nav-item" activeClassName="active" to="/payment"> Pagamento </NavLink> </Step> <Step> <NavLink className="nav-item" activeClassName="active" to="/order-placed"> Confirmação </NavLink> </Step> </StepList> </Nav> </HeadWrapper> ) } export default Header
(function () { 'use strict'; /** * @ngdoc object * @name 0630kinderfest18.controller:C0630kinderfest18Ctrl * * @description * */ angular .module('0630kinderfest18') .controller('C0630kinderfest18Ctrl', C0630kinderfest18Ctrl); function C0630kinderfest18Ctrl() { var vm = this; vm.ctrlName = 'C0630kinderfest18Ctrl'; } }());
import React from 'react'; import { Card } from 'semantic-ui-react' const EventSingle = ({item}) => ( <a href={item.url} target="_blank"> <Card.Group> <Card color= 'blue' image={item.logo ? item.logo.url : null} header={item.name.text} meta={item.start.local} //description={item.description.text} /> </Card.Group> </a> ); export default EventSingle;
'use strict'; exports.index = function (data) { let $this = this; // let insertData = {name:"自建博客", url:"www.masoner.cn"}; console.log($this.db); console.log("========================="); // $this.db.collection("site").insertOne(insertData, function (err, res) { // if (err){ // throw err; // } // console.log("文档插入成功"); // $this.db.close(); // }); this.render('blog/index.html'); };
import { API_SERVICE, PLAYER_SERVICE, TOURNAMENT_SERVICE } from '../../common/api' import { addToken } from '../../common/jwt.storage' import WEBSOCKET_SERVICE from '../../common/websocketApi' const LOADING_MESSAGE = 'loading....' export const state = getDefaultState() export const mutations = { /** * Set the tournament * @param state * @param tournament Tournament that should be set. */ addTournament: (state, tournament) => { state.tournament = tournament state.activeTournament = tournament.active }, /** * Sets the tournament active state. * @param state * @param active Active value that should be set. */ setTournamentActive: (state, active) => { state.activeTournament = active }, /** * Reset the state * @param state */ resetTournamentState: (state) => { // https://github.com/vuejs/vuex/issues/1118 Object.assign(state, getDefaultState()) } } export const actions = { resetTournament: ({ commit }) => { commit('resetTournamentState') }, /** * Send a tournament to the server. * @param commit * @param tournament Tournament that should be sent * @returns {Promise<AxiosResponse<T>>} */ sendTournament: ({ commit }, tournament) => { return API_SERVICE.post('new-tournament', tournament).then(res => { // Adds the tournament ID received from the server to the payload. tournament['user_id'] = res.data.tournament_id addToken(res.data.jwt) // Adds the payload (tournament) to the state in store. commit('addTournament', tournament) }).then(res => { API_SERVICE.setHeader() }) }, /** * Send tournament pause request. * @returns {Promise<AxiosResponse<T>>} */ sendTournamentPauseRequest: () => { return TOURNAMENT_SERVICE.patch('pause').catch(res => { throw res.response }) }, /** * Send tournament unpause request. * @returns {Promise<AxiosResponse<T>>} */ sendTournamentUnpauseRequest: () => { return TOURNAMENT_SERVICE.patch('unpause').catch(res => { throw res.response }) }, /** * Fetch a tournament from the server. * @param commit * @returns {Promise<AxiosResponse<T>>} */ fetchTournament: ({ commit }) => { return TOURNAMENT_SERVICE.get().then(res => { commit('addTournament', res.data) }) }, /** * Signs-in with adminID. * @param NULL * @param uuid the AdminID. * @returns {Promise<AxiosResponse<T>>} */ signInUUID: ({ NULL }, uuid) => { return API_SERVICE.get(`sign-in/${uuid}`).then(res => { addToken(res.data.jwt) }).then(res => { API_SERVICE.setHeader() }) }, /** * Fetch the tournament a player is enrolled in. * @param commit * @returns {Promise<AxiosResponse<T>>} */ fetchPlayersTournament: ({ commit }) => { return PLAYER_SERVICE.get('tournament').then(res => { commit('addTournament', res.data) }) }, /** * Send request to start the tournament * @returns {Promise<AxiosResponse<T>>} */ sendStartRequest: () => { return TOURNAMENT_SERVICE.patch('start').catch(err => { throw err }) }, /** * Send request to end the tournament * @returns {Promise<AxiosResponse<T>>} */ sendEndRequest: () => { return TOURNAMENT_SERVICE.patch('end').catch(err => { throw err }) }, /** * Subscribes to the tournament active endpoint. Receives updates when tournament starts or ends * @param commit * @param userRole */ subscribeToTournamentActive: ({ commit }, { userRole }) => { let activeCallback = function (res) { let active = JSON.parse(res.body).active commit('setTournamentActive', active) } let path = userRole === 'player' ? 'player/tournament-active' : 'tournament/active' let sub = { path: path, callback: activeCallback } WEBSOCKET_SERVICE.connect(sub) } } export const getters = { /** * Returns the tournament's active state * @param state * @returns {boolean} Active state. */ isTournamentActive: (state) => { return state.activeTournament } } /** * Returns the default state * @returns {{playingPlayers: [], players: [], paired: boolean, player: {name: string, points: string}, points: number}} */ function getDefaultState() { return { tournament: { user_id: LOADING_MESSAGE, tournament_name: LOADING_MESSAGE, start: LOADING_MESSAGE, end: LOADING_MESSAGE }, activeTournament: false } }
import React from 'react'; import './Comment.css' ; import {Row , Col} from 'react-bootstrap'; import Sidebar_Student2 from "./Student2/Sidebar_Student2"; import BlockComment_Student2 from "./Student2/BlockComment_Student2"; function Comment2() { return ( <Row> <Sidebar_Student2 /> <BlockComment_Student2 /> </Row> ); } export default Comment2;
/** AIP CONFIGURATIONS */ // const BASE_URL = "https://api.eftapme.com/tccustapi/"; // EURONET APIs export const USER_LOGIN = `customerLogin`; export const USER_REGISTRATION = `CustomerRegistration`; export const VERIFY_OTP = `VerifyOtp`; export const FORGOT_USER_PIN = `forgotPassword`; export const FETCH_CUSTOMER_DETAILS = `fetchCustomerDetails`; export const FETCH_CUSTOMER_PROFILE = `fetchCustomerProfile`; export const CARD_STATUS_MANAGEMENT = `cardStatusManagement`; export const PIN_MANAGEMENT = `pinManagement`; export const CARD_TRANSACTION = `cardTransaction`; export const KEY_EXCHANGE_API = `Customer/keyExchange`; export const CUSTOMER_REQUEST_API = `Customer/request`; //DREAMFOLKS APIs const DREAMFOLKS_BASE_URL = 'https://dev.v2.dreamfolks.in/api/'; export const GET_AIRPORT_LIST = DREAMFOLKS_BASE_URL + `getairports`; export const GET_OUTLET_LIST = DREAMFOLKS_BASE_URL + `getoutlet`; export const GET_VOUCHER = DREAMFOLKS_BASE_URL + `getvoucher`;
describe('VglLineBasicMaterial:', function suite() { const { VglLineBasicMaterial, VglNamespace } = VueGL; it('without properties', function test(done) { const vm = new Vue({ template: '<vgl-namespace><vgl-line-basic-material ref="m" /></vgl-namespace>', components: { VglLineBasicMaterial, VglNamespace }, }).$mount(); vm.$nextTick(() => { try { const expected = new THREE.LineBasicMaterial(); const { inst } = vm.$refs.m; expect(inst).to.deep.equal(Object.assign(expected, { uuid: inst.uuid })); done(); } catch (e) { done(e); } }); }); it('with properties', function test(done) { const vm = new Vue({ template: '<vgl-namespace><vgl-line-basic-material color="#8aeda3" lights linewidth="3.5" linecap="butt" linejoin="miter" ref="m" /></vgl-namespace>', components: { VglLineBasicMaterial, VglNamespace }, }).$mount(); vm.$nextTick(() => { try { const expected = new THREE.LineBasicMaterial({ color: 0x8aeda3, lights: true, linewidth: 3.5, linecap: 'butt', linejoin: 'miter', }); const { inst } = vm.$refs.m; expect(inst).to.deep.equal(Object.assign(expected, { uuid: inst.uuid })); done(); } catch (e) { done(e); } }); }); it('after properties are changed', function test(done) { const vm = new Vue({ template: '<vgl-namespace><vgl-line-basic-material :color="color" :lights="lights" :linewidth="linewidth" :linecap="linecap" :linejoin="linejoin" ref="m" /></vgl-namespace>', components: { VglLineBasicMaterial, VglNamespace }, data: { color: '#dafbc4', lights: false, linewidth: 5, linecap: 'butt', linejoin: 'miter', }, }).$mount(); vm.$nextTick(() => { vm.color = '#abbcaf'; vm.lights = true; vm.linewidth = 4.88; vm.linecap = 'square'; vm.linejoin = 'bevel'; vm.$nextTick(() => { try { const expected = new THREE.LineBasicMaterial({ color: 0xabbcaf, lights: true, linewidth: 4.88, linecap: 'square', linejoin: 'bevel', }); const { inst } = vm.$refs.m; expect(inst).to.deep.equal(Object.assign(expected, { uuid: inst.uuid })); done(); } catch (e) { done(e); } }); }); }); });
export const reset = { '*, *:before, *:after': { boxSizing: 'inherit', }, 'html, body': { padding: 0, margin: 0, }, html: { textRendering: 'optimizeLegibility', overflowX: 'hidden', overflowY: 'auto !important', boxSizing: 'boder-box', }, 'pre, code': { fontFamily: 'SFMono-Regular, Menlo, Monaco, Consolas,"Liberation Mono", "Courier New", monospace', }, };
'use strict'; describe('Filter: jobsFilter', function () { // load the filter's module beforeEach(module('laoshiListApp')); // initialize a new instance of the filter before each test var jobsFilter; beforeEach(inject(function ($filter) { jobsFilter = $filter('jobsFilter'); })); it('should return the input prefixed with "jobsFilter filter:"', function () { var text = 'angularjs'; expect(jobsFilter(text)).toBe('jobsFilter filter: ' + text); }); });
const router = require("express").Router(); const bcrypt = require("bcryptjs"); const jwt = require("jsonwebtoken"); const { User } = require("../models/index"); router.post("/signup", async (req, res) => { await User.create(req.body) .catch(err => res.status(400).send(err)) .then(user => res.status(201).send(user)); }); router.post("/login", async (req, res) => { const { email, password } = req.body; let token; const user = await User.findOne({ attributes: ["id", "username", "email", "password"], where: { email } }); if(user && bcrypt.compareSync(password, user.password)) { token = jwt.sign({auth: user}, "private_key", {expiresIn: "1h"}); } token ? res.status(200).json({ token }) : res.status(404).json({ msg: "Credentials don't match!" }); }); module.exports = router;
import * as React from 'react'; import { DeviceEventEmitter } from 'react-native'; export const isReadyRef = React.createRef(); export const navigationRef = React.createRef(); import { CommonActions, StackActions } from '@react-navigation/native'; export function navigate(name, params) { if (isReadyRef.current && navigationRef.current) { // Perform navigation if the app has mounted if (name === 'login') { DeviceEventEmitter.emit('EMIT_LOGOUT') const resetAction = CommonActions.reset({ index: 1, routes: [{ name: "main" },] }); navigationRef.current.dispatch(resetAction); } else { navigationRef.current.navigate(name, params); } } else { // You can decide what to do if the app hasn't mounted // You can ignore this, or add these actions to a queue you can call later } }
const mongoose = require('mongoose'); const { Note, Asset } = require('../../mongo'); // When given an asset ID, create a new note and associate it with that asset postNoteByAssetId = (req, res) => { let { _id } = req.params; let noteBody = req.body.note; Asset.findOne({_id, deleted: {$ne: true }}, (error, asset) => { console.log("asset:", asset); if (error) { res.json({error}) } else if (asset) { let note = new Note(); note.set({ asset: _id, note: noteBody }); note.save((error, note) => { console.log("asset:", asset) if (error) { res.json({error}); } else { console.log("asset.notes:", asset.notes) asset.notes.push(note._id); asset.save((error) => { if (error) { res.json({ error }); } else { res.json({ message: `Note saved to asset ${_id}`, note }) } }) } }) } else { res.json({ error: `Could not find asset ${_id}` }) } }) } module.exports = postNoteByAssetId;
import React from 'react'; import { KIND } from 'baseui/button'; import MenuIcon from 'baseui/icon/menu'; import { StatefulPopover } from 'baseui/popover'; import { StatefulMenu } from 'baseui/menu'; import { arrayOf, shape, string } from 'prop-types'; import { Button } from '../button'; const BaseButton = { style: ({ $theme }) => ({ display: 'block', paddingTop: 0, paddingRight: 0, paddingBottom: 0, height: '36px', color: $theme.colors.white, ':hover': { backgroundColor: 'transparent' }, ':focus': { backgroundColor: 'transparent' }, ':active': { backgroundColor: 'transparent' } }) }; export const PopoverMenu = ({ items, placement, ...rest }) => { return ( <StatefulPopover placement={placement} content={({ close }) => ( <StatefulMenu items={items} onItemSelect={({ item }) => { if (item.callback) { item.callback(rest); } close(); }} /> )} > <Button kind={KIND.tertiary} overrides={{ BaseButton }}> <MenuIcon size={36} /> </Button> </StatefulPopover> ); }; PopoverMenu.propTypes = { items: arrayOf(shape({})).isRequired, placement: string }; PopoverMenu.defaultProps = { placement: undefined };
/*========================================================== Author : Chandana Date Created: 23 Sep 2016 Description : To handle the home page service Change Log s.no date author description ===========================================================*/ dashboard.service('userHomeService', ['$http', '$q', 'Flash', 'apiService', function ($http, $q, Flash, apiService) { var userHomeService = {}; var getRaisedTickets = function (parameter) { var deferred = $q.defer(); apiService.get("hduserhome/getraisedtickets/", {parameter : parameter}).then(function (response) { if (response) deferred.resolve(response); else deferred.reject("Something went wrong while processing your request. Please Contact Administrator."); }, function (response) { deferred.reject(response); }); return deferred.promise; }; userHomeService.getRaisedTickets = getRaisedTickets; return userHomeService; }]);
/* 在二维平面上计算出两个由直线构成的矩形重叠后形成的总面积。 每个矩形由其左下顶点和右上顶点坐标表示,如图所示。 -------------- | | | -----|-------- | | | | -------------- | | | -------------- 示例: 输入: -3, 0, 3, 4, 0, -1, 9, 2 输出: 45 说明: 假设矩形面积不会超出 int 的范围。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/rectangle-area */ /** * @param {number} A * @param {number} B * @param {number} C * @param {number} D * @param {number} E * @param {number} F * @param {number} G * @param {number} H * @return {number} */ var computeArea = function(A, B, C, D, E, F, G, H) { let area = (a, b, c, d) => (c - a) * (d - b); let all = area(A, B, C, D) + area(E, F, G, H); // 没重叠的话返回两个矩形的面积和 if(C <= E || D <= F || A >= G || B >= H) { return all } // 重叠的话减去重叠部分的面积就行了 return all - area(Math.max(A, E), Math.max(B, F), Math.min(C, G), Math.min(D, H)); }; // const A = -3, B = 0, C = 3, D = 4, E = 0, F = -1, G = 9, H = 2; const A = -3, B = 0, C = 3, D = 4, E = -2, F = 1, G = 2, H = 2; console.log(computeArea(A, B, C, D, E, F, G, H))
import { useState, useEffect } from 'react'; import { getGifs } from '../helpers/getGifs'; //Snippet => rafc y luego borrar el import porque no se necesita react para JSX y quitar el return // export const useFetchImages = () => { //Recibir la categoría export const useFetchImages = (category) => { //Se usa state porque el hook no sabe para que va a trabajar y por convención se usa state en lugar de otro nombre de variable const [state, setState] = useState({ data: [], loading: true }); //Agregar el setTimeout para mostrar como cambia el mensaje cargado // setTimeout( () => { // setState({ // data: [1,2,3,4,5,6], // loading: false // }); // }, 3000); // Comentar el setTimeout //Agergar el useEffect para controlar que solo se ejecute cuando queremos, en esta ocasión cuando cambia la categoría //Los useEffect no pueden ser async, siempre esperan un valor síncrono useEffect(() => { getGifs(category).then(resolve => { //Agregarmos el setTimeout solo para ver como se ejecuta //Comentar al final y solo hacer el useState // setTimeout( () => { // console.log(resolve); // setState({ // data: resolve, // loading: false // }); // }, 3000); setState({ data: resolve, loading: false }); }); }, [category]); return state; }
function addTodo(text) { return {type: ADD_TODO, text}; } function deleteTodo(id) { return {type: DELETE_TODO, id}; } function editTodo(id, text) { return {type: EDIT_TODO, id, text}; } function completeTodo(id) { return {type: COMPLETE_TODO, id}; } function completeAll() { return {type: COMPLETE_ALL}; } function clearCompleted() { return {type: CLEAR_COMPLETED}; }
var express = require('express'); var router = express.Router(); /* GET users listing. */ router.post('/', function(req, res, next) { if(req.body.selectCookie && req.body.cookieName){ if(req.body.selectCookie=="sessionCookie"){ res.cookie("minju",req.body.cookieName); res.send("<a href='/'>세션쿠키생성완료(돌아가기)</a>"); }else{ res.cookie("minju",req.body.cookieName,{maxAge:5000}); res.send("<a href='/'>포미숀꾸키생성완료(돌아가기)</a>"); } }else{ res.send("재대로 안넣나?"); } }); module.exports = router;
module.exports = { productionSourceMap: false, runtimeCompiler: true, publicPath: './', devServer:{ port: 1234, proxy:{ "/":{ ws:false, target:'http://localhost:6666/', } } }, configureWebpack: config => { //组件 const plugins = [ // new MyAwesomeWebpackPlugin() ]; if(process.env.NODE_ENV === 'production'){ //为生产环境修改配置 }else{ //为开发环境修改配置 } }, chainWebpack: config => {//链式操作 config.module //修改Loader选项 .rule('vue') .use('vue-loader') .loader('vue-loader') .tap(options => { //修改选项 return options; }); config.module //添加一个新的 .rule('graphql') .test('/\.graphql$/') .use('graphq1-tag/loader') .loader('graphql-tag/loader') .end(); //替换规则里的loader const svgRule = config.module.rule('svg') //清除已有的所有loader svgRule.uses.clear(); //添加要替换的loader svgRule .use('vue-svg-loader') .loader('vue-svg-loader'); } }
define(['knockout', 'validation', 'webApiClient', 'messageBox'], function (ko, validation, webApiClient, messageBox) { "use strict"; var userViewModel = ko.validatedObservable({ EntityName: "My Account", Url: "/users/myAccount", CanDeleteEntity: false, Name: ko.observable().extend({ maxLength: 40, required: true }), Email: ko.observable().extend({ maxLength: 100, required: false }), Password: ko.observable().extend({ maxLength: 128, required: true }), PasswordConfirm: ko.observable(), SetModel: function (objFromServer) { var self = this; if (!objFromServer) return; self.Name(objFromServer.Name); self.Password(objFromServer.Password); self.PasswordConfirm(objFromServer.Password); self.Email(objFromServer.Email); }, GetEntityModel: function () { var self = this; return { Name: self.Name(), Password: self.Password(), Email: self.Email() }; } }); userViewModel().PasswordConfirm.extend({ maxLength: 128, required: true, passwordConfirm: userViewModel().Password }); return userViewModel; });
var req = new XMLHttpRequest(); // For 'Exercise 2', you will modify this line: req.open("get", "/path1"); req.addEventListener("loadstart", function(){ console.log("loadstart"); }); req.addEventListener("load", function(){ // Your code for Exercise 1 goes here. }); req.send(); // cvcxv
// model-mods.js // Defining several standard-issue model modiciations to be run in the local event.js for a map var inherits = require("inherits"); var extend = require("extend"); function Modification(fn, opts) { extend(this, opts); this.fn = fn; } extend(Modification.prototype, { name: null, prefix: null, suffix: null, regex: null, all: false, fn: null, }); function testName(narray, name) { if (!$.isArray(narray)) narray = [narray]; for (var i = 0; i < narray.length; i++) { if (name == narray[i]) return true; } return false; } function testPrefix(narray, name){ if (!$.isArray(narray)) narray = [narray]; for (var i = 0; i < narray.length; i++) { if (name.startsWith(narray[i])) return true; } return false; } function testSuffix(narray, name){ if (!$.isArray(narray)) narray = [narray]; for (var i = 0; i < narray.length; i++) { if (name.endsWith(narray[i])) return true; } return false; } function testRegex(regex, name) { return regex.test(name); } module.exports = { modify: function (){ var mods = []; for (var p in this) { if (!(this[p] instanceof Modification)) continue; if (!this[p].name && !this[p].prefix && !this[p].suffix) continue; mods.push(this[p]); } var ch = currentMap.mapmodel.children; for (var i = 0; i < ch.length; i++) { for (var m = 0; m < mods.length; m++) { if (mods[m].name && testName(mods[m].name, ch[i].name)) { mods[m].fn(ch[i]); } else if (mods[m].prefix && testPrefix(mods[m].prefix, ch[i].name)) { mods[m].fn(ch[i]); } else if (mods[m].suffix && testSuffix(mods[m].suffix, ch[i].name)) { mods[m].fn(ch[i]); } else if (mods[m].regex && testRegex(mods[m].regex, ch[i].name)) { mods[m].fn(ch[i]); } else if (mods[m].all) { mods[m].fn(ch[i]); } } } for (var m = 0; m < mods.length; m++) { mods[m].name = null; mods[m].prefix = null; mods[m].suffix = null; mods[m].regex = null; mods[m].all = false; } }, /////////////////////////////////////////////////////////////////////////////////////// // Actual modification functions below hide: new Modification(function(obj){ obj.visible = false; }), trees: new Modification(function(tree) { for (var j = 0; j < tree.children.length; j++) { var m = tree.children[j].material; if (m.side != THREE.DoubleSide) { //Need to gate because the color set at the end is destructive m.side = THREE.DoubleSide; m.alphaTest = 0.2; m.transparent = true; m.emissive.set(m.color); m.color.set(0); m.needsUpdate = true; } tree.children[j].renderDepth = (10+j) * -1; } }), doubleSided : new Modification(function(obj){ for (var j = 0; j < obj.children.length; j++) { obj.children[j].material.side = THREE.DoubleSide; } }), renderDepthFix: new Modification(function(obj){ for (var j = 0; j < obj.children.length; j++) { obj.children[j].renderDepth = -50; } }), godrays: new Modification(function(rays){ for (var i = 0; i < rays.children.length; i++) { rays.children[i].renderDepth = -100; rays.children[i].material.blending = THREE.AdditiveBlending; rays.children[i].material.depthWrite = false; } }), refreshMaterials: new Modification(function(obj){ for (var j = 0; j < obj.children.length; j++) { var m = obj.children[j].material; m.needsUpdate = true; } }), };
'use strict'; const BroccoliMergeTrees = require('broccoli-merge-trees'); const fastbootTransform = require('fastboot-transform'); const Funnel = require('broccoli-funnel'); const path = require('path'); const resolve = require('resolve'); const writeFile = require('broccoli-file-creator'); const AngularScssFilter = require('./lib/angular-scss-filter'); /** * Component dependencies, extracted from ember-bootstrap * https://github.com/kaliber5/ember-bootstrap/blob/master/index.js */ const componentDependencies = { 'twyr-autocomplete': { 'styles': [ 'components/autocomplete/autocomplete.scss', 'components/autocomplete/autocomplete-theme.scss' ] }, 'twyr-backdrop': { 'styles': [ 'components/backdrop/backdrop.scss', 'components/backdrop/backdrop-theme.scss' ] }, 'twyr-button': { 'styles': [ 'components/button/button.scss', 'components/button/button-theme.scss' ] }, 'twyr-card': { 'styles': [ 'components/card/card.scss', 'components/card/card-theme.scss' ] }, 'twyr-checkbox': { 'styles': [ 'components/checkbox/checkbox.scss', 'components/checkbox/checkbox-theme.scss' ] }, 'twyr-chips': { 'styles': [ 'components/chips/chips.scss', 'components/chips/chips-theme.scss' ] }, 'twyr-content': { 'styles': [ 'components/content/content.scss', 'components/content/content-theme.scss' ] }, 'twyr-dialog': { 'styles': [ 'components/dialog/dialog.scss', 'components/dialog/dialog-theme.scss' ] }, 'twyr-divider': { 'styles': [ 'components/divider/divider.scss', 'components/divider/divider-theme.scss' ] }, 'twyr-grid-list': { 'styles': [ 'components/gridList/grid-list.scss' ] }, 'twyr-icon': { 'styles': [ 'components/icon/icon.scss', 'components/icon/icon-theme.scss' ] }, 'twyr-input': { 'styles': [ 'components/input/input.scss', 'components/input/input-theme.scss' ] }, 'twyr-list': { 'styles': [ 'components/list/list.scss', 'components/list/list-theme.scss' ] }, 'twyr-menu': { 'styles': [ 'components/menu/menu.scss', 'components/menu/menu-theme.scss' ] }, 'twyr-progress-circular': { 'styles': [ 'components/progressCircular/progress-circular.scss', 'components/progressCircular/progress-circular-theme.scss' ] }, 'twyr-progress-linear': { 'styles': [ 'components/progressLinear/progress-linear.scss', 'components/progressLinear/progress-linear-theme.scss' ] }, 'twyr-radio-base': { 'styles': [ 'components/radioButton/radio-button.scss', 'components/radioButton/radio-button-theme.scss' ] }, 'twyr-select': { 'styles': [ 'components/select/select.scss', 'components/select/select-theme.scss' ] }, 'twyr-sidenav': { 'styles': [ 'components/sidenav/sidenav.scss', 'components/sidenav/sidenav-theme.scss' ] }, 'twyr-slider': { 'styles': [ 'components/slider/slider.scss', 'components/slider/slider-theme.scss' ] }, 'twyr-speed-dial': { 'styles': [ 'components/fabSpeedDial/fabSpeedDial.scss' ] }, 'twyr-subheader': { 'styles': [ 'components/subheader/subheader.scss', 'components/subheader/subheader-theme.scss' ] }, 'twyr-switch': { 'styles': [ 'components/switch/switch.scss', 'components/switch/switch-theme.scss' ] }, 'twyr-tabs': { 'styles': [ 'components/tabs/tabs.scss', 'components/tabs/tabs-theme.scss' ] }, 'twyr-toast': { 'styles': [ 'components/toast/toast.scss', 'components/toast/toast-theme.scss' ] }, 'twyr-toolbar': { 'styles': [ 'components/toolbar/toolbar.scss', 'components/toolbar/toolbar-theme.scss' ] }, 'twyr-tooltip': { 'styles': [ 'components/tooltip/tooltip.scss', 'components/tooltip/tooltip-theme.scss' ] } }; module.exports = { 'name': require('./package').name, 'options': { 'polyfills': { 'classlist-polyfill': { 'files': ['src/index.js'], 'caniuse': 'classlist' }, 'element-closest': { 'files': ['browser.js'], 'caniuse': 'element-closest' }, 'matchmedia-polyfill': { 'files': ['matchMedia.js'], 'caniuse': 'matchmedia' }, 'polyfill-nodelist-foreach': { 'files': ['index.js'], // compatibility from https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach 'browsers': ['ie > 0', 'chrome < 52', 'ff < 50', 'opera < 38', 'safari < 10', 'edge < 16', 'android < 51', 'and_chr < 51', 'and_ff < 50', 'ios_saf < 10', 'Samsung < 5'] } } }, included() { this._super.included.apply(this, arguments); let app; // If the addon has the _findHost() method (in ember-cli >= 2.7.0), we'll just // use that. if(typeof this._findHost === 'function') { app = this._findHost(); } else { // Otherwise, we'll use this implementation borrowed from the _findHost() // method in ember-cli. let current = this; do { app = current.app || app; } while (current.parent.parent && (current = current.parent)); } this.twyrDslOptions = Object.assign({}, app.options['twyr-dsl']); app.import('vendor/twyr-dsl/register-version.js'); app.import('vendor/hammerjs/hammer.js'); app.import('vendor/propagating-hammerjs/propagating.js'); }, config() { return { 'twyr-dsl': { 'insertFontLinks': true } }; }, contentFor(type, config) { if(type === 'head') { if(!config['twyr-dsl'].insertFontLinks) return; return ` <link href="https://fonts.googleapis.com/css?family=Noto+Sans:400,400i,700,700i|Noto+Serif:400,400i,700,700i&subset=devanagari" rel="stylesheet" type="text/css" media="all"> <link href="https://fonts.googleapis.com/css?family=Keania+One" rel="stylesheet" type="text/css" media="all"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" type="text/css" media="all"> `; } if(type === 'body-footer') { if(config.environment !== 'test' && !config._twyrDslContentForInvoked) config._twyrDslContentForInvoked = true; let response = ` <div id="twyr-wormhole"></div> `; return response; } }, treeForVendor(tree) { const version = require('./package.json').version; let versionTree = writeFile( 'twyr-dsl/register-version.js', `Ember.libraries.register('Twyr DSL', '${version}');` ); let hammerJs = fastbootTransform(new Funnel(this._pathBase('hammerjs'), { 'files': ['hammer.js'], 'destDir': 'hammerjs', 'annotation': 'HammerJSFunnel' })); let propagatingHammerJs = fastbootTransform(new Funnel(this._pathBase('propagating-hammerjs'), { 'files': ['propagating.js'], 'destDir': 'propagating-hammerjs', 'annotation': 'PropagatingHammerJSFunnel' })); let trees = [hammerJs, propagatingHammerJs, versionTree]; if(tree) trees.push(tree); return new BroccoliMergeTrees(trees); }, treeForStyles(tree) { let coreScssFiles = [ 'core/style/mixins.scss', 'core/style/variables.scss', 'core/style/structure.scss', 'core/style/typography.scss', 'core/style/layout.scss', 'core/services/layout/layout.scss', 'components/whiteframe/whiteframe.scss', 'components/panel/panel.scss', 'components/panel/panel-theme.scss' ]; let filteredScssFiles = this._addStyles(coreScssFiles) || coreScssFiles; let angularScssFiles = new Funnel(this._pathBase('angular-material-styles'), { 'files': filteredScssFiles, 'srcDir': '/src', 'destDir': 'angular-material', 'annotation': 'AngularScssFunnel' }); angularScssFiles = new AngularScssFilter(angularScssFiles); let importer = writeFile( 'twyr-components.scss', filteredScssFiles.map((path) => `@import './angular-material/${path}';`).join('\n') ); const trees = []; if(angularScssFiles) trees.push(angularScssFiles); if(importer) trees.push(importer); if(tree) trees.push(tree); let mergedTrees = new BroccoliMergeTrees(trees, { 'overwrite': true }); return this._super.treeForStyles(mergedTrees); }, treeForApp(tree) { tree = this._filterComponents(tree); return this._super.treeForApp.call(this, tree); }, treeForAddon(tree) { tree = this._filterComponents(tree); return this._super.treeForAddon.call(this, tree); }, treeForAddonTemplates(tree) { tree = this._filterComponents(tree); return this._super.treeForAddonTemplates.call(this, tree); }, _addStyles(core = []) { let styles = core.slice(); Object.keys(componentDependencies).forEach((key) => { this._addComponentStyle(styles, componentDependencies[key]); }); return styles; }, _addComponentStyle(arr, component) { if(component && component.styles) { component.styles.forEach((scss) => { if(!arr.includes(scss)) arr.push(scss); }); } }, _filterComponents(tree) { return tree; }, /* Rely on the `resolve` package to mimic node's resolve algorithm. It finds the angular-material-source module in a manner that works for npm 2.x, 3.x, and yarn in both the addon itself and projects that depend on this addon. This is an edge case b/c angular-material-source does not have a main module we can require.resolve through node itself and similarily ember-cli does not have such a hack for the same reason. tl;dr - We want the non built scss files, and b/c this dep is only provided via git, we use this hack. Please change it if you read this and know a better way. */ _pathBase(packageName) { return path.dirname(resolve.sync(`${packageName}/package.json`, { 'basedir': __dirname })); } };
let colors = [ {foreground: 'rgb(254,239,143)', background: 'rgb(22,102,47)'}, {foreground: 'rgb(173, 173, 173)', background: 'rgb(32, 32, 32)'}, {foreground: 'rgb(255, 255, 255)', background: 'rgb(255, 69, 0)'}, {foreground: 'rgb(32, 32, 32)', background: 'rgb(173, 173, 173)'} ] let index = 0 export default function (win, dialog) { index = 0 let menuArr = [ { label: 'Main', submenu: [ { label: 'About', role: 'about' }, {type: 'separator'}, {label: 'Quit', role: 'quit'} ] }, { label: 'Edit', submenu: [ { label: 'Cut', accelerator: 'CmdOrCtrl+X', selector: 'cut:' }, { label: 'Copy', accelerator: 'CmdOrCtrl+C', selector: 'copy:' }, { label: 'Paste', accelerator: 'CmdOrCtrl+V', selector: 'paste:' } ] }, { label: 'Settings', submenu: [ { label: 'Change Color', click: () => { if (win && !win.isDestroyed()) { win.webContents.send('toggleColor', colors[++index % colors.length]) } } }, { label: 'Restore', click: () => { if (win && !win.isDestroyed()) { index = 0 win.webContents.send('toggleColor', colors[0]) } } } ] } ] return menuArr }
(function() { 'use strict'; angular .module('friends') .controller('LoginController', LoginController); LoginController.$inject = ['Auth']; /* @ngInject */ function LoginController(Auth) { var vm = this; vm.title = 'login'; console.log(Auth) vm.auth = Auth; vm.login = login activate(); //////////////// function activate() { vm.auth.$onAuth(function(authData) { vm.authData = authData; console.log(authData) }); } function login() { console.log('dudd') Auth.$authWithOAuthPopup('facebook') .then(function(result) { console.log(result) }); } } })();
const express = require('express'); const app = express(); const port = 3001; app.use(express.json()); const modelo = [ 'Nova Toyota Hilux', 'Volkswagen Nivus', 'Ford Territory', 'Honda Civic', 'BMW Série 2 Gran Coupé', 'Nissan Versa', ] const marca = [ 'Toyota', 'Volkswagen', 'Ford', 'Honda', 'BMW', 'Nissan' ] const cor = [ 'vermelho', 'verde', 'preto', 'prata', 'azul', 'branco', ] const combustivel = [ 'gasolina', 'álcool', 'híbrido', 'híbrido', 'álcool', 'gasolina' ] app.get("/", (req, res)=>{ res.send('Dinossauros'); }); app.get("/carros", (req,res) =>{ res.send(`${modelo}, ${marca}, ${cor}, ${combustivel}`); }); app.get("/carros/:id", (req,res) =>{ const id = req.params.id -1; res.send(`${modelo[id]}, ${marca[id]}, ${cor[id]}, ${combustivel[id]}`); }); app.post("/carros", (req,res) =>{ const modelonovo = req.body.modelonovo; const marcanova = req.body.marcanova; const cornova = req.body.cornova; const combustivelnovo = req.body.combustivelnovo; const id = modelo.lenght; modelo.push(modelonovo) marca.push(marcanova) cor.push(cornova) combustivel.push(combustivelnovo) res.send(`O Carro: ${modelonovo}, da marca: ${marcanova}, da cor ${cornova} foi adicionado com sucesso!`) }) app.put("/carros/:id", (req,res)=>{ const id = req.params.id; }) app.listen(port, function () { console.info(`app rodando na porta: http://localhost:${port}/`); });
/* for (var i = 0; i < itemOfCategory.length; i++) { itemOfCategory[i].removeEventListener('click'); } */ $('.first-level, .second-level, .third-level').on("click", function () { this.classList.toggle('selected'); if (this.classList.contains('selected')) { countOfCategory++; var newElementOfCatefory = document.createElement('div'); newElementOfCatefory.classList.add('category-items-item'); newElementOfCatefory.textContent = this.textContent; listOfSelectedCategory.prepend(newElementOfCatefory); } else { countOfCategory--; var collectionOfSelectedItems = document.querySelectorAll('.category-items-item'); for (var c = 0; c < collectionOfSelectedItems.length; c++) { if (this.textContent == collectionOfSelectedItems[c].textContent) { collectionOfSelectedItems[c].remove(); } } } countOfCategoryBtn.textContent = countOfCategory; if (!(document.querySelectorAll('.selected').length == 0)) { openCategory.classList.add('have-category-item'); emptyCategory.classList.add('have-select-category'); listOfSelectedCategory.classList.remove('dnthave-select-category'); } else { openCategory.classList.remove('have-category-item'); emptyCategory.classList.remove('have-select-category'); listOfSelectedCategory.classList.add('dnthave-select-category'); } }); $('.first-level').off('click'); $('.second-level').off('click'); $(".first-level-expand").on('click', function (e) { if ($(this).hasClass('expanded')) $(this).html('+'); else $(this).html('-'); $(this).toggleClass('expanded'); $(this).parent().children('.category__content-item-ul').toggleClass('off'); }); $(".second-level-expand").on('click', function (e) { if ($(this).hasClass('expanded')) $(this).html('+'); else $(this).html('-'); $(this).toggleClass('expanded'); $(this).parent().children('.category__content-item-ul-li-ul').toggleClass('off'); }); $(".first-level").on("click", function () { $(this).toggleClass('selected'); }); $(".second-level").on("click", function () { $(this).toggleClass('selected'); }); $(document).off("mouseup"); $(document).mouseup(function (e) { var container = $('.lk__wrapper').not(".only-desktop .lk__wrapper, .only__pc .lk__wrapper"); if (container.has(e.target).length === 0) { container.addClass('closed-lk'); } });
import {Nav} from 'react-bootstrap'; import Link from 'next/link'; import { useRouter } from 'next/router'; export default function UnauthenticatedLinks() { const router = useRouter(); return ( <> <Nav.Item> <Link href="/signin"> <a className={"nav-link " +(router.pathname == "/signin" ? "active" : "")}> Sign In </a> </Link> </Nav.Item> <Nav.Item> <Link href="/signup"> <a className={"nav-link " +(router.pathname == "/signup" ? "active" : "")}> Sign Up </a> </Link> </Nav.Item> </> ) }
import React from 'react'; import styled from 'styled-components' const ContainerEtapa = styled.div ` display: flex; flex-direction: column; align-items: center; justify-content:center; ` class Final extends React.Component { render() { return( <ContainerEtapa> <h2>Fim do Formulário!</h2> <p>Obrigado! Em breve entramos em contato!</p> </ContainerEtapa> ) } } export default Final;
var backnode = require('../'), assert = require('assert'), http = require('http'), superagent = require('superagent'); var app = backnode(); app.use(backnode.logger('dev')); var TestRouter = backnode.Router.extend({ routes: { '/basic' : 'basic' }, initialize: function initialize() { this.use(this.middlewhatev('foo', 'setup by middleware #1')); this.use(this.middlewhatev('bar', 'setup by middleware #2')); this.use(this.middlewhatev('baz', 'setup by middleware #3')); }, middlewhatev: function middlewhatev(prop, msg) { return function (req, res, next) { req[prop] = msg; next(); } }, basic: function basic(res) { var req = res.req; assert.equal(req.foo, 'setup by middleware #1'); assert.equal(req.bar, 'setup by middleware #2'); assert.equal(req.baz, 'setup by middleware #3'); res.end('basic!'); }, }); app.use(new TestRouter); var server = app.listen(3000, function() { get('/basic', function(res) { assert.equal(res.status, 200); assert.equal(res.text, 'basic!'); done(); }); }); var counter = 0; function done() { if(!--counter) server.close(); } function get(uri, cb) { counter++; return superagent.get('http://localhost:3000' + uri).end(cb); }
/** * 上传图片的service,只能上传单张图片,上传图片之后返回一个地址。 * 公共的上传图片路劲 common/fileUploadAction!uploadOnePictrue.action * @author zw */ app.factory("uploadOneImgService",['FileUploader','previewService',function(FileUploader,previewService){ function initUploadModule(scope){ var uploader = scope.uploader = new FileUploader({ url: 'common/fileUploadAction!uploadOnePictrue.action', alias:"files", autoUpload:false, removeAfterUpload:true }); /** * 过滤器 */ uploader.filters.push({ name: 'imageFilter', fn: function(item /*{File|FileLikeObject}*/, options) { var isImage = false; isImage = item.type.indexOf("image")>=0; if(!isImage){ console.info(item); alert("请选择图片文件!"); }else{ //清除之前的有的,每个单一文件只能有一个 if(uploader.queue&&uploader.queue.length>0){ for(var i=0;i<uploader.queue.length;i++){ if(options.name==uploader.queue[i].name){ uploader.removeFromQueue(i); } } } } return isImage; } }); /** * 预览图片功能 */ scope.previewImg = function(name){ previewService.preview(scope.formData[name]); } /** * 删除一张图片,删除图片只能删除图片formdata中的记录,目前后台不做任何操作 */ scope.deleteImg = function(name){ scope.formData[name] = undefined; scope.formData[name+"Name"] = undefined; } /** * 上传一张图片,根据图片的name来上传指定的图片 */ scope.uploadImg = function(alias){ if(uploader.queue&&uploader.queue.length>0){ for(var i=0;i<uploader.queue.length;i++){ if(uploader.queue[i].name==alias){ //禁用上传按钮 buttonClick(uploader.queue[i].name); //上传 uploader.uploadItem(i); return ; } } }else{ alert("请选择图片文件!"); } } /** * 当成功上传一个文件的时候调用 */ uploader.onSuccessItem = function(fileItem, response, status, headers) { if(response.code){//成功上传 var name = fileItem.name; scope.formData[name] = response.url; scope.formData[name+"Name"] = response.name; console.info(scope.formData); }else{ alert(response.message); } }; /** * 当上传按钮被点击的时候,将该按钮变为disblead,并改变其中的html */ var buttonClick = function(name){ var buttonName = "#"+name+"Button"; $(buttonName).attr("disabled","disabled"); $(buttonName).html("上传中..."); } } return { initUploadModule:initUploadModule } }]);
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import Preloader from '../layout/Preloader'; import ForecastItem from './ForecastItem'; import Carousel from 'react-multi-carousel'; import 'react-multi-carousel/lib/styles.css'; const FiveDayForecast = ({ forecastReducerStateAsAProp: { fiveDayWeatherForecastArray, loading, showFiveDayForecastFlag, showTempInCelcius }, }) => { const responsive = { superLargeDesktop: { // the naming can be any, depends on you. breakpoint: { max: 4000, min: 3000 }, items: 5 }, desktop: { breakpoint: { max: 3000, min: 1024 }, items: 3 }, tablet: { breakpoint: { max: 1024, min: 464 }, items: 2 }, mobile: { breakpoint: { max: 464, min: 0 }, items: 1 } }; if (loading) { return <Preloader/> } else { return ( <Carousel responsive={responsive}> {fiveDayWeatherForecastArray.map( (singleDayWeatherForecastObject, index) => ( <ForecastItem singleDayWeatherForecastObject={singleDayWeatherForecastObject} key={index} /> ) )} </Carousel> ); } }; FiveDayForecast.propTypes = { forecastReducerStateAsAProp: PropTypes.object.isRequired, } const mapStateToProps = (state) => ({ forecastReducerStateAsAProp: state.forecastReducerState, }); export default connect(mapStateToProps)(FiveDayForecast);
let userArray = [ { customer: { id: 1, customerName:"Marilyn Monroe", customerCity:"New York City", customerState:"NY", product:"Yellow Chair", productPrice: 19.99 } }, { customer: { id: 2, customerName:"Abraham Lincoln", customerCity:"Boston", customerState:"MA", product:"Movie Tickets", productPrice: 27.00 } }, { customer: { id: 3, customerName:"John F. Kennedy", customerCity:"Dallas", customerState:"TX", product:"Mustang Convertible", productPrice: 24999.99 } }, { customer: { id: 4, customerName:"Martin Luther King", customerCity:"Burmingham", customerState:"AL", product:"Sandwiches", productPrice: 7.99 } }, ]; let userInfo = function(cust) { let name = cust.customer.customerName; let price = cust.customer.productPrice; let product = cust.customer.product; let city = cust.customer.customerCity; let state = cust.customer.customerState; console.log(name, 'paid', price, 'for', product, 'in', city,',', state); } let userList = userArray.map(userInfo);
module.exports = { env: { browser: true, node: true, es2021: true, }, extends: [ 'eslint:recommended', 'plugin:react/recommended', 'plugin:import/recommended', ], parserOptions: { ecmaFeatures: { jsx: true, }, ecmaVersion: 12, sourceType: 'module', }, plugins: ['react', 'jsx-a11y'], rules: { 'react/prop-types': 0, }, settings: { 'import/resolver': { webpack: { config: { resolve: { extensions: ['.jsx', '.js'], }, }, }, node: { extensions: ['.js', '.jsx'], moduleDirectory: ['node_modules'], }, }, react: { version: 'detect', }, }, globals: { debounce: true, animateValue: true, times: true, getCssVar: true, scrollama: true, L: true, pequeno: true, mobileMediaQuery: true, IS_IOS: true, autoComplete: true, uniqBy: true, tippy: true, Chart: true, workbox: true, importScripts: true, quicklink: true, Hammer: true, dataLayer: true, React: true, }, };
import React from 'react'; import './ButtonInstruction.css'; function ButtonInstruction (props) { return ( <div className='flexFixedSize ButtonInstruction'>{props.text}</div> ); } export default ButtonInstruction;
const jwt = require('jsonwebtoken') module.exports = function (req, res, next) { const authorization = req.header('Authorization') if (!authorization) res.status(401).send('Authorization header not provided') const token = authorization.slice(7) if (!token) return res.status(401).send('Access token is empty') try { const verified = jwt.verify(token, process.env.SECRET_JWT_TOKEN) req.user = verified next() } catch (err) { res.status(400).send('Invalid Token') } }
import React, { Component } from 'react' import { withRouter } from 'next/router' import Template from '../../components/shared/Template' import Auth from '../../auth' import Head from '../../components/shared/head' class PendingApproval extends Component { static getInitialProps = async ctx => { try { const auth = new Auth(ctx) await auth.getUser() return { user: auth.user } } catch (ex) {} } componentDidMount() { this.redirectIfMembershipApproved() } render() { return ( <Template user={this.props.user}> <Head title={'Access Pending'} /> <h2>Your access to this organization is still pending approval</h2> </Template> ) } /** * If a user has already been approved don't let them sit at the pending page * thinking that they're still pending. * * TODO this should happen universally in `getInitialProps`? */ redirectIfMembershipApproved = () => { const { router, user: { organizations } } = this.props const currentOrgMembership = organizations.find( org => org.subdomain === router.query.subdomain ) if (currentOrgMembership && currentOrgMembership.role !== 'pending') { router.replace( { pathname: '/cms', query: { subdomain: currentOrgMembership.subdomain } }, `/${currentOrgMembership.subdomain}` ) } } } export default withRouter(PendingApproval)
const express = require('express') const router = express.Router() const ctrlCard = require('../controllers/card') // Middleware para verificação de autênticação // TODO: generalizar meddleware const authMiddleware = require('../../app/middlewares/auth') router.use(authMiddleware) router.post('/conductor/cartoes/:idcartao/desbloquear', ctrlCard.desbloqueiaCartao) router.post('/conductor/cartoes/:id/bloquear', ctrlCard.bloqueiaCartao) router.post('/conductor/cartoes/lotes-cartoes-pre-pagos', ctrlCard.geraLoteCartao) router.post('/conductor/cartoes/:id/reativar', ctrlCard.reativaCartao) router.put('/conductor/:id/alterar-senha', ctrlCard.alteraSenhaCartao) router.get('/conductor/cartoes', ctrlCard.listaCartoes) router.get('/conductor/cartoes-premiado', ctrlCard.listaCartoesPremiados) router.get('/conductor/cartoes/:cardid', ctrlCard.detalhaCartaoId) router.get('/conductor/cartoes/:idcartao/saldo', ctrlCard.saldo) router.get('/conductor/cartoes/:id/consultar-dados-reais', ctrlCard.consultaDadosReaisCartao) router.get('/conductor/cartoes/:id/portadores', ctrlCard.exibePortadoresCartao) router.get('/conductor/cartoes/:id/validar-senha', ctrlCard.validaSenhaCartao) module.exports = router
var _ = require('underscore'); var models = require('../models'); var Song = models.Song; var makerPage = function(req, res) { Song.SongModel.findByOwner(req.session.account._id, function(err, docs) { if(err) { console.log(err); return res.status(400).json({error:'An error occurred'}); } res.render('app', {songs: docs}); }); }; var makeSong = function(req, res) { if(!req.body.name || !req.body.age) { return res.status(400).json({error: "Both fields required"}); } var songData = { name: req.body.name, age: req.body.age, rating: req.body.rating, owner: req.session.account._id }; var newSong = new Song.SongModel(songData); newSong.save(function(err) { if(err) { console.log(err); return res.status(400).json({error:'An error occurred'}); } res.json({redirect: '/maker'}); }); }; module.exports.makerPage = makerPage; module.exports.make = makeSong;
// 模拟 web端的requestAnimationFrame // lastFrameTime为上次更新时间 let lastFrameTime = 0 let doAnimationFrame = callback => { //当前毫秒数 let currTime = new Date().getTime() //设置执行该函数的等待时间,如果上次执行时间和当前时间间隔大于16ms,则设置timeToCall=0立即执行,否则则取16-(currTime - lastFrameTime),确保16ms后执行动画更新的函数 let timeToCall = Math.max(0, 16 - (currTime - lastFrameTime)) // console.log(timeToCall) let id = setTimeout(() => { //确保每次动画执行时间间隔为16ms callback(currTime + timeToCall) }, timeToCall) //timeToCall小于等于16ms,lastFrameTime为上次更新时间 lastFrameTime = currTime + timeToCall return id } // 模拟 cancelAnimationFrame let abortAnimationFrame = id => { clearTimeout(id) } module.exports = { doAnimationFrame: doAnimationFrame, abortAnimationFrame: abortAnimationFrame }
// Project Title // Your Name // Date // // Extra for Experts: // - describe what you did to take this project "above and beyond" let theBubbles = []; function setup() { createCanvas(windowWidth, windowHeight); // window.setInterval(spawnBubble, 77); //runs function every half second } function draw() { background("black"); if (frameCount % 20 === 0) { spawnBubble(); } for (let i = theBubbles.length -1; i >= 0; i--) { if (theBubbles[i].isPopped) { theBubbles.splice(i, 1); } else { theBubbles[i].display(); theBubbles[i].move(); } } } function spawnBubble() { let someBubble = new Bubble(); theBubbles.push(someBubble); } class Bubble { constructor() { this.x = random(width); this.y = height + random(50, 100); this.dx = 0; this.dy = -2; this.radius = random(17, 37); this.theta = 0; this.isAlive = true; this.whenIDied = 0; this.countdown = 1000; this.isPopped = false; } display() { noStroke(); fill("white"); ellipse(this.x, this.y, this.radius*2, this.radius*2); } move() { if (this.y - this.radius > 0) { this.x += this.dx; this.y += this.dy; this.dx = map(noise(this.theta), 0, 1, -5, 5); this.theta += 0.02; } //when it hits the top else if (this.isAlive) { this.isAlive = false; this.whenIDied = millis(); } //stuck on the top else { if (millis() > this. whenIDied + this.countdown) { this.isPopped = true; } } } }
(() => { const init = () => { window.goldrobot ? window.goldrobot : window.goldrobot = {}; window.goldrobot.banners ? window.goldrobot.banners : window.goldrobot.banners = []; findBanners(); addScrollListener(); parallaxBanners(); }; const findBanners = () => { const banners = document.querySelectorAll(".gr-parallax-banner"); if (!banners.length) return false; banners.forEach((banner, index) => { const bannerObj = { id: banner.id, index: index, element: banner, speed: banner.dataset.speed }; window.goldrobot.banners.push(bannerObj); }); }; const addScrollListener = () => { window.addEventListener("scroll", e => { parallaxBanners(); }); }; const parallaxBanners = () => { const banners = window.goldrobot.banners; const scrollPosition = window.scrollY; let parallaxPos = scrollPosition / 4; banners.forEach((banner, index) => { const element = document.querySelector(`#${banner.id}`); if(banner.speed === "slow") parallaxPos = scrollPosition / 8; if(banner.speed === "medium") parallaxPos = scrollPosition / 4; if(banner.speed === "fast") parallaxPos = scrollPosition / 2; element.style.backgroundPosition = `center ${parallaxPos}px`; }); } return init(); })()
import { makeObservable, observable, action } from "mobx"; import { nanoid } from "nanoid"; import { createContext } from "react"; export class MushroomStoreClass { mushrooms = []; constructor() { makeObservable(this, { mushrooms: observable, addMushroom: action, removeMushroom: action, }); } addMushroom(mushroomName) { this.mushrooms.push({ mushroomName, id: nanoid(), }); } removeMushroom(id) { this.mushrooms = this.mushrooms.filter((mushroom) => mushroom.id !== id); } } export const MushroomClassStoreContext = createContext( new MushroomStoreClass() );
import React from 'react'; import store from 'store'; import { postSavedSearch } from 'api/data'; import { Link, browserHistory } from 'react-router'; require("assets/styles/saveSearch.scss"); export default React.createClass({ getInitialState: function(){ return ({ title: "", search_string: "", likes: "" }) }, componentWillMount: function(){ this.unsubscribe = store.subscribe(function(){ var currentStore = store.getState(); this.setState({ likes: currentStore.whiskeyReducer.likes }) }.bind(this)); }, handleChange: function(e){ this.setState({ title: this.refs.title.value }) }, handleSubmit: function(e){ e.preventDefault(); // var arrToString = this.props.likes; // arrToString = arrToString.toString(); var searchObj = { title: this.state.title, search_string: this.props.likes } // console.log(this.props.likeParams); // console.log('Saved Search_String:', searchObj); postSavedSearch(searchObj); this.setState({ title: "" }) store.dispatch({ type: 'CHANGE_SHOWSEARCH', showSearch: false }) }, componentWillUnmount: function(){ this.unsubscribe(); }, render: function(){ return ( <div className="saveSearchOption2"> <form onSubmit={this.handleSubmit}> <input ref="title" type="text" name="saveSearch" onChange={this.handleChange} value={this.state.title} placeholder="Enter Search Title"/> <button type="submit" className="saveSearchText">save this search</button> </form> </div> ) } })
var searchData= [ ['check_5fempty_5fqueue',['check_empty_queue',['../queue_8h.html#aa6b5cb02e7b721babea577c052370c58',1,'queue.c']]], ['check_5fstop',['check_stop',['../state__machine_8h.html#a075099d294f5f4d5b63f53c2c9edd462',1,'state_machine.c']]] ];
import React, { Component } from 'react'; import 'antd/dist/antd.css'; // or 'antd/dist/antd.less' 引入样式 import { Input, Button, List } from 'antd' // 引入需要的组件 import myStore from './store/store' class Todolist extends Component { state = { } constructor(props) { super(props) // 通过 store.getState() 方法获取到 store 中的值 console.log(myStore.getState()) this.state = myStore.getState() this.addInputValue = this.addInputValue.bind(this) this.addItem = this.addItem.bind(this) this.del = this.del.bind(this) this.storeChage = this.storeChage.bind(this) myStore.subscribe(this.storeChage); } storeChage() { this.setState(myStore.getState()) } addInputValue = (e) => { // console.log(e.target.value) const action = { type: 'add', list: e.target.value } myStore.dispatch(action) } addItem() { console.log('添加?') const action = { type: 'addlist' } myStore.dispatch(action) } del() { console.log('删除?') const action = { type: 'delete', } myStore.dispatch(action) } render() { // const data = [ // '这是一次redux的练习,外加ant', // '祝您福如东海,寿比南山', // '日子过得是真的快呀' // ] // const del = false return ( <div style={ {margin: '30px'} }> {/* redux-todolist */} <div> <Input placeholder={this.state.inputValue} style={ {width: '250px'} } value={ this.state.inputValue } onChange = { this.addInputValue } /> <Button type="primary" style={ {marginLeft: '10px'} } onClick = { this.addItem } >添加</Button> </div> <div> <List style={ {margin: '10px', width: '300px'} } bordered //边框 dataSource = {this.state.list} renderItem = { (item) => <List.Item style={{textDecoration: this.state.del ? 'line-through' : ''}} onClick = { this.del } > {item} </List.Item> } /> </div> </div> ); } } export default Todolist;
import React, { Component } from "react"; import { Avatar, Button, Container, CssBaseline, TextField, Typography, } from "@material-ui/core"; import { withStyles } from "@material-ui/core/styles"; import LockOutlinedIcon from "@material-ui/icons/LockOutlined"; import Swal from "sweetalert2/src/sweetalert2.js"; import "@sweetalert2/theme-dark/dark.css"; import axios from "axios"; const styles = (theme) => ({ paper: { marginTop: theme.spacing(8), display: "flex", flexDirection: "column", alignItems: "center", }, avatar: { margin: theme.spacing(1), backgroundColor: theme.palette.secondary.main, }, form: { width: "100%", marginTop: theme.spacing(1), }, submit: { margin: theme.spacing(3, 0, 2), }, }); class Login extends Component { constructor(props) { super(props); this.state = { auth: "", error: "", password: "", server: "", tempServer: window.location.origin.startsWith("app://-") ? "" : window.location.origin, username: "", }; this.handleTempServerChange = this.handleTempServerChange.bind(this); this.handlePassChange = this.handlePassChange.bind(this); this.handleUserChange = this.handleUserChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); this.dismissError = this.dismissError.bind(this); } componentDidMount() { axios .get(`${window.location.origin}/api/v1/auth?u=&p=`) .then((response) => { localStorage.setItem("server", window.location.origin); sessionStorage.setItem("server", window.location.origin); localStorage.setItem("auth", response.data.auth); sessionStorage.setItem("auth", response.data.auth); this.props.history.push("/browse") }) } dismissError() { this.setState({ error: "" }); } handleSubmit(evt) { evt.preventDefault(); let { auth, password, server, tempServer, username } = this.state; if (!tempServer) { return this.setState({ error: "Server is required" }); } if (!tempServer.startsWith("http")) { tempServer = `https://${tempServer}`; } axios .get(`${tempServer}/api/v1/auth?u=${username}&p=${password}`) .then((response) => { localStorage.setItem("server", tempServer); sessionStorage.setItem("server", tempServer); localStorage.setItem("auth", response.data.auth); sessionStorage.setItem("auth", response.data.auth); this.props.history.push("/"); }) .catch((error) => { console.error(error); if (auth == null || server == null) { this.props.history.push("/login"); } else if (error.response) { if (error.response.status === 401) { Swal.fire({ title: "Error!", text: "Your credentials are invalid!", icon: "error", confirmButtonText: "OK", }); } else { Swal.fire({ title: "Error!", text: "Something went wrong while communicating with the backend!", icon: "error", confirmButtonText: "OK", }); } } else if (error.request) { Swal.fire({ title: "Error!", text: `libDrive could not communicate with the backend! Is ${tempServer} the correct address?`, icon: "error", confirmButtonText: "OK", }); } }); return this.setState({ error: "" }); } handleTempServerChange(evt) { this.setState({ tempServer: evt.target.value, }); } handleUserChange(evt) { this.setState({ username: evt.target.value, }); } handlePassChange(evt) { this.setState({ password: evt.target.value, }); } render() { let { error, password, tempServer, username } = this.state; const { classes } = this.props; return ( <Container component="main" maxWidth="xs"> <CssBaseline /> <div className={classes.paper}> <Avatar className={classes.avatar}> <LockOutlinedIcon /> </Avatar> <Typography component="h1" variant="h5"> Sign in </Typography> <form className={classes.form} onSubmit={this.handleSubmit} noValidate > {error && ( <div style={{}}> <h3 data-test="error" onClick={this.dismissError}> <button onClick={this.dismissError}>✖</button> {error} </h3> </div> )} <TextField variant="outlined" margin="normal" required fullWidth id="server" label="Server" name="server" autoComplete="server" onChange={this.handleTempServerChange} value={tempServer} autoFocus /> <TextField variant="outlined" margin="normal" required fullWidth id="username" label="Username" name="username" autoComplete="username" onChange={this.handleUserChange} value={username} /> <TextField variant="outlined" margin="normal" required fullWidth name="password" label="Password" type="password" id="password" autoComplete="current-password" onChange={this.handlePassChange} value={password} /> <Button type="submit" fullWidth variant="contained" color="primary" className={classes.submit} > Sign In </Button> </form> </div> </Container> ); } } export default withStyles(styles, { withTheme: true })(Login);
const handleProfileGet = (req, res, db) => { // :id is the taken parameter, the part may be needed for future development. A future endpoint const {id} = req.params; db.select('*').from('users').where({id: id}) .then(user => { //it will return the user if(user.length) { // if the length is one which is also true res.json(user[0]) } else { res.status(400).json('Not found') } }) .catch(err => res.status(400).json('Error getting user')) } //end of handleProfileGet module.exports = { handleProfileGet }
// 引入React import React,{Component} from 'react'; //引入其他组件 import TodoForm from './TodoForm'; import TodoContent from './TodoContent'; //引入样式 import '../css/bootstrap.css'; class TodoList extends Component{ constructor(){ super(); this.state = { datalist:[ { content:'你不能拼爹,所以只能拼命', done:false },{ content:'拼搏到无能为力,坚持到感动自己', done:false } ] } //改变this指向 this.handlerAdd = this.handlerAdd.bind(this); this.handlerComplete = this.handlerComplete.bind(this); this.handlerRemove = this.handlerRemove.bind(this); } // 添加待办事件 handlerAdd(txt){console.log(this) // 不能直接修改state中的 // this.state.datalist.unshift({ // content:txt, // done:false // }) this.setState({ datalist:[{ content:txt, done:false },...this.state.datalist] }); } // 完成待办事件 handlerComplete(idx){ let datalist = [...this.state.datalist]; datalist[idx].done = true; this.setState({ datalist }) } // 删除待办事件 handlerRemove(idx){console.log(idx) let datalist = [...this.state.datalist]; datalist.splice(idx,1); this.setState({ datalist }) } render(){ let {datalist} = this.state; return ( <div className="todolist container"> <h1>TodoList</h1> <TodoForm handlerAdd={this.handlerAdd}/> <TodoContent data={datalist} handlerRemove={this.handlerRemove} handlerComplete={this.handlerComplete}/> </div> ) } } export default TodoList;
module.exports = { addClient: async (req, res) => { const db = req.app.get("db"); const { name, email, phoneNumber, agentId } = req.body; const client = await db.client.add_client({ name, email, phoneNumber, agentId, }); res.status(200).send(client[0]); }, deleteClient: (req, res) => { const db = req.app.get("db"); const { clientId } = req.body; db.client.delete_client({ clientId }); res.sendStatus(200); }, updateClient: (req, res) => { const db = req.app.get("db"); const { name, email, phoneNumber, clientId } = req.body; db.client.update_client({ name, email, phoneNumber, clientId }); res.sendStatus(200); }, getClient: async (req, res) => { const db = req.app.get("db"); const { clientId } = req.params; const client = await db.client.get_client({ clientId }); res.status(200).send(client); }, getClients: async (req, res) => { const db = req.app.get("db"); const { agentId } = req.params; const clients = await db.client.get_clients({ agentId }); res.status(200).send(clients); }, getAllClients: async (req, res) => { const db = req.app.get("db"); const list = await db.client.get_clientsAll(); res.status(200).send(list); }, orderByAlphabet: async (req, res) => { const db = req.app.get("db"); const { agent_id } = req.params; const list = await db.client.order_by_a({ agent_id }); res.status(200).send(list); }, orderById: async (req, res) => { const db = req.app.get("db"); const { agent_id } = req.params; const list = await db.client.order_by_id({ agent_id }); res.status(200).send(list); }, };
function get(el) { if(typeof el === "string") return document.getElementById(el); return el; } var rand = function(max, min, _int) { var max = (max === 0 || max)?max:1, min = min || 0, gen = min + (max - min)*Math.random(); return (_int)?Math.round(gen):gen; }; /*============================================*/ var ShineEffect = (function(){ var container = get('widgetContainer'); var canvas = get('canvas'); var ctx = canvas.getContext('2d'); var containerWidth, containerHeight; var isRunning = false; var isStop = false; var gradient; var skew, maxSkew = 0.5; // maxSkew is skew of 30 degree - skew will be used to calculate of rotating angle ( = Math.atag(skewValue))6 var startX, deltaX, currentX, endX, timeoutValue, timeout; var startColor, centerColor; /*--- settings from banner flow ---*/ var duration; var size; var color; var isRepeat; var delayRepeat; var directionFrom; var directionSkew; var angleRotate; function runAnimation() { if(isStop){ isRunning = false; if(timeout) clearTimeout(timeout); return; } ctx.save(); ctx.clearRect(0,0, containerWidth, containerHeight); ctx.translate(containerWidth/2, containerHeight/2); ctx.transform(1, 0, skew, 1, 0, 0); gradient = ctx.createLinearGradient(currentX, 0, currentX + size, 0); gradient.addColorStop(0, startColor); gradient.addColorStop(0.5, centerColor); gradient.addColorStop(1, startColor); ctx.fillStyle = gradient; ctx.fillRect(currentX, -containerHeight/2, size, containerHeight); ctx.restore(); if((currentX > endX && directionSkew == -1) || (currentX < endX && directionSkew == 1)) { if(isRepeat){ currentX = startX; if(delayRepeat) { timeout = setTimeout(function(){ if(timeout) clearTimeout(timeout); runAnimation(); }, delayRepeat * 1000); return false; } } else { isRunning = false; return false; } } currentX += deltaX; timeout = setTimeout(function(){ if(timeout) clearTimeout(timeout); runAnimation(); }, timeoutValue); } function startWidget(currentSesssion) { if(!containerWidth || !containerHeight) // check if the widget is hide return; canvas.setAttribute('width', containerWidth); canvas.setAttribute('height', containerHeight); // Calculate color gradient color = color.substring('rgba('.length); color = color.split(','); startColor = "rgba(" + color[0] + "," + color[1] + "," + color[2] + ", 0)"; centerColor = "rgba(" + color[0] + "," + color[1] + "," + color[2] + ", 0.7)"; // Calculate skew value // skew = containerWidth/containerHeight; // if(skew > maxSkew) // skew = maxSkew; skew = Math.tan(Math.PI * angleRotate / 180); // get rotate angle from the setting parameter // Calculate startX to draw, endX and timeout value if(directionFrom.toLowerCase() == "left") { startX = -(size + containerWidth/2) - skew*containerHeight/2; endX = containerWidth/2 + skew*containerHeight/2; if(skew < 0) { startX = -(size + containerWidth/2) + skew * containerHeight /2; endX = containerWidth/2 - skew * containerHeight /2; } directionSkew = -1; } else if(directionFrom.toLowerCase() == "right") { startX = containerWidth/2 + skew*containerHeight/2; endX = -(size + containerWidth/2) - skew*containerHeight/2; if(skew < 0) { startX = containerWidth/2 - skew*containerHeight/2; endX = -(size + containerWidth/2) + skew*containerHeight/2; } directionSkew = 1; } duration *= 1000/2; timeoutValue = parseInt(1000/60); deltaX = (endX - startX)/(duration/timeoutValue); currentX = startX; // Run animation isRunning = true; runAnimation(); } /*==============================================*/ /*===== Start point of animation =====*/ /*==============================================*/ function reloadGlobalVariables() { containerWidth = parseInt(window.getComputedStyle(container).getPropertyValue('width')); containerHeight = parseInt(window.getComputedStyle(container).getPropertyValue('height')); } function stopCurrentAnimation(callback) { isStop = true; if(isRunning) { var timeout = setTimeout(function(){ clearTimeout(timeout); stopCurrentAnimation(callback); }, 200); } else { isStop = false; if(callback) callback(); } } function startAnimation(currentSesssion) { stopCurrentAnimation(function(){ startWidget(currentSesssion); }); } /*==============================================*/ /*===== Default settings from Banner Flow =====*/ /*==============================================*/ function loadSettings() { if(typeof BannerFlow !== "undefined") { size = BannerFlow.settings.size; color = BannerFlow.settings.color; duration = BannerFlow.settings.duration; if(duration == 0) duration = 1; isRepeat = BannerFlow.settings.isRepeat; delayRepeat = BannerFlow.settings.delayRepeat; directionFrom = BannerFlow.settings.directionFrom; angleRotate = parseInt(BannerFlow.settings.angleRotate); var angleRotateWith90 = parseInt(angleRotate / 90); if(angleRotate % 90 == 0 && angleRotateWith90 % 2 != 0) angleRotate = 0; } else { size = 80; color = "rgba(255,255,255,1)"; duration = 10; isRepeat = true; delayRepeat = 1; directionFrom = "left"; angleRotate = 30; var angleRotateWith90 = parseInt(angleRotate / 90); if(angleRotate % 90 == 0 && angleRotateWith90 % 2 != 0) angleRotate = 0; } } /*====================================================*/ var timeoutStart; var sessionId = 0; function init() { if(timeoutStart) { clearTimeout(timeoutStart); timeoutStart = setTimeout(function() { loadSettings(); reloadGlobalVariables(); startAnimation(++sessionId); }, 500); } else { timeoutStart = setTimeout(function(){ loadSettings(); reloadGlobalVariables(); startAnimation(++sessionId); }, 0); } } var isStartAnimation = false; function onStart() { init(); } function onTextChanged() { if(typeof BannerFlow != "undefined" && !BannerFlow.editorMode) { return; } init(); } function onResize(){ if(typeof BannerFlow != "undefined" && !BannerFlow.editorMode) { return; } init(); } function resetParameter(){ if(typeof BannerFlow != "undefined" && !BannerFlow.editorMode) { return; } init(); } function onStartAnimation() { if(typeof BannerFlow != "undefined" && !BannerFlow.editorMode && isStartAnimation) { return; } isStartAnimation = true; init(); } function getLanguageText() { languageTexts = []; var tmpText = ""; if(typeof BannerFlow !== "undefined") tmpText = BannerFlow.text; if(tmpText && tmpText.length > 0) { languageTexts = tmpText.split(':'); } } return { start: onStart, onTextChanged: onTextChanged, onResized: onResize, onSettingChanged: resetParameter, onStartAnimation: onStartAnimation }; })(); if(typeof BannerFlow == "undefined"){ ShineEffect.start(); } else { BannerFlow.addEventListener(BannerFlow.RESIZE, function () { ShineEffect.onResized(); }); BannerFlow.addEventListener(BannerFlow.SETTINGS_CHANGED, function () { ShineEffect.onSettingChanged(); }); BannerFlow.addEventListener(BannerFlow.TEXT_CHANGED, function () { ShineEffect.onTextChanged(); }); BannerFlow.addEventListener(BannerFlow.START_ANIMATION, function() { ShineEffect.onStartAnimation(); }); }
import React, { Component } from 'react'; import { APIHandler } from "./../../api/handler"; const apiCatHandler = new APIHandler("/api/categories"); export default class DeleteCategory extends Component { state = { category: [], }; async componentDidMount() { const catRes = await apiCatHandler.getAll(); this.setState({category: catRes.data}) } handleDelete = async (id) => { if(window.confirm("Êtes-vous sûre de vouloir supprimé cette catégorie ?")) { await apiCatHandler.deleteOne(id) const apiRes = await apiCatHandler.getAll(); this.setState({ category: apiRes.data }); } }; render(){ const {category} = this.state; return ( <div> <h1 className="title">Supprimer une catégorie</h1> <table className="table"> <thead> <tr> <th>Nom</th> <th>Supprimé</th> </tr> </thead> <tbody> {category.map((cat, i) => ( <tr key={i}> <td>{cat.name}</td> <td> <button className="btn" onClick={() => this.handleDelete(cat._id)}>x</button></td> </tr> ))} </tbody> </table> </div> ) } }
$(document).ready(function(){ $('.notifButton').click(function(e){ e.preventDefault(); $(this).toggleClass('active'); $('.dropdown-content').toggleClass('active'); }); // $('html').on('contextmenu', function(e){ // e.preventDefault(); // alert('Unable to process your request'); // }); });
var express = require('express'); var router = express.Router(); var mongoose = require('mongoose'); var moment = require('moment'); var Event = require('../models/Event.js'); var Phase = require('../models/Phase.js'); var Task = require('../models/Task.js'); var Instruction = require('../models/Instruction.js'); var Email = require('../models/Email.js'); /* GET ALL EVENTS */ router.get('/', function(req, res, next) { Event.find(function (err, events) { if (err) return next(err); res.json(events); }); }); /* GET ALL EVENTS BY USER*/ router.get('/user/', function(req, res, next) { Event.find({ user_id: req.user._id } , function (err, post) { if (err) return next(err); res.json(post); }); }); /* GET SINGLE EVENT BY ID */ router.get('/:id', function(req, res, next) { Event.findById(req.params.id, function (err, post) { if (err) return next(err); res.json(post); }); }); /* CREATE EVENT */ router.post('/', function(req, res, next) { var user_info = req.user; var event_type = req.body.type; var default_id = null; for (let user_default of user_info.defaults) { if(user_default.type === event_type) { default_id = user_default.id } } var event_body = req.body; event_body.user_id = user_info._id; Event.create(event_body, function (err, post) { if (err) return next(err); var event_id = post._id; var event_start_date = post.start_date; var registration_id; var preparation_id; var arrival_id; var during_id; var closing_id; var follow_up_id; createEventPhases(); function createEventPhases() { var registration_body = { 'name': "Registration", 'event_id': event_id }; var preparation_body = { 'name': "Preparation", 'event_id': event_id }; var arrival_body = { 'name': "Arrival", 'event_id': event_id }; var during_body = { 'name': "During", 'event_id': event_id }; var closing_body = { 'name': "Closing", 'event_id': event_id }; var follow_up_body = { 'name': "Follow Up", 'event_id': event_id }; Phase.create(registration_body, function (err, post) { if (err) return next(err); registration_id = post._id; Phase.create(preparation_body, function (err, post) { if (err) return next(err); preparation_id = post._id; Phase.create(arrival_body, function (err, post) { if (err) return next(err); arrival_id = post._id; Phase.create(during_body, function (err, post) { if (err) return next(err); during_id = post._id; Phase.create(closing_body, function (err, post) { if (err) return next(err); closing_id = post._id; Phase.create(follow_up_body, function (err, post) { if (err) return next(err); follow_up_id = post._id; if(default_id != null) { var phases; var default_registration_id; var default_preparation_id; var default_arrival_id; var default_during_id; var default_closing_id; var default_follow_up_id; Phase.find({ event_id: default_id } , function (err, post) { if (err) return next(err); phases = post; for (let phase of phases) { if (phase.name == 'Registration') { default_registration_id = phase._id } else if (phase.name == 'Preparation') { default_preparation_id = phase._id } else if (phase.name == 'Arrival') { default_arrival_id = phase._id } else if (phase.name == 'During') { default_during_id = phase._id } else if (phase.name == 'Closing') { default_closing_id = phase._id } else if (phase.name == 'Follow Up') { default_follow_up_id = phase._id } } createDefaultTasksInstructionsEmails(registration_id,default_registration_id); createDefaultTasksInstructionsEmails(preparation_id,default_preparation_id); createDefaultTasksInstructionsEmails(arrival_id,default_preparation_id); createDefaultTasksInstructionsEmails(during_id,default_during_id); createDefaultTasksInstructionsEmails(closing_id,default_closing_id); createDefaultTasksInstructionsEmails(follow_up_id,default_follow_up_id); }); } }); }); }); }); }); }); } function createDefaultTasksInstructionsEmails(phase_id, default_phase_id) { Task.find({ phase_id: default_phase_id } , function (err, post) { if (err) return next(err); for (let task of post) { let task_body = { name: task.name, phase_id: phase_id, due_date: moment(event_start_date).subtract(task.default_due_date, "days"), complete: 0 }; if (task.content) {task_body.content = task.content} Task.create(task_body, function (err, post) { if (err) return next(err); }); } }); Instruction.find({ phase_id: default_phase_id } , function (err, post) { if (err) return next(err); for (let instruction of post) { let instruction_body = { name: instruction.name, phase_id: phase_id, }; if (instruction.content) {instruction_body.content = instruction.content} Instruction.create(instruction_body, function (err, post) { if (err) return next(err); }); } }); Email.find({ phase_id: default_phase_id } , function (err, post) { if (err) return next(err); for (let email of post) { let email_body = { name: email.name, subject: email.subject, body: email.body, event_id: event_id, phase_id: phase_id }; if (email.type) { email_body.type = email.type; } Email.create(email_body, function (err, post) { if (err) return next(err); }); } }); } res.json(post); }); }); /* UPDATE EVENT */ router.put('/:id', function(req, res, next) { Event.findByIdAndUpdate(req.params.id, req.body, function (err, post) { if (err) return next(err); res.json(post); }); }); /* DELETE EVENT */ router.delete('/:id', function(req, res, next) { Event.findByIdAndRemove(req.params.id, req.body, function (err, post) { if (err) return next(err); Phase.deleteMany({ event_id: req.params.id }, function (err) { if (err) return handleError(err); // deleted at most one tank document }); res.json(post); }); }); module.exports = router;
import Link from 'next/link'; import { useRouter } from 'next/router'; import { useEffect, useState } from 'react'; import Image from 'next/image'; import USER from '../../data/user.json'; import AppToggle from '../atomics/AppToggle'; const AppNav = () => { const [isActiveNav, setIsActiveNav] = useState(false); const [isActiveToggler, setIsActiveToggler] = useState(false); const { pathname } = useRouter(); const activeLink = (url) => { const className = url === pathname ? 'font-bold text-white hover:text-white md:hover:text-orange md:text-orange bg-orange ' : 'bg-light-gray bg-opacity-30 hover:text-orange'; return className; }; const handleWindowScroll = () => { const pageScrollPosition = window.pageYOffset; const targetPosition = 20; if (pageScrollPosition >= targetPosition) { setIsActiveNav(true); } else { setIsActiveNav(false); } }; const handleToggler = (event) => { event.preventDefault(); setIsActiveToggler((prev) => !prev); event.stopPropagation(); }; useEffect(() => { window.addEventListener('scroll', handleWindowScroll); return () => { window.removeEventListener('scroll', handleWindowScroll); }; }, []); return ( <nav className={`flex items-center justify-between fixed top-0 z-40 w-full max-w-[1905px] transform right-1/2 translate-x-1/2 md:px-10 2xl:px-20 md:py-3 transition duration-500 ${ isActiveNav && 'bg-white' }`} > <div className={`flex items-center justify-between w-full z-50 transition duration-500 ${ isActiveToggler && 'bg-white' } ${isActiveNav && 'bg-white'} px-3 md:px-0 py-3 md:py-0`} > <Link href="/" passHref> <a className="flex items-center"> <Image src="/smanse2.png" alt="SMAN 11 Semarang" width={40} height={40} /> </a> </Link> <AppToggle onClick={handleToggler} active={isActiveToggler} /> </div> <ul className={`flex transform transition duration-500 absolute md:static bg-white md:bg-transparent left-3 right-3 border md:border-none border-light-gray p-8 md:p-0 space-y-4 md:space-y-0 flex-col md:flex-row space-x-0 md:space-x-14 rounded-xl z-10 ${ isActiveToggler ? 'translate-y-[220px]' : 'translate-y-[-100vh] md:translate-y-0' }`} > {USER.navigations.map((item) => ( <li key={item.id}> <Link href={item.url} passHref> <a className={`text-sm text-center transition block py-3 md:py-0 rounded-lg md:bg-transparent tracking-widest ${activeLink( item.url )}`} > {item.name} </a> </Link> </li> ))} </ul> <div onClick={handleToggler} aria-hidden="true" className={`fixed h-screen top-16 bottom-0 left-0 right-0 transition duration-500 invisible bg-black bg-opacity-80 ${ isActiveToggler && 'visible' }`} /> </nav> ); }; export default AppNav;
const assert = require('assert'); const make = require('../../src/make/index'); describe('make', () => { it('make', () => { const resultMake = make(15)(34, 21, 666)(41)((a,b)=>a+b); assert.deepEqual(resultMake, 777); }); it('make', () => { const resultMake = make(10)(2, 1, 5)(8)(10)((a, b)=>a*b); assert.deepEqual(resultMake, 8000); }); it('make', () => { const resultMake = make(17, -3, 12)(9, 0)(12, 11, 10)(11)((a,b)=>a-b); assert.deepEqual(resultMake, -45); }); });