text
stringlengths
7
3.69M
import axios from 'axios'; const axiosInstance = axios.create({ baseURL: 'https://cors-anywhere.herokuapp.com/https://r-c-g-burger-builder.firebaseio.com/', }); export default axiosInstance;
var addTodo = function addTodo(text) { return { type: ADD_TODO, text: text }; }; var deleteTodo = function deleteTodo(id) { return { type: DELETE_TODO, id: id }; }; var editTodo = function editTodo(id, text) { return { type: EDIT_TODO, id: id, text: text }; }; var completeTodo = function completeTodo(id) { return { type: COMPLETE_TODO, id: id }; }; var completeAll = function completeAll() { return { type: COMPLETE_ALL }; }; var clearCompleted = function clearCompleted() { return { type: CLEAR_COMPLETED }; };
/** * Задача 1. * * Напишите функцию `inspect`, которая будет принимать массив в качестве аргумента, * и возвращать новый массив. * Этот новый массив должен содержать исключительно длины строк, которые были в * переданном массиве. * Если строк в переданном массиве не было — нужно вернуть пустой массив. * * Условия: * - Обязательно использовать встроенный метод массива filter; * - Обязательно использовать встроенный метод массива map. * * Генерировать ошибки, если: * - При вызове функции не был передан один аргумент; * - В качестве первого аргумента был передан не массив. */ const array = [ false, 'Привет.', 2, 'Здравствуй.', [], 'Прощай.', { name: 'Уолтер', surname: 'Уайт', }, 'Приветствую.', ]; // Решение function inspect(array) { if (arguments.length !== 1) { throw new Error('Number of arguments should be 1, no more, no less!') } else if (!Array.isArray(array)) { throw new Error(`${array} - should be an Array type!`); } return array.filter(item => typeof item === 'string').map(str => str.length); } const result = inspect(array); console.log(result); // [ 7, 11, 7, 12 ] exports.inspect = inspect;
import React from 'react'; import { Router, Stack, Scene } from 'react-native-router-flux'; import PhoneContactList from './components/PhoneContactList'; import PhoneContactDetail from './components/PhoneContactDetail'; const AppRouter = () => ( <Router> <Stack key="root"> <Scene key="phoneContactList" component={PhoneContactList} title="通讯录" initial /> <Scene key="phoneContactDetail" component={PhoneContactDetail} title="详情" /> </Stack> </Router> ); export default AppRouter;
function validarCiclo() { } /** *Para que sea dinámico hay que meterlo dentro del evento html "onmousemove". *El explorador Edge trae incorporado un tooltip que hace esta funcion y no es necesaria. */ function mostrarAnno() { var span = document.getElementById("anno"); var rango = document.getElementById("academico"); span.textContent = rango.value; console.log("el valor del rango es: " + rango.value); }
import axios from 'axios'; export const meses = ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro']; export function convertDate(date) { let time = new Date(date); return `${time.getDate()} de ${meses[time.getMonth()]}, ${time.getFullYear()}` } const baseURL = "https://api.7tonsdebeleza.com.br/" const api = axios.create({ baseURL }); export default api;
import firebase from 'firebase/app'; import 'firebase/firestore'; import 'firebase/auth'; import 'firebase/database'; const firebaseApp = firebase.initializeApp({ apiKey: "AIzaSyDG0EPovkqMqpOj3fT3zFWuOLjnnetlGss", authDomain: "reactachat.firebaseapp.com", projectId: "reactachat", storageBucket: "reactachat.appspot.com", messagingSenderId: "219604564925", appId: "1:219604564925:web:66af7286dcdd69093c70d4", measurementId: "G-RSMTHCPE4N" }); const db = firebaseApp.firestore(); const auth = firebase.auth(); const provider = new firebase.auth.GoogleAuthProvider(); export { db, auth, provider }
import React from "react"; import styled, { css } from "styled-components"; import * as polished from "polished"; // import { foreground, red, lightGrey } from "../utils/colors"; export const background = "#282a36"; export const foreground = "#f8f8f2"; export const red = "#ff5555"; export const blue = polished.lighten(0.1, "#6272a4"); export const lightGrey = polished.darken(0.05, "#282a36"); import { LiveProvider, LiveEditor, LiveError, LivePreview } from "react-live"; import { Header, Wrapper, Photo, Search, DogOfTheDay, ApolloProvider, ApolloClient } from "../components/Demo"; import { Autocomplete, Input, Downshift } from "../components/Autocomplete"; const StyledProvider = styled(LiveProvider)` border-radius: ${polished.rem(3)}; box-shadow: 1px 1px 20px rgba(20, 20, 20, 0.27); overflow: hidden; margin-bottom: ${polished.rem(100)}; width: 90vw; `; const LiveWrapper = styled.div` display: flex; flex-direction: row; justify-content: stretch; align-items: stretch; @media (max-width: 600px) { flex-direction: column; } `; const column = css` flex-basis: 50%; width: 50%; max-width: 50%; @media (max-width: 600px) { flex-basis: auto; width: 100%; max-width: 100%; } `; const StyledEditor = styled(LiveEditor)` font-family: "Source Code Pro", monospace; font-size: ${polished.rem(14)}; height: "100%"; text-align: initial; overflow: scroll; ${column}; `; const StyledPreview = styled(LivePreview)` position: relative; padding: 0.5rem; background: white; color: black; height: auto; overflow: hidden; ${column}; `; const StyledError = styled(LiveError)` display: block; padding: ${polished.rem(8)}; background: ${red}; color: ${foreground}; `; const LiveEdit = ({ code }) => ( <StyledProvider code={code} noInline={true} scope={{ Header, Wrapper, Photo, Search, ApolloProvider, ApolloClient, Autocomplete, Input, Downshift }} mountStylesheet={false} > <LiveWrapper> <StyledEditor /> <StyledPreview /> </LiveWrapper> <StyledError /> </StyledProvider> ); export default LiveEdit;
import React from 'react'; import ReactDOM from 'react-dom'; import { MODAL_CLOSE, MODAL_OPEN } from '../../types'; export const modalOpen = () => ({ type: MODAL_OPEN }); export const modalClose = () => ({ type: MODAL_CLOSE }); export const ModalWindow = ({ visible, onWindowClose, children, styleType }) => { const stopPropagation = (event) => event.stopPropagation(); const button = ( <button className='modal__btn-close' onClick={onWindowClose} title='Close window' > <span>Close window</span> </button> ); let modalClassName = 'modal'; if (styleType) modalClassName += ` modal--${styleType}`; if (!visible) modalClassName += ` modal--hide`; const content = ( <div className={modalClassName}> <div className='modal__background'></div> <div className='modal__container' onClick={onWindowClose}> <div className='modal__content' onClick={stopPropagation}> <div className='modal__btns'> <div className='modal__close'>{button}</div> </div> <div className='modal__body'>{children}</div> </div> </div> </div> ); return ReactDOM.createPortal(content, document.getElementById('modal')); };
const { Post,User } = require('./models') const DataLoader = require('dataloader') const createUserLoader = () =>{ return new DataLoader( async (keys)=>{ const rows = await User.find({ _id:{ $in : keys} }) const results = keys.map((key) => { const matchRow = rows.find((row) => { return `${row._id}` === `${key}` }) return matchRow }) return results },{ cacheKeyFn: (key) => `${key}` }) } const createPostsByUserIdLoader = () =>{ return new DataLoader( async (userIds) =>{ const rows = await Post.find({ authorId: { $in : userIds} }) const results = userIds.map((userId) => { const matchRow = rows.filter((row) => { return `${row.authorId}` === `${userId}` }) return matchRow }) return results },{ cacheKeyFn: (userId) => `${userId}`}) } module.exports = { createUserLoader,createPostsByUserIdLoader }
var total = 0; var scorePoint = function() { total += 1; console.log(total); }; scorePoint(); scorePoint(); scorePoint(); //1 //2 //3 //sample var orderPizzas = function(numberPeople) { var numberPizzas = numberPeople / 3; console.log("You'll need to order " + numberPizzas + " pizzas."); }; orderPizzas(9); //You'll need to order 3 pizzas. function areBothEven(num1, num2) { if (num1 % 2 === 0 && num2 % 2 === 0) { return true; } else { return false; } } console.log(areBothEven(2, 4)); //true var categorize = function(number) { if (number < 8) { return 8; } number += 3; if (number < 15) { return number; } return 100; }; console.log(categorize(10)); //13, if num is 12, will return 100, look through step by step to meet different condition, return is exiting function
export const RELOAD_FLOCK_LIST = 'RELOAD_FLOCK_LIST'; export const LOAD_FLOCK = 'LOAD_FLOCK';
// JavaScript Document function change_status(id,tbl){ var tbl1234 = "'"+tbl+"'"; if(id>0) { if(confirm('Do you really want to change the status ?')) { $.ajax({ dataType: "html", type: "POST", url: 'change_status.php?id='+id+'&tbl='+tbl, data: 'id='+id+'&tbl='+tbl, success: function(data){ if(data==1) { $("#status"+id).html('<a href="#status'+id+'" align="center" class="btn btn-success tooltips" onclick="change_status('+id+','+tbl1234+');" data-original-title="Go for In-Active Status" rel="tooltip"><i class="icon-ok"></i></a>'); } else if(data==0) { $("#status"+id).html('<a href=""#status'+id+'" align="center" class="btn btn-danger tooltips" onclick="change_status('+id+','+tbl1234+');" data-original-title="Go for Active Status" rel="tooltip"><i class="icon-remove"></i></a>'); } } }); } } else { alert("Invalid record ID."); } } function delete_record(id,tbl){ if(id>0) { if(confirm('Do you really want to delete this record ?')) { $.ajax({ dataType: "html", type: "POST", url: 'delete_record.php?id='+id+'&tbl='+tbl, data: 'id='+id+'&tbl='+tbl, success: function(data){ $("#row"+id).html('<p></p>'); } }); } } else { alert("Invalid record ID."); } } function trash_record(id,tbl){ if(id>0) { if(confirm('Do you really want to move trash this record ?')) { $.ajax({ dataType: "html", type: "POST", url: 'trash_record.php?id='+id+'&tbl='+tbl, data: 'id='+id+'&tbl='+tbl, success: function(data){ $("#row"+id).html('<p></p>'); } }); } } else { alert("Invalid record ID."); } } function alphaonly(myname){ $('#'+myname).val( $('#'+myname).val().replace(/[^a-z A-Z]/g,'') ) ; } function onlynewmwric(myname){ $('#'+myname).val( $('#'+myname).val().replace(/[^\d]/ig, '')); } function allowflote(myname){ $('#'+myname).val( $('#'+myname).val().replace(/[^\d.]/ig, '')); }
var fs = require('fs'); var events = require('events'); var exec = require('exec'); var EventEmitter = events.EventEmitter; var ee = new EventEmitter(); /* // Step 1. Gather all the // 1. Regions // 2. Areas // 3. Boulders a. Boulders b. Walls // 4. Trails // 5. Places */ var kmlDirectory = "D:/directedStudy/server/apache2/htdocs/cragmaps/data/Hueco/kml/"; var jsonDirectory = "D:/directedStudy/server/apache2/htdocs/cragmaps/data/Hueco/json/"; var regionsDir = "regions/"; var areasDir = "areas/"; var boulders_bouldersDir = "boulders/boulders/"; var boulders_wallsDir = "boulders/walls/"; var trailsDir = "trails/"; var placesDir = "places/" var regions = []; var areas = []; var boulders_boulders = []; var boulders_walls = []; var trails = []; var places = []; fs.readdir(kmlDirectory + regionsDir, function (err, files) { regions = files; ee.emit("regionsDone"); }); fs.readdir(kmlDirectory + areasDir, function (err, files) { areas = files; ee.emit("areasDone"); }); fs.readdir(kmlDirectory + boulders_bouldersDir, function (err, files) { boulders_boulders = files; ee.emit("bbDone"); }); fs.readdir(kmlDirectory + boulders_wallsDir, function (err, files) { boulders_walls = files; ee.emit("bwDone"); }); fs.readdir(kmlDirectory + trailsDir, function (err, files) { trails = files; ee.emit("trailsDone"); }); fs.readdir(kmlDirectory + placesDir, function (err, files) { places = files; ee.emit("placesDone"); }); /* 2. convert each new .kml file to individual .json files // ogr2ogr -f GeoJSON geojson.json Areas.kml */ function convertToJSON(files, location, callback) { for(var i = 0; i < files.length; i++) { // remove the kml extension to retrieve the filename var fileName = files[i].substring(0, files[i].length - 4); console.log('ogr2ogr', '-f', "GeoJSON", "\"" + jsonDirectory + location + fileName + ".json\"", "\"" + kmlDirectory + location + files[i] + "\""); exec(['ogr2ogr', '-f', "GeoJSON", "\"" + jsonDirectory + location + fileName + ".json\"", "\"" + kmlDirectory + location + files[i] + "\""], function(err, out, code) { if (err instanceof Error) throw err; process.stderr.write(err); process.stdout.write(out); process.exit(code); if(i == (files.length - 1)) { console.log("Done converting " + location); } }); } } ee.on("regionsDone", function () { convertToJSON(regions, regionsDir); }); ee.on("areasDone", function () { convertToJSON(areas, areasDir); }); ee.on("bbDone", function () { convertToJSON(boulders_boulders, boulders_bouldersDir); }); ee.on("bwDone", function () { convertToJSON(boulders_walls, boulders_wallsDir); }); ee.on("trailsDone", function () { convertToJSON(trails, trailsDir); }); ee.on("placesDone", function () { convertToJSON(places, placesDir); }); /* 3. Merge: 1. all regions: regions.json 2. all areas: areas.json 3. all boulders: -boulders: boulders_boulders.json -walls: boulders_Walls.json */
const db = require('../../utils/db') const app = getApp() Page({ data: { review: {} }, onLoad: function () { this.getRandomReview() }, showMovie() { wx.navigateTo({ url: '/pages/detail/detail?id=' + this.data.review.movie._id, }) }, showReview() { wx.navigateTo({ url: '/pages/reviews/show/show?id=' + this.data.review._id, }) }, getRandomReview() { wx.showLoading({ title: '数据加载中' }) db.getRandomReview().then(res => { wx.hideLoading() this.setData({ review: res.result }) }).catch(err => { console.log(err) wx.hideLoading() wx.showToast({ icon: 'none', title: '获取数据失败' }) }) } })
function post_add() { var ip_title = $('#ip_title').val(); var ip_context = $('#ip_context').val(); var csrf_token = $('#csrf_token').html(); console.log('ip_title = ', ip_title); console.log('ip_context = ', ip_context); $.post("/api_post_add", { ip_title: ip_title, ip_context: ip_context, csrfmiddlewaretoken: csrf_token }) .done(function (data) { console.log('data.result = ', data.result); if (data.result == 'success') { alert('글을 작성하셨습니다.'); window.location.href = "/"; } }); }
const express = require('express') const router = express.Router() const { getTodos, postTodo } = require('./controllers/todoController.js'); router.get('/todos', getTodos); router.post('/todos', postTodo); module.exports = router;
'use strict'; angular.module('waitListApp.auth', [ 'waitListApp.constants', 'waitListApp.util', 'ngCookies', 'ui.router' ]) .config(function($httpProvider) { $httpProvider.interceptors.push('authInterceptor'); });
import React from "react"; import Grid from "@material-ui/core/Grid"; import InputLabel from "@material-ui/core/InputLabel"; import FormControl from "@material-ui/core/FormControl"; import Select2 from "react-select"; import withStyles from "@material-ui/core/styles/withStyles"; import "react-select/dist/react-select.css"; import GridItem from "../../components/Grid/GridItem"; import Card from "../../components/Card/Card"; import CardBody from "../../components/Card/CardBody"; import CardHeader from "../../components/Card/CardHeader"; import CustomInput from "../../components/CustomInput/CustomInput"; import Validator from "../../helpers/validator"; import Creatable from "../../../node_modules/react-select/lib/Creatable"; import BezopEditor from "../../bezopComponents/Editor/BezopEditor"; // The component Style const styles = theme => ({ root: { display: "flex", flexWrap: "wrap", }, formControl: { width: "100%", margin: "0px", }, selectEmpty: { marginTop: theme.spacing.unit * 2, }, input: { display: "none", }, fluidButton: { ...theme.button, width: "100%", }, }); class CreateBlog extends React.Component { constructor(props) { super(props); // we use this to make the card to appear after the page has been rendered this.state = { blogDetails: props.blogDetails, selectedBlogKind: Validator.propertyExist(props.blogDetails, "kind") && props.blogDetails.kind !== "" ? { value: props.blogDetails.kind, label: props.blogDetails.kind.replace(/^\w/, c => c.toUpperCase()), } : null, blogKindSelect: `react-select-label-${Validator.propertyExist(props.blogDetails, "kind") && props.blogDetails.kind !== "" ? "visible" : "hidden"}`, selectedBlogTag: Validator.propertyExist(props.blogDetails, "tag") ? props.blogDetails.tag.map(tag => ({ value: tag, label: tag.replace(/^\w/, c => c.toUpperCase()), })) : [], blogTagSelect: `react-select-label-${Validator.propertyExist(props.blogDetails, "tag") && props.blogDetails.tag.length > 0 ? "visible" : "hidden"}`, }; } // Setting the state of all input feilds setBlogDetails = (type, value) => { const { setParentBlogDetails } = this.props; const { blogDetails } = this.state; const newblogDetails = JSON.parse(JSON.stringify(blogDetails)); newblogDetails[type] = value; this.setState({ blogDetails: newblogDetails, }); setParentBlogDetails(newblogDetails); } // Get the value of Input Element handleChange = (event) => { this.setBlogDetails(event.target.name, event.target.value); }; // This handles the blog kind select element handleBlogKindChange = (selectedBlogKind) => { this.setState({ selectedBlogKind }); const blogKind = selectedBlogKind !== null ? selectedBlogKind.value : ""; const kindSelect = `react-select-label-${selectedBlogKind !== null ? "visible" : "hidden"}`; this.setBlogDetails("kind", blogKind); this.setState({ blogKindSelect: kindSelect, }); } // This handles the blog kind select element handleBlogTagChange = (selectedBlogTag) => { this.setState({ selectedBlogTag }); this.filterSelectedOption("tag", selectedBlogTag, "blogTagSelect"); } filterSelectedOption = (type, options, selected) => { const newSelectedOpt = options.map(opt => opt.value); const currentStyle = `react-select-label-${options.length > 0 ? "visible" : "hidden"}`; this.setState({ [selected]: currentStyle, }); this.setBlogDetails(type, newSelectedOpt); } getJsonContent = (jsonData) => { this.setBlogDetails("content", JSON.stringify(jsonData)); } render() { const { classes } = this.props; const { blogDetails, blogKindSelect, selectedBlogKind, blogTagSelect, selectedBlogTag, } = this.state; return ( <div> <Card> <CardHeader color="primary"> <div> <h4> New Blog Post </h4> </div> <div> <p> Create New Blog Post </p> </div> </CardHeader> <CardBody> <Grid container> <GridItem xs={12} sm={12} md={12}> <CustomInput labelText="Blog Title" id="title" inputProps={{ value: blogDetails.title, name: "title", onChange: this.handleChange, }} formControlProps={{ fullWidth: true, required: true, }} /> </GridItem> <GridItem xs={12} sm={12} md={12}> <FormControl className={classes.formControl}> <InputLabel htmlFor="selectedBlogKind" className={blogKindSelect}>Type or Select Blog Kind</InputLabel> <Select2 id="selectedBlogKind" name="selectedBlogKind" value={selectedBlogKind} placeholder="Type or Select Blog Kind" onChange={this.handleBlogKindChange} options={[ { value: "post", label: "Post" }, { value: "news", label: "News" }, ]} /> </FormControl> </GridItem> <GridItem xs={12} sm={12} md={12}> <FormControl className={classes.formControl} style={{ marginTop: "15px" }}> <InputLabel htmlFor="selectedBlogTag" className={blogTagSelect}>Type or Select Blog Tags</InputLabel> <Creatable id="selectedBlogTag" name="selectedBlogTag" value={selectedBlogTag} multi placeholder="Type or Select Blog Tags" onChange={this.handleBlogTagChange} /> </FormControl> </GridItem> <GridItem xs={12}> <CustomInput labelText="Blog Summary" id="summary" formControlProps={{ fullWidth: true, }} inputProps={{ multiline: true, rows: 5, name: "summary", value: blogDetails.summary, onChange: this.handleChange, }} /> </GridItem> <GridItem xs={12}> <BezopEditor placeholder="Write blog post" getJsonContent={jsonData => this.getJsonContent(jsonData)} returnJson={blogDetails.content !== "" ? blogDetails.content : null} /> </GridItem> </Grid> </CardBody> </Card> </div> ); } } export default withStyles(styles)(CreateBlog);
import React, { Component } from 'react'; import './NavBar.css'; import { getData } from '../../helpers/API'; import { connect } from 'react-redux'; import { getAllData } from '../../actions/actions'; export class NavBar extends Component { componentDidMount() { this.props.salaries(); } render() { return ( <div className='nav-bar'> <img className="logo" src={require('../../assets/turing.png')} alt="logo" /> <h1 className='main-header'>Turing Salaries</h1> </div> ); } } export const mapStateToProps = (store) => { return { alumni: store.alumData }; }; export const mapDispatchToProps = (dispatch) => { return { salaries: (newData) => { dispatch(getAllData(newData)); } }; }; export default connect(mapStateToProps, mapDispatchToProps)(NavBar);
const express = require('express'); const router = express.Router(); const mongoose = require('mongoose'); const User = mongoose.model('User'); const Role = mongoose.model('Role'); const Branch = mongoose.model('Branch'); const auth = require('../../config/middlewares/authorization'); const { wrap: async } = require('co'); router.get('/',auth.requiresLogin, function (req, res) { res.render('index'); }); router.get('/login', function (req, res) { res.render('users/login'); }); router.get('/firstLogin', function (req, res) { res.render('users/signup', { user: new User(), }); }); router.get('/logout', function (req, res) { req.logout(); res.redirect('/login'); }); router.post('/firstLogin', async(function* (req, res) { const branch = new Branch({name:"Base"}); yield branch.save(); const role = new Role({name:"Base",rights:[1,2,3,4,5,6,7,8,9,10,11,12]}); yield role.save(); const user = new User(req.body); user.provider = 'local'; user.branchRoles = [{ branch:branch._id, roles:[role._id] }]; try { yield user.save(); req.logIn(user, err => { if (err) req.flash('info', 'Sorry! We are not able to log you in!'); return res.redirect('/'); }); } catch (err) { const errors = Object.keys(err.errors) .map(field => err.errors[field].message); res.render('users/signup', { title: 'Sign up', errors, user }); } })); module.exports = router;
import { useRef, useEffect, useState} from 'react' export default function Visualizer({mediaStream}) { let [audioCtx, _setAudioCtx] = useState(() => new AudioContext()) let [analyser, _setAnalyzer] = useState(() => { const analyser = audioCtx.createAnalyser(); analyser.fftSize = 32 return analyser }) const analyserCanvas = useRef(null); let data = new Uint8Array(analyser.frequencyBinCount) const audioSrc = audioCtx.createMediaStreamSource(mediaStream); const draw = (ctx) => { if (!analyserCanvas.current) return; ctx.clearRect(0, 0, analyserCanvas.current.width, analyserCanvas.current.height) let dataParm = [...data]; ctx.fillStyle = 'white'; //white background ctx.lineWidth = 4; //width of candle/bar ctx.strokeStyle = '#d5d4d5'; //color of candle/bar const space = analyserCanvas.current.width / dataParm.length; dataParm.forEach((value, i) => { ctx.beginPath(); ctx.moveTo(space * i, analyserCanvas.current.height); //x,y ctx.lineTo(space * i, analyserCanvas.current.height - (value * analyserCanvas.current.height / 256)); //x,y ctx.stroke(); }); }; const loopingFunction = (ctx) => { requestAnimationFrame(() => loopingFunction( ctx)); analyser.getByteFrequencyData(data); draw(ctx); }; useEffect(() => { audioSrc.connect(analyser); if (analyserCanvas.current) { const ctx = analyserCanvas.current.getContext('2d'); analyserCanvas.current.width = 100 analyserCanvas.current.height = 50 loopingFunction(ctx); } }) return( <canvas ref={analyserCanvas}></canvas> ); }
//Componentes requeridos por el enrutamiento de proveedores var proveedorM = require("../models/proveedor"); var express = require("express"); var router = express.Router(); /** * Obtiene la vista para dar de alta un proveedor * @var Request req - * @var Response res - * @return render - Vista con form para proveedor */ router.get('/alta-proveedor', function(req, res) { res.render("proveedor/altaProveedor"); }); /** * Obtiene la vista para consultar a los proveedores * @var Request req - * @var Response res - * @return render - Vista con tabla que contiene los datos de todos los proveedores */ router.get('/', function(req, res) { res.render("proveedor/consultaProveedor"); }); /** * Agrega un proveedor a la base de datos * @var Request req - * @var Response res - */ router.post('/alta-proveedor', function(req, res) { var proveedor = { nombre: req.body.nombre }; proveedorM.addOrUpdateProveedor(req.app.get('db') , proveedor,function(id){ console.log("Registro de proveedor exitoso"); }); res.redirect("/proveedor/consulta-proveedor"); }); /** * Agrega un proveedor a la base de datos * @var Request req - * @var Response res - */ router.post('/actualiza-proveedor', function(req, res) { var proveedor = { id_proveedor : req.body.id_proveedor, nombre: req.body.nombre }; proveedorM.addOrUpdateProveedor(req.app.get('db') , proveedor,function(id){ console.log("Registro de proveedor exitoso"); }); res.render("proveedor/altaProveedor"); }); module.exports = router;
import React from 'react'; import styles from './index.module.scss'; function MainAndSubTitle(props) { const { style, className, mainTitle, subTitle } = props; return ( <div className={`${styles.wrap} ${className}`} style={style} > <span>{mainTitle}</span> <i>{subTitle}</i> </div> ); } export default MainAndSubTitle;
module.exports = function(grunt) { 'use strict'; require('grunt-horde') .create(grunt) .demand('initConfig.projName', 'conjure') .demand('initConfig.instanceName', 'conjure') .demand('initConfig.klassName', 'Conjure') .loot('node-component-grunt') .loot('node-lib-grunt') .loot('node-bin-grunt') .loot('./config/grunt') .attack(); };
let platforms; let player; let cursors; let balls; let balls2; let score = 0; let scoreText; let evil; let evil2; let evil3; function collectStar(p, ball) { ball.disableBody(true, true); // Add and update the score score += 10; scoreText.setText(`Score: ${score}`); } function gameOver(p, ball) { player.disableBody(true, true); this.add.text(200, 150, 'Game Over!!!', { fontSize: '96px', fill: '#f02' }); } function preload() { this.load.image('sky', 'assets/sky.png'); this.load.image('brick1', 'assets/brick1.png'); this.load.image('brick2', 'assets/brick2.png'); this.load.image('brick3', 'assets/brick3.png'); this.load.image('bomb', 'assets/bomb.png'); this.load.image('evil', 'assets/evil.png'); } function create() { this.add.image(400, 300, 'sky'); platforms = this.physics.add.staticGroup(); platforms.create(0, 240, 'brick2').setScale(2, 1).refreshBody(); platforms.create(0, 320, 'brick2').setScale(2, 1).refreshBody(); platforms.create(430, 240, 'brick2').setScale(1.5, 1).refreshBody(); platforms.create(430, 320, 'brick2').setScale(1.5, 1).refreshBody(); platforms.create(750, 240, 'brick2'); platforms.create(750, 320, 'brick2'); platforms.create(200, 130, 'brick3').setScale(1, 1.3).refreshBody(); platforms.create(200, 450, 'brick3').setScale(1, 1.5).refreshBody(); platforms.create(300, 130, 'brick3').setScale(1, 1.3).refreshBody(); platforms.create(300, 450, 'brick3').setScale(1, 1.5).refreshBody(); platforms.create(560, 130, 'brick3').setScale(1, 1.3).refreshBody(); platforms.create(560, 450, 'brick3').setScale(1, 1.5).refreshBody(); platforms.create(650, 130, 'brick3').setScale(1, 1.3).refreshBody(); platforms.create(650, 450, 'brick3').setScale(1, 1.5).refreshBody(); player = this.physics.add.sprite(100, 280, 'brick1'); player.body.setAllowGravity(false); evil = this.physics.add.sprite(250, 10, 'evil'); evil.body.setAllowGravity(false); evil.setVelocityY(100); evil2 = this.physics.add.sprite(605, 700, 'evil'); evil2.body.setAllowGravity(false); evil2.setVelocityY(-120); evil3 = this.physics.add.sprite(-400, 280, 'evil'); evil3.body.setAllowGravity(false); evil3.setVelocityX(250); balls = this.physics.add.group({ key: 'bomb', repeat: 11, setXY: { x: 12, y: 280, stepX: 70 }, allowGravity: false, }); balls2 = this.physics.add.group({ key: 'bomb', repeat: 11, setXY: { x: 250, y: 12, stepY: 70 }, allowGravity: false, }); this.physics.add.overlap(player, evil, gameOver, null, this); this.physics.add.overlap(player, evil2, gameOver, null, this); this.physics.add.overlap(player, evil3, gameOver, null, this); this.physics.add.overlap(player, balls, collectStar, null, this); this.physics.add.overlap(player, balls2, collectStar, null, this); this.physics.add.collider(player, platforms); scoreText = this.add.text(16, 16, 'score: 0', { fontSize: '42px', fill: '#fff' }); cursors = this.input.keyboard.createCursorKeys(); } function update() { if (cursors.left.isDown) { player.setVelocityX(-200); } else if (cursors.right.isDown) { player.setVelocityX(200); } else if (cursors.up.isDown) { player.setVelocityY(-200); } else if (cursors.down.isDown) { player.setVelocityY(200); } else { // player.setVelocityX(0); // player.setVelocityY(0); } } const config = { type: Phaser.AUTO, width: 800, height: 600, scene: { preload, create, update, }, physics: { default: 'arcade', arcade: { gravity: { y: 300 }, debug: false, }, }, }; // eslint-disable-next-line no-unused-vars const game = new Phaser.Game(config);
const axios = require('axios'); const allPrompts = require('../app/prompts'); const BaseGenerator = require('../app/base-generator'); function fetchAndWriteGitignore(language, fs, gitignorePath, logError) { const url = `https://raw.githubusercontent.com/github/gitignore/master/${language}.gitignore`; return axios.get(url).then((response) => { let fileContents = fs.read(gitignorePath, { defaults: '' }); fileContents += `\n\n# === ${language} ===\n${response.data}`; fs.write(gitignorePath, fileContents); }).catch(logError); } function languagesAlreadyPresent(filePath, fs) { const languages = new Set(); const fileContents = fs.read(filePath, { defaults: '' }); const search = /^# === ([^=]+) ===$/gm; let match = search.exec(fileContents); while (match !== null) { languages.add(match[1]); match = search.exec(fileContents); } return languages; } module.exports = class extends BaseGenerator { constructor(args, opts) { super(args, opts); this.prompts = [allPrompts.languages]; } prompting() { return this.askAndSavePrompts(); } writing() { const filePath = this.destinationPath('.gitignore'); const existingLanguages = languagesAlreadyPresent(filePath, this.fs); const requests = this.config.get('languages') .filter(language => !existingLanguages.has(language)) .map(language => fetchAndWriteGitignore( language, this.fs, this.destinationPath('.gitignore'), this.env.error.bind(this.env))); return Promise.all(requests); } };
import React, { useState } from 'react' import ViewYear from './ViewYear' import ViewMonth from './ViewMonth' import ViewWeek from './ViewWeek'; import ViewDay from './ViewDay'; import { VIEWS } from './constants'; import { SwitchButtons, ButtonContainer } from './ViewContainer.style' const ViewContainer = () => { const [viewIndex, setViewIndex] = useState(VIEWS.DAY); const [year, setYear] = useState(2022); const [monthIndex, setMonthIndex] = useState(8); const [dayNumberInMonth, setDayNumberInMonth] = useState(1); const onClickMonth = (year, monthIndex) => { setYear(year); setMonthIndex(monthIndex); setViewIndex(VIEWS.MONTH); } const renderView = () => { switch (viewIndex) { case VIEWS.YEAR: return <ViewYear onClickMonth={onClickMonth} />; case VIEWS.MONTH: return <ViewMonth monthIndex={monthIndex} defaultYear={year} setYear={setYear} />; case VIEWS.WEEK: return <ViewWeek monthIndex={monthIndex} defaultYear={year} />; case VIEWS.DAY: return <ViewDay monthIndex={monthIndex} defaultYear={year} day={dayNumberInMonth} />; default: break; } } const switchView = viewId => setViewIndex(viewId); return ( <div> <SwitchButtons> <ButtonContainer onClick={() => switchView(VIEWS.YEAR)}><p>Year</p></ButtonContainer> <ButtonContainer onClick={() => switchView(VIEWS.MONTH)}><p>Month</p></ButtonContainer> <ButtonContainer onClick={() => switchView(VIEWS.WEEK)}><p>Week</p></ButtonContainer> <ButtonContainer onClick={() => switchView(VIEWS.DAY)}><p>Day</p></ButtonContainer> </SwitchButtons> <div> {renderView()} </div> </div> ) } export default ViewContainer;
import React from 'react'; import { StyleSheet, View, Alert, } from 'react-native'; import RNPlus from 'rnplus'; import List from '../../common/List.js'; import listData from './listData.js'; import { STYLE_ALL } from '../../common/styles.js'; import NavBar from 'rnx-ui-navbar'; const COLOR_NAVBAR_TEXT = '#fff'; const styles = StyleSheet.create({ navBar: { backgroundColor: 'pink', }, leftBtn: { flexDirection: 'row', alignItems: 'center', }, leftIcon: { color: COLOR_NAVBAR_TEXT, }, leftBtnText: { marginLeft: 5, color: COLOR_NAVBAR_TEXT, }, }); export default function () { return ( <View style={STYLE_ALL}> <NavBar style={styles.navBar} title="Base" /> <View style={{ flex: 1 }}> <List dataSource={listData} view={this} /> </View> </View> ); }
var express = require('express'); var redis = require('redis'); var _ = require('underscore'); //给华为的服务常常会占用内存暴增 OOM 把这个服务也并到../redis.js中试一下 //var redisOuter = require('../redis.js'); var app = express(); //var client = redis.createClient(6379, 'db01', {detect_buffers: true}); var client = redis.createClient(6379, 'db01', null); client.select(0); //Note that error is a special event type in node. If there are no listeners for an error event, node will exit client.on('error', function(err){ console.log('Error Happens: ' + err); }); client.on('end', function(end){ console.log('Node is Ending...'); }); //var server = require('http').createServer(app); app.use(express.bodyParser({})); app.listen(8085); console.log('监听Restful接口 Port: 8085'); var SUCCESS = 'RestfulAccessSuccess'; var FAILURE = 'RestfulAccessFailure'; var verify = function(p){ if(p.length === 11 && p.charAt(0) === '1'){ return p; }else if(p.length === 13 && p.substr(0, 2) === '86'){ return p.substr(2); }else{ return null; } }; //为了减轻Redis压力 只给返回Unreaded的信息 其余属性强制指定为0 返回值格式不变 //{ // "Result": { // "Unreaded": 3, // "Readed": 82, // "Deleted": 4, // "AccessSuccess": 140513938, // "AccessFailure": "17802" // } //} app.post('/', function(req, res){ var phoneNumber = req.body.phoneNumber; // console.log('Modify: ' + phoneNumber); if(phoneNumber != null && phoneNumber.constructor === String){ var obj = new Object(); phoneNumber = verify(phoneNumber); if(phoneNumber){ client.ZCARD(phoneNumber + 'U', function(e, r){ obj['Result'] = new Object(); // obj['Result'].UnReaded = r; //大小写要看仔细 obj['Result'].Unreaded = r; obj['Result'].Readed = 0; obj['Result'].Deleted = 0; obj['Result'].AccessSuccess = 0; obj['Result'].AccessFailure = 0; console.log('OK: ' + phoneNumber); res.send(obj); }); }else{ obj['Result'] = null; res.send(obj); } } }); // //app.post('/', function(req, res){ // var phoneNumber = req.body.phoneNumber; // console.log('Here: ' + phoneNumber); // //// redisOuter.hwRestful(phoneNumber, function(oo){ //// res.send(oo); //// }); // // if(phoneNumber != null && phoneNumber.constructor === String){ // var o = new Object(); // phoneNumber = verify(phoneNumber); //// console.log('解析的手机号码:' + phoneNumber); // if(phoneNumber){ // client.multi() // .ZCARD(phoneNumber + 'U') //Unreaded // .ZCARD(phoneNumber + 'R') //Readed // .ZCARD(phoneNumber + 'D') //Delete // .INCRBY(SUCCESS, 1) // .GET(FAILURE) // .exec(function(err, replies){ // if(err){ // client.INCRBY(FAILURE, 1); // o['Result'] = null; // res.send(o); // }else{ //// console.log(replies); // replies = _.map(replies, function(item){ // return item ? item : 0; // }); // o['Result'] = _.object(['Unreaded', 'Readed', 'Deleted', 'AccessSuccess', 'AccessFailure'], replies); //// console.log(o); // res.send(o); // //// client.end(); // } // }); // }else{ // client.INCRBY(FAILURE, 1); // o['Result'] = null; // res.send(o); // } // } //}); // app.get('/', function(req, res){ // console.log(req); // var p = req.params.phoneNumber; // console.log(req.route.params); // console.log( p); res.send('请用Post请求携带手机号码访问!!'); });
import _make from 'isotropic-make'; import _Error from 'isotropic-error'; import _InvalidInputError from './InvalidInputError'; import _InvalidTransformError from './InvalidTransformError'; import _MersenneTwister from '@dsibilly/mersenne-twister'; import _transformFunctions from './transforms'; import _transformKeys from './keys'; const _DiceTower = _make({ roll (query, invokedByParse) { if (!query) { throw new _InvalidInputError(); } if (typeof query === 'string') { query = this._parse(query); } const rolled = []; let calculations = [], carryFiller = [], cleaner, sumResult = false; while (rolled.length < query.quantity) { rolled.push(Math.floor((this._seedFunction() * query.sides) + 1)); } this._filler.push(rolled); try { calculations = query.transformations.reduce((previous, transformation) => { let transformationFunction, transformationAdditionalParameter, sumParam = false; if (typeof transformation === 'function') { transformationFunction = transformation; } else if (typeof transformation === 'string') { // 'sum' transformationFunction = _transformFunctions[transformation]; } else if (transformation instanceof Array) { // [ 'add', 3 ] if (transformation[0] instanceof Array) { sumResult = true; cleaner = transformation[1]; transformation = transformation[0]; } else if (transformation[1] instanceof Array) { sumParam = true; cleaner = transformation[0]; transformation = transformation[1]; } transformationFunction = _transformFunctions[transformation[0]]; // fn for 'add' transformationAdditionalParameter = transformation[1]; } else { // Invalid transform type throw new _Error({ details: { transformation }, message: 'Inavlid transformation' }); } if (sumParam && previous[0] instanceof Array) { previous[0] = _transformFunctions[cleaner](previous[0]); } previous.unshift(transformationFunction(previous[0], transformationAdditionalParameter)); return previous; }, [ rolled ]); } catch (error) { throw new _InvalidTransformError(error.details.transformation); } if (sumResult === true && calculations[0] instanceof Array) { calculations[1] = calculations[0]; calculations[0] = _transformFunctions[cleaner](calculations[0]); } if (!invokedByParse) { if (this._filler.length > 1) { this._filler.unshift(this._filler.pop()); } carryFiller = this._filler.length === 1 ? this._filler[0] : this._filler; this._filler = []; } return { calculations, input: query.hasOwnProperty('toString') ? query.toString() : query, result: calculations[0], rolled: carryFiller }; }, _init (seedFunction) { if (seedFunction) { this._seedFunction = seedFunction; } else { this.__generator = new _MersenneTwister(); this._seedFunction = () => this.__generator.random(); } this._filler = []; return this; }, _parse (diceString) { if (!_DiceTower.validate(diceString)) { throw new _InvalidInputError(diceString); } const match = _DiceTower._regex.exec(diceString), quantity = match[1], // 2d20+3 => 2 segments = diceString.split(/[+-]/u), sides = match[2], // 2d20+3 => 20 hasTransformation = !!match[3], // 2d20+3 => true transforms = []; let operator, opIndex = 0, outsideRoll, transformationParameter; if (segments[0].indexOf('b') !== -1) { // A bestOf query... transforms.push(_transformKeys[match[4]](parseInt(match[5], 10))); } for (let s = 1; s < segments.length; s += 1) { opIndex += segments[s - 1].length; operator = diceString[opIndex]; // 2d20+3 => '+' opIndex += 1; transformationParameter = segments[s]; // 2d20+3 => 3 if (transformationParameter.indexOf('d') === -1) { transforms.push(_transformKeys[operator](parseInt(transformationParameter, 10))); } else { // Transformation is another roll... outsideRoll = this.roll(transformationParameter, true); transforms.push(_transformKeys[operator](outsideRoll.result)); } } return { quantity: quantity ? parseInt(quantity, 10) : 1, sides: sides === '%' ? 100 : parseInt(sides, 10), toString () { return diceString; }, transformations: hasTransformation || transforms.length !== 0 ? transforms.length === 0 ? _transformKeys[match[4]](parseInt(match[5], 10)) : transforms : ['sum'] }; } }, { // Static properties and methods validate (diceString) { return _DiceTower._regex.test(diceString); }, _regex: /^(\d*)d(\d+|%)(([+\-/*bw])(\d+))?(([+\-/*])(\d+|(\d*)d(\d+|%)(([+\-/*bw])(\d+))?))*$/u }); export default _DiceTower;
const Student = require("../models/student"); exports.FetchStudentList = function () { return Student.find({}) .sort({ update_at: -1 }) .then(students => { console.log(students) return students }) .catch(err => { throw new Error(err.message) }); } exports.createStudent = function (studentObj) { let tempStudent = { name : studentObj.name, sex : studentObj.sex, address : studentObj.address, teacher: studentObj.teacher } return Student.create(tempStudent) .then(students => { return students }) .catch(err => { return errorHandler(err) }); } exports.createStudentRand = function () { let tempStudent = { name : 'feng_' + new Date().getTime(), sex : [0, 1][Math.floor(Math.random()*2)], address : ['beijing', 'shanghai'][Math.floor(Math.random()*2)], teacher: '1001', } return Student.create(tempStudent) .then(students => { return students }) .catch(err => { return errorHandler(err) }); } exports.updateStudentById = function (id, data) { return Student.findOneAndUpdate( { _id: id }, { $set: { name: data.name, teacher: data.teacher, sex: data.sex, address: data.address } }, { new: true } ) .then(students => { return students }) .catch(err => { return errorHandler(err) }); } exports.delStudentById = function (id) { return Student.findOneAndRemove({ _id: id }) .then(students => { return students }) .catch(err => { return errorHandler(err) }); } exports.findStudentById = function (id) { return Student.findOne({ _id: id }) .then(students => { return students }) .catch(err => { return errorHandler(err) }); }
var legend = document.getElementById('legend'); mapboxgl.accessToken = 'pk.eyJ1Ijoid2Fsa21hcCIsImEiOiJjaXI0d285eXIwMDR1aHRtOWQ3YWE3d2JtIn0.pqyo1f-gocUK9i819vmQBQ'; var map = new mapboxgl.Map({ container: 'map', style: 'mapbox://styles/walkmap/cj0hn4l6t00bu2rn479399xfv', zoom: 9, center: [30.118430, 59.944354], minZoom: 8, maxZoom: 18, }); map.addControl(new mapboxgl.NavigationControl()); map.on('load', function () { toggleLayer('1', ['alldata'], 'Все музеи'); toggleLayer('2', ['children'], 'Музеи с детскими программами'); toggleLayer('3', ['7', '7bg'], 'Программы для дошкольников'); toggleLayer('4', ['7-18', '7-18bg'], 'Программы для школьников'); toggleLayer('5', ['family', 'familybg'], 'Семейные программы'); toggleLayer('6', ['education', 'educationbg'], 'Образовательные программы'); toggleLayer('7', ['dischildren', 'dischildrenbg'], 'Программы для детей с ограниченными возможностями'); toggleLayer('8', ['catering', 'cateringbg'], 'Кейтеринг'); toggleLayer('9', ['0', '1-5', '6-10', '11-20', '21-30', 'okruga_bound'], 'Музеи по муниципальным округам'); function toggleLayer(id, ids, name) { var link = document.createElement('a'); link.href = '#'; // link.className = 'active'; link.textContent = name; link.onclick = function (e) { e.preventDefault(); e.stopPropagation(); console.log(e.target, e); if (id == '9') { if (legend.style.display == 'block') { legend.style.display = 'none'; } else { legend.style.display = 'block'; } } for (layers in ids) { var visibility = map.getLayoutProperty(ids[layers], 'visibility'); if (visibility === 'visible') { map.setLayoutProperty(ids[layers], 'visibility', 'none'); this.className = ''; } else { this.className = 'active'; map.setLayoutProperty(ids[layers], 'visibility', 'visible'); } } }; var layers = document.getElementById('menu'); layers.appendChild(link); } var layers = ['0', '1-5', '6-10', '11-20', '21-30']; layers.forEach(function (layer) { var color = map.getPaintProperty(layer, 'fill-color'); var item = document.createElement('div'); var key = document.createElement('span'); key.className = 'legend-key'; key.style.backgroundColor = color; var value = document.createElement('span'); value.innerHTML = layer; item.appendChild(key); item.appendChild(value); legend.appendChild(item); }); }); var popup = new mapboxgl.Popup({ closeButton: false, closeOnClick: false }); map.on('mousemove', function (e) { var features = map.queryRenderedFeatures(e.point, { layers: ['0', '1-5', '6-10', '11-20', '21-30'] }); map.getCanvas().style.cursor = (features.length) ? 'pointer' : ''; if (!features.length) { popup.remove(); return; } popup .setLngLat(map.unproject(e.point)) .setHTML(features.map(function(feature) {return feature.properties.name})) .addTo(map); });
// == comparação implicita const numero = 5; const texto = "5"; console.log(numero === texto); console.log(numero == texto); console.log(typeof numreo); console.log(typeof texto); // == só compara o valor // === compara o valor e o tipo de dado
export default class ApiError { constructor(fetchResponse) { this.ok = false; this.response = fetchResponse; } }
import userService from "../services/userService.js"; const userController = { async signIn(req,res) { try{ const user = await userService.signInUser(req.body); return res.json(user); }catch (err){ res.status(500).json("Error Signing In") } }, async register(req,res) { try{ await userService.registerUser(req.body); return res.json("Success"); }catch (err){ return res.status(500).json("Failed"); } } }; export default userController;
import React, {useState} from 'react' function Products({name,price,parentFun, onCalculateTotal}) { const[quantity, setQuantity] = useState(0) // We are creating a state variable "qunatity" and set value 0. We can change this "quantity" state variable by setQuantity function const changeQuantity = ()=>{ setQuantity(quantity+1); } const yellowButton = { backgroundColor:"yellow", color:"red", padding:"5px 15px" } // const buyFun=()=>{ // alert("You selected this product!"); // } // const buyFun=()=>{ // onCalculateTotal(price); // }; return ( <div> <h1 style={{color:"red"}}>{name}</h1> <p>Price:${price}</p> {/* <button style={yellowButton} onClick={buyFun}>Buy</button> */} <button style={yellowButton} onClick={()=>onCalculateTotal(price)}>Buy</button> <h3>{quantity}</h3> <button onClick={changeQuantity}>Update quantity</button> <button onClick={() => parentFun(name)}>Call Parent Function</button> </div> ) } export default Products
/** * Created by May on 2015/8/5. */ //========= // 顶点 //========= function Vertex(label){ this.label = label; } //======== // 图(邻接表) //======== function Graph(v){ // 顶点数量 this.vertices = v; this.edges = 0; this.adj = []; this.marked = []; this.edgeTo = []; // 从一个顶点到下一个顶点的所有的边 this.pathTo = pathTo; this.hasPathTo = hasPathTo; this.dfs = dfs; // 深度搜索遍历顶点 this.bfs = bfs; // 广度搜索遍历顶点 for(var i = 0; i < this.vertices; ++i){ this.adj[i] = []; //this.adj[i].push(""); this.marked[i] = false; } this.addEdge = addEdge; this.toString = toString; } function addEdge(v, w){ this.adj[v].push(w); this.adj[w].push(v); this.edges++; } function toString(){ for(var i = 0; i < this.vertices; i++) { var str = i + " -> "; str += this.adj[i].join(" "); console.log(str); } } // 深度搜索指定顶点到目标顶点的路径 function dfs(v){ this.marked[v] = true; if(this.adj[v] != undefined) // 邻接表数组 console.log("Visited Vertex: " + v); for(var w in this.adj[v]){ if(!this.marked[this.adj[v][w]]) this.dfs(this.adj[v][w]); } } // 广度优先搜索函数 function bfs(s){ var queue = []; this.marked[s] = true; queue.push(s); while(queue.length > 0){ var v = queue.shift(); // 从队列首位删除 if(v != undefined){ console.log("Visited Vertex: " + v); } for(var w in this.adj[v]) { var val = this.adj[v][w]; if(!this.marked[val]){ this.edgeTo[val] = v; this.marked[val] = true; queue.push(val); } } } } // 存储与指定顶点有共同边的所有顶点 function pathTo(v){ var source = 0; if(!this.hasPathTo(v)){ return undefined; } var path = []; for(var i = v; i != source; i = this.edgeTo[i]){ path.push(i); } path.push(source); return path; } // function hasPathTo(v){ return this.marked[v]; } //================= // test //================= var g = new Graph(5); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 3); g.addEdge(2, 4); g.toString(); //g.dfs(0); console.log('\n================='); //g.bfs(0); /** * This book is absolutely shit! * Codes can't run properly * var paths = g.pathTo(2); console.log(paths); */
/** @format */ import React from "react"; import { useHistory } from "react-router-dom"; import "./home.css"; import heroSvg from "../../assets/images/hero.svg"; import startupImg from "../../assets/images/startup.jpg"; import mentorImg from "../../assets/images/mentor.png"; const Home = () => { const history = useHistory(); return ( <div className='container'> <div className='row align-items-center'> <div className='col-md-6'> <img className='img_100' style={{ padding: "30px" }} src={heroSvg} alt='hero' /> </div> <div className='col-md-6'> <h1 className='heroTitle'> We're In The Business Of Helping <br /> You Start Your <strong> Business</strong> </h1> </div> </div> <div className='row mt-100'> <div className='col-6'> <div className=' card' onClick={(e) => { history.push("/startup/login"); }} style={{ backgroundImage: `url("${startupImg}")`, }}> <h1>login as founder</h1> </div> </div> <div className='col-6'> <div className=' card' onClick={(e) => { history.push("/mentor/login"); }} style={{ backgroundImage: `url("${mentorImg}")`, }}> <h1>login as Mentor</h1> </div> </div> </div> </div> ); }; export default Home;
/* eslint-disable import/prefer-default-export */ import { cartTypes } from '../actions/cartActions'; import * as notify from '../../utils/notification'; const initialState = { books: [], }; export const cartReducer = (state = initialState, { type, payload }) => { switch (type) { case cartTypes.ADD_BOOK_SUCCESS: if (state.books.length > 0) { const existOrder = state.books.find(el => el.id === payload.id); if (existOrder) { return { ...state, books: [ ...state.books.filter(el => el.id !== payload.id), { ...payload, quantity: Number(payload.quantity) + Number(existOrder.quantity), totalPrice: Number(payload.totalPrice) + Number(existOrder.totalPrice), }, ], }; } return { ...state, books: [...state.books, payload], }; } return { ...state, books: [payload], }; case cartTypes.ADD_BOOK_ERROR: return { ...state }; case cartTypes.PURCHASE_REQUEST: return { ...state }; case cartTypes.PURCHASE_SUCCESS: notify.success('Thanks you for yor order!'); return { ...state, books: [], }; case cartTypes.PURCHASE_ERROR: notify.error('Something went wrong'); return { ...state }; default: return state; } };
Ext.ns('App'); App.createViewPersonalTasks = function() { var personalTasks = new Ext.grid.GridPanel({ id: 'personalTasks', title: App.locale['personalTasks.title'], x: 20, y: 20, width: 350, height: 250, loadMask: true, shim: true, viewConfig: { forceFit: true }, store: new Ext.data.JsonStore({ url: 'jbpm.do?action=personalTasks', root: 'result', fields: ['name', 'assignee', 'createTime', 'duedate', 'priority', 'description', 'dbid'] }), columns: [{ header: App.locale['viewTaskManagement.name'], dataIndex: 'name' }, { header: App.locale['viewTaskManagement.assignTo'], dataIndex: 'assignee' }, { header: App.locale['viewTaskManagement.createTime'], dataIndex: 'createTime' }, { header: App.locale['viewTaskManagement.duedate'], dataIndex: 'duedate' }, { header: App.locale['viewTaskManagement.priority'], dataIndex: 'priority' }, { header: App.locale['viewTaskManagement.description'], dataIndex: 'description' }], bbar: new Ext.Toolbar(['->', { text: App.locale['cancel'], handler: function() { var selections = personalTasks.getSelectionModel().getSelections(); if (selections.length == 1) { var record = selections[0]; Ext.Ajax.request({ url: 'jbpm.do?action=cancelTask', params: { id: record.get('dbid') }, success: function() { Ext.Msg.alert(App.locale['info'], App.locale['success']); personalTasks.getStore().reload(); groupTasks.getStore().reload(); } }); } } }, { text: App.locale['release'], handler: function() { var selections = personalTasks.getSelectionModel().getSelections(); if (selections.length == 1) { var record = selections[0]; Ext.Ajax.request({ url: 'jbpm.do?action=releaseTask', params: { id: record.get('dbid') }, success: function() { Ext.Msg.alert(App.locale['info'], App.locale['success']); personalTasks.getStore().reload(); groupTasks.getStore().reload(); } }); } } }]) }); personalTasks.getStore().load(); var groupTasks = new Ext.grid.GridPanel({ id: 'groupTasks', title: App.locale['groupTasks.title'], x: 400, y: 20, width: 350, height: 250, loadMask: true, shim: true, viewConfig: { forceFit: true }, store: new Ext.data.JsonStore({ url: 'jbpm.do?action=groupTasks', root: 'result', fields: ['name', 'assignee', 'createTime', 'duedate', 'priority', 'description', 'dbid'] }), columns: [{ header: App.locale['viewTaskManagement.name'], dataIndex: 'name' }, { header: App.locale['viewTaskManagement.assignTo'], dataIndex: 'assignee' }, { header: App.locale['viewTaskManagement.createTime'], dataIndex: 'createTime' }, { header: App.locale['viewTaskManagement.duedate'], dataIndex: 'duedate' }, { header: App.locale['viewTaskManagement.priority'], dataIndex: 'priority' }, { header: App.locale['viewTaskManagement.description'], dataIndex: 'description' }], bbar: new Ext.Toolbar(['->', { text: App.locale['take'], handler: function() { var selections = groupTasks.getSelectionModel().getSelections(); if (selections.length == 1) { var record = selections[0]; Ext.Ajax.request({ url: 'jbpm.do?action=takeTask', params: { id: record.get('dbid') }, success: function() { Ext.Msg.alert(App.locale['info'], App.locale['success']); personalTasks.getStore().reload(); groupTasks.getStore().reload(); } }); } } }]) }); groupTasks.getStore().load(); var panel = new Ext.Panel({ id: 'ViewPersonalTasks', title: App.locale['viewPersonalTasks.title'], iconCls: 'taskManagement', closable: true, layout: 'absolute', items: [personalTasks, groupTasks] }); return panel; };
// // precomputing a tpd file for topology optimization // // @param mesh - the initial volume to be optimized // (e.g., a connector made from a sphere with space carved out for the things it connects) // @param boundaryVertices - vertices specified as boundary // @param loadVertices - vertices specified as sustaining loads // @param loadAmnts - amounts of load corresponding to loadVertices // function preCompTpd(mesh, boundaryVertices, loadVertices, loadAmnts) { } // // a more compact way to call elm2nodes // function compactElm2Nodes(index) { var nelx = parseInt(gTpd['NUM_ELEM_X']); var nely = parseInt(gTpd['NUM_ELEM_Y']); var nelz = parseInt(gTpd['NUM_ELEM_Z']); if(isNaN(nelx) || isNaN(nely) || isNaN(nelz)) { console.error('check number of elements') } return elm2nodes(nelx, nely, nelz, index[0] + 1, index[1] + 1, index[2] + 1); } // // based on topy's nodenums.py // function elm2nodes(nelx, nely, nelz, mpx, mpy, mpz) { var innback = [0, 1, nely + 1, nely + 2]; var enback = nely * (mpx - 1) + mpy; var nnback = addScalar(innback, enback + mpx - 1); var nnfront = addScalar(nnback, (nelx + 1) * (nely + 1)); var nn = addScalar(nnfront.concat(nnback), (mpz - 1) * (nelx + 1) * (nely + 1)); log('Node numbers for ' + nelx + 'x' + nely + 'x' + nelz + ' 3D element at position x = ' + mpx + ',' + ' y = ' + mpy + ' and z = ' + mpz + ' :\n' + nn); log('Element number = ' + (enback + nelx * nely * (mpz - 1))); log('Highest node number in domain = ' + ((nelx + 1) * (nely + 1) * (nelz + 1))); return nn; } // // subroutine for adding a scalar to each element in an array // function addScalar(array, s) { var array2 = []; for (var i = array.length - 1; i >= 0; i--) { array2.push(array[i] + s); } return array2; }
/** * Date:01/04/2021 * Author: Muhammad Minhaj * Title: WEB HEADER * Description: Website head section * * */ import { useEffect, useRef } from 'react'; import { useSelector } from 'react-redux'; import LoadingBar from 'react-top-loading-bar'; function Header() { const ref = useRef(null); const { topLoadingProgress } = useSelector((state) => state).content; useEffect(() => { if (topLoadingProgress === true) { ref.current.continuousStart(); } else if (topLoadingProgress === false) { ref.current.complete(); } }, [topLoadingProgress]); return ( <> <LoadingBar color="#f11946" ref={ref} /> </> ); } export default Header;
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const Frame_1 = require("./Frame"); const ContainerFactory_1 = require("../utilities/ContainerFactory"); /** * うごイラ管理用オブジェクト */ class Ugoira { constructor(pixivJson, ugoiraMetaJson) { this.ugoiraContainerID = 'popup-ugoira'; this.pixivJson = pixivJson; this.ugoiraMetaJson = ugoiraMetaJson; } async init() { const innerContainer = this.innerContainer; let finished = false; const factory = new ContainerFactory_1.ContainerFactory(); innerContainer.textContent = null; const canvas = document.createElement('canvas'); canvas.id = this.ugoiraContainerID; canvas.className = this.className; this.ugoiraContainer = canvas; innerContainer.appendChild(canvas); let myHeaders = new Headers(); myHeaders.append("Accept-Encoding", "gzip, deflate, br"); myHeaders.append("Connection", 'keep-alive'); myHeaders.append("HOST", "www.pixiv.net"); const myInit = { method: 'GET', headers: myHeaders, mode: 'same-origin', credentials: 'same-origin', cache: 'default' }; // @ts-ignore let zip = new JSZip(); //const ugoira = new Ugoira() const frames = this.ugoiraMetaJson.body.frames; // const ImgElem: HTMLImageElement = document.createElement('img') const frameData = new Frame_1.Frame(); const zipData = await fetch(this.ugoiraMetaJson.body.src, { method: 'GET', headers: myHeaders, mode: 'cors', keepalive: true }).then(response => { if (response.ok) { return response.blob(); } }).then(async (zipData) => { await zip.loadAsync(zipData, { base64: true }); }).then(() => { for (let i = 0; i < frames.length; i++) { zip.file(frames[i].file) .async("base64", function updateCallback(metadata) { // console.log("progression: " + metadata.percent.toFixed(2) + " %"); if (metadata.percent === 100) { finished = true; } }) .then(function success(content) { frameData.pushImgString(`data:image/jpeg;base64,${content}`); }, function error(e) { console.log("download error."); }); } }).then(() => { this.frameData = frameData; }); } setScreenContainer(innerContainer) { this.innerContainer = innerContainer; } resize(elem, scale) { const oldWidth = this.pixivJson.body.width; const oldHeight = this.pixivJson.body.height; let newWidth = oldWidth; let newHeight = oldHeight; if (oldHeight > window.innerHeight * scale || oldWidth > window.innerWidth * scale) { const heightScale = oldHeight / Number(window.innerHeight * scale); const widthScale = oldWidth / Number(window.innerWidth * scale); if (heightScale > widthScale) { newHeight /= heightScale; newWidth /= heightScale; } else { newHeight /= widthScale; newWidth /= widthScale; } } this.ugoiraContainer.width = newWidth; this.ugoiraContainer.height = newHeight; elem.style.width = `${Math.round(newWidth)}px`; elem.style.height = `${Math.round(newHeight)}px`; } popup(outerContainer) { const frameArray = this.frameData.frameArray; const stringArray = this.frameData.imgStringArray; const img = new Image(); let index = 0; const counter = () => { img.src = stringArray[index]; const context = this.ugoiraContainer.getContext('2d'); //座標(10, 10)の位置にイメージを表示 context.drawImage(img, 0, 0, this.ugoiraContainer.clientWidth, this.ugoiraContainer.clientHeight); if (outerContainer.style.display !== 'none') { setTimeout(counter, this.ugoiraMetaJson.body.frames[index].delay); index += 1; index = index === stringArray.length ? 0 : index; } }; counter(); } setClassName(className) { this.className = className; } } //imageElement配列 Ugoira.imgArray = []; //imageElementのsrc文字列の配列 Ugoira.imgStringArray = []; exports.Ugoira = Ugoira;
import React from 'react'; import { Link } from 'react-router'; import RankingItem from './ranking_item'; import Infinite from 'react-infinite'; export default class Rankings extends React.Component { constructor(props){ super(props); this.fetching = false; this.state = {summoners: [], isInfiniteLoading: false,}; this.paginationInit(); } paginationInit(){ this.over = false; this.offset = 0; this.limit = 50; } currentQueue(){ return window.location.hash.split('/')[2] || "solo_5x5"; } componentDidMount(){ $(document).scrollTop(0); } updateSummoners(entries){ this.setState({summoners: this.state.summoners.concat(entries)}); } // Ensures component updates state when revisiting. componentWillMount(){ if(this.props.rank.entries){ const entries = this.throttleEntries(this.props.rank.entries); this.updateSummoners(entries); } } // Styling for queue headers componentDidUpdate(){ $('.queues > a').removeAttr('id', 'current-queue'); $(`.${this.currentQueue()}`).attr('id','current-queue'); } // Ensures component updates state on page refresh or first enter(offset = 50) componentWillReceiveProps(newProps){ this.fetching = false; //Notify #currentBatch that slice has been updated. if (!newProps.rank.entries) return; // Function also gets called on //internal state change. newProps might be empty. // First condition will be satisfied when changing routes if (newProps.rank.queue !== this.props.rank.queue){ this.paginationInit(); this.setState({summoners: this.throttleEntries(newProps.rank.entries)}); } else if (this.offset === 50) { return; } else if (newProps.rank.entries){ const entries = this.throttleEntries(newProps.rank.entries); this.updateSummoners(entries); } } elementInfiniteLoad(){ if (this.state.over){ return ( <div>Nothing more to show</div> ); } else { return ( <div className="infinite-list-item"> Loading... </div> ); } } // Handles pagination. No need to hit DB for new summoners. All are retrieved // in initial call so pagination logic can be handled locally throttleEntries(entries){ const offset = this.offset; const limit = this.limit; this.offset += 50; this.limit += 50; return entries.slice(offset, limit); } // this.fetching is utilized to signal if the ajax call is currently underway currentBatch(entries){ if (this.fetching) return []; const numOfEntries = this.props.rank.entries.length; // Challenger ranking only holds up to 203 players if(this.offset >= numOfEntries && !this.over) { this.fetching = true; this.props.fetchRankings("master"); return []; } else { return this.throttleEntries(entries); } } // Function is called when user has scroll to bottom of window. // Infinite component is oddly calling function before this condition is // satisfied. Added conditional early return to account for this case handleInfiniteLoad(){ console.log("loading"); if(!this.state.summoners.length) return; this.setState({isInfiniteLoading: true}); const newSummoners = this.currentBatch(this.props.rank.entries); if (newSummoners.length){ this.setState({ isInfiniteLoading: false, summoners: this.state.summoners.concat(newSummoners) }); } else { this.over = true; this.setState({isInfiniteLoading: false}); } } tier(idx){ return idx > 199 ? "master" : "challenger"; } render(){ window.that = this; return( <main className='rankings'> <div className='queues'> <Link className='solo_5x5' to='rankings'>RANKED_SOLO_5x5</Link> <Link className='flex_sr' to='rankings/flex_sr'>RANKED_FLEX_SR</Link> <Link className='flex_tt' to='rankings/flex_tt'>RANKED_FLEX_TT</Link> <Link className='team_5x5' to='rankings/team_5x5'> RANKED_TEAM_5x5 </Link> <Link className='team_3x3' to='rankings/team_3x3'> RANKED_TEAM_3x3 </Link> </div> <ul className='rankings-header'> <li className='name'>Name</li> <li>LP</li> <li>Tier</li> <li>Win Ratio</li> </ul> <Infinite elementHeight={21} useWindowAsScrollContainer infiniteLoadBeginEdgeOffset={200} onInfiniteLoad={() => this.handleInfiniteLoad()} loadingSpinnerDelegate={this.elementInfiniteLoad()} isInfiniteLoading={this.state.isInfiniteLoading}> {this.state.summoners.map((entry, idx) => { return ( <RankingItem key={idx} entry={entry} idx={idx + 1} tier={this.tier(idx)} queue={this.props.rank.queue}/> ); })} </Infinite> </main> ); } }
import { takeLatest, put } from 'redux-saga/effects'; import { API } from 'aws-amplify'; import log from '../../common/libs/logger'; import { PHOTO_FAV_GET_MANY } from '../actions/types'; import { photoFavSetMany } from '../actions'; export function* photoFavGetMany() { log.info('photoFavsGetMany fired...'); const promise = API.get('unsplashed', '/photo/get-many'); const result = yield promise; if (result) { log.info('[photoFavsGetMany] data received: ', result); yield put(photoFavSetMany(result)); } } export function* watchPhotoFavGetMany() { log.info('watchphotoFavsGetMany starting'); yield takeLatest(PHOTO_FAV_GET_MANY, photoFavGetMany); }
*** BASIC ALGORITHM SCRIPTING *** Convert celsius to farenheit: function convertToF(celsius) { let fahrenheit=celsius/5*9+32; return fahrenheit; } Reverse a string: function reverseString(str) { for(var reversedStr=[], i=str.length-1;i>=0;i--){ reversedStr += str[i]; } return reversedStr; } Factorialize a number: function factorialize(num) { var numb=1; for(let i=num;i>0;i--){ numb *= i; } return numb; } Find the longest word in a string: function findLongestWordLength(str) { var array = str.split(" "); var longestWord=array[0].length; for (let i=1; i<array.length;i++){ if(array[i].length>longestWord){ longestWord=array[i].length; } } return longestWord; } Return larger numbers in arrays: function largestOfFour(arr) { var largestArray=[arr[0][0],arr[1][0],arr[2][0],arr[3][0]]; for(let i=0;i<4;i++){ for(let j=1;j<arr[i].length;j++){ if(arr[i][j]>largestArray[i]){ largestArray[i]=arr[i][j]; } } } return largestArray; } Confirm the ending: function confirmEnding(str, target) { let string = str.split(''); let targ = target.split(''); let check = string.slice(string.length-targ.length,string.length); for(let i=0;i<targ.length;i++){ if(check[i]!=targ[i]){ return false; } } return true; } Repeat a string repeat a string: function repeatStringNumTimes(str, num) { var string = str.split(); if(num<1){ return ''; } else{ for(let i=1;i<num;i++){ string.push(str); } string=string.join(''); return string; } } Truncate a string: function truncateString(str, num) { var string=str.split(''); var result=[]; if(num>=string.length){ return str; } else{ for(let i=0;i<num;i++){ result[i]=string[i]; } result.push('...'); result=result.join(''); return result; } } Finders keepers: function findElement(arr, func) { for(let i=0;i<arr.length;i++){ if(func(arr[i])==true){ return arr[i]; } } } Boo who: function booWho(bool) { if(bool===true | bool===false){ return true;} else{ return false; } } Title case a sentence: function titleCase(str) { // transform all the string in lowercase // then replace in uppercase the pattern (beginning of string OR whitespace + non-whitespace)each return str.toLowerCase().replace(/(^|\s)\S/g, L=>L.toUpperCase()); } Slice and splice: function frankenSplice(arr1, arr2, n) { var arr3=[]; for(let i=0;i<n;i++){ arr3[i]=arr2[i]; } for(let i=0;i<arr1.length;i++){ arr3.push(arr1[i]); } for(let i=n;i<arr2.length;i++){ arr3.push(arr2[i]); } return arr3; } Falsy bouncer: function bouncer(arr) { var newArr=[]; for(let i=0;i<arr.length;i++){ if(arr[i]){ newArr.push(arr[i]); } } return newArr; } Where do I belong: function getIndexToIns(arr, num) { var result=0; for(let i=0;i<arr.length;i++){ if(num>arr[i]){ result++; } } return result; } Mutations: function mutation(arr) { var string1=arr[0].toLowerCase().split(''); let string2=arr[1].toLowerCase().split(''); for(let i=0;i<string2.length;i++){ if(string1.indexOf(string2[i])==-1){ return false; } } return true; } Chunky monkey: function chunkArrayInGroups(arr, size) { var newArr=[]; for(let i=0;i<arr.length/size;i++){ newArr[i]=arr.slice(size*i,i*size+size); } return newArr; }
import React, { Component } from 'react'; import FamousPeople from './famous_people/famousPeople'; import PeopleArray from './PeopleArray/PeopleArray'; class People extends Component { // handle anything about people [people [famousPeople][PeopleArray]] state = { person: { name: '', role: '', for: '' }, people: [ { name: 'Flavius Valerius Aurelius Constantinus Augustus', role: 'Roman Emperor', for: ' Romans conversion to Christianity' }, { name: 'Felicia Day', role: 'Codex', for: 'The Guild' } ] } handleChangeFor = (propertyName) => { return (event) => { this.setState( { person: { ...this.state.person, [propertyName]: event.target.value } } ) } } handleClick = (event) => { if (this.state.person.name === '' || this.state.person.for === '' || this.state.person.role === '') { // validation return alert('all the form not fill'); } console.log(this.state); let NewFamousPerson = this.state.person; // grab what is on the input this.setState( // add person to array { people: [ ...this.state.people, NewFamousPerson ] } ) this.setState( // clear input { person: { name: '', role: '', for: '' }, } ) } render() { return ( <div> <FamousPeople people={this.state.people} person={this.state.person} handleChangeFor={this.handleChangeFor} handleClick={this.handleClick} /> <PeopleArray people={this.state.people} /> </div> ); } } export default People
$(document).ready(function() { // different colour settings for graphs var palette1 = { fill: "steelblue", hover: "brown" }; var palette2 = { fill: "seagreen", hover: "darkorange" }; // set title for user defined graph var graphTitle = $("#userTitle"); $(graphTitle).append(searchData.from + " to " + searchData.to); // change graph according to dropdown choice var wrapperG = $(".graph_fields_wrap"); // wrapper for div containing graphs var selector = $("#timeSelect"); // dropdown graph menu ID // when the selection is changed in the dropdown menu do: $(selector).on("change", function(e) { // ignore default action for this event e.preventDefault(); // remove currently displayed graph, 1st child of div (1st graph is 0th) $($(wrapperG).children()[1]).remove(); // get value of currently selected var selectedVal = $(this).val(); // check value of selected // append new graph to wrapper div & run loadGraph to reprocess data if (selectedVal == "chart2") { $(wrapperG).append("<div class='col-lg-6'><h3 class='titles'>Top Ten Author Citations</h3><h4 class='titles'>" + searchData.from + " to " + searchData.to + "</h4><div class='chart2 well bs-component'></div></div>").loadGraph(topCitedYears, selectedVal, palette2); } else if (selectedVal == "chart4") { $(wrapperG).append("<div class='col-lg-6' id='tenYear'><h3 class='titles'>Top Ten Author Citations</h3><h4 class='titles'>(Last 10 years)</h4><div class='chart4 well bs-component'></div></div>").loadGraph(topCitedTen, selectedVal, palette2); } else if (selectedVal == "chart5") { $(wrapperG).append("<div class='col-lg-6' id='fiveYear'><h3 class='titles'>Top Ten Author Citations</h3><h4 class='titles'>(Last 5 years)</h4><div class='chart5 well bs-component'></div></div>").loadGraph(topCitedFive, selectedVal, palette2); } else if (selectedVal == "chart6") { $(wrapperG).append("<div class='col-lg-6' id='twoYear'><h3 class='titles'>Top Ten Author Citations</h3><h4 class='titles'>(Last 2 years)</h4><div class='chart6 well bs-component'></div></div>").loadGraph(topCitedTwo, selectedVal, palette2); } }); // Immediately Invoked Function Expression: allows '$' to work with any other plugins (function ($) { // add function to '$.fn' object (contains all jQuery object methods) $.fn.loadGraph = function(graphData, graphSelect, graphColour) { // establish some margins for the graph area to avoid overlap with other HTML elements var margin = { top: 30, right: 0, bottom: 180, left: 90 }; // initiate variables for max width and height of canvas for chart, determine largest citation value for domain and scaling // width, 10 bars at 75px each plus 3px padding & space for axis labelling var height = 300; var width = 510; // set a value for the number of authors in the dataset * width of one bar (420) var numAuthor = ((graphData.length) * 42); // maximum height of y axis is maximum number of citations/values (first element) if (graphSelect == "chart3") { var citedMaxY = graphData[0].values; } else { var citedMaxY = graphData[0].citations; } // set scale to alter data set so that it fits well in the canvas space // map the domain (actual data range) to the range (size of canvas) var citedLinearScale = d3.scale.linear() // 0 -> largest citations value .domain([0, citedMaxY]) // 0 -> 500 .range([0, height]); // create canvas for citations (user defined) chart var svgContainer = d3.select("." + graphSelect).append("svg") .attr("width", width) // max size from data set plus 20px margin .attr("height", height + margin.bottom); // create an SVG Grouped Element (<g>) to contain all the 'bars' of the graph var barGroup = svgContainer.append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); // bind the data to SVG Rectangle elements, set colours var citedBar = barGroup.selectAll("rect") .data(graphData) .enter() .append("rect") .attr("fill", graphColour.fill) // highlight each bar as you hover over it .on("mouseover", function () { d3.select(this) .attr("fill", graphColour.hover); }) // transition to remove highlight from bar .on("mouseout", function() { d3.select(this) .transition() .duration(250) .attr("fill", graphColour.fill); }) // when click on bar, performs Google search according to author name .on("click", function (d) { // variable stores url for google and adds author name relevant to bar that was clicked var url = "https://www.google.co.uk/#q=" + d.author1; // add an href html element with the url attached $(location).attr("href", url); window.location = url; }); // set variable to store bar width + padding var barWidth = 42; // set attributes for the rectangles (bars) var citedRect = citedBar.attr("width", 40) // set bar height by value of citations .attr("height", 0) // index * 78 will move each bar (width, 75px) one bar width along and leave 3px padding .attr("x", function (d, i) { return i * barWidth; }) // this is determined from the top left corner so to get the bar at the bottom, take the bar height from the canvas height .attr("y", function (d) { return height; }) // animated bars .transition() .delay(function (d, i) { return i * 100; }) .duration(200) .attr("y", function (d) { if (graphSelect == "chart3") { return height - citedLinearScale(d.values); } else { return height - citedLinearScale(d.citations); } }) .attr("height", function (d) { if (graphSelect == "chart3") { return citedLinearScale(d.values); } else { return citedLinearScale(d.citations); } }); // bind the data to SVG Text elements var citedText = barGroup.selectAll("text") .data(graphData) .enter() .append("text"); // set attributes for the text on bars (citation values) var citedLabels = citedText.attr("x", function (d, i) { return (barWidth * i) + 20; // sets to halfway between each bar horizontally }) .attr("y", function (d) { if (graphSelect == "chart3") { return height - (citedLinearScale(d.values)) -5; } else { return height - (citedLinearScale(d.citations)) - 5; // sets to top of each bar -3 to sit just above bar } }) .text(function (d) { if (graphSelect == "chart3") { return d.values; } else { return d.citations; // value to display, citations value (number) } }) .style("text-anchor", "middle") .attr("font-family", "Raleway") .attr("font-size", "18px") .attr("font-weight", "900") .attr("fill", graphColour.fill); //***** SCALES *****// // create a scale for the horizontal axis // creates a new ordinal scale (allows strings in domain) with empty domain and range var xScale = d3.scale.ordinal() // set input domain to specified values from data .domain(graphData.map(function (d) { return d.author1; })) // sets output range to fit number of authors, and therefore bars (0-780) .rangeBands([0, numAuthor]); // create a scale for the vertical axis var yScale = d3.scale.linear() .domain([0, citedMaxY]) .range([height, 0]); //***** AXES *****// // define x-axes var xAxis = d3.svg.axis() .scale(xScale) .orient("bottom") .ticks(10); // define y-axes var yAxis = d3.svg.axis() .scale(yScale) .orient("left") .ticks(10); //***** BAR & AXIS LABELLING *****// // if this calculation is done in "translate" below, it concatenates instead of adding values var translateY = height + margin.top; // create x-axes svgContainer.append("g") .attr("class", "axis") .attr("transform", "translate(" + margin.left + "," + translateY + ")") .call(xAxis) // select author names .selectAll("text") .attr("font-family", "Lora") .style("text-anchor", "end") // spacing .attr("dx", "-.8em") .attr("dy", ".15em") .attr("font-size", "14px") // rotate text as too long to display horizontally .attr("transform", function (d) { return "rotate(-45)"; }); // create y-axes svgContainer.append("g") .attr("class", "axis") .attr("transform", "translate(" + margin.left + "," + margin.top + ")") .call(yAxis) // append a title to the y-axis .append("text") .attr("transform", "rotate(-90)") .attr("y", -70) .attr("x", -50) .style("text-anchor", "end") .attr("fill", "#000") .attr("font-family", "Lora") .attr("font-size", "20px") // allows 'chaining', i.e. link multiple actions to single selector (e.g. '.attr' followed by '.css') // return this; }; } (jQuery)); // bubble chart (function ($) { $.fn.loadBubbles = function(graphData, graphSelect) { var width = 600; var height = 600; // create new pack layout as bubble var bubble = d3.layout.pack() .sort(null) .value(function (d) { return d.values; }) .size([width, height]); // .padding(3); // select chart3 div and append an svg canvas to draw the circles onto var canvas = d3.select(".chart3").append("svg") .attr("width", width) .attr("height", height) .append("g"); // create a tooltip var tooltip = d3.select("body") .append("div") .style("position", "absolute") .style("z-index", "10") .style("visibility", "hidden") .style("color", "white") .style("padding", "8px") .style("background-color", "rgba(0,0,0,0.75)") .style("border-radius", "6px") .style("font", "12px sans-serif") .text("tooltip"); // parse data for use with bubble chart jsonData = JSON.parse(topValued); // run bubble returning array of nodes associated with data // will output array of data with computed position of all nodes // and populates some data for each node: // depth, starting at 0 for root, x coord, y coord, radius var nodes = bubble.nodes(jsonData) // filter out the outer circle (root node) .filter(function (d) { return !d.children; }); var node = canvas.selectAll(".node") .data(nodes) .enter() .append("g") // give nodes a class name for referencing .attr("class", "node") .attr("transform", function (d) { return "translate(" + d.x + "," + d.y + ")"; }); // append the circle graphic for each node node.append("circle") // radius from data .attr("r", function (d) { return d.r; }) // colour circles according to associated values .attr("fill", function (d, i) { if (i == 0) { return "#5c0000"; } else if (i == 1) { return "#6b0000"; } else if (i == 2) { return "#7a0000"; } else if (i == 3) { return "#8a0000"; } else if (i == 4) { return "#990000"; } else if (i == 5) { return "#a31919"; } else if (i == 6) { return "#ad3333"; } else if (i == 7) { return "#b84d4d"; } else if (i == 8) { return "#c26666"; } else { return "#cc8080"; } }) // set stroke for circles // .attr("stroke", "#000") // .attr("stroke-width", 5) // display author name when hover over circle .on("mouseover", function (d) { tooltip.text(d.author1); tooltip.style("visibility", "visible"); }) // when move mouse around circle, keep tooltip affixed to same place relative to pointer .on("mousemove", function (d) { return tooltip.style("top", (d3.event.pageY-10)+"px").style("left", (d3.event.pageX+10)) }) .on("mouseout", function (d) { return tooltip.style("visibility", "hidden"); }) // when click on bar, performs Google search according to author name .on("click", function (d) { // variable stores url for google and adds author name relevant to bar that was clicked var url = "https://www.google.co.uk/#q=" + d.author1; // add an href html element with the url attached $(location).attr("href", url); window.location = url; }); // add author name to identify nodes node.append("text") .style("text-anchor", "middle") .style("font-family", "'Raleway', sans-serif") .style("font-weight", "bold") .style("font-size", "24px") .style("fill", "#000") .attr("dy", ".3em"); //.text(function (d) { // return d.children ? "" : d.values; // }); }; } (jQuery)); // load initial graphs to page $(".chart1").loadGraph($finalData->records, "chart1", palette1); $(".chart2").loadGraph(topCitedYears, "chart2", palette2); $(".chart3").loadBubbles(topValued, "chart3"); });
domReady(function () { const model = new Model(); ko.applyBindings(model, document.getElementById('app')); }); domReady(function () { console.log("hello"); });
// If importing something other than a .js(x) or .ts(x) file in Jest, // use this file to treat it as an empty object (eg: .css or .jpeg) module.exports = {};
import React, {Component} from 'react'; import Dialog from '@material-ui/core/Dialog'; import AppBar from '@material-ui/core/AppBar'; import {ThemeProvider as MuiThemeProvider} from '@material-ui/core/styles'; import {List, ListItem, ListItemText} from '@material-ui/core/'; import Button from '@material-ui/core/Button'; import axios from 'axios'; export class Confirm extends Component { state = {} save = e => { e.preventDefault(); alert("Your data has been submited succefully" + this.props.values.firstName) const config={ "Content-Type":"application/json" } const user = { first_name: this.props.values.firstName, last_name: this.props.values.lastName, email: this.props.values.email, phone_number: this.props.values.phone_number, id_number: 5 }; axios.post("/api/events/1/subs/",user,config) .catch(res => { console.log(res.response.data); }) } render() { const { values: { firstName, lastName, email, mobile, natioanlCardId, titleDocument, dateDocument, sourceDocument, descriptionDocument, attachDocument, ccp, visaId } } = this.props; return ( <MuiThemeProvider> <> <Dialog open fullWidth maxWidth='sm'> <AppBar title="Confirm User Data"/> <List> <ListItem> <ListItemText primary="First Name" secondary={firstName}/> </ListItem> <ListItem> <ListItemText primary="Last Name" secondary={lastName}/> </ListItem> <ListItem> <ListItemText primary="Mobile" secondary={mobile}/> </ListItem> <ListItem> <ListItemText primary="Natioanl Card Id" secondary={natioanlCardId}/> </ListItem> <ListItem> <ListItemText primary="Title Document" secondary={titleDocument}/> </ListItem> <ListItem> <ListItemText primary="Date Document" secondary={dateDocument}/> </ListItem> <ListItem> <ListItemText primary="Source Document" secondary={sourceDocument}/> </ListItem> <ListItem> <ListItemText primary="Description Document" secondary={descriptionDocument}/> </ListItem> <ListItem> <ListItemText primary="Attach Document" secondary={attachDocument}/> </ListItem> <ListItem> <ListItemText primary="Ccp" secondary={ccp}/> </ListItem> <ListItem> <ListItemText primary="visaId" secondary={visaId}/> </ListItem> </List> <br/> <Button color="primary" variant="contained" onClick={this.save}>Confirm & Continue</Button> </Dialog> </> </MuiThemeProvider> ); } } export default Confirm;
const depositspageCopy = { "en": { "TABLE": { "DEPOSITS": { "TITLE": "Deposits", "ITEMS": [ "Tx Hash", "Creation Date", "Amount", "Bonus Amount", "Status" ] } } }, "kr": { "TABLE": { "DEPOSITS": { "TITLE": "입금", "ITEMS": [ "Tx 해시", "생성일", "금액", "Bonus Amount", "상태" ] } } }, "ch": { "TABLE": { "DEPOSITS": { "TITLE": "充币", "ITEMS": [ "Tx 杂凑", "创建日期", "金额", "Bonus Amount", "状态" ] } } }, "jp": { "TABLE": { "DEPOSITS": { "TITLE": "Deposits", "ITEMS": [ "Tx Hash", "Creation Date", "Amount", "Bonus Amount", "Status" ] } } }, "ru": { "TABLE": { "DEPOSITS": { "TITLE": "Deposits", "ITEMS": [ "Хеш транзакции", "Дата создания", "Количество", "Бонусная сумма", "Статус" ] } } } } export default depositspageCopy;
var url = require('url'); var routeParser = require('./routes'); var Router = {}; Router.methods =[ 'get', 'post', 'put', 'patch', 'delete' ]; Router.routes = {}; var _extractPostData = (req, done) => { var body = ''; req.on('data', (data) => { body += data; }); req.on('end', () => { req.body = body; done(); }); } Router.methods.forEach((method) => { Router.routes[method] = Router.routes[method] || {}; Router[method] = (path, callback) => { Router.routes[method][path] = callback; } }); Router.routes['get'] = {}; Router.routes['get']['/foo/:bar'] = (req, res) => { res.end('GET /foo/:bar'); } Router.routes['get']['/foo/:bar/fiz/:baz'] = (req, res) => { res.end('GET /foo/:bar/fiz/:baz'); } Router.handle = (req, res) => { var method = req.method.toLowerCase(); var path = url.parse(req.url).pathname; var pathPattern; var availRoutes = Object.keys(Router.routes[method]); availRoutes.forEach( (pattern)=> { if ( routeParser.isMatching(path, pattern) ) { pathPattern = pattern; } }) console.log(pathPattern) console.log(req.method) req.params = routeParser.getParams(path, pathPattern); if (Router.routes[method][pathPattern]) { var p = new Promise( (resolve ) => { if (method !== 'get') { _extractPostData(req, resolve); } else { resolve(); } }); p.then( function() { Router.routes[method][pathPattern](req, res); }) } else { res.statusCode = 404; res.end('404 Not Found'); } }; module.exports = Router;
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'; import { getDataApiFromThunk } from '../../utils/common'; import { GetSettings, SetNoteImageScale } from '../../utils/db'; const initialState = { imageScale: 100, }; const noteSlice = createSlice({ name: 'note', initialState, reducers: { setImageScale: { reducer(state, action) { console.log('set image scale action: ', action); state.imageScale = action.payload.scale; SetNoteImageScale(state.imageScale); }, prepare(scale) { return { payload: { scale, }, }; }, }, }, }); export default noteSlice.reducer; export const initializeNoteSettings = createAsyncThunk( 'note/initializeSettings', async (data, thunkAPI) => { const s = await GetSettings(); if (!s) return; const { scale } = s; if (!scale) return; thunkAPI.dispatch(noteSlice.actions.setImageScale(scale)); } ); export const { setImageScale } = noteSlice.actions;
import indexesOf from 'indexes-of'; import uniq from 'uniq'; import Root from './selectors/root'; import Selector from './selectors/selector'; import ClassName from './selectors/className'; import Comment from './selectors/comment'; import ID from './selectors/id'; import Tag from './selectors/tag'; import Str from './selectors/string'; import Pseudo from './selectors/pseudo'; import Attribute from './selectors/attribute'; import Universal from './selectors/universal'; import Combinator from './selectors/combinator'; import Nesting from './selectors/nesting'; import sortAsc from './sortAscending'; import tokenize from './tokenize'; import * as tokens from './tokenTypes'; import * as types from './selectors/types'; function getSource (startLine, startColumn, endLine, endColumn) { return { start: { line: startLine, column: startColumn, }, end: { line: endLine, column: endColumn, }, }; } function ensureObject (obj, ...props) { while (props.length > 0) { const prop = props.shift(); if (!obj[prop]) { obj[prop] = {}; } obj = obj[prop]; } } function getProp (obj, ...props) { while (props.length > 0) { const prop = props.shift(); if (!obj[prop]) { return undefined; } obj = obj[prop]; } return obj; } export default class Parser { constructor (rule, options = {}) { this.rule = rule; this.options = Object.assign({lossy: false, safe: false}, options); this.position = 0; this.root = new Root(); this.root.errorGenerator = this._errorGenerator(); const selector = new Selector(); this.root.append(selector); this.current = selector; this.css = typeof this.rule === 'string' ? this.rule : this.rule.selector; if (this.options.lossy) { this.css = this.css.trim(); } this.tokens = tokenize({ css: this.css, error: this._errorGenerator(), safe: this.options.safe, }); this.loop(); } _errorGenerator () { return (message, errorOptions) => { if (typeof this.rule === 'string') { return new Error(message); } return this.rule.error(message, errorOptions); }; } attribute () { const attr = []; const startingToken = this.currToken; this.position ++; while ( this.position < this.tokens.length && this.currToken[0] !== tokens.closeSquare ) { attr.push(this.currToken); this.position ++; } if (this.currToken[0] !== tokens.closeSquare) { return this.expected('closing square bracket', this.currToken[5]); } const len = attr.length; const node = { source: getSource( startingToken[1], startingToken[2], this.currToken[3], this.currToken[4] ), sourceIndex: startingToken[5], }; if (len === 1 && !~[tokens.word].indexOf(attr[0][0])) { return this.expected('attribute', attr[0][5]); } let pos = 0; let spaceBefore = ''; let commentBefore = ''; let lastAdded = null; let spaceAfterMeaningfulToken = false; while (pos < len) { const token = attr[pos]; const content = this.content(token); const next = attr[pos + 1]; switch (token[0]) { case tokens.space: if ( len === 1 || pos === 0 && this.content(next) === '|' ) { return this.expected('attribute', token[5], content); } spaceAfterMeaningfulToken = true; if (this.options.lossy) { break; } if (lastAdded) { ensureObject(node, 'spaces', lastAdded); const prevContent = node.spaces[lastAdded].after || ''; node.spaces[lastAdded].after = prevContent + content; const existingComment = getProp(node, 'raws', 'spaces', lastAdded, 'after') || null; if (existingComment) { node.raws.spaces[lastAdded].after = existingComment + content; } } else { spaceBefore = spaceBefore + content; commentBefore = commentBefore + content; } break; case tokens.asterisk: if (next[0] === tokens.equals) { node.operator = content; lastAdded = 'operator'; } else if ((!node.namespace || (lastAdded === "namespace" && !spaceAfterMeaningfulToken)) && next) { if (spaceBefore) { ensureObject(node, 'spaces', 'attribute'); node.spaces.attribute.before = spaceBefore; spaceBefore = ''; } if (commentBefore) { ensureObject(node, 'raws', 'spaces', 'attribute'); node.raws.spaces.attribute.before = spaceBefore; commentBefore = ''; } node.namespace = (node.namespace || "") + content; const rawValue = getProp(node, 'raws', 'namespace') || null; if (rawValue) { node.raws.namespace += content; } lastAdded = 'namespace'; } spaceAfterMeaningfulToken = false; break; case tokens.dollar: case tokens.caret: if (next[0] === tokens.equals) { node.operator = content; lastAdded = 'operator'; } spaceAfterMeaningfulToken = false; break; case tokens.combinator: if (content === '~' && next[0] === tokens.equals) { node.operator = content; lastAdded = 'operator'; } if (content !== '|') { spaceAfterMeaningfulToken = false; break; } if (next[0] === tokens.equals) { node.operator = content; lastAdded = 'operator'; } else if (!node.namespace && !node.attribute) { node.namespace = true; } spaceAfterMeaningfulToken = false; break; case tokens.word: if ( next && this.content(next) === '|' && (attr[pos + 2] && attr[pos + 2][0] !== tokens.equals) && // this look-ahead probably fails with comment nodes involved. !node.operator && !node.namespace ) { node.namespace = content; lastAdded = 'namespace'; } else if (!node.attribute || (lastAdded === "attribute" && !spaceAfterMeaningfulToken)) { if (spaceBefore) { ensureObject(node, 'spaces', 'attribute'); node.spaces.attribute.before = spaceBefore; spaceBefore = ''; } if (commentBefore) { ensureObject(node, 'raws', 'spaces', 'attribute'); node.raws.spaces.attribute.before = commentBefore; commentBefore = ''; } node.attribute = (node.attribute || "") + content; const rawValue = getProp(node, 'raws', 'attribute') || null; if (rawValue) { node.raws.attribute += content; } lastAdded = 'attribute'; } else if (!node.value || (lastAdded === "value" && !spaceAfterMeaningfulToken)) { node.value = (node.value || "") + content; const rawValue = getProp(node, 'raws', 'value') || null; if (rawValue) { node.raws.value += content; } lastAdded = 'value'; ensureObject(node, 'raws'); const prevContent = getProp(node, 'raws', 'unquoted') || ''; node.raws.unquoted = prevContent + content; } else if (content === 'i') { if (node.value && (node.quoted || spaceAfterMeaningfulToken)) { node.insensitive = true; lastAdded = 'insensitive'; if (spaceBefore) { ensureObject(node, 'spaces', 'insensitive'); node.spaces.insensitive.before = spaceBefore; spaceBefore = ''; } if (commentBefore) { ensureObject(node, 'raws', 'spaces', 'insensitive'); node.raws.spaces.insensitive.before = commentBefore; commentBefore = ''; } } else if (node.value) { lastAdded = 'value'; node.value += 'i'; if (node.raws.value) { node.raws.value += 'i'; } } } spaceAfterMeaningfulToken = false; break; case tokens.str: if (!node.attribute || !node.operator) { return this.error(`Expected an attribute followed by an operator preceding the string.`, { index: token[5], }); } node.value = content; node.quoted = true; lastAdded = 'value'; ensureObject(node, 'raws'); node.raws.unquoted = content.slice(1, -1); spaceAfterMeaningfulToken = false; break; case tokens.equals: if (!node.attribute) { return this.expected('attribute', token[5], content); } if (node.value) { return this.error('Unexpected "=" found; an operator was already defined.', {index: token[5]}); } node.operator = node.operator ? node.operator + content : content; lastAdded = 'operator'; spaceAfterMeaningfulToken = false; break; case tokens.comment: if (lastAdded) { if (spaceAfterMeaningfulToken || (next && next[0] === tokens.space)) { const lastComment = getProp(node, 'spaces', lastAdded, 'after') || ''; const rawLastComment = getProp(node, 'raws', 'spaces', lastAdded, 'after') || lastComment; ensureObject(node, 'raws', 'spaces', lastAdded); node.raws.spaces[lastAdded].after = rawLastComment + content; } else { const lastValue = node[lastAdded] || ''; const rawLastValue = getProp(node, 'raws', lastAdded) || lastValue; ensureObject(node, 'raws'); node.raws[lastAdded] = rawLastValue + content; } } else { commentBefore = commentBefore + content; } break; default: return this.error(`Unexpected "${content}" found.`, {index: token[5]}); } pos ++; } this.newNode(new Attribute(node)); this.position ++; } combinator () { const current = this.currToken; if (this.content() === '|') { return this.namespace(); } const node = new Combinator({ value: '', source: getSource( current[1], current[2], current[3], current[4] ), sourceIndex: current[5], }); while ( this.position < this.tokens.length && this.currToken && (this.currToken[0] === tokens.space || this.currToken[0] === tokens.combinator)) { const content = this.content(); if (this.nextToken && this.nextToken[0] === tokens.combinator) { node.spaces.before = this.parseSpace(content); node.source = getSource( this.nextToken[1], this.nextToken[2], this.nextToken[3], this.nextToken[4] ); node.sourceIndex = this.nextToken[5]; } else if (this.prevToken && this.prevToken[0] === tokens.combinator) { node.spaces.after = this.parseSpace(content); } else if (this.currToken[0] === tokens.combinator) { node.value = content; } else if (this.currToken[0] === tokens.space) { node.value = this.parseSpace(content, ' '); } this.position ++; } return this.newNode(node); } comma () { if (this.position === this.tokens.length - 1) { this.root.trailingComma = true; this.position ++; return; } const selector = new Selector(); this.current.parent.append(selector); this.current = selector; this.position ++; } comment () { const current = this.currToken; this.newNode(new Comment({ value: this.content(), source: getSource( current[1], current[2], current[3], current[4] ), sourceIndex: current[5], })); this.position ++; } error (message, opts) { throw this.root.error(message, opts); } missingBackslash () { return this.error('Expected a backslash preceding the semicolon.', { index: this.currToken[5], }); } missingParenthesis () { return this.expected('opening parenthesis', this.currToken[5]); } missingSquareBracket () { return this.expected('opening square bracket', this.currToken[5]); } namespace () { const before = this.prevToken && this.content(this.prevToken) || true; if (this.nextToken[0] === tokens.word) { this.position ++; return this.word(before); } else if (this.nextToken[0] === tokens.asterisk) { this.position ++; return this.universal(before); } } nesting () { const current = this.currToken; this.newNode(new Nesting({ value: this.content(), source: getSource( current[1], current[2], current[3], current[4] ), sourceIndex: current[5], })); this.position ++; } parentheses () { const last = this.current.last; let balanced = 1; this.position ++; if (last && last.type === types.PSEUDO) { const selector = new Selector(); const cache = this.current; last.append(selector); this.current = selector; while (this.position < this.tokens.length && balanced) { if (this.currToken[0] === tokens.openParenthesis) { balanced ++; } if (this.currToken[0] === tokens.closeParenthesis) { balanced --; } if (balanced) { this.parse(); } else { selector.parent.source.end.line = this.currToken[3]; selector.parent.source.end.column = this.currToken[4]; this.position ++; } } this.current = cache; } else { last.value += '('; while (this.position < this.tokens.length && balanced) { if (this.currToken[0] === tokens.openParenthesis) { balanced ++; } if (this.currToken[0] === tokens.closeParenthesis) { balanced --; } last.value += this.parseParenthesisToken(this.currToken); this.position ++; } } if (balanced) { return this.expected('closing parenthesis', this.currToken[5]); } } pseudo () { let pseudoStr = ''; let startingToken = this.currToken; while (this.currToken && this.currToken[0] === tokens.colon) { pseudoStr += this.content(); this.position ++; } if (!this.currToken) { return this.expected(['pseudo-class', 'pseudo-element'], this.position - 1); } if (this.currToken[0] === tokens.word) { this.splitWord(false, (first, length) => { pseudoStr += first; this.newNode(new Pseudo({ value: pseudoStr, source: getSource( startingToken[1], startingToken[2], this.currToken[3], this.currToken[4] ), sourceIndex: startingToken[5], })); if ( length > 1 && this.nextToken && this.nextToken[0] === tokens.openParenthesis ) { this.error('Misplaced parenthesis.', { index: this.nextToken[5], }); } }); } else { return this.expected(['pseudo-class', 'pseudo-element'], this.currToken[5]); } } space () { const content = this.content(); // Handle space before and after the selector if ( this.position === 0 || this.prevToken[0] === tokens.comma || this.prevToken[0] === tokens.openParenthesis ) { this.spaces = this.parseSpace(content); this.position ++; } else if ( this.position === (this.tokens.length - 1) || this.nextToken[0] === tokens.comma || this.nextToken[0] === tokens.closeParenthesis ) { this.current.last.spaces.after = this.parseSpace(content); this.position ++; } else { this.combinator(); } } string () { const current = this.currToken; this.newNode(new Str({ value: this.content(), source: getSource( current[1], current[2], current[3], current[4] ), sourceIndex: current[5], })); this.position ++; } universal (namespace) { const nextToken = this.nextToken; if (nextToken && this.content(nextToken) === '|') { this.position ++; return this.namespace(); } const current = this.currToken; this.newNode(new Universal({ value: this.content(), source: getSource( current[1], current[2], current[3], current[4] ), sourceIndex: current[5], }), namespace); this.position ++; } splitWord (namespace, firstCallback) { let nextToken = this.nextToken; let word = this.content(); while ( nextToken && ~[tokens.dollar, tokens.caret, tokens.equals, tokens.word].indexOf(nextToken[0]) ) { this.position ++; let current = this.content(); word += current; if (current.lastIndexOf('\\') === current.length - 1) { let next = this.nextToken; if (next && next[0] === tokens.space) { word += this.parseSpace(this.content(next), ' '); this.position ++; } } nextToken = this.nextToken; } const hasClass = indexesOf(word, '.'); let hasId = indexesOf(word, '#'); // Eliminate Sass interpolations from the list of id indexes const interpolations = indexesOf(word, '#{'); if (interpolations.length) { hasId = hasId.filter(hashIndex => !~interpolations.indexOf(hashIndex)); } let indices = sortAsc(uniq([0, ...hasClass, ...hasId])); indices.forEach((ind, i) => { const index = indices[i + 1] || word.length; const value = word.slice(ind, index); if (i === 0 && firstCallback) { return firstCallback.call(this, value, indices.length); } let node; const current = this.currToken; const sourceIndex = current[5] + indices[i]; const source = getSource( current[1], current[2] + ind, current[3], current[2] + (index - 1) ); if (~hasClass.indexOf(ind)) { node = new ClassName({ value: value.slice(1), source, sourceIndex, }); } else if (~hasId.indexOf(ind)) { node = new ID({ value: value.slice(1), source, sourceIndex, }); } else { node = new Tag({ value, source, sourceIndex, }); } this.newNode(node, namespace); // Ensure that the namespace is used only once namespace = null; }); this.position ++; } word (namespace) { const nextToken = this.nextToken; if (nextToken && this.content(nextToken) === '|') { this.position ++; return this.namespace(); } return this.splitWord(namespace); } loop () { while (this.position < this.tokens.length) { this.parse(true); } return this.root; } parse (throwOnParenthesis) { switch (this.currToken[0]) { case tokens.space: this.space(); break; case tokens.comment: this.comment(); break; case tokens.openParenthesis: this.parentheses(); break; case tokens.closeParenthesis: if (throwOnParenthesis) { this.missingParenthesis(); } break; case tokens.openSquare: this.attribute(); break; case tokens.dollar: case tokens.caret: case tokens.equals: case tokens.word: this.word(); break; case tokens.colon: this.pseudo(); break; case tokens.comma: this.comma(); break; case tokens.asterisk: this.universal(); break; case tokens.ampersand: this.nesting(); break; case tokens.combinator: this.combinator(); break; case tokens.str: this.string(); break; // These cases throw; no break needed. case tokens.closeSquare: this.missingSquareBracket(); case tokens.semicolon: this.missingBackslash(); } } /** * Helpers */ expected (description, index, found) { if (Array.isArray(description)) { const last = description.pop(); description = `${description.join(', ')} or ${last}`; } const an = /^[aeiou]/.test(description[0]) ? 'an' : 'a'; if (!found) { return this.error( `Expected ${an} ${description}.`, {index} ); } return this.error( `Expected ${an} ${description}, found "${found}" instead.`, {index} ); } parseNamespace (namespace) { if (this.options.lossy && typeof namespace === 'string') { const trimmed = namespace.trim(); if (!trimmed.length) { return true; } return trimmed; } return namespace; } parseSpace (space, replacement = '') { return this.options.lossy ? replacement : space; } parseValue (value) { if (!this.options.lossy || !value || typeof value !== 'string') { return value; } return value.trim(); } parseParenthesisToken (token) { const content = this.content(token); if (!this.options.lossy) { return content; } if (token[0] === tokens.space) { return this.parseSpace(content, ' '); } return this.parseValue(content); } newNode (node, namespace) { if (namespace) { node.namespace = this.parseNamespace(namespace); } if (this.spaces) { node.spaces.before = this.spaces; this.spaces = ''; } return this.current.append(node); } content (token = this.currToken) { return this.css.slice(token[5], token[6]); } get currToken () { return this.tokens[this.position]; } get nextToken () { return this.tokens[this.position + 1]; } get prevToken () { return this.tokens[this.position - 1]; } }
import { GraphQLObjectType, GraphQLID, GraphQLList, GraphQLNonNull } from 'graphql' import storyType from '../types/story' import resolve from '../resolvers/story' import { StorySlugInput } from '../types/inputs' const story = { name: 'story', type: storyType, args: { id: { type: GraphQLID }, slugInput: { type: StorySlugInput } }, resolve } export default story
var pickFiles = require('broccoli-static-compiler'); var compileModules = require('broccoli-babel-transpiler'); var mergeTrees = require('broccoli-merge-trees'); var path = require('path'); var concat = require('broccoli-concat'); var replace = require('broccoli-string-replace'); var optionalTreesToMerge = []; var libTreeES6 = pickFiles('lib', { srcDir: '/', files: ['**/*.js'], destDir: '/pinky-swear' }); var testsTreeES6 = pickFiles('tests', { srcDir: '/', files: ['**/*.js'], destDir: '/tests' }); var libTree = compileModules(libTreeES6, { modules: 'umd', moduleIds: true }); var testsTree = compileModules(testsTreeES6, { modules: 'umd', moduleIds: true }); var libConcat = concat(libTree, { inputFiles: [ '**/*.js' ], outputFile: '/pinky-swear.js' }); var testsConcat = concat(testsTree, { inputFiles: [ '**/*.js' ], outputFile: '/tests.js' }); var cpToTest = function(absPath) { var dir = path.dirname(absPath); var filename = path.basename(absPath); return pickFiles(dir, { srcDir: '/', files: [filename], destDir: '/tests' }); } var testIndex = cpToTest('tests/index.html'); var loader = cpToTest('vendor/loader.js'); if (process.env.INTEGRATION_TEST) { var promisesAplusTests = pickFiles('node_modules/promises-aplus-tests/lib/tests', { srcDir: '/', files: ['helpers/*.js', '*.js'], destDir: '/' }); promisesAplusTests = compileModules(promisesAplusTests, { modules: 'umd', moduleIds: true }); promisesAplusTests = concat(promisesAplusTests, { inputFiles: ['**/*.js'], outputFile: '/tests/promises-aplus-specification.js' }); promisesAplusTests = replace(promisesAplusTests, { files: ['**/*.js'], pattern: { match: /require\("\.\//g, replacement: 'require("' } }); optionalTreesToMerge.push(promisesAplusTests); } RSVPTree = cpToTest('node_modules/rsvp/dist/rsvp.js'); chaiTree = cpToTest('node_modules/testem/public/testem/chai.js'); sinonTree = cpToTest('node_modules/sinon/pkg/sinon.js'); module.exports = mergeTrees([ libTree, testsTree, testIndex, testsConcat, libConcat, loader, chaiTree, sinonTree, RSVPTree ].concat(optionalTreesToMerge));
export default /* glsl */` attribute vec3 aPosition; #ifndef VIEWMATRIX #define VIEWMATRIX uniform mat4 matrix_view; #endif uniform mat4 matrix_projectionSkybox; uniform mat3 cubeMapRotationMatrix; varying vec3 vViewDir; void main(void) { mat4 view = matrix_view; view[3][0] = view[3][1] = view[3][2] = 0.0; gl_Position = matrix_projectionSkybox * view * vec4(aPosition, 1.0); // Force skybox to far Z, regardless of the clip planes on the camera // Subtract a tiny fudge factor to ensure floating point errors don't // still push pixels beyond far Z. See: // http://www.opengl.org/discussion_boards/showthread.php/171867-skybox-problem gl_Position.z = gl_Position.w - 0.00001; vViewDir = aPosition * cubeMapRotationMatrix; } `;
#!/usr/bin/env node // make package.json accessible const pkg = require('../package.json'); // dependencies const config = require('./config'); const docopt = require('docopt').docopt; const expand = require('expand-tilde'); const fs = require('fs'); const path = require('path'); const sqlite3 = require('sqlite3').verbose(); // generate and parse the command-line options const doc = fs.readFileSync(path.join(__dirname, 'docopt.txt'), 'utf8'); const options = docopt(doc, { version: pkg.version }); // database config.database = expand(config.database); const existed = fs.existsSync(config.database); const db = new sqlite3.Database(config.database); // continue when the database has opened db.on('open', function() { // emit 'ready' if the database previously existed if (existed) { db.emit('ready'); } // otherwise, create the table else { const query = 'CREATE TABLE Log(id INTEGER PRIMARY KEY, entry TEXT, timestamp DATE)'; db.run(query, function(err) { if (err) { console.warn(err.message); process.exit(1); } db.emit('ready'); }); } }); // execute the subcommands when the database is ready db.on('ready', function() { // load the subcommands const cmd = { delete : require('./cmd-delete'), edit : require('./cmd-edit'), log : require('./cmd-log'), write : require('./cmd-write'), }; // execute the appropriate subcommand const fn = (options.delete) ? cmd.delete : (options.edit) ? cmd.edit : (options.log) ? cmd.log : cmd.write ; fn(config, options, db, function(err, output) { // handle errors if (err) { console.warn(err.message); process.exit(1); } // display output if (output) { console.log(output); } }); });
function needsController( $scope, $http ){ $scope.url = 'http://172.20.15.40:8080/api/user' $scope.getAllByUser = function( id_user ){ var xhr = $http.get( $scope.url + '/' + id_user + '/needs' ); xhr.success( function( data ){ console.info( data ); $scope.needs_user = data.needs; } ); } }
$(function() { deleteSwap(); cloneSwap(); runSwap(); }) function deleteSwap() { var img_src = "images/delete.png" var hover_src = "images/delete_hover.png" $(document).on("mouseover", ".deleteLink", function(e){ var img_tag = $(this).children("img").first(); img_tag.attr('src', hover_src); }); $(document).on("mouseout", ".deleteLink", function(e){ var img_tag = $(this).children("img").first(); img_tag.attr('src', img_src); }); } function cloneSwap(){ var img_src = "images/clone.png" var hover_src = "images/clone_hover.png" $(document).on("mouseover", ".copyLink", function(e){ var img_tag = $(this).children("img").first(); img_tag.attr('src', hover_src); }); $(document).on("mouseout", ".copyLink", function(e) { var img_tag = $(this).children("img").first(); img_tag.attr('src', img_src); }); } function runSwap() { var img_src = "images/run.png" var hover_src = "images/run_hover.png" $(document).on("mouseover", ".runLink", function(e) { var img_tag = $(this).children("img").first(); img_tag.attr('src', hover_src); }); $(document).on("mouseout", ".runLink", function(e){ var img_tag = $(this).children("img").first(); img_tag.attr('src', img_src); }); }
const puppeteer = require('puppeteer') describe('My First Pippeteer Test',()=>{ it('Launch the Browser',async()=>{ const browser = await puppeteer.launch({headless:false ,slowMo:1000,devtools:true}); const page = await browser.newPage() await page.goto('http://example.com/') await page.waitFor(5000) await page.waitForSelector('h1') await page.reload() await page.waitForSelector('h1') await page.goForward() await page.goBack() await browser.close() }) })
var config = { 'secrets' : { 'clientId' : process.env.CLIENT_ID, 'clientSecret' : process.env.CLIENT_SECRET, 'redirectUrl' : process.env.REDIRECT } } const foursquare = require('node-foursquare')(config) // returns JSON checkin data from foursquare exports.getCheckins = () => { } module.exports = foursquare
import React from 'react'; import { Switch, Route} from 'react-router-dom'; import {FilterContextProvider} from './contexts/FilterContext'; // Styles import './styles/bootstrap/dist/css/bootstrap.min.css'; import './styles/main.css' // Components import NavBar from './Components/NavBar' // Pages import HomePage from './Pages/HomePage' import ResultsPage from './Pages/ResultsPage'; import Personas from './Pages/Personas'; import CustomFilters from './Pages/CustomFilters'; export default function App() { return ( <> <NavBar /> <FilterContextProvider> <Switch> <Route path="/" exact component={HomePage} /> <Route path="/results" component={ResultsPage} /> <Route path="/personas" component={Personas} /> <Route path="/custom" component={CustomFilters} /> </Switch> </FilterContextProvider> </> ); }
import { useState, useEffect, } from 'react'; import { Table } from 'react-bootstrap'; import { useForm } from 'react-hook-form'; import TasksService from '../../services/tasks.service'; import ErrorMessage from '../forms/ErrorMessage'; import { SrvNumber } from '../tasks/TaskHelpers'; import ReportWrite from '../reports/ReportWrite'; const TaskService = new TasksService(); const REQUIRED = 'Не выбрано ни одной задчи для отчёта!'; const AssignedTasks = () => { document.title = 'Мои задачи'; const [assignedTasks, setAssignedTasks] = useState([]); const { register, handleSubmit, formState: { errors, isSubmitSuccessful } } = useForm(); const [tasksForReport, setTasksForReport] = useState([]); const onSubmit = (data) => { const filteredAssignedTasks = assignedTasks.filter(task => { const taskId = String(task.id); return (data.tasks.includes(taskId)); }); setTasksForReport(filteredAssignedTasks); } const retrieveAssignedTasks = () => { console.log('Retrieve tasks!'); TaskService.getAssignedTasks() .then((response) => { setAssignedTasks(response.data.results); }) .catch((error) => { console.log(error) } ); } useEffect(() => { retrieveAssignedTasks(); }, []) return( <> { isSubmitSuccessful ? <ReportWrite forReport={tasksForReport} /> : <form onSubmit={handleSubmit(onSubmit)}> <Table striped bordered hover> <thead> <tr> <th>Включить в отчёт</th> <th>Номер запроса</th> <th>Название запроса</th> <th>Due date</th> <th>Оригинатор</th> </tr> </thead> <tbody> { assignedTasks.map((wt) => { return( <tr key={wt.id}> <td> { !wt.have_report && <input type='checkbox' value={wt.id} name='tasks' {...register( 'tasks', { required: {value: true, message: REQUIRED }} ) } /> } </td> <td><SrvNumber idx={wt.id} srvNumber={wt.srv_number} /></td> <td>{wt.srv_title}</td> <td>{wt.due_date}</td> <td>{wt.originator.full_name}</td> </tr>); }) } </tbody> </Table> <ErrorMessage message={errors.tasks} /> <input type='submit' value='Написать отчёт' className='btn btn-dark btn-block' /> </form> } </> ); } export default AssignedTasks;
var express = require('express'); var router = express.Router(); const nodemailer = require("nodemailer"); /* GET home page. */ router.get('/', function(req, res, next) { res.render('index', { title: 'Express' }); }); /* GET home page. */ router.get('/thanks', function(req, res, next) { res.render('thanks', { title: 'Thanks' }); }); router.post("/contact", function(req, res){ async function main(){ // need to authenticate EMAIL and get clientID, Secret, and Refresh token when adding a new email // using OAuth specifications found on Google's developer platform let transporter = nodemailer.createTransport({ host: "smtp.gmail.com", auth: { type: "OAuth2", user: process.env.EMAIL, clientId:"\n" + process.env.CLIENTID + "\n" , clientSecret: "\n" + process.env.CLIENTSECRET + "\n" , refreshToken: process.env.REFRESHTOKEN } }); // setup email data let mailOptions = { from: "Kyle's Portfolio Site", to: process.env.EMAIL, subject: "Message from Kyle's Portfolio Site", // Subject line text:"Subject:\n" + req.body.subject + "\n\n Message: \n" + req.body.message + "\n\nTo reply to this inquiry, please send response to the user's email:\n" + req.body.email // plain text body }; console.log(req.body); // send mail with defined transport object let info = await transporter.sendMail(mailOptions); console.log("Message sent: %s", info.messageId); // Preview only available when sending through an Ethereal account console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info)); console.log(req.body); } main().catch(console.error); res.redirect("/thanks"); }); module.exports = router;
import EventEmitter from "./EventEmitter"; import AElement from "./AElement"; import OOP from "./OOP"; import AttachHook from "./AttachHook"; /*** * * @extends EventEmitter * @param {AElement=} attachHookElt * @constructor */ function DomSignal(attachHookElt) { EventEmitter.call(this); this.signals = {}; this.ev_attached = this.ev_attached.bind(this); this.$attachhook = attachHookElt || this.createBuildInAttachHook(); this.$attachhookParent = (attachHookElt && attachHookElt.parentElement) || null; this.$attachhook.on('attached', this.ev_attached); } OOP.mixClass(DomSignal, EventEmitter); DomSignal.prototype.createBuildInAttachHook = function (){ var elt = document.createElement('img'); Object.defineProperties(elt, Object.getOwnPropertyDescriptors(AElement.prototype)); Object.defineProperties(elt, Object.getOwnPropertyDescriptors(AttachHook.prototype)); Object.defineProperties(elt, AttachHook.property); AElement.call(elt); elt.setAttribute('src', ''); elt.defineEvent('attached'); AttachHook.call(elt); return elt; } DomSignal.prototype.execSignal = function () { var signals = this.signals; if (this.$attachhook) { this.$attachhook.remove(); this.$attachhook.resetState(); } this.signals = {}; for (var name in signals) { this.fire.apply(this, [name].concat(signals[name])); } }; DomSignal.prototype.emit = function (name) { this.signals[name] = Array.prototype.slice.call(arguments, 1); if (!this.$attachhookParent) { this.$attachhookParent = document.body; } if (!this.$attachhook.parentElement) { this.$attachhookParent.appendChild(this.$attachhook); } }; DomSignal.prototype.ev_attached = function () { this.execSignal(); }; export default DomSignal;
var gulp = require('gulp'), browserify = require('gulp-browserify'), rename = require('gulp-rename'), //concat = require('gulp-concat'), uglify = require('gulp-uglify'), imagemin = require('gulp-imagemin'), jshint = require('gulp-jshint'), compass = require('gulp-compass'), //sourcemaps = require('gulp-sourcemaps'), paths = { javascripts: [ 'javascripts/app/*.js', 'javascripts/helpers/*.js', 'javascripts/config/*.js' ], images: 'images/*.{png,jpg,gif}', test: ['gulpfile.js', 'javascripts/app/*.js', 'javascripts/helpers/*.js', 'javascripts/config/*.js'], sass: 'sass/**/*.{sass,scss}' }; gulp.task('js', function() { gulp.src('javascripts/config/main.js') .pipe(browserify({ debug: true })) .pipe(rename('scripts.min.js')) .pipe(gulp.dest('javascripts')) }); //gulp.task('minify', function () { // gulp.src(paths.javascripts) // .pipe(sourcemaps.init()) // .pipe(concat('scripts.min.js')) // .pipe(uglify()) // .pipe(sourcemaps.write('./')) // .pipe(gulp.dest('javascripts')); //}); gulp.task('image', function () { gulp.src(paths.images) .pipe(imagemin({ progressive: true, interlaced: true, svgoPlugins: [{removeViewBox: false}] })) .pipe(gulp.dest('images')); }); gulp.task('test', function () { gulp.src(paths.test) .pipe(jshint()) .pipe(jshint.reporter('default')); }); gulp.task('compass', function () { gulp.src(paths.sass) .pipe(compass({ config_file: 'config.rb', css: 'stylesheets' })) .pipe(gulp.dest('stylesheets')); }); gulp.task('watch', function() { gulp.watch(paths.javascripts, ['js']); gulp.watch(paths.sass, ['compass']); }); gulp.task('default', ['js', 'image']);
/*!build time : 2014-10-14 11:38:22 AM*/
import styled from "styled-components"; import QuestionStats from "./QuestionStats"; import CreatedInfo from "./CreatedInfo"; import { Container, StyledLink, Heading } from "components/shared/lib"; import Tag from "components/shared/Tag"; import { tablet } from "constants/screenBreakpoints"; const QuestionCard = ({ id, authorName, authorId, title, answerCount, score, isClosed, createdAt, tags, dark = false, onTagClick, }) => { return ( <CardContainer dark={dark}> <QuestionStats answerCount={answerCount} score={score} isClosed={isClosed} /> <ContentContainer> <TitleLink to={`/question/${id}`}> <Heading>{title}</Heading> </TitleLink> <InfoBottom> <TagContainer> {tags?.length > 0 && tags.map((tag, i) => ( <Tag onClick={() => { if (onTagClick) onTagClick(tag); }} key={`${tag}${i}`} light > {tag} </Tag> ))} </TagContainer> <CreatedInfo createdAt={createdAt} name={authorName} id={authorId} /> </InfoBottom> </ContentContainer> </CardContainer> ); }; const CardContainer = styled(Container)` flex-direction: row; justify-items: space-between; align-items: stretch; padding: 0.75rem 1.25rem; transition: box-shadow 0.15s ease-in-out; &:hover, &:focus { box-shadow: var(--bs-large); } @media (max-width: ${tablet}px) { flex-direction: column; } `; const InfoBottom = styled.div` display: flex; justify-content: space-between; align-items: flex-end; `; const TagContainer = styled.div``; const ContentContainer = styled.div` display: flex; flex-direction: column; justify-content: space-between; flex: 1; `; const TitleLink = styled(StyledLink)` align-self: flex-start; `; export default QuestionCard;
$(function() { $('.input').change(function(e) { $('.sub').click(); }) $('#red').click(function(e) { }) })
// // code related to uploading (publishing) a folder to S3 folder // const path = require('path') const chalk = require('chalk') const { filenameToShellVariable, configFromEnvOrJsonFile } = require('@cypress/env-or-json-file') const la = require('lazy-ass') const is = require('check-more-types') const awspublish = require('gulp-awspublish') const human = require('human-interval') const gulp = require('gulp') const merge = require('merge-stream') const isAWSKey = s => is.unemptyString(s) && s.length === 20 const isAWSSecret = s => is.unemptyString(s) && s.length === 40 const isConfig = is.schema({ 'bucket-production': is.unemptyString, 'bucket-staging': is.unemptyString, key: is.unemptyString, secret: is.unemptyString }) const isPublisher = is.schema({ publish: is.fn }) function getS3Config () { const key = path.join('support', '.aws-credentials.json') const config = configFromEnvOrJsonFile(key) if (!config) { console.error('⛔️ Cannot find AWS credentials') console.error('Using @cypress/env-or-json-file module') console.error('and key', filenameToShellVariable(key)) throw new Error('AWS config not found') } if (!isConfig(config)) { console.error('⛔️ Invalid AWS credentials') console.error('Have keys', Object.keys(config)) throw new Error('Invalid AWS config') } return config } function getS3Publisher (bucket, key, secret) { la(is.unemptyString(bucket), 'missing S3 bucket', bucket) la(isAWSKey(key), 'invalid AWS key with type', typeof key) la(isAWSSecret(secret), 'invalid AWS secret with type', typeof secret) return awspublish.create({ httpOptions: { timeout: human('10 minutes') }, params: { Bucket: bucket }, accessKeyId: key, secretAccessKey: secret }) } function publishToS3 (distDir, publisher) { la(is.unemptyString(distDir), 'missing directory to publish to S3', distDir) la(isPublisher(publisher), 'not an instance of gulp-awspublish') const headers = {} // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control const nocacheHeaders = { 'Cache-Control': 'max-age=0, no-cache, no-store, no-transform, must-revalidate' } return new Promise((resolve, reject) => { const files = path.join(distDir, '**', '*') const buildJsonFile = path.join(distDir, 'build.json') const noBuildJsonFile = `!${buildJsonFile}` // merging deployment streams // https://github.com/pgherveou/gulp-awspublish#upload-both-gzipped-and-plain-files-in-one-stream const mostFiles = gulp .src([files, noBuildJsonFile]) .pipe(publisher.publish(headers)) const buildJson = gulp .src(buildJsonFile) .pipe(publisher.publish(nocacheHeaders)) merge(mostFiles, buildJson) // we dont need to gzip here because cloudflare // will automatically gzip the content for us // after its cached at their edge location // but we should probably gzip the index.html? // .pipe(awspublish.gzip({ext: '.gz'})) .pipe(awspublish.reporter()) .on('error', reject) .on('end', resolve) }) } // "normal" folder upload to S3 using default config flow function uploadToS3 (folder, env) { la(is.unemptyString(folder), 'missing local folder to upload', folder) la(is.unemptyString(env), 'missing S3 environment', env) const config = getS3Config() const bucketName = `bucket-${env}` const bucket = config[bucketName] la( is.unemptyString(bucket), 'Could not find a bucket for environment', env, 'in AWS config under key', bucketName ) console.log('') console.log('Deploying to:', chalk.green(bucket)) console.log('') const publisher = getS3Publisher(bucket, config.key, config.secret) la(publisher, 'could not get publisher for bucket', bucket) return publishToS3(folder, publisher) } module.exports = { getS3Config, getS3Publisher, publishToS3, uploadToS3 }
window.start = moment().subtract(1, 'year'); window.end = moment(); title = $('title').text(); function cb(start, end) { window.start = start; window.end = end; range = start.format('DD-MM-YYYY') + ' - ' + end.format('DD-MM-YYYY'); $('#daterange span').html(range); $('title').text(`${title} [${range}]`); table.draw(); } $.fn.daterangepicker.defaultOptions = { locale: { "format": "DD/MM/YYYY", "applyLabel": "Appliquer", "cancelLabel": "Annuler", "customRangeLabel": "Choisir", "daysOfWeek": ["Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam"], "monthNames": ["Janvier", "Février", "Mars", "Avril", "May", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"], "firstDay": 1 }, ranges: { 'Cette semaine': [moment().subtract(6, 'days'), moment()], '30 derniers jours': [moment().subtract(29, 'days'), moment()], 'Ce mois-ci': [moment().startOf('month'), moment().endOf('month')], 'Le mois dernier': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')], 'Les 3 derniers mois': [moment().subtract(3, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')] } } $('#daterange').daterangepicker({}, cb);
exports.login = function(req,res){ PlUsers.find({username:req.body.username,password:req.body.password},function(err, types) { let code=0 if(err) { code=ERRORCODE.CREATE_FAILED } else{ if(types.length<=0) code=ERRORCODE.AUTHENTICATION_FAILED else{ req.session.user=req.body.username; } } return res.json({code:code}) }) } exports.register = function(req,res){ PlUsers.find({username:req.body.username},function(err, types) { if(err){ console.log(err) return res.json({code:ERRORCODE.QUERY_FAILED}) } else{ if(types.length<=0){ var user=new PlUsers({ username:req.body.username, password:req.body.password }) user.save(function (err) { if(err) res.json({code:ERRORCODE.CREATE_FAILED,errormessage:err}) else res.json({code:ERRORCODE.SUCCESS}) }) } else res.json({code:ERRORCODE.WRONG_USERNAME_OR_PASSWORD}) } }) } exports.logout = function(req,res){ req.session.user=null; return res.json({code:ERRORCODE.SUCCESS,url:"/"}); } exports.session = function(req,res){ if(req.session.user) res.json({user:req.session.user,code:ERRORCODE.SUCCESS}); else res.json({code:-1}) }
import { LOGIN_SUCCESS, LOGOUT_SUCCESS } from "../constants/actions"; const userReducer = (userStateObj, action) => { switch (action.type) { case LOGIN_SUCCESS: const tempUserObj = { ...action.payload, isAuthenticated: true, }; localStorage.setItem("user", JSON.stringify(tempUserObj)); return tempUserObj; case LOGOUT_SUCCESS: const tempUserObj1 = { isAuthenticated: false, }; localStorage.setItem("user", JSON.stringify(tempUserObj1)); return tempUserObj1; default: return userStateObj; } }; export default userReducer;
import React from 'react'; import { View, Dimensions } from 'react-native'; import { Divider } from 'react-native-elements'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import { setVehicleType, vehicleBrandsRequest } from '../../actions'; import { Caption, ButtonContainer2, HeaderTitle } from './styles'; import { Container } from '../../../../components/container'; import { VehicleSelector } from '../../../../components/vehicle-selector'; import { Button } from '../../../../components/button'; import { VEHICLES } from '../../../../utils/vehicle-utils'; class VehicleInformation extends React.Component { static navigationOptions = () => { return { title: '', headerStyle: { backgroundColor: '#fff', elevation: 0, borderBottomWidth: 0 } }; }; constructor(props) { super(props); this.state = { vehicleType: undefined }; } goToSend = () => { const { vehicleType } = this.state; const { navigation, actions } = this.props; actions.setVehicleType(vehicleType); navigation.navigate('Send'); }; render() { const { vehicleType } = this.state; const { actions } = this.props; return ( <Container> <HeaderTitle>Elegí el tipo de vehículo</HeaderTitle> <Caption>DESLIZÁ Y SELECCIONÁ EL QUE NECESITES</Caption> <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}> <VehicleSelector vehicles={VEHICLES} vehicleType={vehicleType} onVehiclePress={(item) => { this.setState({ vehicleType: item.key }); actions.vehicleBrandsRequest(item.key); }} /> </View> <ButtonContainer2> <View> <Divider style={{ backgroundColor: 'gray', opacity: 0.2, marginVertical: 10 }} /> <Button width={Dimensions.get('window').width - 40} title="CONTINUAR" color="#665EFF" onPress={this.goToSend} disabled={vehicleType === undefined} /> </View> </ButtonContainer2> </Container> ); } } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators({ setVehicleType, vehicleBrandsRequest }, dispatch) }; } export default connect( null, mapDispatchToProps )(VehicleInformation);
import Moment from "moment" const CommonFunc = { compare (propertyName) { return function (obj1, obj2) { let value1 = parseInt(obj1[propertyName]); let value2 = parseInt(obj2[propertyName]); if (value1 < value2) { return 1; } else if (value1 > value2) { return -1; } else { return 0; } }; }, sortGroup (data, name = null) { let temp = data.slice(0); if (name !== null) { temp.sort(this.compare(name)); return temp } else { temp.sort(); return temp } }, getMaxValue (data, name = null) { let temp = data.slice(0); if (name !== null) { temp.sort(this.compare(name)); return parseInt(temp[0][name]) } else { temp.sort(); return temp[0] } }, getSumValue (data, name = null) { let temp = data.slice(0); if (name !== null) { let sum = 0; temp.map((item) => { sum += parseInt(item[name]); }); return sum; } else { return temp.reduce((value1, value2) => { return (value1 + value2); }) } }, getRandomColor () { let letters = "0123456789ABCDEF"; let color = "#"; for (let i = 0; i < 6; i++) { color += letters[Math.floor(Math.random() * 16)]; } return color; }, compareObjKey (obj, keys) { let n = keys.length, key = []; while(n--){ key.push(obj[keys[n]]); } return key.join("|"); }, uniqeByKeys(array,keys){ let arr = []; let hash = {}; for (let i = 0, j = array.length; i < j; i++) { let k = this.compareObjKey(array[i], keys); if (!(k in hash)) { hash[k] = true; arr .push(array[i]); } } return arr ; }, getRandomId () { return "_" + Math.random().toString(36).substr(2, 9) }, dateTimeFormat (value) { let temp = value; if (parseInt(temp, 10) < 10) { temp = "0" + parseInt(temp, 10); } return temp; }, format (date, format) { if ( date === "" || date === null) return ""; let o = { "M+" : date.getMonth()+1, //month "d+" : date.getDate(), //day "H+" : date.getHours(), //hour "m+" : date.getMinutes(), //minute "s+" : date.getSeconds(), //second "q+" : Math.floor((date.getMonth()+3)/3), //quarter "S" : date.getMilliseconds() //millisecond }; if(/(y+)/.test(format)) { format = format.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length)); } for (let k in o) { if(new RegExp("("+ k +")").test(format)) { format = format.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length)); } } return format; }, momentConverter (date, format, defaultValue) { return Moment(date).isValid() ? Moment(date).format(format) : defaultValue }, momentCompare (date, name) { if (name) { let diff = Moment().diff(date, "minutes") return diff > 0 ? this.momentConverter(date, "HH:mm", "") : name } else { let diff = (Moment().startOf("days")).diff(Moment(date).startOf("days"), "days"); if (diff === 1) return "昨天" if (diff === 2) return "前天" if (diff > 2) return "3天前" } }, numberDecimal (num, point) { let targetIndex = (num + "").indexOf(".") return targetIndex > 0 ? +(parseFloat(num).toFixed(point)) : num }, transTenThousandData (value) { let valueTemp = parseFloat(value); let total = valueTemp.toFixed(2); if (String(valueTemp.toFixed(0)).length > 4) { total = (valueTemp / 10000).toFixed(2) + "万"; } return total; }, dealPieData (pieDataToDeal) { let ratioData = []; pieDataToDeal.forEach((item) => { ratioData.push({ name: item.name, pieData: { text: "{big|" + parseFloat(item.data.totalration).toFixed(1) + "}{small| %}", data:[ { value: parseFloat(item.data.totalration).toFixed(1) }, { value: 100 - parseFloat(item.data.totalration).toFixed(1) } ], }, detail: item.data.countys }) }); return ratioData; }, gradientColor (startColor, endColor, step) { let startRGB = this.colorRgb(startColor);//转换为rgb数组模式 let startR = startRGB[0]; let startG = startRGB[1]; let startB = startRGB[2]; let endRGB = this.colorRgb(endColor); let endR = endRGB[0]; let endG = endRGB[1]; let endB = endRGB[2]; let sR = (endR-startR)/step;//总差值 let sG = (endG-startG)/step; let sB = (endB-startB)/step; let colorArr = []; for(let i = 0; i < step; i++){ //计算每一步的hex值 var hex = this.colorHex("rgb("+parseInt((sR*i+startR))+","+parseInt((sG*i+startG))+","+parseInt((sB*i+startB))+")"); colorArr.push(hex); } return colorArr; }, // 将hex表示方式转换为rgb表示方式(这里返回rgb数组模式) colorRgb (sColor) { let reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/; sColor = sColor.toLowerCase(); if(sColor && reg.test(sColor)){ if(sColor.length === 4){ var sColorNew = "#"; for(let i = 1; i < 4; i++){ sColorNew += sColor.slice(i,i+1).concat(sColor.slice(i,i+1)); } sColor = sColorNew; } //处理六位的颜色值 let sColorChange = []; for(let i=1; i<7; i+=2){ sColorChange.push(parseInt("0x"+sColor.slice(i,i+2))); } return sColorChange; }else{ return sColor; } }, colorHex (rgb) { let _this = rgb; let reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/; if(/^(rgb|RGB)/.test(_this)){ let aColor = _this.replace(/(?:(|)|rgb|RGB)*/g,"").split(","); let strHex = "#"; for (let i = 0; i < aColor.length; i++) { let hex = Number(aColor[i]).toString(16); hex = hex<10 ? 0+""+hex :hex;// 保证每个rgb的值为2位 if (hex === "0") { hex += hex; } strHex += hex; } if (strHex.length !== 7) { strHex = _this; } return strHex; } else if (reg.test(_this)) { let aNum = _this.replace(/#/,"").split(""); if(aNum.length === 6){ return _this; } else if (aNum.length === 3) { let numHex = "#"; for(let i = 0; i < aNum.length; i++) { numHex += (aNum[i]+aNum[i]); } return numHex; } } else { return _this; } }, twoDimenArrayTrans (value) { let arr = [...value]; return arr[0].map(function(col, i) { return arr.map(function(row) { return row[i]; }) }); }, }; export default CommonFunc;
import React from 'react' import Link from 'next/link' import styled from 'styled-components' export const Photo = styled.div` display: inline-block; width: 800px; height: 500px; overflow: hidden; ` const Image = styled.div` width: 600px; height: 500px; float: left; background: #333; color: #fff; font-size: 40px; line-height: 500px; text-align: center; vertical-align: middle; ` const Sidebar = styled.div` box-sizing: border-box; width: 200px; height: 500px; padding: 20px; background: #fff; font-family: Monaco, sans-serif; font-size: 11px; text-align: left; ` const SidebarList = styled.ul` margin: 0; padding: 0; list-style-type: none; ` export default ({ id }) => ( <Photo> <Image>{id}</Image> <Sidebar> <SidebarList> <li> <Link href="/profile?id=nkzawa"> <a href="/profile?id=nkzawa">@nkzawa</a> </Link> - Great photo! </li> </SidebarList> </Sidebar> </Photo> )
import { tailwind } from '@theme-ui/presets'; import "typeface-aleo" export default { ...tailwind, initialColorMode: `light`, useCustomProperties: true, colors: { ...tailwind.colors, primary: '#ff7f00', secondary: tailwind.colors.indigo[6], background: tailwind.colors.white, modes: { dark: { text: tailwind.colors.white, primary: tailwind.colors.pink[4], background: tailwind.colors.gray[8], textMuted: tailwind.colors.gray[5], }, }, }, fonts: { ...tailwind.fonts, heading: 'Inter, Cambria, "Times New Roman", Times, serif', }, badges: { primary: { color: 'background', bg: 'primary', }, outline: { color: 'primary', bg: 'transparent', boxShadow: 'inset 0 0 0 1px', ':hover': { color: 'background', bg: 'primary', }, }, }, styles: { ...tailwind.styles, root: { ...tailwind.styles.root, color: `text`, backgroundColor: `background`, }, p: { fontSize: ['18px', '20px'], letterSpacing: `0.003em`, lineHeight: `body`, '--baseline-multiplier': 0.179, '--x-height-multiplier': 0.35, }, h1: { fontFamily: 'heading', letterSpacing: 'tight', fontSize: [5, 6], mt: 2, }, h2: { ...tailwind.styles.h2, letterSpacing: 'tight', fontSize: [4, 5], mt: 5, mb: 4, }, h3: { ...tailwind.styles.h3, fontSize: [3, 4], mt: 3, }, h4: { ...tailwind.styles.h4, fontSize: [2, 3], }, h5: { ...tailwind.styles.h5, fontSize: [1, 2], }, h6: { ...tailwind.styles.h6, fontSize: 1, mb: 2, }, blockquote: { borderLeft: `4px solid #ff7f00`, px: ['1em', '2em'], mx: ['0em', '2em'], }, ul: { padding: 0, fontSize: ['18px', '20px'], listStylePosition: 'outside', listStyle: 'circle', }, ol: { padding: 0, fontSize: ['18px', '20px'], listStylePosition: 'outside', }, li: { display: 'list-item' }, }, buttons: { toggle: { color: `background`, border: `none`, backgroundColor: `text`, cursor: `pointer`, alignSelf: `center`, px: 3, py: 2, ml: 3, }, }, }; //console.log(tailwind)
/** OOP in Javascript ES6 **/ var Vehicle = class Vehicle { constructor(name, colour, wheels, model, doors) { this.name = name; this.colour = colour; this.wheels = wheels; this.model = model; this.doors = doors; } }; var Car = class Car extends Vehicle { get carWheels(){ return this.wheels = 4; } } var Truck = class Truck extends Vehicle { get truckWheels(){ return this.wheels = 12; } } var aCar = new Car('Cammry', 'blue', 'Toyota', 4); let car = aCar.carWheels; console.log(car.wheels);
import { createRouter, createWebHistory } from "vue-router"; import Home from "../components/Home.vue"; import NosRestaurants from "../components/NosRestaurants.vue" import NosAssociations from "../components/NosAssociations.vue" import NosPartenaires from "../components/NosPartenaires.vue" import Coursiers from "../components/Coursiers.vue" import Contact from "../components/Contact.vue" const routerHistory = createWebHistory(); const router = createRouter({ history: routerHistory, routes: [ { path: "/", component: Home, }, { path: "/NosRestaurants", component: NosRestaurants, }, { path: "/NosAssociations", component: NosAssociations, }, { path: "/NosPartenaires", component: NosPartenaires, }, { path: "/Coursiers", component: Coursiers, }, { path: "/Contact", component: Contact, }, ], }); export default router;
var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; import { GridDataSource } from './grid-source'; /** Remote Source of Grid Data - Server side Paging and Sorting */ var RemoteGridData = (function (_super) { __extends(RemoteGridData, _super); function RemoteGridData() { return _super !== null && _super.apply(this, arguments) || this; } return RemoteGridData; }(GridDataSource)); export { RemoteGridData };
var TutorialManager = new function() { var isTutorial = false; var tutorialStep = 0; this.setTutorial = function(isTuto) { tutorialStep = 0; isTutorial = isTuto == 0; }; this.getTutorial = function() { return isTutorial; }; this.setTutorialStep = function() { tutorialStep++; }; this.getTutorialStep = function() { return tutorialStep; }; this.tutorialGiveup = function() { tutorialStep++; }; this.tutorialPlay = function() { tutorialStep += 2; }; this.destroy = function () { }; };
import { combineReducers, configureStore } from '@reduxjs/toolkit' import appReducer from './app/reducer' import authReducer from './auth/reducer' import coursesReducer from './courses/reducer' import lessonReducer from './lesson/reducer' import lessonStepsReducer from './lessonSteps/reducer' import { createWrapper } from 'next-redux-wrapper' const rootReducer = combineReducers({ appReducer, authReducer, coursesReducer, lessonReducer, lessonStepsReducer, }) const makeStore = (context) => configureStore({ reducer: rootReducer, }) export const wrapper = createWrapper(makeStore, { debug: false })
export default { addLog(state, log) { log = { time: Date.now(), title: typeof log === 'object' ? 'tx' : log, data: typeof log === 'object' && log } state.log.unshift(log) }, setQuerying(state, bool) { state.querying = bool }, setTryAgain(state, bool) { state.tryAgain = bool }, setUnlocked(state, unlocked) { state.unlocked = unlocked }, setAccount(state, account) { state.account = account }, setStatus(state, status) { state.status = status }, setError(state, error) { state.error = error }, setContracts(state, { Patches, Controller }) { state.Patches = Patches state.Controller = Controller }, setNetwork(state, networkId) { state.networkId = networkId }, setAdmin(state, admin) { state.admin = admin }, setBilly(state, billy) { state.billy = billy }, setPatches(state, patches) { state.patches = patches }, addPatch(state, patch) { // state.patches = { ...state.patches, [patch.patchId]: patch } state.patches.push(patch) }, addWork(state, work) { let workIndex = state.works.findIndex(w => w.workId === work.workId) if (workIndex > -1) { state.works.splice(workIndex, 1, work) } else { state.works.push(work) } }, markAllNotifications (state) { if (!state.notifications.length) return let opposite = !state.notifications[state.notifications.length - 1].seen state.notifications.forEach(n => { n.seen = opposite }) }, addNotification(state, notification) { if (state.notifications.length && notification.body === state.notifications[0].body) return let uid = (new Date()).getTime().toString(16) notification.id = uid notification.seen = false state.notifications.unshift(notification) }, removeNotification(state, id) { let nIndex = state.notifications.findIndex(n => n.id === id) if (nIndex > -1) { let notification = state.notifications[nIndex] notification.seen = true state.notifications.splice(nIndex, 1, notification) } } }
import React, { useEffect, useState } from 'react'; import BannerMain from '../../components/BannerMain'; import Carrosel from '../../components/Carrousel'; import PageDefault from '../../components/PageDefault'; import categoriasRepository from '../../repositories/categorias'; function Home() { // http://localhost:3001/categorias?_embed=videos const [dadosIniciais, setDadosIniciais] = useState([]); useEffect(() => { categoriasRepository.getAllWithVideos() .then((categoriasComVideos) => { setDadosIniciais(categoriasComVideos); }).catch((err) => { console.log(err.message); }); }, []); return ( <> <PageDefault paddingAll={0}> {dadosIniciais.length === 0 && ( <div> Carrengando... </div> )} {dadosIniciais.map((categoria, index) => { if (index === 0) { return ( <div key={categoria.id}> <BannerMain videoTitle={dadosIniciais[0].videos[0].titulo} url={dadosIniciais[0].videos[0].url} videoDescription="Krisiun está aqui! - Gravado em 2020 no estúdio Family Mob (São Paulo, SP)" /> <Carrosel ignoreFirstVideo category={dadosIniciais[0]} /> </div> ); } return ( <Carrosel key={categoria.id} category={categoria} /> ); })} </PageDefault> </> ); } export default Home;
angular .module('atentamente', [ 'ui.router', 'templates', 'ngSanitize', 'angularMoment', 'ui.bootstrap', 'ui.tinymce', 'ngStorage', 'ngAnimate', 'truncate', 'Devise' ]);
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const THREE = SupEngine.THREE; const Light_1 = require("./Light"); class LightMarker extends Light_1.default { setType(type) { if (this.lightMarker != null) this.actor.gameInstance.threeScene.remove(this.lightMarker); if (this.cameraHelper != null) { this.actor.gameInstance.threeScene.remove(this.cameraHelper); this.cameraHelper = null; } super.setType(type); switch (type) { case "ambient": this.lightMarker = null; break; case "point": this.lightMarker = new THREE.PointLightHelper(this.light, 1); break; case "spot": this.lightMarker = new THREE.SpotLightHelper(this.light); // if (this.castShadow) this.cameraHelper = new THREE.CameraHelper((<THREE.SpotLight>this.light).shadowCamera); break; case "directional": this.lightMarker = new THREE.DirectionalLightHelper(this.light, 1); // if (this.castShadow) this.cameraHelper = new THREE.CameraHelper((<THREE.DirectionalLight>this.light).shadowCamera); break; } if (this.lightMarker != null) { this.actor.gameInstance.threeScene.add(this.lightMarker); this.lightMarker.updateMatrixWorld(true); } // if (type === "spot" && this.cameraHelper != null && this.castShadow) this.actor.gameInstance.threeScene.add(this.cameraHelper); } setColor(color) { super.setColor(color); if (this.lightMarker != null) this.lightMarker.update(); } setIntensity(intensity) { super.setIntensity(intensity); if (this.lightMarker != null) this.lightMarker.update(); } setDistance(distance) { super.setDistance(distance); if (this.lightMarker != null) this.lightMarker.update(); } setAngle(angle) { super.setAngle(angle); if (this.lightMarker != null) this.lightMarker.update(); } setTarget(x, y, z) { super.setTarget(x, y, z); if (this.lightMarker != null) this.lightMarker.update(); } setCastShadow(castShadow) { super.setCastShadow(castShadow); if (castShadow) { this.cameraHelper = new THREE.CameraHelper(this.light.shadow.camera); this.actor.gameInstance.threeScene.add(this.cameraHelper); } else { this.actor.gameInstance.threeScene.remove(this.cameraHelper); this.cameraHelper = null; } } setShadowCameraNearPlane(near) { super.setShadowCameraNearPlane(near); if (this.cameraHelper != null) this.cameraHelper.update(); } setShadowCameraFarPlane(far) { super.setShadowCameraFarPlane(far); if (this.cameraHelper != null) this.cameraHelper.update(); } setShadowCameraFov(fov) { super.setShadowCameraFov(fov); if (this.cameraHelper != null) this.cameraHelper.update(); } setShadowCameraSize(top, bottom, left, right) { super.setShadowCameraSize(top, bottom, left, right); if (this.cameraHelper != null) this.cameraHelper.update(); } update() { // TODO: Only do that when the transform has changed if (this.lightMarker != null) { this.lightMarker.updateMatrixWorld(true); this.lightMarker.update(); } this.actor.gameInstance.threeScene.updateMatrixWorld(false); } _destroy() { if (this.lightMarker != null) this.actor.gameInstance.threeScene.remove(this.lightMarker); if (this.cameraHelper != null) this.actor.gameInstance.threeScene.remove(this.cameraHelper); super._destroy(); } } exports.default = LightMarker;
import 'bootstrap/dist/css/bootstrap.min.css'; import '../scss/index.scss'; import React from 'react'; import ReactDOM from 'react-dom'; import {AppContainer as HotContainer} from 'react-hot-loader'; import {createStore} from 'redux'; import {Provider} from 'react-redux'; import App from './components/app'; import Frames from './components/frames'; import Analytics from './components/analytics'; import allReducers from './reducers'; class Aggregator { constructor() { const appContainer = document.getElementById('app'); const store = createStore( allReducers, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__() ); ReactDOM.render( <HotContainer> <Provider store={store}> <App> <Frames /> <Analytics /> </App> </Provider> </HotContainer>, appContainer ); if (module.hot) { module.hot.accept('./components/app', () => { require('./components/app'); ReactDOM.render( <HotContainer> <Provider store={store}> <App> <Frames /> <Analytics /> </App> </Provider> </HotContainer>, appContainer ); }); } } } export default new Aggregator();
var http = require('http'); var fs = require('fs'); var qs = require('querystring'); var redis = require('redis'); var client = redis.createClient(6379, 'redis'); client.on('connect', function() { console.log('Redis client connected'); }); client.on('error', function (err) { console.log('Something went wrong ' + err); }); // http.createServer(function (req, res) { if (req.method === 'GET' && req.url === '/') { res.writeHead(200, {'Content-Type': 'text/html'}); fs.readFile ('index.html', function(err, data) { res.write(data); res.end(); } ); } else if (req.method === 'GET' && req.url === '/status') { res.writeHead(200, {'Content-Type': 'application/json'}); var answer = { endpoint: req.url, clientIP: req.connection.remoteAddress }; res.write(JSON.stringify(answer)); res.end(); } else if (req.method === 'GET' && req.url === '/item') { res.writeHead(200, {'Content-Type': 'application/json'}); var dict = {}; client.keys('*', function(err, reply) { var keys = reply; var processItems = async function(x) { if (x === keys.length) { await res.end(JSON.stringify(dict)); return; } var value = keys[x]; client.get(value, function(err, reply) { dict[value]=reply; processItems(x+1); }); } processItems(0); }); } else if (req.method === 'POST' && req.url === '/item') { var postData = ''; req.on('data', function(content) { postData += content; if (postData.length > 1e6) { request.connection.destroy(); } }); req.on('end', function() { var payload = qs.parse(postData); res.writeHead(200, {'Content-Type': 'text/plain'}); client.set(payload.key, payload.value); res.write('New item added!'); res.end(); }); } else { res.statusCode = 404; res.end(); } }).listen(80);
import React from 'react' const Index = () => { return ( <div className="container-fluid"> <div className="row"> <div className="col-12"> <h1>Dashboard 1st</h1> </div> </div> </div> ); } export default Index;
import React, { useState } from 'react'; import { View, Text, TouchableOpacity, TextInput, Keyboard, } from 'react-native'; import globalStyles from './GlobalStyles'; export default function PetitGateau({ navigation }) { const [qtd, setQtd] = useState(''); const [ingredientes, setIngredientes] = useState({}); function handleSubmit() { setIngredientes({ chocolate: Math.round(((qtd * 120) / 5) * 100) / 100, manteiga: Math.round(((qtd * 100) / 5) * 100) / 100, ovos: Math.round(((qtd * 2) / 5) * 100) / 100, acucar: Math.round(((qtd * 0.25) / 5) * 100) / 100, farinha: Math.round(((qtd * 2) / 5) * 100) / 100, }); Keyboard.dismiss(); } return ( <View style={globalStyles.container}> <TextInput style={globalStyles.input} value={qtd} onChangeText={value => setQtd(value)} keyboardType="numeric" placeholder="Digite a quantidade desejada..." placeholderTextColor="#999" onSubmitEditing={handleSubmit} /> <TouchableOpacity onPress={handleSubmit} style={globalStyles.primaryButton}> <Text style={globalStyles.primaryButtonText}>Calcular</Text> </TouchableOpacity> {ingredientes.chocolate && ( <View style={globalStyles.ingredientes}> <Text style={globalStyles.ingredientesTitle}>Ingredientes: </Text> <Text style={globalStyles.ingredientesText}> {ingredientes.chocolate} g de chocolate meio amargo </Text> <Text style={globalStyles.ingredientesText}> {ingredientes.manteiga} g de manteiga </Text> <Text style={globalStyles.ingredientesText}> {ingredientes.ovos} ovos </Text> <Text style={globalStyles.ingredientesText}> {ingredientes.acucar} de xícara (chá) de açúcar </Text> <Text style={globalStyles.ingredientesText}> {ingredientes.farinha} colheres (sopa) de farinha de trigo </Text> </View> )} </View> ); } PetitGateau.navigationOptions = { title: 'Petit Gateau', };
import saveFile from "../saveFile"; import tag from 'html-tag-js'; import searchSettings from "../../pages/settings/searchSettings"; /** * * @param {TouchEvent | MouseEvent} e * @param {HTMLElement} footer * @param {string} row1 * @param {string} row2 */ function quickToolAction(e, footer, row1, row2, search) { if (!e.target) return; const el = e.target; const action = el.getAttribute('action'); if (!action) return; const editor = editorManager.editor; const $row2 = footer.querySelector('#row2'); const $searchRow1 = footer.querySelector('#search_row1'); const $searchRow2 = footer.querySelector('#search_row2'); const $textarea = editor.textInput.getElement(); const shiftKey = footer.querySelector('#shift-key').getAttribute('data-state') === 'on' ? true : false; let $searchInput = footer.querySelector('#searchInput'), $replaceInput = footer.querySelector('#replaceInput'), state, selectedText = editor.getCopyText(); if (selectedText.length > 50) selectedText = ''; if (!['pallete', 'search', 'search-settings'].includes(action) && editorManager.state === 'focus') editor.focus(); switch (action) { case 'pallete': editor.execCommand('openCommandPallete'); break; case 'tab': $textarea.dispatchEvent(new KeyboardEvent('keydown', { key: 9, keyCode: 9, shiftKey })); break; case 'shift': state = el.getAttribute('data-state') || 'off'; if (state === 'off') { $textarea.dispatchEvent(new KeyboardEvent('keydown')); el.setAttribute('data-state', 'on'); el.classList.add('active'); } else { $textarea.dispatchEvent(new KeyboardEvent('keyup')); el.setAttribute('data-state', 'off'); el.classList.remove('active'); } break; case 'undo': if (editor.session.getUndoManager().hasUndo()) editor.undo(); else break; if (!editor.session.getUndoManager().hasUndo()) { editorManager.activeFile.isUnsaved = false; editorManager.onupdate(); } break; case 'redo': editor.redo(); break; case 'search': if (!$searchRow1) { if ($row2) { removeRow2(); } footer.append(...tag.parse(search)); if (!$searchInput) $searchInput = footer.querySelector('#searchInput'); $searchInput.value = selectedText || ''; if (!selectedText) $searchInput.focus(); $searchInput.oninput = function () { if (this.value) find(false, false); }; root.classList.add('threestories'); find(false, false); } else { removeSearchRow2(); } editor.resize(true); break; case 'save': saveFile(editorManager.activeFile); break; case 'more': if (!$row2) { if ($searchRow1) { removeSearchRow2(); } footer.appendChild(tag.parse(row2)); root.classList.add('twostories'); } else { removeRow2(); } editor.resize(true); break; case 'moveline-up': editor.moveLinesUp(); break; case 'moveline-down': editor.moveLinesDown(); break; case 'copyline-up': editor.copyLinesUp(); break; case 'copyline-down': editor.copyLinesDown(); break; case 'next': find(true, false); break; case 'prev': find(true, true); break; case 'replace': editor.replace($replaceInput.value || ''); break; case 'replace-all': editor.replaceAll($replaceInput.value || ''); break; case 'search-settings': editor.blur(); searchSettings(); break; } function removeRow2() { footer.removeChild($row2); root.classList.remove('twostories'); } function removeSearchRow2() { footer.removeAttribute('data-searching'); footer.removeChild($searchRow1); footer.removeChild($searchRow2); root.classList.remove('threestories'); } function find(skip, backward) { const searchSettings = appSettings.value.search; editor.find($searchInput.value, { skipCurrent: skip, backwards: backward, caseSensitive: searchSettings.caseSensitive, wrap: searchSettings.wrap, wholeWord: searchSettings.wholeWord, regExp: searchSettings.regExp }); updateStatus(); } function updateStatus() { var regex = editor.$search.$options.re; var all = 0; var before = 0; const MAX_COUNT = 999; if (regex) { const value = editor.getValue(); const offset = editor.session.doc.positionToIndex(editor.selection.anchor); let last = regex.lastIndex = 0; let m; while ((m = regex.exec(value))) { all++; last = m.index; if (last <= offset) before++; if (all > MAX_COUNT) break; if (!m[0]) { regex.lastIndex = last += 1; if (last >= value.length) break; } } } footer.querySelector('#total-result').textContent = all > MAX_COUNT ? '999+' : all; footer.querySelector('#current-pos').textContent = before; } } export default quickToolAction;
export default { userInfo: 'init', showToast: false, }
// Youtube Video React component to render based on an input video ID import React from 'react'; import YouTube from 'react-youtube'; import PropTypes from "prop-types"; class YoutubeVideo extends React.Component { render() { // Video dimensions const opts = { height: '500', width: '750', playerVars: { // https://developers.google.com/youtube/player_parameters autoplay: 0 } }; return ( <YouTube videoId={this.props.videoURL} opts={opts} onReady={this._onReady} /> ); } _onReady(event) { // access to player in all event handlers via event.target event.target.pauseVideo(); } } YoutubeVideo.propTypes = { videoURL: PropTypes.string.isRequired }; export default YoutubeVideo;
import React, { useEffect, useState } from 'react'; import Axios from 'axios'; import { navigate } from '@reach/router'; const EditExample = (props) => { const [exampleDetails, setExampleDetails] = useState({ firstName: "", lastName: "", points: "" }) const [errors, setErrors] = useState({}) useEffect(() => { Axios.get(`http://localhost:8000/api/examples/${props.exampleId}`) .then(response => { console.log("RESPONSE FROM API CALL", response) setExampleDetails(response.data.results) }) .catch() }, []) console.log("********", props.exampleId) const changeHandler = e => { console.log("ohhhhh you tryin to edit something huhhh") setExampleDetails({ ...exampleDetails, [e.target.name]: e.target.value }) } const submitHandler = e => { e.preventDefault(); Axios.put(`http://localhost:8000/api/examples/update/${props.exampleId}`, exampleDetails) .then(response => { console.log("JUST UPDATED SOMETHANGGG! HERE IS THE RESPONSE", response) if (response.data.results) { navigate('/') } else { setErrors(response.data.errors) } }) .catch(err => console.log("ERROR ON TRYIN TO UPDATE", err)) } return ( <div> <h2>Edit {exampleDetails.name}</h2> <form onSubmit={submitHandler}> <div className="row"> <div className="col-2"></div> <div className="col-4"> <h3>Info</h3> <h3>(required)</h3> <div> <div><label htmlFor="">Pet Name</label></div> <div><input type="text" name="name" onChange={changeHandler} id="" value={exampleDetails.name} /></div> <span className="text-danger">{errors.name ? errors.name.message : ""}</span> </div> <div> <div><label htmlFor="">Type</label></div> <div><input type="text" name="type" onChange={changeHandler} id="" value={exampleDetails.type} /></div> <span className="text-danger">{errors.type ? errors.type.message : ""}</span> </div> <div> <div><label htmlFor="">Description</label></div> <div><input type="text" name="description" onChange={changeHandler} id="" value={exampleDetails.description} /></div> <span className="text-danger">{errors.description ? errors.description.message : ""}</span> </div> <br /> <input style={{ backgroundColor: "blue" }} type="submit" value=" Add Pet " /> </div> <div className="col-4"> <h3>Skills</h3> <h3>(optional):</h3> <div> <div><label htmlFor="">Skill 1:</label></div> <div><input type="text" name="skill1" onChange={changeHandler} id="" value={exampleDetails.skill1} /></div> <span className="text-danger">{errors.skill1 ? errors.skill1.message : ""}</span> </div> <div> <div><label htmlFor="">Skill 2:</label></div> <div><input type="text" name="skill2" onChange={changeHandler} id="" value={exampleDetails.skill2} /></div> <span className="text-danger">{errors.skill2 ? errors.skill2.message : ""}</span> </div> <div> <div><label htmlFor="">Skill 3:</label></div> <div><input type="text" name="skill3" onChange={changeHandler} id="" value={exampleDetails.skill3} /></div> <span className="text-danger">{errors.skill3 ? errors.skill3.message : ""}</span> </div> <div className="col-2"></div> </div> </div> </form> </div> ); }; export default EditExample;
import { DefaultTheme } from 'styled-components'; export const theme = { main_color : "#418AFF", hover_color : "#2D59B8", white : "#FFFFFF", grey : "#C4C4C4", light_grey : "#EFEFEF", text_grey : "#898989", light_blue : "#D7E6FF", black : "#000000", footer_bg_color : "#F6F6F8", footer_text_color : "#6C6C6C", } /* 사용 시 ${props => props.theme.main_color}; */
var o, i = require("./Util"), d = require("./Fish_UserData"); (o = exports.emTargetType || (exports.emTargetType = {}))[o.T_BeEaten = 0] = "T_BeEaten", o[o.T_FishMax = 1] = "T_FishMax", o[o.T_FishTypeMax = 2] = "T_FishTypeMax", o[o.T_EatFishTotal = 3] = "T_EatFishTotal", o[o.T_BigFishNum = 4] = "T_BigFishNum", o[o.T_FishFeedTotal = 5] = "T_FishFeedTotal", o[o.T_BigFishFeedTotal = 6] = "T_BigFishFeedTotal", o[o.T_ContinuousFeed_1 = 7] = "T_ContinuousFeed_1", o[o.T_ContinuousFeed_2 = 8] = "T_ContinuousFeed_2", o[o.T_Survival = 9] = "T_Survival", o[o.T_SharkNum = 10] = "T_SharkNum", o[o.T_GoldTotal = 11] = "T_GoldTotal", o[o.T_ContinuousGold_1 = 12] = "T_ContinuousGold_1", o[o.T_ContinuousGold_2 = 13] = "T_ContinuousGold_2", o[o.T_OpenBoxNum = 14] = "T_OpenBoxNum"; var n = function() { function t() {} return exports.CfgLoadComplete = function() { return 6 <= this.loadNum; }, exports.LoadCfg = function() { if (!(7 <= this.loadNum)) { console.log("初始化json存储数据"); var t = cc.url.raw("resources/fishPop/config/FishCfg.json"); cc.loader.load(t, function(o, e) { return (this.loadNum++, o) ? (console.error("load FishCfg failed"), void console.error(o.message || o)) : void(console.log("load FishCfg success"), this.analysisFishCfg(e, "targetType", this.FishTargetDatas)); }.bind(this)), t = cc.url.raw("resources/fishPop/config/FishSkinCfg.json"), cc.loader.load(t, function(o, e) { return (this.loadNum++, o) ? (console.error("load FishSkinCfg failed"), void console.error(o.message || o)) : void(console.log("load FishSkinCfg success"), this.FishSkinDatas = e); }.bind(this)), t = cc.url.raw("resources/fishPop/config/FishSignCfg.json"), cc.loader.load(t, function(o, e) { return (this.loadNum++, o) ? (console.error("load FishSignCfg failed"), void console.error(o.message || o)) : void(console.log("load FishSignCfg success"), this.analysisFishCfg(e, "key", this.FishSignList, 1)); }.bind(this)), cc.loader.loadRes("atlas/fishSkin", cc.SpriteAtlas, function(o, e) { this.loadNum++, o ? cc.error("no loadRes fishSkin") : (cc.log("fishSkin ok"), this.FishSkinSpriteFrames = e._spriteFrames); }.bind(this)), cc.loader.loadRes("fishPop/Texture/public_icon_gold", cc.SpriteFrame, function(o, e) { this.loadNum++, o ? cc.error("no loadRes public_icon_gold") : (cc.log("public_icon_gold ok"), this.RewardSpriteFrames[0] = e); }.bind(this)), cc.loader.loadRes("fishPop/Texture/public_icon_protect", cc.SpriteFrame, function(o, e) { this.loadNum++, o ? cc.error("no loadRes public_icon_protect") : (cc.log("public_icon_protect ok"), this.RewardSpriteFrames[1] = e); }.bind(this)), cc.loader.loadRes("fishPop/Texture/public_icon_magnet", cc.SpriteFrame, function(o, e) { this.loadNum++, o ? cc.error("no loadRes public_icon_magnet") : (cc.log("public_icon_magnet ok"), this.RewardSpriteFrames[2] = e); }.bind(this)); } }, exports.pushObj = function(a, e, t, o) { void 0 === o && (o = 0), e.rewardNum = JSON.parse(e.rewardNum), e.rewardType = "" == e.rewardType ? [] : JSON.parse(e.rewardType), void 0 === t[a] && (t[a] = []), 0 == o ? t[a].push(e) : t[a] = e; }, exports.analysisFishCfg = function(r, e, t, o) { void 0 === o && (o = 0); for (var i, s = 0; r;) { if (i = r[(++s).toString()], !i) return; this.pushObj(i[e], i, t, o); } console.log(t); }, exports.getSignRewardByDay = function(t) { return this.FishSignList[t] || null; }, exports.getTargetsByType = function(t) { return this.FishTargetDatas[t] ? this.FishTargetDatas[t] : (console.error("不存在该类型目标_1" + t), null); }, exports.getTargetValidByType = function(r, e, t) { var o = this.FishTargetDatas[r]; this.FishCompleteList = d.Fish_UserData.getCompleteList(); var l = this.FishCompleteList[t], n = []; if (!o) return console.error("不存在该类型目标_2" + r), n; for (var a = 0; a < o.length; a++) { if (!(o[a].num <= e)) return n; l < o[a].level && n.push(o[a]); } return n; }, exports.getAllTargetValidByArryType = function(r) { for (var e, i = [], t = 0; t < r.length; t++) { e = this.FishTargetDatas[t], this.FishCompleteList = d.Fish_UserData.getCompleteList(); var o = this.FishCompleteList[t]; if (e) for (var n = 0; n < e.length && e[n].num <= r[t]; n++) o < e[n].level && (i.push(e[n]), this.FishCompleteList[t] = e[n].level, console.log("完成目标保存:" + t + ":" + this.FishCompleteList[t])); else console.log("不存在该类型目标_3" + t); } return d.Fish_UserData.setCompleteList(this.FishCompleteList), i; }, exports.getNoCompleteByType = function(a, e) { var t = this.FishTargetDatas[a]; this.FishCompleteList = d.Fish_UserData.getCompleteList(); var o = this.FishCompleteList[a]; if (t) { for (var i = 0; i < t.length; i++) if (t[i].num > e && (console.log("完成等级:" + o), o < t[i].level)) return t[i]; return console.log("该类型不存在未完成目标"), null; } return console.log("不存在该类型目标_3" + a), null; }, exports.getSkinList = function() { return this.FishSkinDatas; }, exports.getSkinSpriteFrameByKey = function(t) { return this.FishSkinSpriteFrames[t]; }, exports.saveComplete = function(o) { var e = JSON.stringify(o); console.log("本地保存完成记录:" + e), i.Util.SaveDataByKey("fristComplete", e); }, exports.getRewardFrameByKey = function(t) { return this.RewardSpriteFrames[t]; }, exports.loadNum = 0, exports.FishTargetDatas = {}, exports.FishSkinDatas = {}, exports.FishSkinSpriteFrames = {}, exports.FishCompleteList = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], exports.FishSignList = {}, exports.RewardSpriteFrames = [null, null, null], exports; }(); exports.FishCfgMgr = n;
import PropTypes from 'prop-types'; import React from 'react'; import { SvgIcon } from '@material-ui/core'; const CloseIcon = ({ color, fontSize }) => ( <SvgIcon style={{ color, fontSize }} width="29" height="29" viewBox="0 0 21.96 21.96"> <path className="cls-close" d="M37.77,22.23a11,11,0,1,0,0,15.54A11,11,0,0,0,37.77,22.23Zm-.71,14.83a10,10,0,1,1,0-14.12A10,10,0,0,1,37.06,37.06ZM34.51,26.55,31.06,30l3.45,3.45a.75.75,0,0,1,0,1.06.79.79,0,0,1-.53.22.75.75,0,0,1-.53-.22L30,31.06l-3.45,3.45a.75.75,0,0,1-.53.22.79.79,0,0,1-.53-.22.75.75,0,0,1,0-1.06L28.94,30l-3.45-3.45a.75.75,0,0,1,1.06-1.06L30,28.94l3.45-3.45a.75.75,0,1,1,1.06,1.06Z" transform="translate(-19.02 -19.02)" /> </SvgIcon> ); CloseIcon.propTypes = { color: PropTypes.string, fontSize: PropTypes.number, }; CloseIcon.defaultProps = { color: '#fff', fontSize: 20, }; export default CloseIcon;