text
stringlengths
7
3.69M
const validateRequest = ({ tableName, operation, dataKeys, excludeAdminEvents, comparisonFunction }) => req => { const { table = {}, event = {} } = req.body if ( table.name !== tableName || event.op !== operation || !event.data || (Array.isArray(dataKeys) && dataKeys.some(key => !event.data[key])) ) { return true } if (excludeAdminEvents && event.session_variables && event.session_variables['x-hasura-role'] === 'admin') { return true } if (typeof comparisonFunction === 'function' && comparisonFunction(event.data.old, event.data.new)) { return true } return false } module.exports = { validateRequest }
const github = 'https://github.com/login/oauth/authorize' const clientId = import.meta.env.VITE_CLIENT_ID import { loginRedirectTo } from '$lib/stores'; export async function get(req) { const redirectTo = req.query.get("redirectTo") || '/' loginRedirectTo.update(() => redirectTo) const sessionId = 'den0IsN3xt' return { status: 302, headers: { location: `${github}?client_id=${clientId}&state=${sessionId}` }, body: 'redirecting...' } }
jQuery(document).ready(function(){ jQuery('input.birthdate,input.psprt_date').datepicker({ changeMonth: true, changeYear: true, yearRange: Date.today().add({years: -120}).toString('yyyy') + ":" + Date.today().toString('yyyy') }); });
const fruits = ['maçã', 'pêra', 'uva']; for(let i = 0; i < fruits.length; i++) { console.log(`índice ${i}:`, fruits[i]); } // const even = i % 2 == 0 ? `${i} é par` : `${i} é ímpar`; // console.log(even);
const { addDocument } = require('./dataHandler'); const questions = require('./question_data'); const questions_in_exam = process.env.QUESTION_COUNT || 1; //FOR DEV PURPOSE 1 let current_chunk = 0; let shuffled_index = shuffle([...Array(questions.length).keys()]) ; function pre_process_questions(from, to) { shuffle_part = shuffled_index.slice(from, to) filtered = shuffle_part.map((elem, index) => (questions[elem])) return filtered.map((elem, index) => { let ret = {} ret.title = ['نسبت', elem.question.w0, 'به', elem.question.w1, 'مثل کدام است؟'].join(' '); ret.options = elem.options.map((el) => { return [el.w0, 'به', el.w1].join(' '); }); ret.options.push('هیچکدام'); ret.index = shuffle_part[index]; return ret; }); } function post_process_answers(payload) { ret = { userData: payload.userData, answers: payload.answers, } ret.questions = payload.questions.map((elem)=> { return { shown_question: elem, original_question: questions[elem.index] } }) ; return ret ; } function shuffle(a) { for (let i = a.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [a[i], a[j]] = [a[j], a[i]]; } return a; } module.exports.answerHandler = function (req, res) { let payload = req.body ; addDocument(post_process_answers(payload), console.log); res.send('Done'); } module.exports.questionHandler = function (req, res) { if ((current_chunk + 1) * questions_in_exam > questions.length){ current_chunk = 0; console.log('Resetting Chunk'); } console.log('sending next chunck ', current_chunk); ret = pre_process_questions(current_chunk * questions_in_exam, (current_chunk + 1) * questions_in_exam) ; res.send(ret); current_chunk = current_chunk + 1 }
const express = require("express"); const db = require("../../models/index"); const { countries,license,licenseRole } = require("../../constants"); const router = {}; // Get Login Activities router.saveLoginActivities = async () => { try { console.log("===================================="); console.log("saveLoginActivities"); console.log("===================================="); // Get All Users Who have last login let getAllData = await db.sequelize.query( `SELECT * FROM ( SELECT user.id, IFNULL(user.lastLogin, "" ) AS lastLogin, DATE_FORMAT(lastLogin,'%Y-%m-%d') AS loginDate, IFNULL(shield_login.superUser, 0 ) AS superUserText FROM user LEFT JOIN shield_login ON shield_login.userId = user.id ) AS TEMP WHERE superUserText=0 AND lastLogin!=''`, { type: db.sequelize.QueryTypes.SELECT } ); console.log("getAllData:",getAllData); for (const user of getAllData) { let userId = user.id; let loginDate = user.loginDate; let lastLogin = user.lastLogin; // Check Same User On Same Date let getLoginActivities = await db.sequelize.query( `SELECT id FROM login_activities WHERE userId = '${userId}' AND loginDate = '${loginDate}'`, { type: db.sequelize.QueryTypes.SELECT } ); // If available then update console.log("getLoginActivitiesL:",getLoginActivities.length); if(getLoginActivities.length > 0) { for (const lt of getLoginActivities) { // console.log("lt:",lt); let updateLoginActivities = await db.sequelize.query(`UPDATE login_activities SET loginDateTime='${lastLogin}' WHERE id='${lt.id}'`, { type: db.sequelize.QueryTypes.UPDATE } ); // console.log("updateLoginActivities:",updateLoginActivities); } } // Not Available then insert else { let addLoginActivities = await db.sequelize.query( `INSERT INTO login_activities SET userId='${userId}',loginDate='${loginDate}',loginDateTime='${lastLogin}'`, { type: db.sequelize.QueryTypes.INSERT } ); } } } catch (error) { console.log("error.message:",error.message); } }; module.exports = router;
import React from 'react'; import './Footer.css'; import GithubLogo from '../../images/github.png'; import LinkedInLogo from '../../images/linked.png'; const Footer = () => ( <div> <div className="footer-buffer"> </div> <footer className="page-footer font-small"> <div className="container-fluid text-center"> <div className="row justify-content-center"> <a href="https://github.com/JameyMcAuliffe"> <img src={GithubLogo} alt="github-logo" className="footer-logo mt-3 mb-3 mr-3"/> </a> <a href="https://www.linkedin.com/in/jamey-mcauliffe/"> <img src={LinkedInLogo} alt="linked-in-logo" className="footer-logo mt-3 mb-3 ml-3"/> </a> </div> <div className="row justify-content-center footer-copyright copyright-div"> <p>Copyright 2019 <a href="https://jameymcauliffe.github.io/">Jamey McAuliffe</a></p> </div> </div> </footer> </div> ); export default Footer
import React, { useState, memo, useEffect,useMemo } from 'react'; import { connect } from 'react-redux'; import { OrderTab, OrderType, TypeItem, OrderAd } from './Order.style'; import { NavLink, Link, withRouter } from 'react-router-dom'; import * as actionTypes from '../../pages/details/store/actionCreators' import { renderRoutes } from "react-router-config"; import OrderItem from './OrderItem' import BlankOrderComponent from './BlankOrder'; function Order(props) { const { route } = props; const { orderdata } = props; const [orderIndex, setorderIndex] = useState(0); const handleOnclick = (index) => { setorderIndex(index); } const init=()=>{ if(props.location.pathname==="/order/all"){ handleOnclick(4); } if(props.location.pathname==="/order/evaluated"){ handleOnclick(3); } if(props.location.pathname==="/order/paid"){ handleOnclick(2); } if(props.location.pathname==="/order/service"){ handleOnclick(1); } if(props.location.pathname==="/order/confirm"){ handleOnclick(0); } // console.log(props); }; useEffect(()=>{ init(); },[]) // console.log(orderdata, '获取到detail的store啦',orderIndex) return ( <> <OrderTab> <Link to='/home/my'> <div className="iconfont order-tab__icon">&#xe670;</div> </Link> <div className="order-tab__title">全部订单</div> <div className=" order-tab__right">分类 <span className='iconfont'>&#xe63d;</span></div> </OrderTab> <OrderType> <NavLink to='/order/confirm' activeClassName='selected' onClick={() => { handleOnclick(0); }}> <TypeItem><span>待确认</span></TypeItem> </NavLink> <NavLink to='/order/service' activeClassName='selected' onClick={() => { handleOnclick(1); }}> <TypeItem><span>待服务</span></TypeItem> </NavLink> <NavLink to='/order/paid' activeClassName='selected' onClick={() => { handleOnclick(2); }}> <TypeItem><span>待支付</span></TypeItem> </NavLink> <NavLink to='/order/evaluated' activeClassName='selected' onClick={() => { handleOnclick(3); }}> <TypeItem><span>待评价</span></TypeItem> </NavLink> <NavLink to='/order/all' activeClassName='selected' onClick={() => { handleOnclick(4); }}> <TypeItem><span>全部</span></TypeItem> </NavLink> </OrderType> <OrderAd> 到家优选订单,点击这里查看 &#62; </OrderAd> { orderIndex ==4?(orderdata.length!=0 ? (<OrderItem data={orderdata} />) : (<BlankOrderComponent />)): (orderdata.filter((item) => item.type == orderIndex).length!=0? (<OrderItem data={orderdata} />) : (<BlankOrderComponent />)) } {renderRoutes(route.routes)} </> ) } const mapStateToProps = (state) => ({ orderdata: state.order.orderdata }) const mapDispatchToProps = (dispatch) => { return { initorderDataDiapatch() { dispatch(actionTypes.initorderData()) } } } export default connect(mapStateToProps, mapDispatchToProps)( withRouter(memo(Order)))
"use strict" jest.unmock('../Category.jsx'); var React = require('react'); var TestUtils = require('react-dom/test-utils'); var Category = require('../Category.jsx'); describe('Category', function() { it('renders without throwing', function() { TestUtils.renderIntoDocument( <Category /> ); }); });
ejs.xml.XmlNamespace = function(name, prefix) { this.urn = name; this.prefix = prefix; }
'use strict'; angular.module('pupparoniApp') .controller('ProductListCtrl', function ($scope, $http, socket) { $scope.productList = []; $http.get('/api/products').success(function(productList) { $scope.productList = productList; socket.syncUpdates('product', $scope.productList); }); $scope.addItem = function() { if($scope.newProduct === '') { return; } $http.post('/api/products', { name: $scope.newProduct }); $scope.newProduct = ''; }; $scope.deleteProduct = function(product) { $http.delete('/api/products/' + product._id); }; $scope.$on('$destroy', function () { socket.unsyncUpdates('product'); }); });
// main document ready function to check if dom is loaded fully or not let myFacebookToken; $(document).ready(() => { $('#dataSection4').css('display','none'); $('#dataSection1').css('display','none'); $('#dataSection2').css('display','none'); $('#dataSection3').css('display','none'); myFacebookToken = prompt("Please enter your Facebook Token:", ""); if (myFacebookToken == null || myFacebookToken == "") { alert("No usr Token found"); } else { showAllDetails(); } // end if condition }); // end document.ready function let showAllDetails = () => { console.log("showalldetails called"); $('#dataSection4').css('display','block'); $('#dataSection1').css('display','none'); $('#dataSection2').css('display','none'); $('#dataSection3').css('display','none'); $('#dataSection4 #fbFeedBtn').on('click', function () { console.log("fbFeedbutton clicked"); var display = $("#dataSection3").css("display"); if(display!="none") { $('#dataSection3').css('display','none'); } else{ showFeedPage();//call to show fb feed page } }) $('#dataSection4 #fbProfileBtn').on('click', function () { console.log("fbprofilebutton clicked"); var display = $("#dataSection1").css("display"); if(display!="none") { $('#dataSection1').css('display','none'); } else{ console.log("fbBlockMainProfileprofilebutton clicked"); getAllDetails();//call to show fb profile page } }) } let getAllDetails = () => { // API call to get user details $.ajax({ type: 'GET', dataType: 'json', async: true, url: 'https://graph.facebook.com/me?fields=name,quotes,cover,picture.type(large)&access_token=' + myFacebookToken, success: (response) => { $('#dataSection3').css('display','none'); $('#dataSection1').css('display','block'); console.log(response); $('#userName').append(response.name); $('#profilePhoto').html('<img src="' + response.picture.data.url + '" class="img-fluid profileHeight"/>'); $('#cover').css('background-image', 'url(' + response.cover.source + ')'); }, error: (err) => { console.log(err.responseJSON.error.message); alert(err.responseJSON.error.message) } });// end ajax call } //Function to show fb posts feed on click of Get Fb Posts Feed button on homepage //var myFacebookToken = $("#api").val();//store the api token from homepage let showFeedPage = () => { //ajax request to get fb data $.ajax({ type: 'GET', dataType: 'json', async: true, url: 'https://graph.facebook.com/me?fields=posts{created_time,type,full_picture,story,message,source,likes.limit(1).summary(true),comments.limit(1).summary(true)},picture.width(250).height(250),cover,name&access_token=' + myFacebookToken, success: function (response) { $('#dataSection1').css('display','none'); $('#dataSection2').css('display','none'); $('#dataSection3').css('display','block'); $("#fbFeedInfo").html('<div></div>');//clear the data when user makes consecutive requests var feeds = response.posts.data;//store the fb posts data array console.log(feeds); //map function to loop through the posts data $.map(feeds, function (value, index) { var post = feeds[index]; //switch case to call particular posts function based on fb posts type switch (post.type) { case 'photo':{ var likes=post.likes; var likesCount = post.likes.summary.total_count; var commentsCount = post.comments.summary.total_count; createPhotoPost(post.story,likes, post.full_picture,likesCount,commentsCount); } break; case 'video':{ var likesCount = post.likes.summary.total_count; var likes=post.likes; var commentsCount = post.comments.summary.total_count; createVideoPost(post.story,likes, post.source,likesCount,commentsCount); } break; } }); //function to create photo post function createPhotoPost(story,Likes,full_picture,likesCount,commentsCount) { var sectionStart = '<section id="photo" class="post1">'+'<div class="story">'+story+'</div>'; var pictureURL = '<div class="picture" style ="background-image:url('+full_picture+')";>'+'</div>'; //var pictureURL = '<img src="url('+full_picture+')";>'+'</img>'; var sectionEnd = '</span>'+'</a>'+'</div>'+'</section>'; var postElement = sectionStart+pictureURL+sectionEnd; $("#fbFeedInfo").append(postElement); } //function to create video post function createVideoPost(story,Likes,source,likesCount,commentsCount) { var sectionStart = '<section id="video" class="post1">'; var postStory = '<div class="story">'+story+'</div>'; var postVideo = '<div class="video">'+'<video controls>'+'<source src= '+source+' type= "video/mp4">'+'</video>'+'</div>'; var likeSection = '<div class="likeCommentContainer">'+'<a href="#" class="likeBox">'+Likes+'<span class="badge">' +likesCount+''; var commentSection = '</span>'+'</a>'+'<a href="#" class="commentBox">'+Comment+'<span class="badge">'+ commentsCount+'</section>'; var postElement = sectionStart+postStory+postVideo; $("#fbFeedInfo").append(postElement); } }, // end of success //error handling error: function (jqXHR) { alert(jqXHR.responseJSON.error.message + "Please refresh the page and Enter valid API token"); }, });//end ajax call }
var myModule = (function(window, $, undefined) { var _myPrivateVar1 = ""; var _myPrivateVar2 = ""; var _myPrivateFunc = function() { return _myPrivateVar1 + _myPrivateVar2; }; return { getMyVar1: function() { return _myPrivateVar1; }, setMyVar1: function(val) { _myPrivateVar1 = val; }, someFunc: _myPrivateFunc }; }) (window, jQuery);
import React from 'react' import { connect } from 'react-redux' import SearchBar from './SearchBar' import VideoList from './VideoList' import SelectedVideo from './SelectedVideo' import { searchVideos, onInputChange } from '../../redux/actions/youtube' import './YoutubeSearch.css' class YoutubeSearch extends React.PureComponent { componentDidMount() { const firstSearch = 'react conf' this.props.onInputChange(firstSearch) this.props.searchVideos(firstSearch) } render() { return ( <React.Fragment> <SearchBar /> <div className="videos-container"> <SelectedVideo /> <VideoList /> </div> </React.Fragment> ) } } export default connect(null, { searchVideos, onInputChange })(YoutubeSearch)
const request = require("supertest"); const app = require("../src/preloadSetup"); const Task = require("../models/task"); const { preloadDatabaseSetup, userOne, userOneId, taskOne, userTwo } = require("./fixtures/dbPreload"); // jests global lifecycle methods beforeEach(() => {...}) and afterEach(() => {...}) beforeEach(preloadDatabaseSetup); test("should create task for auth user", async () => { await request(app) .post("/tasks") .set("Authorization", `Bearer ${userOne.tokens[0].token}`) .send({ description: "third task for user one" }) .expect(201); const tasks = await Task.find({ author: userOneId }) .populate("author") .exec(); expect(tasks).toHaveLength(3); // console.log(tasks[0]); // {_id: ObjectId, completed: fasle, description: "...", author: {...}} expect(tasks[2].description).toBe("third task for user one"); expect(tasks[2].completed).toBeFalsy(); }); test("should get all tasks for auth user", async () => { const res = await request(app) .get("/tasks") .set("Authorization", `Bearer ${userOne.tokens[0].token}`) .send() .expect(200); // console.log(res.body); // [{...}, ...] expect(res.body).toHaveLength(2); }); test("should fail to delete task when owner is another user", async () => { // ... await request(app) .delete(`/tasks/${taskOne._id}`) .set("Authorization", `Bearer ${userTwo.tokens[0].token}`) .send() .expect(404); const task = await Task.findById(taskOne._id); expect(task).not.toBeNull(); }); test("Should not create task with invalid description/completed", async () => { await request(app) .post("/tasks") .set("Authorization", `Bearer ${userOne.tokens[0].token}`) .send({ description: "" }) .expect(400); await request(app) .post("/tasks") .set("Authorization", `Bearer ${userOne.tokens[0].token}`) .send({ description: "description from test", completed: 12 * 10 }) .expect(400); }); test("Should not update task with invalid description/completed", async () => { await request(app) .patch(`/tasks/${taskOne._id}`) .set("Authorization", `Bearer ${userOne.tokens[0].token}`) .send({ description: "" }) .expect(400); await request(app) .patch(`/tasks/${taskOne._id}`) .set("Authorization", `Bearer ${userOne.tokens[0].token}`) .send({ completed: 12 * 10 }) .expect(400); }); test("Should delete user task", async () => { await request(app) .delete(`/tasks/${taskOne._id}`) .set("Authorization", `Bearer ${userOne.tokens[0].token}`) .send() .expect(200); }); test("Should not delete task if unauthenticated", async () => { await request(app) .delete(`/tasks/${taskOne._id}`) .send() .expect(401); }); test("Should not update other users task", async () => { await request(app) .patch(`/tasks/${taskOne._id}`) .set("Authorization", `Bearer ${userTwo.tokens[0].token}`) .send({ completed: true }) .expect(404); }); test("Should fetch user task by id", async () => { const res = await request(app) .get(`/tasks/${taskOne._id}`) .set("Authorization", `Bearer ${userOne.tokens[0].token}`) .send() .expect(200); expect(res.body).not.toBeNull(); }); test("Should not fetch user task by id if unauthenticated", async () => { await request(app) .get(`/tasks/${taskOne._id}`) .send() .expect(401); }); test("Should not fetch other users task by id", async () => { await request(app) .get(`/tasks/${taskOne._id}`) .set("Authorization", `Bearer ${userTwo.tokens[0].token}`) .send() .expect(404); }); test("Should fetch only completed tasks", async () => { const res = await request(app) .get("/tasks?completed=true") .set("Authorization", `Bearer ${userOne.tokens[0].token}`) .send() .expect(200); expect(res.body).toHaveLength(1); }); test("Should fetch only incompleted tasks", async () => { const res = await request(app) .get("/tasks?completed=false") .set("Authorization", `Bearer ${userOne.tokens[0].token}`) .send() .expect(200); expect(res.body).toHaveLength(1); }); test("Should sort tasks by description/completed/createdAt/updatedAt", async () => { const res1 = await request(app) .get("/tasks?sortBy=description:asc") .set("Authorization", `Bearer ${userOne.tokens[0].token}`) .send() .expect(200); expect(res1.body).toHaveLength(2); const res2 = await request(app) .get("/tasks?sortBy=completed:asc") .set("Authorization", `Bearer ${userOne.tokens[0].token}`) .send() .expect(200); expect(res2.body).toHaveLength(2); const res3 = await request(app) .get("/tasks?sortBy=createdAt:desc") .set("Authorization", `Bearer ${userOne.tokens[0].token}`) .send() .expect(200); expect(res3.body).toHaveLength(2); const res4 = await request(app) .get("/tasks?sortBy=updatedAt:desc") .set("Authorization", `Bearer ${userOne.tokens[0].token}`) .send() .expect(200); expect(res4.body).toHaveLength(2); }); test("Should fetch page of tasks", async () => { const res = await request(app) .get("/tasks?limit=2&skip=1") .set("Authorization", `Bearer ${userOne.tokens[0].token}`) .send() .expect(200); expect(res.body).toHaveLength(1); });
/* JQuery */ $(document).ready(function() { /* ===== INICIO - Menu de Categorias ===== */ $('#menuHorizontal ul li').click(function(){ var url = $(this).attr('url'); if(url != undefined){ window.location.href = url; return false; } }); $('#menuHorizontal ul li ul li').click(function(){ var url = $(this).attr('url'); if(url != undefined){ window.location.href = url; return false; } }); $('#menuVertical li').click(function(){ var url = $(this).attr('url'); if(url != undefined){ window.location.href = url; return false; } }); $('#menuVertical ul li ul div li').click(function(){ var url = $(this).attr('url'); if(url != undefined){ window.location.href = url; return false; } }); /*** Painel do Cliente ***/ $('#SideAccountMenu div ul li').click(function(){ var url = $(this).attr('url'); if(url != undefined){ window.location.href = url; return false; } }); /*** Painel de Novos Produtos ***/ $('.attributes_wrapper_div div#SideNewProducts div.BlockContent ul li').click(function(){ var url = $(this).attr('url'); if(url != undefined){ window.location.href = url; return false; } }); /* ===== FIM - Menu de Categorias ===== */ /* ===== SCROLL EM MENSAGEM DE AVISO NA TELA ===== */ /* if($('.InfoMessage').length || $('.SuccessMessage').length || $('.ErrorMessage').length){ var campoMensagem; if($('.InfoMessage').length){ campoMensagem = $('.InfoMessage').eq(0); }else if($('.SuccessMessage').length){ campoMensagem = $('.SuccessMessage').eq(0); }else if($('.ErrorMessage').length){ campoMensagem = $('.ErrorMessage').eq(0); } $('html,body').animate({scrollTop: $(campoMensagem).offset().top - 35}, 1500); } */ /* ===== INICIO - CHECKOUT CIELO ===== */ /* $('.checkout_cielo_parcelas_div > div > input:radio').click(function(){ pegavalor(); }); */ /* ===== FIM - CHECKOUT CIELO ===== */ /* ===== INICIO - BUSCA POR CEP ===== */ $('.buscaCep').blur(function(event){ var cep = $.trim($(this).val()).replace('-', '').replace('_', ''); var parentForm = $(this).parents('form'); if(cep != "" && cep.length == 8){ buscaCep($(this).val(), parentForm); } }); /* ===== FIM - BUSCA POR CEP ===== */ /* ===== INICIO - TRATAMENTO CAMPOS CADASTRO DO CLIENTE ===== */ $('[attributeprivateid="companyname"]').hide(); $('[attributeprivateid="companyname"]').parent().prev().hide(); $('[attributeprivateid="cpf"]').mask("999.999.999-99"); $('[attributeprivateid="datanascimento"]').mask("99/99/9999"); $('[attributeprivateid="phone"]').mask("(99) 9999-9999"); $('[attributeprivateid="zip"]').mask("99999-999"); $('[attributeprivateid="country"]').hide(); $('[attributeprivateid="country"]').parent().prev().hide(); /* ===== FIM - TRATAMENTO CAMPOS CADASTRO DO CLIENTE ===== */ /* ===== INICIO - VARIAÇÃO DE PRODUTOS ===== */ $('.itemVariationProduct').click(function(){ var valorAtributoSelecionado = $(this).attr('value'); var indiceAtributoVariacao = $(this).parents('.GrupoAtributoVariacaoProduto').eq(0).attr('indiceAtributoVariacao'); if(!$(this).hasClass('itemVariationProductSelected') && !$(this).hasClass('itemVariationProductDisabled')){ var qtdeAtributos = $('.GrupoAtributoVariacaoProduto').length; $('.GrupoAtributoVariacaoProduto').each(function(){ if($(this).attr('indiceAtributoVariacao') >= indiceAtributoVariacao){ $(this).find('li').removeClass('itemVariationProductSelected'); // Desabilitando Atributos if($(this).attr('indiceAtributoVariacao') > indiceAtributoVariacao){ $(this).find('li').addClass('itemVariationProductDisabled'); } } }); $(this).addClass('itemVariationProductSelected'); // Mostra a Qtde de Estoque da Seleção mostraQtdeEstoqueSelecao(indiceAtributoVariacao, qtdeAtributos); /* Carrega Atributos Disponiveis Para Seleção */ carregaAtributosDisponiveisParaSelecao(indiceAtributoVariacao, valorAtributoSelecionado); /* Ajax - Carrega do Servidor o Conteudo da Selecao de Atributos */ carregaConteudoSelecaoServidorAjax(); } }); $('.itemVariationImageProduct').mouseover(function(){ selecionarImagemVariacaoProduto($(this), 'mouseover'); }); $('.itemVariationImageProduct').mouseout(function(){ if($(this).attr('imagemSelecionada') != true){ var imgProduto = $('.ProductThumbImage').find('img'); var srcImageProdutoOriginal = $(imgProduto).attr('srcOriginalBKP'); $(imgProduto).attr('src',srcImageProdutoOriginal); } }); $('.itemVariationImageProduct').click(function(){ $('.itemVariationImageProduct').removeAttr('imagemSelecionada'); $(this).attr('imagemSelecionada','true'); selecionarImagemVariacaoProduto($(this), 'click'); }); /* ===== FIM - VARIAÇÃO DE PRODUTOS ===== */ $('[alt=Comprar]').click(function(){ window.location = $(this).parent().attr('href'); return false; }); /* Footer Links */ $('#footerLinksCMS ul li a span').click(function(){ var link; var nomeLink = $(this).html(); if(nomeLink != ''){ if(nomeLink.toLowerCase().indexOf('contato') != -1 || nomeLink.toLowerCase().indexOf('fale conosco') != -1){ window.location = urlWebsite + '/faleconosco.php'; return false; } } }); /* SLIDER */ if(jQuery('.sliderCarousel').length != 0){ jQuery('.sliderCarousel').tinycarousel({start: 2}); } /* FORMAS DE PAGAMENTO - PAG DE PRODUTO */ var cliqueHabilitado = true; /* Habilita o Primeiro Item */ $('#bandeirasFormasPagamento li').eq(0).addClass('bandeiraSelecionada'); $('#parcelasFormasPagamento div.ConteudoFormaPagamento').eq(0).addClass('parcelaSelecionada').show(); $('#metodoPagamentoSelecionado').html($('#bandeirasFormasPagamento li').eq(0).attr('descricao')); $('#bandeirasFormasPagamento li img').click(function(){ var countNumber = $(this).parent().attr('count'); var descricaoMetodo = $(this).parent().attr('descricao'); if(cliqueHabilitado){ cliqueHabilitado = false; $('#metodoPagamentoSelecionado').html(descricaoMetodo); $('#bandeirasFormasPagamento li').each(function(){ if($(this).attr('count') == countNumber){ $(this).addClass('bandeiraSelecionada'); }else{ $(this).removeClass('bandeiraSelecionada'); } }); $('#parcelasFormasPagamento div.ConteudoFormaPagamento').each(function(){ if($(this).attr('count') == countNumber){ $(this).addClass('parcelaSelecionada'); $(this).slideDown('slow', function(){ cliqueHabilitado = true; }); }else{ $(this).hide(); $(this).removeClass('parcelaSelecionada'); } }); } }); }); /* ===== INICIO - BUSCA POR CEP ===== */ function buscaCep(cep, form){ var arrayEstados = new Array(); arrayEstados['AC'] = 'Acre'; arrayEstados['AL'] = 'Alagoas'; arrayEstados['AP'] = 'Amapa'; arrayEstados['AM'] = 'Amazonas'; arrayEstados['BA'] = 'Bahia'; arrayEstados['CE'] = 'Ceara'; arrayEstados['DF'] = 'Distrito Federal'; arrayEstados['ES'] = 'Espirito Santo'; arrayEstados['GO'] = 'Goias'; arrayEstados['MA'] = 'Maranhao'; arrayEstados['MT'] = 'Mato Grosso'; arrayEstados['MS'] = 'Mato Grosso do Sul'; arrayEstados['MG'] = 'Minas Gerais'; arrayEstados['PA'] = 'Para'; arrayEstados['PB'] = 'Paraiba'; arrayEstados['PR'] = 'Parana'; arrayEstados['PE'] = 'Pernambuco'; arrayEstados['PI'] = 'Piaui'; arrayEstados['RJ'] = 'Rio de Janeiro'; arrayEstados['RN'] = 'Rio Grande do Norte'; arrayEstados['RS'] = 'Rio Grande do Sul'; arrayEstados['RO'] = 'Rondonia'; arrayEstados['RR'] = 'Roraima'; arrayEstados['SC'] = 'Santa Catarina'; arrayEstados['SP'] = 'Sao Paulo'; arrayEstados['SE'] = 'Sergipe'; arrayEstados['TO'] = 'Tocantins'; $.getScript(urlWebsite + "/modificacoes/buscacep.php?cep=" + cep, function(){ if(resultadoCEP["resultado"] && resultadoCEP["resultado"] != 0){ $(form).find('input').each(function(){ if($(this).attr('attributeprivateid') == 'addressline1'){ $(this).val(unescape(resultadoCEP["tipo_logradouro"])+": "+unescape(resultadoCEP["logradouro"])); } if($(this).attr('attributeprivateid') == 'bairro'){ $(this).val(unescape(resultadoCEP["bairro"])); } if($(this).attr('attributeprivateid') == 'city'){ $(this).val(unescape(resultadoCEP["cidade"])); } if($(this).attr('attributeprivateid') == 'numero'){ $(this).focus(); } }); $('.FormContainer').find('select').each(function(){ if($(this).attr('attributeprivateid') == 'state'){ $(this).children('option[value="' + arrayEstados[unescape(resultadoCEP["uf"])] + '"]').attr({ selected : "selected" }); } }); }else{ alert("Endereço não encontrado!"); return false; } }); } /* ===== FIM - BUSCA POR CEP ===== */ /* Aplica Máscaras e Oculta Campos do Cadastro de Clientes */ function mascaraCamposCadastroCliente(){ $('[attributeprivateid="companyname"]').hide(); $('[attributeprivateid="companyname"]').parent().prev().hide(); $('[attributeprivateid="cpf"]').mask("999.999.999-99"); $('[attributeprivateid="datanascimento"]').mask("99/99/9999"); $('[attributeprivateid="phone"]').mask("(99) 9999-9999"); $('[attributeprivateid="zip"]').mask("99999-999"); $('[attributeprivateid="country"]').hide(); $('[attributeprivateid="country"]').parent().prev().hide(); } function inArray(array, valor) { for(var i=0; i<array.length; i++) { if(array[i] == valor) { return true; } } return false; } /* Ajax - Carrega do Servidor o Conteudo da Selecao de Atributos */ function carregaConteudoSelecaoServidorAjax(){ var optionIds = ''; $('.GrupoAtributoVariacaoProduto').find('li.itemVariationProductSelected').each(function(){ optionIds += $(this).attr('value') + ","; }); if(optionIds != ''){ optionIds = optionIds.substr(0, optionIds.length-1); } $.getJSON( config.AppPath + '/remote.php?w=GetVariationOptions&productId=' + productId + '&options=' + optionIds, function(data) { if (data.comboFound) { // was a combination found instead? // display price, image etc updateSelectedVariation($('body'), data, data.combinationid); } } ); } /* Mostra a Qtde de Estoque da Seleção */ function mostraQtdeEstoqueSelecao(indiceAtributoVariacao, qtdeAtributos){ if(indiceAtributoVariacao == qtdeAtributos){ var qtdeEstoqueProduto; var atributosSelecionadosString = ''; var valoresPreSelecaoString; var achouEstoqueDaSelecao = false; $('.GrupoAtributoVariacaoProduto').find('li.itemVariationProductSelected').each(function(){ atributosSelecionadosString += $(this).attr('value') + ","; }); if(atributosSelecionadosString.length > 1){ atributosSelecionadosString = atributosSelecionadosString.substr(0, atributosSelecionadosString.length-1); for(var i=0; i<arrayCombinacaoAtributos.length; i++){ valoresPreSelecaoString = arrayCombinacaoAtributos[i].join(","); if(trim(valoresPreSelecaoString) == trim(atributosSelecionadosString)){ achouEstoqueDaSelecao = true; qtdeEstoqueProduto = arrayCombinacaoEstoque[i]; break; } } if(achouEstoqueDaSelecao){ $('#qtdeEstoqueAtributosDiv').fadeOut('slow',function(){ $('#qtdeEstoqueAtributosDiv').html('Em estoque: ' + qtdeEstoqueProduto + ' unidade(s)'); $('#qtdeEstoqueAtributosDiv').fadeIn(1200); }); }else{ $('#qtdeEstoqueAtributosDiv').fadeOut('slow'); } } }else{ $('#qtdeEstoqueAtributosDiv').fadeOut('slow'); } } function compareProductSubmit(){ var form; form = document.frmCompare; form.action = "%%GLOBAL_CompareLink%%"; form.submit(); } /* Carrega Atributos Disponiveis Para Seleção */ function carregaAtributosDisponiveisParaSelecao(indice, valor){ var indiceAtributoVariacao; var valorAtributoSeleciondo; var removerIndice = 0; var arrayAtributosSelecionados = new Array(); var arrayCombinacaoAtributosTempAlterar = new Array(); var conteudoRestanteSelecaoAtributos = new Array(); arrayCombinacaoAtributosTempAlterar = arrayCombinacaoAtributos.slice(); /* Monta Array Coms os Atributos Já Selecionados */ $('.GrupoAtributoVariacaoProduto').each(function(){ indiceAtributoVariacao = $(this).attr('indiceAtributoVariacao'); valorAtributoSeleciondo = $(this).find('li.itemVariationProductSelected').eq(0).attr('value'); if(valorAtributoSeleciondo != undefined){ arrayAtributosSelecionados[indiceAtributoVariacao-1] = valorAtributoSeleciondo; } }); var addCombinacaoAtributosValido = true; for(var y=0; y<arrayCombinacaoAtributosTempAlterar.length; y++){ addCombinacaoAtributosValido = true; for(var i=0; i<indice; i++){ if(!arrayCombinacaoAtributosTempAlterar[y][i] || (arrayCombinacaoAtributosTempAlterar[y][i] != arrayAtributosSelecionados[i])){ addCombinacaoAtributosValido = false; break; } } if(addCombinacaoAtributosValido){ conteudoRestanteSelecaoAtributos.push(arrayCombinacaoAtributosTempAlterar[y]); } } $('.GrupoAtributoVariacaoProduto').each(function(){ if($(this).attr('indiceAtributoVariacao') == (parseInt(indice)+1)){ $(this).find('li').each(function(){ for(var i=0; i<conteudoRestanteSelecaoAtributos.length; i++){ if(conteudoRestanteSelecaoAtributos[i] != undefined){ if(inArray(conteudoRestanteSelecaoAtributos[i], $(this).attr('value'))){ $(this).removeClass('itemVariationProductDisabled'); $(this).addClass('itemVariationProduct'); } } } }); } }); } /* Seleciona a Imagem do Atributo Cor da Variação do Produto */ function selecionarImagemVariacaoProduto(obj, evento){ var imgAtributo = $(obj).find('img'); var imageZoom = $(imgAtributo).attr('imageProdutoHover'); var imgProduto = $('.ProductThumbImage').find('img'); var srcImageProdutoOriginal = $(imgProduto).attr('src'); $(imgProduto).attr('srcOriginalBKP',srcImageProdutoOriginal); $(imgProduto).attr('width',ProductThumbWidth).css('height',ProductThumbHeight); $(imgProduto).attr('src',imageZoom); if(evento == 'click'){ $('.ProductThumbImage a').attr("href", imageZoom); $('.ProductThumbImage a').css({'cursor':'pointer'}); } } function mostraDivComentariosProduto(animation){ var codigoDivComentarioProdutos = 4; $('#divTabs').find('li').each(function(){ if($(this).attr('id') != 'li' + codigoDivComentarioProdutos){ $(this).removeClass("on"); }else{ $(this).addClass("on"); } }); $('.divTabArea').each(function(){ $(this).removeClass("on"); }); if(animation){ $('#div4').slideDown(1200, function(){ $(this).addClass("on"); $(this).removeAttr('style'); }); }else{ $('#div4').addClass("on"); window.location.href = '#divTC'; } } function trim(str){ while (str.charAt(0) == " ") str = str.substr(1,str.length -1); while (str.charAt(str.length-1) == " ") str = str.substr(0,str.length-1); return str; } // RETIRA UM CARACTER ESPECÍFICO DE UMA STRING function retiraCaracter(string, caracter) { var i = 0; var final = ''; while (i < string.length) { if (string.charAt(i) == caracter) { final += string.substr(0, i); string = string.substr(i+1, string.length - (i+1)); i = 0; } else { i++; } } return final + string; } function validaEmail(email){ var er = new RegExp(/^[A-Za-z0-9_\-\.]+@[A-Za-z0-9_\-\.]{2,}\.[A-Za-z0-9]{2,}(\.[A-Za-z0-9])?/); if(typeof(email) == "string"){ if(er.test(email)){ return true; } }else if(typeof(email) == "object"){ if(er.test(email.value)){ return true; } }else{ return false; } } /* Verifica se o método de pagamento selecionado possui desconto cadastrado */ function verificaDescontoMetodoPagamento(metodoPagamento){ var total, totalDesconto, descontoPercentual, novoElementoTR, novoElementoTD1, novoElementoTD2, qtdeTR, tabelaRecebeResultado; $.ajax({ url: 'remote.php', data: 'w=discountMethodPaymentEdaz&metodoPagamento=' + metodoPagamento, dataType: 'json', type: 'post', success: function(data){ /* Altera os Valores Originais da Quotação */ total = data.total; totalDesconto = data.totalDesconto; descontoPercentual = data.descontoPercentual; if($('#OrderConfirmationForm').length > 0){ qtdeTR = $('#OrderConfirmationForm .CartContents tfoot tr').size(); tabelaRecebeResultado = '#OrderConfirmationForm .CartContents tfoot tr'; }else if($('.OrderContents').length > 0){ qtdeTR = $('.OrderContents .CartContents tfoot tr').size(); tabelaRecebeResultado = '.OrderContents .CartContents tfoot tr'; } if(totalDesconto != '-R$0,00' || $('#descontoQuotacaoTR').length > 0){ if($('#descontoQuotacaoTR').length == 0){ novoElementoTR = $('<tr></tr>').attr({ id : 'descontoQuotacaoTR' }).addClass('SubTotal').addClass('displayNone'); novoElementoTD1 = $('<td></td>').attr({ id : 'labelDescontoQuotacao', colspan : '3' }); novoElementoTD2 = $('<td></td>').attr({ id : 'valorDescontoQuotacao' }); $(novoElementoTR).append(novoElementoTD1).append(novoElementoTD2); $(tabelaRecebeResultado).each(function(i, obj){ //Pega a Penultima Linha if(i+1 == (qtdeTR-1)){ /* Verifica se Já não Inseriu */ if($(this).attr('id') != undefined && $(this).attr('id') != 'descontoQuotacaoTR'){ $(this).after($(novoElementoTR)); $(this).next().fadeIn(800); return false; } } }); } /* Insere os Valores de Desconto */ $('#labelDescontoQuotacao').fadeOut('fast', function(){ $(this).html('Desconto (' + descontoPercentual + '%):').fadeIn(800); }); $('#valorDescontoQuotacao').fadeOut('fast', function(){ $(this).html(totalDesconto).fadeIn(800); }); $(tabelaRecebeResultado + ':last-child td:last-child').fadeOut('fast', function(){ $(this).html(total).fadeIn(800); }); } } }); } function avisemeQuandoChegar(codProduto){ var url, parametros, variacaoProdutoID; variacaoProdutoID = ($('.CartVariationId').length > 0) ? $('.CartVariationId').val() : ''; parametros = '?codprod=' + codProduto + '&variacaoProdutoID=' + variacaoProdutoID; url = urlWebsite + '/faleconosco.php' + parametros; window.location = url; return false; }
'use strict'; var min = 2; var reason = (function() { var m = ''; return { set: function(r) { m = r; }, get: function() { return m; }, reset: function() { m = ''; }, }; })(); var is = function(n) { if (n < min) { reason.set('prime must be integer greater than 2'); return false; } var sqrt = Math.floor(Math.sqrt(n)); for (var i = min; i <= sqrt; i++) { if (n % i === 0) { reason.set(i + ' is divisor of ' + n); return false; } } reason.reset(); return true; } var first = function(n) { var x = min, y = 0, r = []; while (y < n) { if (is(x)) { r.push(x); y++; } x++; } return r; } var between = function(x, y) { var r = []; for (var i = x; i <= y; i++) { if (is(i)) r.push(i); } return r; } var why = function() { return reason.get(); } exports.is = is; exports.first = first; exports.between = between; exports.why = why;
const request = require('request'); const appToken = require('../components/AppToken'); const config = require('../config') const cache = require('memory-cache'); const uuidv4 = require('uuid/v4') module.exports = (req, res) => { let requestBody = req.body; let folio = requestBody.folios.folio; let cacheKey = 'asset-' + folio; let cacheObject = cache.get(cacheKey); if (cacheObject) { res.json(cacheObject); return; } appToken(req, (appToken) => { if (appToken) { request.post({ url: config.mmendpoint + '/NMP/OperacionPrendaria/Partidas/v1/Folio', headers: { 'Content-Type': 'application/json', 'usuario': req.headers.usuario, 'idConsumidor': config.mmconsumerId, 'idDestino': config.mmdestinationId, Authorization: 'Bearer ' + appToken }, json: true, body: requestBody, options: { checkServerIdentity: function (host, cert) { return true; } } }, (e1, r1, b1) => { if (e1) { console.error(e1); } if (b1) { cache.put(cacheKey, b1, 120 * 1000); } res.json(b1); }); } else { res.json({ codigoError: "FEB-0001", descripcionError: "No pudo obtenerse el token de aplicación", tipoError: "Error de Servicio", severidad: "1" }); } }); }
import UserActionTypes from "./user.types"; export const updatePaymentLinkTable = () => ({ type: UserActionTypes.UPDATE_PAYMENTLINK_TABLE, }) export const loadPaymentLinks = (links) => ({ type: UserActionTypes.LOAD_PAYMENTlINKS, payload: links }) export const getWalletDetails = () => ({ type: UserActionTypes.GET_WALLET_DETAILS }) export const getUserDetails = () => ({ type: UserActionTypes.GET_USER_DETAILS }) export const loadWalletDetails = (walletDetails) => ({ type: UserActionTypes.LOAD_WALLET_DETAILS, payload: walletDetails }) export const loadUserDetails = (userDetails) => ({ type: UserActionTypes.LOAD_USER_DETAILS, payload: userDetails }) export const refresh = (refresh) => ({ type: UserActionTypes.REFRESH, payload: refresh })
// referenciando as tags HTML const [minuteLeftSpan, minuteRightSpan] = document.querySelectorAll('div#minutes span') const [secondLeftSpan, secondRightSpan] = document.querySelectorAll('div#seconds span') const buttonsDiv = document.querySelector('div#buttons') const startButton = document.querySelector('button#start') // começando do ZERO a contagem let minutes = 0 let seconds = 0 // função responsável por criar botões function createButton(id) { // criando o botão const button = document.createElement('button') // adicionando os atributos button.setAttribute('type', 'button') button.setAttribute('id', id) // preparando o texto para ir para o HTML id = id.split('') id[0] = id[0].toUpperCase() id = id.join('') // adicionando o texto na TAG button.innerHTML = id // adicionando o botão dentro da DIV buttonsDiv.appendChild(button) return button } // função responsável por alterar o innerHTML function addToHTML(seconds, minutes) { // definindo as variáveis que irão para o HTML const [secondLeft, secondRight] = String(seconds).padStart(2, '0').split('') const [minuteLeft, minuteRight] = String(minutes).padStart(2, '0').split('') // colocando os MINUTOS e SEGUNDOS no corpo da página secondLeftSpan.innerHTML = secondLeft secondRightSpan.innerHTML = secondRight minuteLeftSpan.innerHTML = minuteLeft minuteRightSpan.innerHTML = minuteRight } // função responsável por iniciar a countagem do cronômetro function startCount() { // cada vez que for chamada, a função irá adicionar +1 SEGUNDO seconds++ // se SEGUNDO for IGUAL a 60, adicionar 1 MINUTO e ZERAR os SEGUNDOS if (seconds == 60) { minutes++ seconds = 0 } addToHTML(seconds, minutes) } // função responsável por setar o intervalo do cronômetro (1 SEGUNDO) function mineSetInterval() { // definindo um intervado de 1 SEGUNDO para realizar a contagem return setInterval(startCount, 1000) } // iniciando o cronômetro quando o botão START for clicado startButton.onclick = () => { // apagando o botão START startButton.remove() // criando o botão STOP const stopButton = createButton('stop') // definindo um intervado de 1 SEGUNDO para realizar a contagem let count = mineSetInterval() // parando a contagem quando o botão STOP for clicado stopButton.onclick = () => { // parando a contagem clearInterval(count) // apagando o botão STOP stopButton.remove() // criando o botão RESET const resetButton = createButton('reset') // zerando o cronômetro quando o botão RESET for clicado resetButton.onclick = () => { // zerando as variáveis seconds = 0 minutes = 0 // apagando os botões RESET e RESUME resetButton.remove() resumeButton.remove() // atualizando os valores no HTML addToHTML(seconds, minutes) // adicionando o botão START buttonsDiv.appendChild(startButton) } // criando o botão RESUME const resumeButton = createButton('resume') // continuando a contagem quando o botão RESUME for clicado resumeButton.onclick = () => { // apagando os botões RESET e RESUME resetButton.remove() resumeButton.remove() // adicionando o botão STOP buttonsDiv.appendChild(stopButton) // definindo o intervalo de 1 SEGUNDO count = mineSetInterval() } } }
import * as THREE from 'three'; // import TrackballControls from "../threeJS_extensions/TrackballControls"; import React, { Component } from 'react'; import PropTypes from 'prop-types'; import parse_type from "../workers/parse_type" import calc_xy_on_circle from "../workers/calc_xy_on_circle" import MakeTextSprite from "../threeJS_extensions/build/MakeTextSprite" import ExtrudeGeometry from "../threeJS_extensions/build/ExtrudeGeometry" import red_dot from "../../assets/red_dot.png" import { MeshBasicMaterial } from 'three'; import CogWheel2D from "../threeJS_extensions/build/CogWheel2D" const round_to_x_curry = ( round_to)=>{ let pow = Math.pow( 10, round_to ) console.log(pow) return (num)=>{ return ( Math.round( num * pow ) / pow ) } } const round_2_dec = round_to_x_curry(2) const round_3_dec = round_to_x_curry(3) //GLOBALS CAPITAL VARIABELS PARAMS ====================================================================================================================== //GLOBALS CAPITAL VARIABELS PARAMS ====================================================================================================================== //GLOBALS CAPITAL VARIABELS PARAMS ====================================================================================================================== //GLOBALS CAPITAL VARIABELS PARAMS ====================================================================================================================== //GLOBALS CAPITAL VARIABELS PARAMS ====================================================================================================================== //GLOBALS CAPITAL VARIABELS PARAMS ====================================================================================================================== //GLOBALS CAPITAL VARIABELS PARAMS ====================================================================================================================== /**EXTRUDE contains points/coords that can be used in ExtrudeGeometry to create shapes */ const EXTRUDE = { arrow : [[0, 0],[-0.7, 0],[-0.7, -2],[-1.5, -2],[ 0, -3.5],[1.5, -2],[0.7, -2],[0.7, 0]], sqaure : [[0.9, 0.9], [-0.9, 0.9], [-0.9, -0.9], [0.9, -0.9]], cog : CogWheel2D( 152, 20) } let TEST_MESH, TEST_ROTATE = 0 let DEGREES_ARR = new Array(360).fill(0).map((z, i)=> i); /**45 degrees in radeans */let RADS_45 = THREE.Math.degToRad(45) /**90 degrees in radeans */let RADS_90 = THREE.Math.degToRad(90) // same as Math.PI / 2 /**180 degrees in radeans */let RADS_180 = THREE.Math.degToRad(180) /**270 degrees in radeans */let RADS_270 = THREE.Math.degToRad(270) let SCALE_I_INIT = 1 /** REFACTORS SPRITE SIZE DEPENDING ON THE DEPTH OF Y CAMERA */ const text_scale_factor = 10 const TEXT_SCALES = [ { width_scale : 0.73, height_scale : 0.36, alignV2_x: new THREE.Vector2(0.1, 1), alignV2_z: new THREE.Vector2(0, 0.8)}, { width_scale : 0.73, height_scale : 0.36, alignV2_x: new THREE.Vector2(0.1, 1), alignV2_z: new THREE.Vector2(0, 0.8)}, { width_scale : 1.47, height_scale : 0.73, alignV2_x: new THREE.Vector2(0.1, 1), alignV2_z: new THREE.Vector2(0, 0.8)}, { width_scale : 2.21, height_scale : 1.1, alignV2_x: new THREE.Vector2(0.1, 1), alignV2_z: new THREE.Vector2(0, 0.8)}, { width_scale : 2.94, height_scale : 1.47, alignV2_x: new THREE.Vector2(0.1, 1), alignV2_z: new THREE.Vector2(0, 0.8)}, { width_scale : 3.68, height_scale : 1.84, alignV2_x: new THREE.Vector2(0.1, 1), alignV2_z: new THREE.Vector2(0, 0.8)}, { width_scale : 4.42, height_scale : 2.21, alignV2_x: new THREE.Vector2(0.1, 1), alignV2_z: new THREE.Vector2(0, 0.8)}, { width_scale : 5.15, height_scale : 2.57, alignV2_x: new THREE.Vector2(0.1, 1), alignV2_z: new THREE.Vector2(0, 0.8)}, { width_scale : 5.89, height_scale : 2.94, alignV2_x: new THREE.Vector2(0.1, 1), alignV2_z: new THREE.Vector2(0, 0.8)}, { width_scale : 6.63, height_scale : 3.31, alignV2_x: new THREE.Vector2(0.1, 1), alignV2_z: new THREE.Vector2(0, 0.8)}, { width_scale : 7.36, height_scale : 3.68, alignV2_x: new THREE.Vector2(0.1, 1), alignV2_z: new THREE.Vector2(0, 0.8)}, { width_scale : 8.1, height_scale : 4.05, alignV2_x: new THREE.Vector2(0.1, 1), alignV2_z: new THREE.Vector2(0, 0.8)}, { width_scale : 8.84, height_scale : 4.42, alignV2_x: new THREE.Vector2(0.1, 1), alignV2_z: new THREE.Vector2(0, 0.8)}, { width_scale : 9.57, height_scale : 4.78, alignV2_x: new THREE.Vector2(0.1, 1), alignV2_z: new THREE.Vector2(0, 0.8)}, { width_scale : 10.31, height_scale : 5.15, alignV2_x: new THREE.Vector2(0.1, 1), alignV2_z: new THREE.Vector2(0, 0.8)}, { width_scale : 11.05, height_scale : 5.52, alignV2_x: new THREE.Vector2(0.1, 1), alignV2_z: new THREE.Vector2(0, 0.8)}, { width_scale : 11.78, height_scale : 5.89, alignV2_x: new THREE.Vector2(0.1, 1), alignV2_z: new THREE.Vector2(0, 0.8)}, { width_scale : 12.52, height_scale : 6.26, alignV2_x: new THREE.Vector2(0.1, 1), alignV2_z: new THREE.Vector2(0, 0.8)}, { width_scale : 13.26, height_scale : 6.63, alignV2_x: new THREE.Vector2(0.1, 1), alignV2_z: new THREE.Vector2(0, 0.8)}, { width_scale : 14, height_scale : 7, alignV2_x: new THREE.Vector2(0.1, 1), alignV2_z: new THREE.Vector2(0, 0.8)}, { width_scale : 14.73, height_scale : 7.36, alignV2_x: new THREE.Vector2(0.1, 1), alignV2_z: new THREE.Vector2(0, 0.8)}, { width_scale : 15.47, height_scale : 7.73, alignV2_x: new THREE.Vector2(0.1, 1), alignV2_z: new THREE.Vector2(0, 0.8)}, { width_scale : 16.21, height_scale : 8.1, alignV2_x: new THREE.Vector2(0.1, 1), alignV2_z: new THREE.Vector2(0, 0.8)}, { width_scale : 16.94, height_scale : 8.47, alignV2_x: new THREE.Vector2(0.1, 1), alignV2_z: new THREE.Vector2(0, 0.8)}, { width_scale : 17.68, height_scale : 8.84, alignV2_x: new THREE.Vector2(0.1, 1), alignV2_z: new THREE.Vector2(0, 0.8)}, { width_scale : 18.42, height_scale : 9.21, alignV2_x: new THREE.Vector2(0.1, 1), alignV2_z: new THREE.Vector2(0, 0.8)}, { width_scale : 19.15, height_scale : 9.57, alignV2_x: new THREE.Vector2(0.1, 1), alignV2_z: new THREE.Vector2(0, 0.8)}, // { width_scale : 2.20, height_scale : 1.1, alignV2_x: new THREE.Vector2(0.1, 1), alignV2_z: new THREE.Vector2(0, 0.8)}, // { width_scale : 4.4, height_scale : 2.2, alignV2_x: new THREE.Vector2(0.1, 1), alignV2_z: new THREE.Vector2(0, 0.8)}, // { width_scale : 8, height_scale : 4, alignV2_x: new THREE.Vector2(0.1, 1), alignV2_z: new THREE.Vector2(0, 0.8)}, // { width_scale : 10, height_scale : 5, alignV2_x: new THREE.Vector2(0.1, 1), alignV2_z: new THREE.Vector2(0, 0.8)}, // { width_scale : 14, height_scale : 7, alignV2_x: new THREE.Vector2(0.1, 1), alignV2_z: new THREE.Vector2(0, 0.8)}, ] /** REFACTORS SPRITE SIZE DEPENDING ON THE DEPTH OF Y CAMERA */ const RED_DOT_SCALE_FACTOR = 10 /** contains one factor to apply to x y and z when scaling */ const RED_DOT_SCALES = new Array(40).fill(0.03).map( (base_factor, i)=> base_factor * (i+1) ) /**REFACTORS ARROW SIZE DEPENDING ON THE DEPTH OF CAMERA Y */ const MOVE_ARROW_FACTOR = 10 /** contains one factor to apply to X and Z when scaling keep Y at 0.1 */ const MOVE_ARROW_SCALES = new Array(40).fill(0.15).map( (base_factor, i)=> base_factor * (i+1) ) const ARROW_MATERIAL = new THREE.MeshBasicMaterial( {color:0x00ff00, opacity : 0.3, transparent:true}) const ARROW_MATERIAL_HIGHLIGHT = new THREE.MeshBasicMaterial( {color:0x00ff00, opacity : 0.7, transparent:true}) /** * TODO refactor to new new system * create object containing all THREE draw methods. * export all THREE drawings to separate file and function * !consider precurring materials by wrapping imported draw methods into a curry * * create object containing all HUD THREE drawings with their names and coordinates, materials, etc * * */ class ThreeDrawGrid extends Component{ state = { canvasElement : document.querySelector(`#${this.props.id}`), drawing : { }, mouse : { down : false, x : 0, y : 0, snap_increment : 1,// ! DO NOT SET TO 0 /* value indicated the nearest increment to round to (1,2,5) */ snap_decimal : 100,// ! DO NOT SET TO 0 /*value indicates the product to divide and multiply during conversion 1 = m, 10 = dm, 100 = cm*/ snap_point : false, }, red_dot : { TObj : null, scale_i : SCALE_I_INIT, }, move_arrows : { TObj : null, TObj_up : null, TObj_down : null, TObj_left : null, TObj_right : null, TObj_center : null, scale_i : SCALE_I_INIT, hover_up : false, hover_down : false, hover_left : false, hover_right : false, hover_center : false }, ruler : { text_scale_i : SCALE_I_INIT,/**defined which scaling object to get from text_scale */ texts_x : [],//TObjs texts_z : [],//TObjs }, live_ruler : { red:null,/** x axis */ blue : null,/** z axis */ green: null,/** point*/ red_distance: 0, blue_distance: 0, green_distance: 0, // lastV3: new THREE.Vector3( 0,0,0), // history : [/**{ shape_type, V3s} */] }, plane : { TObj : null, width : 500, height : 500 }, camera : { x: 0, y: 60, z: 0, look_x: 0, look_y: 0, look_z: 0, }, moveing: { speed : 0, accelerate : 0.01, speed_max : 1 }, active_mode : "navigate", active_keys : { } }; scene = new THREE.Scene(); renderer = new THREE.WebGLRenderer(); camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 10000); raycaster = new THREE.Raycaster(); mouse = new THREE.Vector2(); move_arrows = new THREE.Group(); red_dot = null/* sprite that points out mouse location as snapped to grid*/ red_line_x = null// connects red dot to X ruler red_line_y = null// connects red dot to Y ruler red_text_x = null// displays x distance between ruler and red_dot red_text_y = null// displays y distance between ruler and red_dot constructor(props){ super(props) this.render3D = this.render3D.bind(this) this.start = this.start.bind(this) this.stop = this.stop.bind(this) this.animate = this.animate.bind(this) this.set_1_state = this.set_1_state.bind(this) this.set_prop = this.set_prop.bind(this) this.set_prop_from_input_event = this.set_prop_from_input_event.bind(this) this.new_or_state = this.new_or_state.bind(this) this.remove_from_scene = this.remove_from_scene.bind(this) //DRAW this.draw_plane = this.draw_plane.bind(this) this.draw_plane_rulers = this.draw_plane_rulers.bind(this) this.draw_red_dot = this.draw_red_dot.bind(this) this.draw_red_lines = this.draw_red_lines.bind(this) this.draw_red_coords = this.draw_red_coords.bind(this) this.draw_point_move_arrows = this.draw_point_move_arrows.bind(this) this.draw_2_point_ruler = this.draw_2_point_ruler.bind(this) //UPDATE this.on_mouse_move = this.on_mouse_move.bind(this) this.loc_parse = this.loc_parse.bind(this) this.update_ruler_text_scales = this.update_ruler_text_scales.bind(this) this.update_red_dot_scale = this.update_red_dot_scale.bind(this) this.update_move_arrows_scale = this.update_move_arrows_scale.bind(this) //MOUSE this.prevent_bubbles = this.prevent_bubbles.bind(this) this.drag_active = this.drag_active.bind(this) //KEYBOARD this.activate_keyboard_button = this.activate_keyboard_button.bind(this) this.deactivate_keyboard_button = this.deactivate_keyboard_button.bind(this) this.reset_key_variables = this.reset_key_variables.bind(this) this.move_general = this.move_general.bind(this) //CAMERA this.update_camera = this.update_camera.bind(this) this.move_camera.in = this.move_camera.in.bind(this) this.move_camera.out = this.move_camera.out.bind(this) this.move_camera.up = this.move_camera.up.bind(this) this.move_camera.down = this.move_camera.down.bind(this) this.move_camera.left = this.move_camera.left.bind(this) this.move_camera.right = this.move_camera.right.bind(this) //MODES // this.modes.draw_polygon = this.modes.draw_polygon.bind(this) this.custom_event_listeners_add = this.custom_event_listeners_add.bind(this) this.custom_event_listeners_remove = this.custom_event_listeners_remove.bind(this) this.raycast_mouse_position = this.raycast_mouse_position.bind(this) } _isMounted = false componentDidMount(){ this._isMounted = true this.init3D() } new_or_state(property, category, funct_fn ){ if( this.state[property][category] === null){ return funct_fn(); }else{ return this.state[property][category]; } } remove_from_scene( id, scene ){ if( scene !== undefined || scene !== null ){ let object = scene.getObjectByName(id) // console.log(object) if(object) scene.remove( object ); }else{ let object = this.scene.getObjectByName(id) // console.log(object) if(object)this.scene.remove( object ); } } loc_parse( num ){/**parse location to snap_to value */ /** * TODO: add snap to point toggle, if enabled find nearest point and snap to it * */ let increment = this.state.mouse.snap_increment let decimal = this.state.mouse.snap_decimal let rounded_num = num * decimal let increment_difference = rounded_num % increment if(increment_difference < increment / 2){ return (rounded_num - increment_difference) / decimal }else{ return (rounded_num + (increment - increment_difference)) / decimal } } on_mouse_move( event ) { // calculate mouse position in normalized device coordinates // (-1 to +1) for both components this.mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1; this.mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1; } move_general(pos_state_category, pos_state_keys, backwards=false, cb=()=>{} ){ let {speed, accelerate, speed_max} = this.state.moveing let new_state = {...this.state} if(speed < speed_max) speed += accelerate; new_state.moveing.speed = speed pos_state_keys.forEach( pos_state_key => { if(backwards === true) new_state[ pos_state_category ][ pos_state_key ] -= speed; else new_state[ pos_state_category ][ pos_state_key ] += speed; }) this.setState(new_state, cb) } move_camera = { in: ()=>{ this.move_general( "camera", ["y"], true, this.update_camera ) }, out: ()=>{ this.move_general( "camera", ["y"], false, this.update_camera ) }, up: ()=>{ this.move_general( "camera", ["z", "look_z"], true, this.update_camera ) }, down: ()=>{ this.move_general( "camera", ["z", "look_z"], false, this.update_camera ) }, left: ()=>{ this.move_general( "camera", ["x", "look_x"], true, this.update_camera ) }, right: ()=>{ this.move_general( "camera", ["x", "look_x"], false, this.update_camera ) }, } update_camera( camera ){ if(camera === undefined || camera === null){ this.camera.position.set( this.state.camera.x, this.state.camera.y, this.state.camera.z); this.camera.lookAt( new THREE.Vector3( this.state.camera.look_x, this.state.camera.look_y, this.state.camera.look_z ) ) }else{ camera.position.set( this.state.camera.x, this.state.camera.y, this.state.camera.z); camera.lookAt( new THREE.Vector3( this.state.camera.look_x, this.state.camera.look_y, this.state.camera.look_z ) ) } //! if scale out of array range use last let red_dot_i = Math.floor( this.state.camera.y / RED_DOT_SCALE_FACTOR) if(red_dot_i !== this.state.red_dot.scale_i && this.state.red_dot.TObj !== null && RED_DOT_SCALES[ red_dot_i ] !== undefined ){ let new_state = {...this.state} new_state.red_dot.scale_i = red_dot_i this.setState(new_state, ()=>{ this.update_red_dot_scale() }) }else if(red_dot_i !== this.state.red_dot.scale_i){ let new_state = {...this.state} new_state.red_dot.scale_i = red_dot_i this.setState(new_state, ()=>{ }) } let move_arrows_i = Math.floor( this.state.camera.y / MOVE_ARROW_FACTOR) if(move_arrows_i !== this.state.move_arrows.scale_i && this.state.move_arrows.TObj !== null && MOVE_ARROW_SCALES[ move_arrows_i ] !== undefined ){ let new_state = {...this.state} new_state.move_arrows.scale_i = move_arrows_i this.setState(new_state, ()=>{ this.update_move_arrows_scale() }) }else if(move_arrows_i !== this.state.move_arrows.scale_i){ let new_state = {...this.state} new_state.move_arrows.scale_i = move_arrows_i this.setState(new_state, ()=>{ }) } let new_scale_i = Math.floor( this.state.camera.y / text_scale_factor ) if(new_scale_i !== this.state.ruler.text_scale_i && TEXT_SCALES[ new_scale_i ] !== undefined && this.state.ruler.texts_x.children !== undefined && this.state.ruler.texts_z.children !== undefined ){ let new_state = {...this.state} new_state.ruler.text_scale_i = new_scale_i this.setState(new_state, ()=>{ this.update_ruler_text_scales() }) }else if(new_scale_i !== this.state.ruler.text_scale_i ){ let new_state = {...this.state} new_state.ruler.text_scale_i = new_scale_i this.setState(new_state, ()=>{ }) } } update_ruler_text_scales(){ /**reapply the scale and align ratio of all texts in texts_x and texts_y */ let scale = TEXT_SCALES[ this.state.ruler.text_scale_i ] console.log("scaling", scale) let { alignV2_x, alignV2_z, width_scale, height_scale} = scale let new_ruler_texts_x = this.state.ruler.texts_x.children.map( text => { text.center = alignV2_x text.scale.set( width_scale , height_scale) // text.verticesNeedUpdate = true return text }) let new_ruler_texts_z = this.state.ruler.texts_z.children.map( text => { text.center = alignV2_z text.scale.set( width_scale , height_scale) // text.verticesNeedUpdate = true return text }) } update_red_dot_scale(){ let new_scale = RED_DOT_SCALES[ this.state.red_dot.scale_i ] this.state.red_dot.TObj.scale.set( new_scale, new_scale, 0.01 ) } update_move_arrows_scale(){ let new_scale = MOVE_ARROW_SCALES[ this.state.move_arrows.scale_i ] this.state.move_arrows.TObj.scale.set( new_scale, 0.01, new_scale ) } //DRAW DRAW DRAW DRAW=============================================================================================================== //DRAW DRAW DRAW DRAW=============================================================================================================== //DRAW DRAW DRAW DRAW=============================================================================================================== //DRAW DRAW DRAW DRAW=============================================================================================================== //DRAW DRAW DRAW DRAW=============================================================================================================== //DRAW DRAW DRAW DRAW=============================================================================================================== //DRAW DRAW DRAW DRAW=============================================================================================================== draw_2_point_ruler( cb ){ } draw_CogWheel(cb){ let cogwheel = ExtrudeGeometry(EXTRUDE.cog, ARROW_MATERIAL, { depth: 0.01, bevelEnabled: true,bevelThickness: 0.2, bevelSize: 0.1,}, {x:0.3, y:0.3, z:0.3} ) cogwheel.rotateX(RADS_90) this.scene.add( cogwheel ) } draw_point_move_arrows( cb ){ if(this.state.move_arrows.TObj === null){ let arrows = this.move_arrows // let material = new THREE.MeshBasicMaterial( {color:0x00ff00, opacity : 0.3, transparent:true}) let up = ExtrudeGeometry(EXTRUDE.arrow, ARROW_MATERIAL, { depth: 0.01, bevelEnabled: true,bevelThickness: 0.2, bevelSize: 0.1,}, {x:0.3, y:0.3, z:0.3} ) up.rotateX(RADS_90) up.name = "arrow_up" let down = up.clone() down.rotateZ(RADS_180) down.name = "arrow_down" let left = up.clone() left.rotateZ(RADS_270) left.name = "arrow_left" let right = up.clone() right.rotateZ(RADS_90) right.name = "arrow_right" let center = ExtrudeGeometry(EXTRUDE.sqaure, ARROW_MATERIAL, { depth: 0.01, bevelEnabled: true,bevelThickness: 0.2, bevelSize: 0.1,}, {x:0.3, y:0.3, z:0.3} ) center.rotateX(RADS_90) center.name = "arrow_center" //move arrows const spacing = 0.7 up.position.set(0, 0, -spacing) down.position.set(0, 0, spacing) left.position.set(-spacing, 0, 0) right.position.set(spacing, 0, 0) center.position.set(0,0,0) // up_arrow.scale.set(new THREE.Vector3(0.3, 0.3, 0.3)) console.log(up) arrows.add(up) arrows.add(down) arrows.add(left) arrows.add(right) arrows.add(center) this.scene.add(arrows) //scale to scale_i const scale = MOVE_ARROW_SCALES[ this.state.move_arrows.scale_i ] console.log(scale) arrows.scale.set(scale, 0.1, scale) let new_state = {...this.state} new_state.move_arrows.TObj = arrows new_state.move_arrows.TObj_up = up new_state.move_arrows.TObj_down = down new_state.move_arrows.TObj_left = left new_state.move_arrows.TObj_right = right new_state.move_arrows.TObj_center = center this.setState(new_state, cb) }else{ cb() } } draw_text_sprite( message, { width_scale=2, height_scale=1.5, alignV2=new THREE.Vector2(0,1), textColor = {r:255, g:255, b:255, a:1}, sizeAttenuation=true} ){ // TODO depending on the z location of camera the scale of the letters must be adjusted let sprite = MakeTextSprite( message, { textColor, sizeAttenuation } ) // textSprite.rotation.x = Math.PI / 2 // sprite.position.set(0, 1, 0) sprite.center = alignV2 sprite.scale.set( width_scale , height_scale) return sprite // this.scene.add(sprite) } draw_plane_rulers( cb ){//RUNS AT INIT THEREFORE IN A CALLBACK CHAIN /**get text scale */ let scale_i = this.state.ruler.text_scale_i let scale = TEXT_SCALES[scale_i] let w_m = this.state.plane.width / 2 let h_m = this.state.plane.height / 2 // let w_dm = this.state.plane.width * 10 / 2 // let h_dm = this.state.plane.height * 10 / 2 // let w_cm = this.state.plane.width * 100 / 2 // let h_cm = this.state.plane.height * 100 / 2 // let start_p = 0 // ! we are iterating half only, so we must add negative as well as positive points at the same time let m_geo = new THREE.Geometry(); let m_mat = new THREE.LineBasicMaterial({color:0xffffff, opacity : 0.6, transparent:false, linewidth : 10}) let texts_x = new THREE.Group() let texts_z = new THREE.Group() //width lines and width texts for(let i = 0; i < w_m; i++){ let modulo = i % 10 let length = 0.1; if( modulo === 0 ){//0, 10, 20... length = 0.25 if(i !== 0){ let text = this.draw_text_sprite( `${i}`, {alignV2:scale.alignV2_x, width_scale:scale.width_scale, height_scale:scale.height_scale}) let neg_text = text.clone() text.position.set( i , 0.001, length ) neg_text.position.set( -i , 0.001, length ) texts_x.add(text) texts_x.add(neg_text) } }else if( modulo === 5){//5, 15, 25, ... length = 0.15 if(i !== 0){ let text = this.draw_text_sprite( `${i}`, {alignV2:scale.alignV2_x, width_scale:scale.width_scale, height_scale:scale.height_scale}) let neg_text = text.clone() text.position.set( i , 0.001, length ) neg_text.position.set( -i , 0.001, length ) texts_x.add(text) texts_x.add(neg_text) } } m_geo.vertices.push( new THREE.Vector3( i , 0.001, length)); m_geo.vertices.push( new THREE.Vector3( i , 0.001, -length)); m_geo.vertices.push( new THREE.Vector3( -i , 0.001, -length)); m_geo.vertices.push( new THREE.Vector3( -i , 0.001, length)); } //height lines and height texts for(let i = 0; i < h_m; i++){ let modulo = i % 10 let length = 0.1; if( modulo === 0 ){//0, 10, 20... length = 0.25 if(i !== 0){ let text = this.draw_text_sprite( `${i}`, {alignV2:scale.alignV2_z, width_scale:scale.width_scale, height_scale:scale.height_scale}) let neg_text = text.clone() text.position.set( length , 0.001, i ) neg_text.position.set( length , 0.001, -i ) texts_z.add(text) texts_z.add(neg_text) } }else if( modulo === 5){//5, 15, 25, ... length = 0.15 if(i !== 0){ let text = this.draw_text_sprite( `${i}`, {alignV2:scale.alignV2_z, width_scale:scale.width_scale, height_scale:scale.height_scale}) let neg_text = text.clone() text.position.set( length , 0.001, i ) neg_text.position.set( length , 0.001, -i ) texts_z.add(text) texts_z.add(neg_text) } } m_geo.vertices.push( new THREE.Vector3( length , 0.001, i)); m_geo.vertices.push( new THREE.Vector3( -length , 0.001, i)); m_geo.vertices.push( new THREE.Vector3( -length , 0.001, -i)); m_geo.vertices.push( new THREE.Vector3( length , 0.001, -i)); } let m_ruler = new THREE.LineSegments( m_geo, m_mat ) this.scene.add(m_ruler); this.scene.add(texts_x) this.scene.add(texts_z) let new_state = {...this.state} new_state.ruler.texts_x = texts_x new_state.ruler.texts_z = texts_z this.setState(new_state, cb)// ! /*KEEP LAST AS IT CONTAINS CALLBACK */ } draw_red_lines( cb ){//RUNS AT INIT THEREFORE IN A CALLBACK CHAIN let material = new THREE.LineBasicMaterial({color:0xff0000, transparent:true, opacity:0.6, linewidth : 10}) let geo_x = new THREE.Geometry() let geo_y = new THREE.Geometry() //line x coords geo_x.vertices.push(new THREE.Vector3(5, 0, 10)) geo_x.vertices.push(new THREE.Vector3(0, 0, 10)) //line y coords geo_y.vertices.push(new THREE.Vector3(5, 0, 10)) geo_y.vertices.push(new THREE.Vector3(5, 0, 0)) let line_x = new THREE.Line(geo_x, material) let line_y = new THREE.Line(geo_y, material) this.scene.add(line_x) this.scene.add(line_y) this.red_line_x = line_x this.red_line_y = line_y cb() } draw_red_coords( cb ){//RUNS AT INIT THEREFORE IN A CALLBACK CHAIN // use .material.map.needsUpdate = true; to update during the animate section //need to make a new MakeTextSprite that comes with a way to update the text //link do existing cavas that was used so that the dom we can modify it rather than make a new one // // // TODO depending on the z location of camera the scale of the letters must be adjusted // let sprite = MakeTextSprite( message, { textColor, sizeAttenuation } ) // // textSprite.rotation.x = Math.PI / 2 // // sprite.position.set(0, 1, 0) // sprite.center = alignV2 // sprite.scale.set( width_scale , height_scale) // return sprite cb() } draw_red_dot( cb ){//RUNS AT INIT THEREFORE IN A CALLBACK CHAIN var spriteMap = new THREE.TextureLoader().load( red_dot ); var spriteMaterial = new THREE.SpriteMaterial( { map: spriteMap, color: 0xffffff } ); var sprite = new THREE.Sprite( spriteMaterial ); sprite.scale.set( 0.2, 0.2, 1 ); sprite.center = new THREE.Vector2( 0.5, 0.5) sprite.position.set( 0,0.1,0) this.red_dot = sprite; this.scene.add( sprite ); let new_state = {...this.state} new_state.red_dot.TObj = sprite cb() } draw_plane( cb ){//RUNS AT INIT THEREFORE IN A CALLBACK CHAIN let geometry = new THREE.PlaneGeometry(this.state.plane.width, this.state.plane.height, 4) let material = new THREE.MeshBasicMaterial({color:0xffffff, transparent:true, opacity:0, side : THREE.DoubleSide}) let mesh = new THREE.Mesh( geometry, material) mesh.rotation.x = Math.PI / 2 mesh.position.set(0, 0, 0) mesh.name = "plane" // mesh.rotation.y = 0.09 console.log(mesh) this.scene.add(mesh) let new_state = this.state new_state.plane.TObj = mesh this.setState( new_state ,()=>{ console.log("redrew grid") geometry.dispose() material.dispose() cb() }) } //CONTROLS MOUSE KEYS EVENTLISTENERS=============================================================================================================== //CONTROLS MOUSE KEYS EVENTLISTENERS=============================================================================================================== //CONTROLS MOUSE KEYS EVENTLISTENERS=============================================================================================================== //CONTROLS MOUSE KEYS EVENTLISTENERS=============================================================================================================== //CONTROLS MOUSE KEYS EVENTLISTENERS=============================================================================================================== //CONTROLS MOUSE KEYS EVENTLISTENERS=============================================================================================================== //CONTROLS MOUSE KEYS EVENTLISTENERS=============================================================================================================== //CONTROLS MOUSE KEYS EVENTLISTENERS=============================================================================================================== modes = {//!modes must ALWAYS CONTAIN active_keys, EVEN IF EMPTY (CRASH ANIMATE LOOP) navigate:{ mouse_drag : ()=>{ console.log("navigate drag") }, active_keys : { "PageDown" : this.move_camera.in, "PageUp" : this.move_camera.out, "ArrowUp" : this.move_camera.up, "ArrowDown" : this.move_camera.down, "ArrowLeft" : this.move_camera.left, "ArrowRight" : this.move_camera.right, } }, draw_polygon:{ mouse_drag : ()=>{ console.log("draw_polygon drag") let set_x = this.state.move_arrows.hover_left_right let set_y = this.state.move_arrows.hover_up_down //TODO change to position of point rather than move arrow let x = this.move_arrows.position.x let y = this.move_arrows.position.y let z = this.move_arrows.position.z if(set_x) x = this.state.mouse.x if(set_y) z = this.state.mouse.y //set arrow this.move_arrows.position.set(x, y, z) }, active_keys : { // "PageDown" : this.move_camera.in, // "PageUp" : this.move_camera.out, // "ArrowUp" : this.move_camera.up, // "ArrowDown" : this.move_camera.down, // "ArrowLeft" : this.move_camera.left, // "ArrowRight" : this.move_camera.right, } }, } drag_active(){ this.modes[ this.state.active_mode ].mouse_drag() } reset_key_variables(event){ if(Object.keys(this.state.active_keys).length === 0){ if(this.state.moveing.speed > 0) this.set_prop("moveing", "speed", ()=>{return 0} ) } } activate_keyboard_button(event){ if ( event.key === "F5" || event.key ==="F12") return; if ( event.repeat === true){ return; } if ( event.defaultPrevented) { return; // Do nothing if the event was already processed } //for keys that need to be held down to move faster //! DO NOT USE FOR ONE TIME PRESS KEYS const activate_key = (key)=>{ let new_state = {...this.state}; new_state.active_keys[ key ] = true; this.setState(new_state, console.log(Object.keys( this.state.active_keys))) } let registered_keys = { "1" : ()=>{console.log(event.key, "navigate"); this.set_1_state("active_mode", ()=>"navigate") }, "2" : ()=>{console.log(event.key, "draw_polygon"); this.set_1_state("active_mode", ()=>"draw_polygon") }, "3" : ()=>{console.log(event.key)}, "Enter" : ()=>{console.log(event.key)}, } if( registered_keys[ event.key ] ){ registered_keys[ event.key ]() }else{ //! the following keys are not one time press keys //! they must be held in, must be deactivated activate_key(event.key) // "ArrowDown" : ()=>{}, // "ArrowUp" : ()=>{}, // "ArrowLeft" : ()=>{}, // "ArrowRight" : ()=>{}, // "PageUp" : ()=>{console.log(event.key)}, // "PageDown" : ()=>{console.log(event.key)}, } // Cancel the default action to avoid it being handled twice event.preventDefault(); } deactivate_keyboard_button(event){ if (event.defaultPrevented) { return; // Do nothing if the event was already processed } //for keys that need to be held down to move faster //! DO NOT USE FOR ONE TIME PRESS KEYS const deactivate_key = (key)=>{ let new_state = {...this.state}; if( new_state.active_keys[ key ] ){ delete new_state.active_keys[ key ] this.setState(new_state, console.log(Object.keys( this.state.active_keys))) } } //! the following keys are not one time press keys //! they must be held in, must be deactivated deactivate_key(event.key) // Cancel the default action to avoid it being handled twice event.preventDefault(); this.reset_key_variables(event)//! clean up any variables that were being used by active keys prior to release } custom_event_listeners_add(){ this.mount.addEventListener( 'mousemove', this.on_mouse_move, false ); this.mount.addEventListener( 'mousedown', ()=>this.set_prop("mouse", "down",()=>{return true}), false) this.mount.addEventListener( 'mouseup', ()=>this.set_prop("mouse", "down",()=>{return false}), false) window.addEventListener("keydown", this.activate_keyboard_button, true ); window.addEventListener("keyup", this.deactivate_keyboard_button, true ); } custom_event_listeners_remove(){ this.mount.removeEventListener( 'mousemove', this.on_mouse_move, false ); this.mount.removeEventListener( 'mousedown', ()=>this.set_prop("mouse", "down",()=>{return true}), false) this.mount.removeEventListener( 'mouseup', ()=>this.set_prop("mouse", "down",()=>{return false}), false) window.removeEventListener("keydown", this.activate_keyboard_button, true ); window.removeEventListener("keyup", this.deactivate_keyboard_button, true ); } //RAYCASTING =========================================================================================================================== //RAYCASTING =========================================================================================================================== //RAYCASTING =========================================================================================================================== //RAYCASTING =========================================================================================================================== //RAYCASTING =========================================================================================================================== raycast_mouse_position(){ /** * ``` raycastnames = { plane : "captures mouse location on drawing plane", arrow_up : "moves point up when dragged", arrow_down : "moves point up when dragged", arrow_left : "moves point up when dragged", arrow_right : "moves point up when dragged", } ``` */ this.raycaster.setFromCamera( this.mouse, this.camera ); let intersects if(//prevent raycasting if objects do not exist this.state.move_arrows.TObj_up !== null && this.state.move_arrows.TObj_down !== null && this.state.move_arrows.TObj_left !== null && this.state.move_arrows.TObj_right !== null && this.state.move_arrows.TObj_centert !== null && this.state.plane.TObj !== null ){//CALCULATES WHERE THE MOUSE IS ON THE DRAWING PLANE WHICH IS ON Y 0 intersects = this.raycaster.intersectObjects( [ this.state.move_arrows.TObj_up, this.state.move_arrows.TObj_down, this.state.move_arrows.TObj_left, this.state.move_arrows.TObj_right, this.state.move_arrows.TObj_center, this.state.plane.TObj//keep plane at bottom index ] ); if(intersects.length > 0){ // console.log(intersects) let new_state = this.state // console.log( this.loc_parse( intersects[intersects.length -1].point.x )) const actions = { "arrow_up" : (TObj)=>{ if(this.state.mouse.down)return; if(new_state.move_arrows.hover_up_down) return; new_state.move_arrows.TObj_up.material = ARROW_MATERIAL_HIGHLIGHT new_state.move_arrows.TObj_down.material = ARROW_MATERIAL_HIGHLIGHT new_state.move_arrows.TObj_left.material = ARROW_MATERIAL new_state.move_arrows.TObj_right.material = ARROW_MATERIAL new_state.move_arrows.TObj_center.material = ARROW_MATERIAL new_state.move_arrows.hover_up_down = true new_state.move_arrows.hover_left_right = false }, "arrow_down" : (TObj)=>{ if(this.state.mouse.down)return; if(new_state.move_arrows.hover_up_down) return; new_state.move_arrows.TObj_up.material = ARROW_MATERIAL_HIGHLIGHT new_state.move_arrows.TObj_down.material = ARROW_MATERIAL_HIGHLIGHT new_state.move_arrows.TObj_left.material = ARROW_MATERIAL new_state.move_arrows.TObj_right.material = ARROW_MATERIAL new_state.move_arrows.TObj_center.material = ARROW_MATERIAL new_state.move_arrows.hover_up_down = true new_state.move_arrows.hover_left_right = false }, "arrow_left" : (TObj)=>{ if(this.state.mouse.down)return; if( new_state.move_arrows.hover_left_right) return; new_state.move_arrows.TObj_up.material = ARROW_MATERIAL new_state.move_arrows.TObj_down.material = ARROW_MATERIAL new_state.move_arrows.TObj_left.material = ARROW_MATERIAL_HIGHLIGHT new_state.move_arrows.TObj_right.material = ARROW_MATERIAL_HIGHLIGHT new_state.move_arrows.TObj_center.material = ARROW_MATERIAL new_state.move_arrows.hover_up_down = false new_state.move_arrows.hover_left_right = true }, "arrow_right" : (TObj)=>{ if(this.state.mouse.down)return; if(new_state.move_arrows.hover_left_right) return; new_state.move_arrows.TObj_up.material = ARROW_MATERIAL new_state.move_arrows.TObj_down.material = ARROW_MATERIAL new_state.move_arrows.TObj_left.material = ARROW_MATERIAL_HIGHLIGHT new_state.move_arrows.TObj_right.material = ARROW_MATERIAL_HIGHLIGHT new_state.move_arrows.TObj_center.material = ARROW_MATERIAL new_state.move_arrows.hover_up_down = false new_state.move_arrows.hover_left_right = true }, "arrow_center" : (TObj)=>{ if(this.state.mouse.down)return; if(new_state.move_arrows.hover_up_down && new_state.move_arrows.hover_left_right ) return; new_state.move_arrows.TObj_up.material = ARROW_MATERIAL_HIGHLIGHT new_state.move_arrows.TObj_down.material = ARROW_MATERIAL_HIGHLIGHT new_state.move_arrows.TObj_left.material = ARROW_MATERIAL_HIGHLIGHT new_state.move_arrows.TObj_right.material = ARROW_MATERIAL_HIGHLIGHT new_state.move_arrows.TObj_center.material = ARROW_MATERIAL_HIGHLIGHT new_state.move_arrows.hover_up_down = true new_state.move_arrows.hover_left_right = true }, "plane" : (TObj)=>{ new_state.mouse.x = this.loc_parse( TObj.point.x ) new_state.mouse.y = this.loc_parse( TObj.point.z )//z because the plane has been rotated } } intersects.forEach( (TObj, i )=> { actions[ TObj.object.name ](TObj) }) const remove_arrow_highlights = ()=>{ if( this.state.mouse.down ) return ; new_state.move_arrows.TObj_up.material = ARROW_MATERIAL new_state.move_arrows.TObj_down.material = ARROW_MATERIAL new_state.move_arrows.TObj_left.material = ARROW_MATERIAL new_state.move_arrows.TObj_right.material = ARROW_MATERIAL new_state.move_arrows.TObj_center.material = ARROW_MATERIAL new_state.move_arrows.hover_up_down = false new_state.move_arrows.hover_left_right = false } if(intersects.length === 1 && intersects[0].object.name ==="plane") remove_arrow_highlights(); this.setState(new_state) } } } //INIT ANIMATE START STOP=============================================================================================================== //INIT ANIMATE START STOP=============================================================================================================== //INIT ANIMATE START STOP=============================================================================================================== //INIT ANIMATE START STOP=============================================================================================================== //INIT ANIMATE START STOP=============================================================================================================== //INIT ANIMATE START STOP=============================================================================================================== //INIT ANIMATE START STOP=============================================================================================================== init3D(){ let scene = this.scene; let renderer = this.renderer; let camera = this.camera; this.update_camera( camera ) renderer.setSize( window.innerWidth, window.innerHeight) this.mount.appendChild( renderer.domElement ) // positioning a light above the camera var light = new THREE.PointLight( 0xffffff, 4, 1000, 1 ); light.position.set( this.state.camera.x, this.state.camera.y, this.state.camera.z); camera.add(light); // let grid = this.draw_grid() // this.mount =this.state.canvasElement // console.log(this.mount) this.setState( { ...this.state, grid:{ ...this.state.grid } },()=>{ this.custom_event_listeners_add() // ! FUNCTIONS HERE MUST END WITH CALLBACK // ! I AM SO SORRY FOR THIS HAYNES CALLBACK SIN, PLEASE FORGIVE ME T.T this.draw_plane( ()=> this.draw_plane_rulers(//enclose by unexecuted function otherwise it will attempt to run immediately rather than at cb moment ()=> this.draw_red_dot(//enclose by unexecuted function otherwise it will attempt to run immediately rather than at cb moment ()=> this.draw_point_move_arrows(//enclose by unexecuted function otherwise it will attempt to run immediately rather than at cb moment ()=> this.draw_red_lines( ()=>this.draw_red_coords( ()=>{ console.log("starting") this.draw_CogWheel( this.start() ) } ) ) ) ) ) ) })//callback after setstate // this.render3D() } start = () => { if (!this.frameId && this._isMounted) { this.frameId = requestAnimationFrame(this.animate) } } stop = () => { cancelAnimationFrame(this.frameId) } previously_intersected = [] animate = () => { //!check activate_keys against active_keys in modes , trigger one iteration if mode and active key is valid if( this.modes[ this.state.active_mode ]["active_keys"] ){ Object.keys( this.state.active_keys ).forEach( active_key => { if(this.modes[ this.state.active_mode ]["active_keys"][ active_key ]) this.modes[ this.state.active_mode ]["active_keys"][ active_key ]() }) } //!set state.mouse.x and state.mouse.y this.raycast_mouse_position() //!PAINTS RED DOT IN NEW POSITION if( this.red_dot ) this.red_dot.position.set( this.state.mouse.x, 0.001, this.state.mouse.y ) //!UPDATE RED DOT LINE POSITIONS if( this.red_line_x ){ this.red_line_x.geometry.vertices[0].set(this.state.mouse.x, 0.001, this.state.mouse.y) this.red_line_x.geometry.vertices[1].set(0, 0.001, this.state.mouse.y) this.red_line_x.geometry.verticesNeedUpdate = true; } if( this.red_line_y ){ this.red_line_y.geometry.vertices[0].set(this.state.mouse.x, 0.001, this.state.mouse.y) this.red_line_y.geometry.vertices[1].set(this.state.mouse.x, 0.001, 0) this.red_line_y.geometry.verticesNeedUpdate = true; } //!UPDATE RED DOT COORD TEXT //!MOVES ARROW IF HOVERED AND MOUSE DOWN if( this.state.mouse.down ) this.drag_active(); this.render3D()//this.renderer.render this.frameId = window.requestAnimationFrame(this.animate) } render3D(){ this.renderer.render(this.scene, this.camera); } set_1_state( property, set_fn, cb_fn = ()=>{} ){ let new_state = this.state new_state[property] = set_fn() this.setState( new_state, cb_fn) } set_prop(category, property, set_fn, cb_fn = ()=>{} ){ let new_state = this.state new_state[category][property] = set_fn() this.setState( new_state, cb_fn) } set_prop_from_input_event( category, property, type, this_fn ){ // console.log(category, property) return (e)=>{ let new_state = {...this.state} new_state[category][property] = parse_type(type, e.target.value) this.setState({...new_state,}, this_fn ) } } componentWillUnmount(){ this._isMounted = false this.stop() this.custom_event_listeners_remove() this.mount.removeChild(this.renderer.domElement) } prevent_bubbles(e, cb){ e.stopPropagation(); e.preventDefault(); if (cb !== undefined) cb(e); } render(){ return( <div > {(this.props.id === null)?null: <div id={`${this.props.id}`} style={{ width: `100%`, height: `${window.innerHeight /** 0.85*/}px` }} ref={(mount) => { this.mount = mount }}//3D CANVAS GETS MOUNTED HERE />} {/* BUTTONS CONTAINER */} <form className="px-2 py-1" style={{minWidth:400}} onSubmit={(e)=>{ this.prevent_bubbles(e, ()=>{})}} onMouseOver={(e)=>{ this.prevent_bubbles(e, ()=>{})}} /**DISABLE onMouseMove event because it prevents user of range slider */ // onMouseMove={(e)=>{ this.prevent_bubbles(e, ()=>{})}} > {/* BUTTONS VISUAL CONTAINER */} <div style={{ position: "absolute", top: "32px", left: "0px", opacity: 0.9, zIndex: 10000 }} className="container"> <div className="row col col-sm-3 unselectable"> <span className="col col-sm text-white unselectable" >{`Camera X:${ round_2_dec( this.state.camera.x ) } Y:${ round_2_dec(this.state.camera.y) } Z:${ round_2_dec(this.state.camera.z) }`}</span> </div> <div className="row col col-sm-3 unselectable"> <span className="col col-sm text-white unselectable" >{`Mouse X:${this.state.mouse.x} Y:${this.state.mouse.y}`}</span> </div> <div className="row col col-sm-3 unselectable"> <div className="col text-white text-left border-light border d-flex align-items-start justify-content-center unselectable"> <span> Snap To </span> </div> </div> <div className="row col col-sm-3 unselectable"> <select className="col bg-dark text-white" value = {this.state.mouse.snap_increment} onChange={this.set_prop_from_input_event("mouse", "snap_increment", "number", ()=>{} )} > {/*value indicated the nearest increment to round to */} <option value = {1}>1</option> <option value = {2}>2</option> <option value = {5}>5</option> </select> <select className="col col-sm-8 bg-dark text-white" value = {this.state.mouse.snap_decimal} onChange={this.set_prop_from_input_event("mouse", "snap_decimal", "number", ()=>{} )} > {/*value indicates the product to divide and multiply during conversion 1 = m, 10 = dm, 100 = cm*/} <option value = {1}>meter</option> <option value = {10}>decimeter</option> <option value = {100}>centimeter</option> </select> </div> <div className="row col col-sm-3 input-group unselectable"> <div className="col text-white text-left border-light border d-flex align-items-start justify-content-center p-0"> <input type="checkbox" data-toggle="toggle" data-size="xs" data-onstyle="primary" data-offstyle="secondary" className = "m-0" data-on="Point Snap ON" data-off="Point Snap OFF" data-width="100%" data-height="100%" defaultChecked={this.state.mouse.snap_point} onChange={this.set_prop_from_input_event("mouse", "snap_point", "boolean", ()=>{} )} /> </div> </div> <div className="row col col-sm-3 input-group unselectable"> <div className="col text-white text-left border-light bg-dark border d-flex align-items-start justify-content-center p-0"> <div className="col p-0 m-0" > <button className="btn btn-dark btn-sm border-none pt-0" type="button" data-reactroot="" // onClick={ this.set_prop("camera", "y", "number", ()=>{}, ()=>{ return this.state.camera.y - 5} )} > <span className="glyph glyph-mountain_small glyph-small glyph-white align-middle"> </span> </button> </div> <div className="col col-8 pl-0 pr-0" > <input type="range" className="form-control p-1" min={5} max={200} value = { this.state.camera.y } onChange={ this.set_prop_from_input_event("camera", "y", "number", this.update_camera )} /> </div> <div className="col p-0 m-0" > <button className="btn btn-dark btn-sm border-none pt-0" type="button" data-reactroot=""> <span className="glyph glyph-mountain_large glyph-small glyph-white align-middle"> </span> </button> </div> </div> </div> </div> </form> </div> ) } } ThreeDrawGrid.propTypes = { id : PropTypes.string.isRequired, // match : PropTypes.shape({ // params: PropTypes.shape({ // field1: PropTypes.number, // field2: PropTypes.string // }) // }), // current_department : PropTypes.string, // current_company_currency : PropTypes.string, // whoami : PropTypes.object, // width : PropTypes.number, // height : PropTypes.number, } export default ThreeDrawGrid /** * important terms * console.log( THREE.Math.euclideanModulo(11, 3) ) // same as % oeprator * * LERP = Linear Interpolation (give 2 vectors or points and %/decimal place) * it will than return a point between the 2 points depending on the decimal * mimics straight line movement between 2 points * THREE.Math.degToRad( deg ) * THREE.Math. * THREE.Math.lerp( x, y, t) * Vector3.lerpVectors(v1, v2, t) * * * ``` const calc_xy_on_circle = (r, a, cx , cy) =>{ //! angle converted to radians let radians = a * Math.PI / 180 let x = Math.cos(radians) * (cx + r) let y = Math.sin(radians) * (cy + r) return [x, y] } const calc_xy_on_circle2 = (r, a, cx , cy) =>{ //! angle converted to radians let radians = THREE.Math.degToRad(a) let V3 = new THREE.Vector3( cx , cy, 0) let c = new THREE.Cylindrical( r, radians, cy) let new_V3 = V3.setFromCylindrical( c ) return [V3.z, V3.x] } ``` * EXAMPLE OF ROTATION AROUND SPHERICAL POSITION (ORBITTING) * * ``` let sphere_geo = new THREE.SphereGeometry(1, 8, 8) let sphere_mat = new THREE.MeshBasicMaterial({color: 0x993333, wireframe: true}) TEST_MESH = new THREE.Mesh( sphere_geo, sphere_mat) this.scene.add(TEST_MESH) //! convert degrees to radians console.log( TEST_MESH.position.setFromSpherical( new THREE.Spherical( 10, THREE.Math.degToRad(45), THREE.Math.degToRad(45)) ) ) console.log(TEST_MESH) //! THIS PART GOES IN animate TEST_ROTATE += 0.03 TEST_MESH.position.setFromSpherical( new THREE.Spherical( 10, TEST_ROTATE , TEST_ROTATE) ) ``` * * * */
import animejs from "animejs"; const modernizr = require("modernizr"); require('../menu'); /** * Faz o registro do Service Worker para servir a página no modo offline ... */ /* if ('serviceWorker' in navigator) { window.addEventListener('load', () => { navigator.serviceWorker.register('/service-worker.js').then(registration => { console.log('SW registered: ', registration); }).catch(registrationError => { console.log('SW registration failed: ', registrationError); }); }); } */ const blur = () => { }; const focus = () => { }; if (modernizr.hasEvent('blur')) { if (window.addEventListener) { window.addEventListener('blur', blur, false); } else if (window.attachEvent) { window.attachEvent('onblur', window.addEventListener('blur', blur, false)); } } if (modernizr.hasEvent('focus')) { if (window.addEventListener) { window.addEventListener('focus', focus, false); } else if (window.attachEvent) { window.attachEvent('onfocus', window.addEventListener('focus', focus, false)); } } let one = animejs.path('.emotion__ways .emotion__ways__one'); let two = animejs.path('.emotion__ways .emotion__ways__two'); // let three = animejs.path('.emotion__ways .emotion__ways__three'); let four = animejs.path('.emotion__ways .emotion__ways__four'); //let five = animejs.path('.emotion__ways .emotion__ways__five'); animejs({ targets: '.emotion__follower__one', translateX: one('x'), translateY: one('y'), rotate: one('angle'), easing: 'linear', duration: 15000, loop: true }); animejs({ targets: '.emotion__follower__two', translateX: two('x'), translateY: two('y'), easing: 'linear', duration: 25000, delay: 10000, loop: true }); /*animejs({ targets: '.emotion__follower__three', translateX: three('x'), translateY: three('y'), easing: 'linear', duration: 25000, delay: 5000, loop: true });*/ animejs({ targets: '.emotion__follower__four', translateX: four('x'), translateY: four('y'), easing: 'linear', duration: 20000, delay: 9000, loop: true }); /*animejs({ targets: '.emotion__follower__five', translateX: five('x'), translateY: five('y'), easing: 'linear', duration: 35000, loop: true });*/
function data(){ var mobiles = { samsung : { Data1 : { brand: "samsung", name : "Samsung Galaxy s4", screen : "5.0 inch", camera : "13 mp", ram : "2GB", rom : "16/32/64 GB storage, microSD card slot", battry : "2600 MAH", }, Data2: { brand: "samsung", name : "Samsung Galaxy s5", screen : "5.1 inch", camera : "14 mp", ram : "2GB", rom : "16/32 GB storage, microSD card slot", battry : "2800 MAH", }, Data3: { brand: "samsung", name : "Samsung Galaxy s6", screen : "5.1 inch", camera : "16 mp", ram : "3GB", rom : "32/64/128 GB storage, microSD card slot", battry : "2550 MAH", }, Data4:{ brand: "samsung", name : "Samsung Galaxy s7", screen : "5.1 inch", camera : "16 mp", ram : "4GB", rom : "32/64 GB storage, microSD card slot", battry : "3000 MAH", }, Data5: { brand: "samsung", name : "Samsung Galaxy s8", screen : "5.8 inch", camera : "12 mp", ram : "4GB", rom : "64 GB storage, microSD card slot", battry : "3000 MAH", }, }, Iphone: { Data6:{ brand: "Iphone", name : "Iphone 4s", screen : "3.5 inch", camera : "", ram : "512 MB", rom : "8/16/32/64GB storage, no card slot", battry : "1432 mAh", }, Data7:{ brand: "Iphone", name : "Iphone 5s", screen : "4.0 inch", camera : "", ram : "1 GB", rom : "16/32/64 GB storage, no card slot", battry : "1560 mAh", }, Data8:{ brand: "Iphone", name : "Iphone 6s", screen : "3.5 inch", camera : "", ram : "512 MB", rom : "8/16/32/64GB storage, no card slot", battry : "1432 mAh", }, Data9:{ brand: "Iphone", name : "Iphone 7s", screen : "3.5 inch", camera : "", ram : "512 MB", rom : "8/16/32/64GB storage, no card slot", battry : "1432 mAh", }, Data10:{ brand: "Iphone", name : "Iphone 8s", screen : "3.5 inch", camera : "", ram : "512 MB", rom : "8/16/32/64GB storage, no card slot", battry : "1432 mAh", }, } } var prodect = [] for(var key in mobiles){ for(var key2 in mobiles[key]){ prodect.push(mobiles[key][key2]) } } // console.log(prodect) localStorage.setItem("prodect", JSON.stringify(prodect)); var sales = []; localStorage.setItem("sales", JSON.stringify(sales)); }
const primeFactors = n => { output = {} while (n%2 === 0) { if(!output[2]){ output[2] = 0 } n = n/2; output[2] += 1 } for (let i = 3; i <= Math.sqrt(n); i = i+2) { while (n%i === 0){ if(!output[i]){ output[i] = 0 } n = n/i; output[i] += 1 } } if (n > 2){ output[n] = 1 } return output //{factor: frequency} } const consecutivePrimeFactors = howMany => { let test = 1 let done = false while(!done){ test++ if(Object.keys(primeFactors(test)).length === howMany){ let possiblydone = true for(let offset = 1; offset <= howMany - 1; offset++){ if(Object.keys(primeFactors(test+offset)).length != howMany){ possiblydone = false break } } done = possiblydone } } return test } console.log(consecutivePrimeFactors(4)) //134043
'use strict'; /** * @author ankostyuk */ describe('app travelService', function(){ var $httpBackend, travelService; beforeEach(angular.mock.module('app')); beforeEach(inject(function($injector) { travelService = $injector.get('travelService'); $httpBackend = $injector.get('$httpBackend'); // $httpBackend.whenGET(/places.aviasales.ru\/match/).respond(function(method, url, data, headers, params){ return [200, require('./places-aviasales-match--' + params.term + '.json')]; }); })); afterEach(function() { $httpBackend.verifyNoOutstandingExpectation(); $httpBackend.verifyNoOutstandingRequest(); }); it('travelService.searchPoint("lon"), locale = en', function() { travelService.searchPoint('lon', function(points) { expect(points).to.have.lengthOf(3); // LON expect(points).to.have.deep.property('[0].city._type', 'city'); expect(points).to.have.deep.property('[0].city.iata', 'LON'); expect(points).to.have.deep.property('[0].airports.length', 6); // LON -> LHR expect(points).to.have.deep.property('[0].airports[0]._type', 'airport'); expect(points).to.have.deep.property('[0].airports[0].iata', 'LHR'); expect(points).to.have.deep.property('[0].airports[0].city_iata', 'LON'); // LON -> LGW expect(points).to.have.deep.property('[0].airports[1]._type', 'airport'); expect(points).to.have.deep.property('[0].airports[1].iata', 'LGW'); expect(points).to.have.deep.property('[0].airports[1].city_iata', 'LON'); // LON -> STN expect(points).to.have.deep.property('[0].airports[2]._type', 'airport'); expect(points).to.have.deep.property('[0].airports[2].iata', 'STN'); expect(points).to.have.deep.property('[0].airports[2].city_iata', 'LON'); // LON -> LTN expect(points).to.have.deep.property('[0].airports[3]._type', 'airport'); expect(points).to.have.deep.property('[0].airports[3].iata', 'LTN'); expect(points).to.have.deep.property('[0].airports[3].city_iata', 'LON'); // LON -> LCY expect(points).to.have.deep.property('[0].airports[4]._type', 'airport'); expect(points).to.have.deep.property('[0].airports[4].iata', 'LCY'); expect(points).to.have.deep.property('[0].airports[4].city_iata', 'LON'); // LON -> SEN expect(points).to.have.deep.property('[0].airports[5]._type', 'airport'); expect(points).to.have.deep.property('[0].airports[5].iata', 'SEN'); expect(points).to.have.deep.property('[0].airports[5].city_iata', 'LON'); // LGB expect(points).to.have.deep.property('[1].city', null); expect(points).to.have.deep.property('[1].airports.length', 1); expect(points).to.have.deep.property('[1].airports[0]._type', 'airport'); expect(points).to.have.deep.property('[1].airports[0].iata', 'LGB'); expect(points).to.have.deep.property('[1].airports[0].city_iata', 'LGB'); // YXU expect(points).to.have.deep.property('[2].city._type', 'city'); expect(points).to.have.deep.property('[2].city.iata', 'YXU'); expect(points).to.have.deep.property('[2].airports.length', 1); // YXU -> YXU expect(points).to.have.deep.property('[2].airports[0]._type', 'airport'); expect(points).to.have.deep.property('[2].airports[0].iata', 'YXU'); expect(points).to.have.deep.property('[2].airports[0].city_iata', 'YXU'); }); $httpBackend.flush(); }); it('travelService.searchPoint("мос"), locale = ru', function() { travelService.searchPoint('мос', function(points) { expect(points).to.have.lengthOf(5); // MOW expect(points).to.have.deep.property('[0].city._type', 'city'); expect(points).to.have.deep.property('[0].city.iata', 'MOW'); expect(points).to.have.deep.property('[0].airports.length', 4); // MOW -> DME expect(points).to.have.deep.property('[0].airports[0]._type', 'airport'); expect(points).to.have.deep.property('[0].airports[0].iata', 'DME'); expect(points).to.have.deep.property('[0].airports[0].city_iata', 'MOW'); // MOW -> SVO expect(points).to.have.deep.property('[0].airports[1]._type', 'airport'); expect(points).to.have.deep.property('[0].airports[1].iata', 'SVO'); expect(points).to.have.deep.property('[0].airports[1].city_iata', 'MOW'); // MOW -> VKO expect(points).to.have.deep.property('[0].airports[2]._type', 'airport'); expect(points).to.have.deep.property('[0].airports[2].iata', 'VKO'); expect(points).to.have.deep.property('[0].airports[2].city_iata', 'MOW'); // MOW -> ZIA expect(points).to.have.deep.property('[0].airports[3]._type', 'airport'); expect(points).to.have.deep.property('[0].airports[3].iata', 'ZIA'); expect(points).to.have.deep.property('[0].airports[3].city_iata', 'MOW'); // OMO expect(points).to.have.deep.property('[1].city', null); expect(points).to.have.deep.property('[1].airports.length', 1); expect(points).to.have.deep.property('[1].airports[0]._type', 'airport'); expect(points).to.have.deep.property('[1].airports[0].iata', 'OMO'); expect(points).to.have.deep.property('[1].airports[0].city_iata', 'OMO'); // OSM expect(points).to.have.deep.property('[2].city', null); expect(points).to.have.deep.property('[2].airports.length', 1); expect(points).to.have.deep.property('[2].airports[0]._type', 'airport'); expect(points).to.have.deep.property('[2].airports[0].iata', 'OSM'); expect(points).to.have.deep.property('[2].airports[0].city_iata', 'OSM'); // LAX expect(points).to.have.deep.property('[3].city._type', 'city'); expect(points).to.have.deep.property('[3].city.iata', 'LAX'); expect(points).to.have.deep.property('[3].airports.length', 1); // LAX -> LAX expect(points).to.have.deep.property('[3].airports[0]._type', 'airport'); expect(points).to.have.deep.property('[3].airports[0].iata', 'LAX'); expect(points).to.have.deep.property('[3].airports[0].city_iata', 'LAX'); // KGS expect(points).to.have.deep.property('[4].city', null); expect(points).to.have.deep.property('[4].airports.length', 1); expect(points).to.have.deep.property('[4].airports[0]._type', 'airport'); expect(points).to.have.deep.property('[4].airports[0].iata', 'KGS'); expect(points).to.have.deep.property('[4].airports[0].city_iata', 'KGS'); }); $httpBackend.flush(); }); });
import React, { Component } from 'react'; import Logo from '../media/images/Logo.png' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { faBars, faUser } from '@fortawesome/free-solid-svg-icons' export default class Header extends Component { state = { toggle: this.props.toggle, toggleAccount: this.props.toggle, selected: this.props.selected } componentDidUpdate(prevProps, prevState) { prevProps !== this.props ? this.setState({ toggle: this.props.toggle, selected: this.props.selected }) : "" const x = document.getElementsByClassName("contentParent")[0] !this.state.toggle ? x.setAttribute("class", "blur0 contentParent") : x.setAttribute("class", "blur30 contentParent") } onClick = () => { this.setState({ toggle: !this.state.toggle }) } render() { return ( <div className={"nav" + (this.state.selected ? " bgi" : "")}> <div> <a href=""><img src={Logo} /></a> </div> <div onClick={this.onClick} className="menu-toggler"> <FontAwesomeIcon icon={faBars} /> </div> <ul className={this.state.toggle ? "show" : ""}> <li className={(this.state.toggle ? "show" : "") + (this.state.selected === "Technology" ? " selected" : "") + " noblur" + (!this.state.selected ? " nothingSelected" : "")} onClick={this.props.onClick}>Technology</li> <li className={(this.state.toggle ? "show" : "") + (this.state.selected === "Projects" ? " selected" : "") + " noblur" + (!this.state.selected ? " nothingSelected" : "")} onClick={this.props.onClick}>Projects</li> <li className={(this.state.toggle ? "show" : "") + (this.state.selected === "About" ? " selected" : "") + " noblur" + (!this.state.selected ? " nothingSelected" : "")} onClick={this.props.onClick}>About</li> </ul> <FontAwesomeIcon className="account" icon={faUser} /> </div> ); } }
function runTest() { FBTest.openNewTab(basePath + "html/5483/issue5483.html", function(win) { // 1. Open Firebug FBTest.openFirebug(function () { // 2. Switch to the HTML panel // 3. Inspect the Firebug logo (#image) inside the blue <div> FBTest.selectElementInHtmlPanel("image", function(node) { var attributes = node.getElementsByClassName("nodeAttr"); var valueNode = null; for (var i = 0; i < attributes.length; i++) { var name = attributes[i].getElementsByClassName("nodeName")[0].textContent; if (name === "src") { valueNode = attributes[i].getElementsByClassName("nodeValue")[0]; break; } } if (!FBTest.ok(valueNode, "Value must be displayed within the HTML panel")) FBTest.testDone(); var config = { tagName: "img", classes: "infoTipImage" }; FBTest.waitForDisplayedElement("html", config, function(node) { function verifyImageDimensions() { node.removeEventListener("load", verifyImageDimensions); var imageBox = FW.FBL.getAncestorByClass(node, "infoTipImageBox"); var infoTipCaption = imageBox.getElementsByClassName("infoTipCaption")[0]. textContent; FBTest.compare("64 x 64", infoTipCaption, "Image dimensions must be displayed"); FBTest.testDone(); } node.addEventListener("load", verifyImageDimensions); }); // 4. Hover the image URL inside the panel FBTest.mouseOver(valueNode); }); }); }); }
// Menu actions export const NEXT_MENU = 'NEXT_MENU'; export const PREVIOUS_MENU = 'PREVIOUS_MENU'; export const SET_MENU = 'SET_MENU'; export const RESET_MENU = 'RESET_MENU'; export const CLEAR_PREVIOUS_MENU = 'CLEAR_PREVIOUS_MENU'; export const SET_POP_CART = 'SET_POP_CART'; // Authentication export const AUTH_PROGRESS = 'AUTH_PROGRESS'; export const AUTH_ERROR = 'AUTH_ERROR'; export const REGISTER_SUCCESS = 'REGISTER_SUCCESS'; export const REGISTER_FAILURE = 'REGISTER_FAILURE'; export const LOGIN_SUCCESS = 'LOGIN_SUCCESS'; export const LOGIN_FAILURE = 'LOGIN_FAILURE'; export const LOGOUT = 'LOGOUT'; export const USER_LOADED = 'USER_LOADED'; // Email export const SEND_EMAIL_PROGRESS = 'SEND_EMAIL_PROGRESS'; export const SEND_EMAIL_SUCCESS = 'SEND_EMAIL_SUCCESS'; export const SEND_EMAIL_FAILURE = 'SEND_EMAIL_FAILURE'; // Guest customer export const SET_GUEST = 'SET_GUEST'; // pizza actions export const ADD_TOPPING = 'ADD_TOPPING'; export const REMOVE_TOPPING = 'REMOVE_TOPPING'; export const SET_PIZZA_BASE = 'SET_PIZZA_BASE'; export const SET_QUANTITY = 'SET_QUANTITY'; export const ADD_BASE_PRICE = 'ADD_BASE_PRICE'; export const ADD_TOTAL_PRICE = 'ADD_TOTAL_PRICE'; export const SET_PIZZA = 'SET_PIZZA'; export const SET_EDIT_PIZZA_FLAG = 'SET_EDIT_PIZZA_FLAG'; export const SET_INDEX = 'SET_INDEX'; export const CLEAR_PIZZA = 'CLEAR_PIZZA'; // Database actions export const LOAD_TOPPINGS = 'LOAD_TOPPINGS'; export const LOAD_CHEESES = 'LOAD_CHEESES'; export const LOAD_CRUSTS = 'LOAD_CRUSTS'; export const LOAD_SAUCES = 'LOAD_SAUCES'; export const LOAD_SIZES = 'LOAD_SIZES'; export const SET_PAST_ORDERS = 'SET_PAST_ORDERS'; export const SET_PAST_PIZZAS = 'SET_PAST_PIZZAS'; export const SET_VEGGIE_COUNT = 'SET_VEGGIE_COUNT'; export const SET_MEATS_COUNT = 'SET_MEATS_COUNT'; export const SET_CHEESE_COUNT = 'SET_CHEESE_COUNT'; export const CLEAR_USER_HISTORY = 'CLEAR_USER_HISTORY'; // Array of Pizzas export const ADD_PIZZA = 'ADD_PIZZA'; export const REMOVE_PIZZA = 'REMOVE_PIZZA'; export const CLEAR_PIZZAS = 'CLEAR_PIZZAS'; export const UPDATE_PIZZA_IN_PIZZAS = 'UPDATE_PIZZA_IN_PIZZAS'; // Order actions export const ORDER_PROCESS = 'ORDER_PROCESS'; export const ORDER_SUCCESS = 'ORDER_SUCCESS'; export const ORDER_FAILURE = 'ORDER_FAILURE'; export const CLEAR_ORDER = 'CLEAR_ORDER'; // Other action defines here...
import React, { useState, useEffect } from 'react'; import '../ListasEstilos/listVinos.css'; import { getVinosApi } from "../../../Api/vinos"; import ListaVinos from "../../../Components/Vinos/ListaVinos"; import { Link } from 'react-router-dom'; export default function ListVinos() { const [vinos, setVinoss] = useState([]); const [reloadVino, setReloadVino] = useState(false); useEffect(() => { getVinosApi().then(response => { setVinoss(response.vinos); }); setReloadVino(false) }, [reloadVino]) return ( <> <div className="row"> <div className="col-2"> <div class="row"> <div class="col-1"></div> <div class="col-sm" id="bannerVino"> <br /> <br /> <h2 class="listLabel">Lista de Vinos</h2> <div class="row"> <div id="circle-background"> <img src="https://icons.iconarchive.com/icons/paomedia/small-n-flat/1024/wine-icon.png" alt="" id="imgWine" /> </div> </div> </div> </div> </div> <div className="col-sm"> <div className="row-row-cols-lg-6"> <ListaVinos vinos={vinos} setReloadVino={setReloadVino} /> </div> <div className="row"> <div className="col-sm d-flex justify-content-center"> <Link to='/AdminRestaurante/AgregarVino' className='routing'><button class="btn btn-secondary ">Agregar Vinos</button></Link> </div> </div> </div> </div> </> ); }
import React from 'react'; import {hot} from 'react-hot-loader'; import NavigationBar from './NavigationBar'; import Greetings from './Greetings'; import AppRoutes from '../AppRoutes'; import FlashMessagesList from './flash/FlashMessagesList'; class App extends React.Component { constructor(props) { super(props); } render() { return ( <div className="container"> <NavigationBar /> <FlashMessagesList /> <AppRoutes/> </div> ); } } export default hot(module)(App);
/* * Playing Card Data and Methods * * Make sure you have loaded the utility library Lodash in order to use this. * * - https://lodash.com (documentation) * - https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.0/lodash.js * * This library adds two global variables and five global functions: * * (variable) deckOfCards: a single deck that represents the working deck * (variable) deckIsShuffled: a bool describing if the deck is shuffled or * sorted * * (function) shuffle: shuffle (or re-shuffle) the current deckOfCards * (function) sort: sort the current deckOfCards * (function) pickRandom: pick a random card from the deckOfCards - only * useful when the deck is sorted, since you can * just pop off of the top of a shuffled deck! * (function) dealDeck: returns a full deck of cards, sorted * (function) resetDeckOfCards: resets the deckOfCards to a full deck, sorted * */ function isFunction(functionToCheck) { 'use strict'; var getType = {}; return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]'; } // create globally accessible variables var deckOfCards, deckIsShuffled, shuffle, sort, pickRandom, dealDeck, resetDeckOfCards, _ = _ || undefined; // ensure that Lodash is loaded before defining methods that use it if (!isFunction(_)) { console.log("> ERROR: make sure that you load lodash with a script tag before card.js!"); console.log("> Lodash can be found at: cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.0/lodash.js"); } else { console.log("Lodash is loaded... ready to go!"); // always load lodash for its methods "shuffle", "sortBy" and "sample" // (pick random) // shuffle: https://lodash.com/docs#shuffle // sortBy: https://lodash.com/docs#sortBy // sample: https://lodash.com/docs#sample // remove: https://lodash.com/docs#remove var cards = [ "dA", "dK", "dQ", "dJ", "d10", "d09", "d08", "d07", "d06", "d05", "d04", "d03", "d02", "cA", "cK", "cQ", "cJ", "c10", "c09", "c08", "c07", "c06", "c05", "c04", "c03", "c02", "hA", "hK", "hQ", "hJ", "h10", "h09", "h08", "h07", "h06", "h05", "h04", "h03", "h02", "sA", "sK", "sQ", "sJ", "s10", "s09", "s08", "s07", "s06", "s05", "s04", "s03", "s02" ]; var cardValue = function(card) { 'use strict'; return cards.indexOf(card); }; dealDeck = function() { 'use strict'; var deckCopy = cards.join(','); deckCopy = deckCopy.split(','); return deckCopy; }; resetDeckOfCards = function() { 'use strict'; deckIsShuffled = false; deckOfCards = dealDeck(); return deckOfCards; }; shuffle = function() { 'use strict'; deckIsShuffled = true; deckOfCards = _.shuffle(deckOfCards); return deckOfCards; }; sort = function() { 'use strict'; deckIsShuffled = false; deckOfCards = _.sortBy(deckOfCards, cardValue); return deckOfCards; }; pickRandom = function() { 'use strict'; var card = _.sample(deckOfCards); deckOfCards = _.remove(deckOfCards, function(c) { return c !== card; }); return card; }; //resetDeckOfCards(); }
; (function ($) { $(document).ready(function () { // Include pages var includes = $('[data-include]') $.each(includes, function () { var file = 'views/' + $(this).data('include') + '.html' $(this).load(file) }) // Sticky header $(window).scroll(function () { var sticky = $('.header_block'), scroll = $(window).scrollTop(); if (scroll >= 50) sticky.addClass('fixed'); else sticky.removeClass('fixed'); // Scroll Watch setTimeout(function () { var swInstance = new ScrollWatch({ watchOnce: false }); swInstance }, 500);; }); // Slick Gallery $(document).on('click', 'a[class^=carousel-control-]', function (e) { var galleryItemOne = $('.item_one'); var galleryItemTwo = $('.item_two'); var galleryItemThree = $('.item_three'); if (galleryItemOne.hasClass('active')) { $('.gallery_section').css('background-color', '#26e69b'); } if (galleryItemTwo.hasClass('active')) { $('.gallery_section').css('background-color', '#e6ca26'); } if (galleryItemThree.hasClass('active')) { $('.gallery_section').css('background-color', '#26e6e6'); } e.stopImmediatePropagation(); e.preventDefault(); e.stopPropagation(); return false; }); // Smooth links $(document).on('click', 'a[href^="#"]', function (event) { event.preventDefault(); $('html, body').animate({ scrollTop: $($.attr(this, 'href')).offset().top - 100 }, 500); }); $(document).on('click', '.to_top', function (event) { event.preventDefault(); $("html, body").animate({ scrollTop: 0 }, 500); }); // Toggle Menu $(document).on('click', '.humburger', function (event) { event.preventDefault(); $(this).toggleClass('active'); $('.humburger_side_menu').toggleClass('active'); }); // Toggle Menu Mobile $(document).on('click', '.humburger_mobile', function (event) { event.preventDefault(); $(this).toggleClass('active'); $('.menu_mobile').toggleClass('open'); $('.header_block').toggleClass('active'); $('body').toggleClass('no_scroll'); }); // Close All $(document).on('click', '.close_menu', function (event) { event.preventDefault(); $('.humburger_mobile').removeClass('active'); $('.menu_mobile').removeClass('open'); $('.header_block').removeClass('active'); $('body').removeClass('no_scroll'); }); }); })(jQuery);
import map from 'ramda/src/map' import propEq from 'ramda/src/propEq' import filter from 'ramda/src/filter' export default (model) => map((col) => ({ ...col, over: col.id === model.over, tasks: map((task) => ({ ...task, dragging: model.dragging === task.id }), filter(propEq('col', col.id), model.tasks)) }), model.cols)
import { getTeacherFromDB, getCurriculumFromDB } from "../../database/dal/firebase/homeDal"; // import {getNotificationFromDB} from '../../database/dal/firebase/studentDal'; import { getNotificationForStudentBasedFromDB, getNotificationFromDB } from "../../database/dal/firebase/notificationdal"; export const getCurriculum = () => { return dispatch => { getCurriculumFromDB(dispatch); }; }; export const getTeacher = () => { return dispatch => { getTeacherFromDB(dispatch); }; }; export const getNotificationsBasedOnStudentID = id => { return dispatch => { getNotificationForStudentBasedFromDB(dispatch, id); }; }; // export const getNotification = () => { // return (dispatch) => { // getNotificationFromDB(dispatch); // } // } export const getNotification = () => { return dispatch => { getNotificationFromDB(dispatch); }; }; export const setKeyForNotificationPage = (notificationDetails) => { return { type: "GO_BACK_TO_NOTIFICATION", payload: notificationDetails }; }
let adminC = { props: ["bruker"], template: /*html*/` <div class="tittel"> <h1>Velkommen {{styret.firstname}}!</h1> <p>Kun styret kan se denne siden!</p> </div> <div class="pages content"> <div class="publish"> <h2>Legg ut et innlegg</h2> <p>Innlegget vil bli publisert under "For studenter"!</p> <form action="#" method="POST" v-on:submit="sendAnnonse" autocomplete="off"> <input type="text" name="title" v-model="title" placeholder="Tittel" required /><br /> <input type="text" name="link" v-model="link" placeholder="https://www.example.com"><br /> <textarea id="desc" name="text" v-model="text" placeholder="Beskrivelse" required ></textarea><br /> <input type="submit" value="send"> <p>{{validateTxt}}</p> </form> </div> <div class="adminDeal post"> <h1>LED avtaler</h1> <div class="deals"> <div v-for="deal in avtaler"> <h4>{{deal.type}} - {{deal.bid["name"]}}</h4> <p>Med {{deal.owner}}.</p> <p>Avtalt pris: {{deal.price}}</p> <p>{{deal.start_date}} - {{deal.end_date}}</p> </div> </div> </div> </div> `, data: function(){ return{ title: null, link: null, text: null, styret: [], avtaler: null, validateTxt: null } }, created: async function(){ // Henter admin-brukeren. Hvis det ikke er en adminbruker som er logget inn, blir brukeren sendt til /404 let response = await fetch('/admin'); if (response.status == 200){ let result = await response.json(); if (result){ this.styret = result; }else{ router.push("/404") } } // Henter LED sine avtaler med bedrifter let request = await fetch('/alleAvtaler'); if (request.status == 200){ let result = await request.json(); this.avtaler = result } }, methods: { // Lager et innlegg sendAnnonse: async function(event){ event.preventDefault(); var currentDateWithFormat = new Date().toJSON().slice(0,10).replace(/-/g,'/'); let request = await fetch("/innlegg",{ method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({Lenke: this.link, Beskrivelse: this.text, type: "innlegg", Dato: currentDateWithFormat, Sted: null, Tittel:this.title}) }); // Hvis brukerinput var godkjent blir brukeren sendt til /studenter hvor innlegget blir publisert. Hvis det ikke er // godkjent vises feilmeldingen. if (request.status == 200){ result = await request.json(); if (result == "Success"){ router.push("/studenter") }else{ this.validateTxt = result; } } } }, };
const { onUpdateTrigger } = require('../../knexfile') exports.up = async knex => { await knex.schema .createTable('products', table => { table.uuid('id').primary().notNullable() table.uuid('team_id').notNullable() table.string('name', 45).notNullable() table.string('description', 150) table.date('deadline') table.timestamps(true, true) table.timestamp('deleted_at') table.foreign('team_id').references('teams.id') .onUpdate('CASCADE') .onDelete('CASCADE') }) .then(() => knex.raw(onUpdateTrigger('products'))) } exports.down = async knex => { await knex.schema.dropTable('products') }
import React from 'react' import {Link} from 'react-router-dom' import "../styles/Startupbtn.css" const Istruzioni = () => { return ( <div className="section"> <h1>ISTRUZIONI</h1> <p>Il quiz consiste in 10 domande</p> <p>Ogni domanda ha un'unica risposta esatta e un tempo di 20 secondi per rispondere. <br/> Se la risposta selezionata è corretta si prosegue alla domanda successiva e il timer si resetta.<br/> In caso di risposta sbagliata il gioco termina!<br/> Si vince in caso si risponda correttamente a tutte e 10 le domande poste.<br/> </p> <Link to = "/"><button className = "smallbtn" >Homepage</button></Link> </div> ) } export default Istruzioni;
import { call, put } from 'redux-saga/effects'; import * as userApi from 'api/user'; import { uiActions, userActions } from 'ducks'; export function* login({ email, password }) { const payload = { email, password, }; try { const response = yield call(userApi.login, payload); yield put(userActions.loginSuccess(response)); yield put(uiActions.pushNotificationSuccess('Login successful.')); } catch (error) { yield put(userActions.loginFailure(error)); console.error(error); } } export function* logout() { try { yield call(userApi.logout); yield put(userActions.logoutSuccess()); } catch (error) { console.error(error); } }
/** * 导出reducer */ // 工具函数,用于组织多个reducer,并返回reducer集合 import { combineReducers } from 'redux'; import totalReducer from './totalReducer'; import userReducer from './userReducer'; import shopReducer from './shopReducer'; import mallReducer from './mallReducer'; import orderReducer from './orderReducer'; import welfareReducer from './welfareReducer'; import freightManageReducer from './freightManageReducer' import invoiceReducer from './invoiceReducer' import taskReducer from './taskReducer' import systemReducer from './systemReducer' import nav, { navAppReducer } from './navReducer' export default { totalReducer, userReducer, mallReducer, shopReducer, orderReducer, freightManageReducer, welfareReducer, invoiceReducer, taskReducer, systemReducer, nav, navApp: navAppReducer, };
var constant = -0.01; var ballsArr = [] function setup(){ createCanvas(600,600) for (i = 0; i < 10; i++){ ballsArr[i] = new Ball(300 + random(-200, 200),300 ,30) } } function draw(){ background(200) for (ball of ballsArr){ var gravity = createVector(0, 0.03) gravity.mult(ball.mass)//Make them fall at same time. Multiply the gravity and ball mass to make it back to 0.05. Which it was before. Sooo all balls affected by same amount of gravity var wind = createVector(0.02, 0) var friction = createVector(ball.vel.x, ball.vel.y) friction.normalize() var co = -0.01; friction.mult(co) var drag = createVector(ball.vel.x, ball.vel.y); drag.normalize(); var speed = ball.vel.magSq() drag.mult(speed * speed * constant ) if (keyIsPressed){ ball.applyForce(drag) } ball.applyForce(gravity) ball.applyForce(wind) if(keyIsPressed){ ball.applyForce(friction) } ball.show() ball.update() ball.bounce() } }
import React from 'react'; import {graphql} from 'gatsby'; import Layout from './layout'; import Image from 'gatsby-image'; import {css} from '@emotion/core'; export const query = graphql` query($slug : String!){ allDatoCmsHabitacion(filter : {slug : {eq:$slug} }){ nodes{ titulo contenido imagen{ fluid(maxWidth:1200){ ...GatsbyDatoCmsFluid } } } } } ` function HabitacionTemplate({data: {allDatoCmsHabitacion : {nodes}}}) { const {contenido , titulo, imagen} = nodes[0]; return ( <Layout> <main css={css`margin:0 auto; max-width:1200px; width:95% `}> <h1 css={css`text-align:center; margin-top:4rem;`}>{titulo}</h1> <p>{contenido}</p> <Image fluid={imagen.fluid} /> </main> </Layout> ) } export default HabitacionTemplate;
import Taro, { Component } from '@tarojs/taro'; import { View, Text } from '@tarojs/components'; import Header from '../../../components/header/header'; import GameItem from '../../../components/game/game'; import './blackmanage.scss'; import global from '../../../global'; import pvpIcon from '../../../images/black_logo/王者荣耀@2x.png'; import lolIcon from '../../../images/black_logo/英雄联盟@2x.png'; import cfIcon from '../../../images/black_logo/CF@2x.png'; export default class BlackManage extends Component { config = { navigationBarTitleText: '编辑黑名单' }; constructor() { super(...arguments); this.state = { gameList: [ { merchant: '王者荣耀点券充值', logo: pvpIcon, checked: false }, { merchant: '英雄联盟充值服务', logo: lolIcon, checked: false, }, { merchant: 'CF充值服务', logo: cfIcon, checked: false, } ] }; } componentDidMount() { const gameList = global.get('blacklist') || this.state.gameList; this.setState({gameList}); } onItemClick(index) { const {gameList} = this.state; gameList[index].checked = !gameList[index].checked; this.setState({gameList}); } onCancelBtnClick() { // 黑名单恢复为初始值 TODO Taro.navigateBack(); } onConfirmBtnClick() { const selectedList = this.state.gameList.filter(item => { return item.checked; }); console.log(selectedList); const param = { peopleId: global.get('people') || '', black_list: JSON.stringify(selectedList), }; global.post('setblacklist', param).then(res => { console.log('setblack', res); }) Taro.navigateBack(); } render() { const { gameList } = this.state; const games = gameList.map((item, index) => { return <GameItem key={index} name={item.merchant} logo={item.logo} checked={item.checked} onItemClick={this.onItemClick.bind(this, index)} />; }); return ( <View className="container"> <Header text={this.config.navigationBarTitleText} /> <View className="manage-main">{games}</View> <View className="manage-footer"> <View className="footer-btn cancel" onClick={this.onCancelBtnClick.bind(this)}>取消</View> <View className="footer-btn confirm" onClick={this.onConfirmBtnClick.bind(this)}>确认</View> </View> </View> ); } }
console.log("I did nazi that coming")
import "./styles.css"; const factMessageHTMLElement = document.querySelector(".factMessage"); //TODO récupérer l'élément html avec la classe .factMessage const nextButtonElement = document.querySelector(".nextButton"); // TODO récupérer l'élément html avec la classe .nextButton const previousFacts = []; // TODO: appeller l'api Chuck Norris Fact // Url: https://api.chucknorris.io/jokes/random const fetchFact = () => fetch("https://api.chucknorris.io/jokes/random") .then((res) => res.json()) .then((fact) => { factMessageHTMLElement.innerText = fact.value; }); // TODO: faites en sorte qu'un fact s'affiche dès le chargement de la page fetchFact(); // TODO: brancher vous sur l'événement click du nextButtonElement nextButtonElement.onclick = () => fetchFact(); // TODO: deployer le site web sur netlify // TODO: insérer un li pour chaque fact dans .previousFacts
function Location (column, row, left, top){ this.column = column; this.row = row; this.left = left; this.top = top; } module.exports = Location;
import Footer from './footer'; import FooterContainer from './footer.container'; export default FooterContainer(Footer);
import React, { useState, useEffect } from "react"; import { Info, LogIn, LogOut } from "react-feather"; import { useSelector } from "react-redux"; import { SpinnerRoundFilled } from "spinners-react"; import { Person } from "@material-ui/icons"; import { WordPlay } from "../WordPlay"; import { Snackbar } from "@material-ui/core"; import MuiAlert from "@material-ui/lab/Alert"; import { Slide } from "@material-ui/core"; import { AppBar } from "@material-ui/core"; import { Toolbar } from "@material-ui/core"; import { palette } from "../../Utils/theme"; export const Header = ({ onLogin, onLogout, onProfile, loading }) => { const user = useSelector(state => state.app.user); const [showAbout, setShowAbout] = useState(false); return ( <> <AppBar position="static" style={{ marginBottom: "10px", color: "black", width: "100%" }} > <Toolbar style={{ backgroundColor: palette.headerBackground, display: "flex", justifyContent: "space-between" }} > <div style={{ display: "flex", justifyContent: "center", alignItems: "center" }} > {user && ( <> <div style={{ display: "flex", alignItems: "center" }} onClick={onLogout} > <LogOut style={{ cursor: "pointer", color: palette.alert }} /> </div> <div onClick={onProfile} style={{ display: "flex", flexDirection: "column", justifyContent: "center", alignItems: "center", cursor: "pointer" }} > <Person style={{ color: palette.screenBackground }} /> <span style={{ fontSize: "10px", color: palette.textColor }}> {user.name || "Who are you ?!"} </span> </div> </> )} {!user && !loading && ( <> Login <LogIn style={{ cursor: "pointer" }} onClick={onLogin} /> </> )} {loading && <SpinnerRoundFilled color={palette.alert} />} </div> <div style={{ display: "flex", justifyContent: "center" }} > <WordPlay /> </div> <div style={{ display: "flex", position: "relative", justifyContent: "center", alignItems: "center" }} > <Info onClick={() => setShowAbout(!showAbout)} style={{ cursor: "pointer", color: palette.screenBackground }} /> <Snackbar open={showAbout} onClose={() => setShowAbout(false)} message="I love snacks" anchorOrigin={{ vertical: "top", horizontal: "right" }} autoHideDuration={6000} > <Slide in={showAbout} mountOnEnter unmountOnExit> <MuiAlert elevation={6} variant="filled" severity="info"> <p> <i> The dictionary section uses the{" "} <a href="https://cc-cedict.org/wiki/start">CC-CEDICT</a>{" "} </i> </p> <p> <i> database under the terms of{" "} <a href="https://creativecommons.org/licenses/by-sa/4.0/"> CC BY-SA 4.0 </a> </i> </p> </MuiAlert> </Slide> </Snackbar> </div> </Toolbar> </AppBar> </> ); };
angular.module('library.shared', []).factory('libraryShared', function () { var libraryShared = {}; // patron libraryShared.patronHeading = {}; libraryShared.patronHeading._010_id = {}; libraryShared.patronHeading._010_id.name = 'id'; libraryShared.patronHeading._010_id.text = 'Id'; libraryShared.patronHeading._010_id.type = 'Number'; libraryShared.patronHeading._020_name = {}; libraryShared.patronHeading._020_name.name = 'name'; libraryShared.patronHeading._020_name.text = 'Name'; libraryShared.patronHeading._020_name.type = 'String'; // media libraryShared.mediaHeading = {}; libraryShared.mediaHeading._010_id = {}; libraryShared.mediaHeading._010_id.name = "id"; libraryShared.mediaHeading._010_id.text = "Id"; libraryShared.mediaHeading._010_id.type = "Number"; libraryShared.mediaHeading._020_title = {}; libraryShared.mediaHeading._020_title.name = "title"; libraryShared.mediaHeading._020_title.text = "Title"; libraryShared.mediaHeading._020_title.type = "String"; libraryShared.mediaHeading._030_author = {}; libraryShared.mediaHeading._030_author.name = "author"; libraryShared.mediaHeading._030_author.text = "Author"; libraryShared.mediaHeading._030_author.type = "String"; libraryShared.mediaHeading._040_format = {}; libraryShared.mediaHeading._040_format.name = "format"; libraryShared.mediaHeading._040_format.text = "Format"; libraryShared.mediaHeading._040_format.type = "String"; libraryShared.mediaHeading._050_genre = {}; libraryShared.mediaHeading._050_genre.name = "genre"; libraryShared.mediaHeading._050_genre.text = "Genre"; libraryShared.mediaHeading._050_genre.type = "String"; libraryShared.mediaHeading._060_isbn = {}; libraryShared.mediaHeading._060_isbn.name = "isbn"; libraryShared.mediaHeading._060_isbn.text = "ISBN"; libraryShared.mediaHeading._060_isbn.type = "String"; libraryShared.mediaHeading._070_copies = {}; libraryShared.mediaHeading._070_copies.text = "Copies"; libraryShared.mediaHeading._070_copies.name = "copies"; libraryShared.mediaHeading._070_copies.type = "Number"; // record libraryShared.recordHeading = {}; libraryShared.recordHeading._010_id = {}; libraryShared.recordHeading._010_id.name = "id"; libraryShared.recordHeading._010_id.text = "Id"; libraryShared.recordHeading._010_id.type = "Number"; libraryShared.recordHeading._015_name = {}; libraryShared.recordHeading._015_name.name = "name"; libraryShared.recordHeading._015_name.text = "Name"; libraryShared.recordHeading._015_name.type = "String"; libraryShared.recordHeading._020_title = {}; libraryShared.recordHeading._020_title.name = "title"; libraryShared.recordHeading._020_title.text = "Title"; libraryShared.recordHeading._020_title.type = "String"; libraryShared.recordHeading._030_author = {}; libraryShared.recordHeading._030_author.name = "author"; libraryShared.recordHeading._030_author.text = "Author"; libraryShared.recordHeading._030_author.type = "String"; libraryShared.recordHeading._040_barcode = {}; libraryShared.recordHeading._040_barcode.name = "barcode"; libraryShared.recordHeading._040_barcode.text = "Barcode"; libraryShared.recordHeading._040_barcode.type = "String"; libraryShared.recordHeading._050_status = {}; libraryShared.recordHeading._050_status.name = "status"; libraryShared.recordHeading._050_status.text = "Status"; libraryShared.recordHeading._050_status.type = "String"; libraryShared.recordHeading._060_checkout = {}; libraryShared.recordHeading._060_checkout.name = "checkout"; libraryShared.recordHeading._060_checkout.text = "Checkout"; libraryShared.recordHeading._060_checkout.type = "Date"; libraryShared.recordHeading._070_due = {}; libraryShared.recordHeading._070_due.name = "due"; libraryShared.recordHeading._070_due.text = "Due date"; libraryShared.recordHeading._070_due.type = "Date"; libraryShared.recordHeading._080_checkin = {}; libraryShared.recordHeading._080_checkin.name = "checkin"; libraryShared.recordHeading._080_checkin.text = "Checkin"; libraryShared.recordHeading._080_checkin.type = "Date"; // return myself; return libraryShared; });
const initialState = { group: { id: null, promotionImgUrl: null, authorAvatar: null, authorNickname: null, authorSlogan: null, authorIsVip: false, canEdit: false, declaration: null }, entryType: null, entryQuery: {}, entryPath: null, scene: null, shareTicket: null, reLaunch: null, location: { province: { id: 1, name: '北京市' }, city: { id: 41, name: '朝阳区' } }, manualLocation: null, wxGetLocationSuccess: false, wxGetLocationFail: false, categories: [], notices: null, saleSupportReasonList: [], searchLocation:{}, saleSupportMessage:null } let location const global = (state = initialState, action) => { switch (action.type) { case 'WEAPP_ENTRY_OPTIONS': const { path, query, scene, shareTicket, reLaunch } = action.payload return { ...state, entryPath: path, entryQuery: query, scene, shareTicket, reLaunch } case 'SET_ENTRY_TYPE': const { entryType } = action.payload return { ...state, entryType } case 'SET_GROUP': const { group } = action.payload return { ...state, group: { ...group }} case 'FETCH_SUBJECT_LIST_SUCCESS': const { isUpdateSalerInfo: canEdit, avatar: authorAvatar, description: authorSlogan, declaration: declaration, isVipUser: authorIsVip, nickname: authorNickname } = action.payload return { ...state, group: { ...state.group, canEdit, authorAvatar, authorSlogan, authorIsVip, authorNickname, declaration } } case 'FETCH_GLOBAL_DATA_SUCCESS': const { province, city, categories, notifications: notices } = action.payload location = province ? { province, city } : state.location return { ...state, location, categories, notices } case 'PUT_LOCATION': location = action.payload.location return { ...state, location } case 'FETCH_SALE_SUPPORT_REASON_LIST_SUCCESS': const { saleSupportReasonList } = action.payload return { ...state, saleSupportReasonList } case 'CHECK_SALE_SUPPORT_SUCCESS': const { saleSupportMessage } = action.payload return { ...state, saleSupportMessage } case 'PUT_LOCATION_BY_MANUAL': location = action.payload.location return { ...state, manualLocation: location } case 'POST_LOCATION_SUCCESS': location = action.payload.location return { ...state, location, manualLocation: null } case 'FETCH_WX_GET_LOCATION_SUCCESS': return { ...state, wxGetLocationFail: false, wxGetLocationSuccess: true } case 'FETCH_WX_GET_LOCATION_FAIL': return { ...state, wxGetLocationFail: true } case 'PUT_PROFILE_SUCCESS': const { avatar, nickname, description } = action.payload return { ...state, group: { ...state.group, authorAvatar: avatar, authorNickname: nickname, authorSlogan: description, declaration: declaration } } default: return state } } export default global
/** * Created by iyobo on 2016-08-24. */ const config = require('../configurator').settings; const log = require('../log') const path = require('path'); /** * Handles uploaded file storage and persistence within eluvianJS */ class FileStorage { * store( file, opts = {} ) { try { //Only process file upload if it has no 'key' field i.e. File hasn't been uploaded before if(file['key']) return file; let engineName = opts.engineOverride || config.fileStorage.defaultEngine; let engine = require(path.join(__dirname, 'engines', engineName)); if (!engine) { log.warn(`No such engine name: ${engineName}. Defaulting to local`) engine = require('./engines/local') } const res= yield engine.store(file, opts); return res; } catch (err) { log.error(`There was an error storing the file`, err.stack); throw err; } } * retrieve( path, opts = {} ) { } * delete( path, opts = {} ) { } } module.exports = new FileStorage();
import Vue from 'vue'; import VueRouter from 'vue-router'; import VueResource from 'vue-resource'; import Vuex from 'vuex'; // 引入 store 資料夾(上面五隻 js ) // 預設會去找 index.js 如果沒有的話會報錯! // 我們在上一個範例已經組合所有指揮挺了!! import store from './store' // init Vue.use(VueRouter); Vue.use(VueResource); Vue.use(Vuex); // page import Hello from './pages/Hello.vue'; import CtoF from './pages/C2F.vue'; import CountVue from './pages/count.vue'; import Login from './pages/Login.vue'; import App from './App.vue'; const router = new VueRouter({ // 使用 HTML 5 模式 mode: 'history', base: __dirname, // routre 表 routes: [ { path: '/login', name: 'login', component: Login }, { path: '/hello', name: 'hello', component: Hello }, { path: '/c2f', name: 'c2f', component: CtoF }, { path: '/count', name: 'count', component: CountVue }, // router 轉址 { path: '/*', redirect: '/hello' } ] }); new Vue({ el: '#app', // router 掛載設定 router, // 加入 store store, // app.vue 掛載並 replace index.html 原始掛載點: <div id="app"></div> render: h => h( App ), watch:{ "$route" : 'checkLogin' }, created() { this.checkLogin(); }, methods:{ checkLogin(){ //检查是否存在session if(!this.$store.getters.getLogin){ this.$router.push('/login'); }else{ //this.$router.push('/'); } } } }); //const resource = new VueResource();
import Queue from './queue'; describe('Scene queue', () => { it('exists', () => { expect(new Queue()).toBeDefined(); }); it('executes a single item', async () => { const queue = new Queue(); expect(await queue.add({ id: 0, tasks: [ () => Promise.resolve(5), ], })).toEqual(5); }); it('executes multiple tasks together', async () => { const queue = new Queue(); expect(await queue.add({ id: 0, tasks: [ () => Promise.resolve(5), result => Promise.resolve(result * result), ], })).toEqual(25); }); it('can cancel', () => { let resolveTask1Start; let resolveTask1End; const task1Start = jest.fn().mockReturnValue(new Promise((resolve) => { resolveTask1Start = resolve; })); const task1End = jest.fn().mockReturnValue(new Promise((resolve) => { resolveTask1End = resolve; })); const task2 = jest.fn().mockReturnValue(Promise.resolve(5)); const queue = new Queue(); const tasks = [ () => task1Start().then(() => { queue.cancel(0); return task1End(); }), task2, ]; const finished = queue.add({ id: 0, tasks, }); resolveTask1Start(); resolveTask1End(1); return finished.then((result) => { expect(task2).toHaveBeenCalledTimes(0); expect(result).toEqual(1); }); }); it('can cancel with new task', () => { let resolveTask1Start; let resolveTask1End; const task1Start = jest.fn().mockReturnValue(new Promise((resolve) => { resolveTask1Start = resolve; })); const task1End = jest.fn().mockReturnValue(new Promise((resolve) => { resolveTask1End = resolve; })); const task2 = jest.fn().mockReturnValue(Promise.resolve(5)); const queue = new Queue(); const tasks = [ () => task1Start().then(() => { queue.cancel(0); return task1End(); }), task2, ]; queue.add({ id: 0, tasks, }); const finished = queue.add({ id: 1, tasks: [ () => Promise.resolve(2), ], }); resolveTask1Start(); resolveTask1End(1); return finished.then((result) => { expect(result).toEqual(2); }); }); it('cancel all', async () => { const queue = new Queue(); const job1End = jest.fn().mockReturnValue(Promise.resolve()); const job2End = jest.fn().mockReturnValue(Promise.resolve()); queue.add({ id: 0, tasks: [ queue.cancel, job1End, ], }); await queue.add({ id: 1, tasks: [ job2End, ], }); expect(job1End).toHaveBeenCalledTimes(0); expect(job2End).toHaveBeenCalledTimes(0); }); it('error', async () => { const queue = new Queue(); const job1End = jest.fn().mockReturnValue(Promise.resolve()); let didThrow = false; try { await queue.add({ id: 0, tasks: [ () => Promise.reject(new Error('foo')), job1End, ], }); } catch (e) { didThrow = true; expect(() => { throw e; }).toThrowError('foo'); } finally { expect(job1End).toHaveBeenCalledTimes(0); expect(didThrow).toEqual(true); } }); });
import React from 'react' import { useHub } from '@sporttotal/hub' const Button = ({ style, children, to, active, onClick }) => { // const isFn = typeof active === "function"; // let isActive = isFn ? active(to) : active; const hub = useHub() return ( <div onClick={e => { if (to) { e.preventDefault() e.stopPropagation() hub.set('device.history', to) } else { onClick(e) } }} style={{ cursor: 'pointer', padding: 5, display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'San Fransisco, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"', fontSize: 12, paddingBottom: 5, border: '1px solid black', transition: 'box-shadow 0.15s', ':hover': { boxShadow: '0px 0px 10px rgba(215,215,225,1)' }, ...style }} to={to} > {children} </div> ) } export default Button
export { default } from './GalleryAll.layout'
const express = require('express'); const path = require('path'); const bodyParser = require('body-parser'); const cookieParser = require('cookie-parser'); const compress = require('compression'); const helmet = require('helmet'); const mongoose = require('mongoose'); const cors = require('cors'); const routes = require('./routes'); const app = express(); const config = require('./config'); const authOptions = { origin: true, methods: ['POST', 'PUT', 'DELETE', 'GET'], credentials: true, maxAge: 3600, }; app.set('secret', config.secret); app.set('dbUrl', config.db[app.settings.env]); mongoose.connect(app.get('dbUrl')); app.use(bodyParser.json()); // app.use(bodyParser.json({ type: 'application/vnd.api+json' })); app.use(bodyParser.urlencoded({ extended: true })); app.use(cookieParser()); app.use(compress()); app.use(helmet()); app.use(cors(authOptions)); const build_dir = path.resolve(__dirname, '../../build'); app.use(express.static(build_dir)); app.use('/api/v1/', routes); // process.env.PORT lets the port be set by Heroku const port = process.env.PORT || 4000; app.listen(port, () => console.log(`Listening on port ${port}!`));
// Copyright (C) 2020 to the present, Crestron Electronics, Inc. // All rights reserved. // No part of this software may be reproduced in any form, machine // or natural, without the express written consent of Crestron Electronics. // Use of this source code is subject to the terms of the Crestron Software License Agreement // under which you licensed this source code. var utilsModule = (function () { "use strict"; function log(...input) { let allowLogging = true; if (allowLogging === true) { console.log(...input); } } function dynamicsort(order, ...property) { var sort_order = 1; if (order === "desc") { sort_order = -1; } return function (a, b) { if (property.length > 1) { let propA = a[property[0]]; let propB = b[property[0]]; for (let i = 1; i < property.length; i++) { propA = propA[property[i]]; propB = propB[property[i]]; } // a should come before b in the sorted order if (propA < propB) { return -1 * sort_order; // a should come after b in the sorted order } else if (propA > propB) { return 1 * sort_order; // a and b are the same } else { return 0 * sort_order; } } else { // a should come before b in the sorted order if (a[property] < b[property]) { return -1 * sort_order; // a should come after b in the sorted order } else if (a[property] > b[property]) { return 1 * sort_order; // a and b are the same } else { return 0 * sort_order; } } } } return { log: log, dynamicsort: dynamicsort }; })();
// Importing Core Packages const express = require("express"); const is_ = require("is-base64"); const cors = require("cors"); const fs = require('fs'); const path = require('path'); // Images Directory const directoryPath = path.join(__dirname, 'images/'); // Initializing Application const app = express(); const port = process.env.PORT || 5000; // Express Things app.use(cors()); app.use(express.json({limit: '50mb'})); app.use(express.urlencoded({limit: '50mb', extended: false})); // Body if (!fs.existsSync(directoryPath)){ fs.mkdirSync(directoryPath); } // Returns all the image in the directory app.get('/', (req, res) => { let arrayOfFiles = []; fs.readdir(directoryPath, function (err, files) { if (err) { return console.log('Unable to scan directory: ' + err); } files.forEach(function (file) { arrayOfFiles.push(file) }); res.json(arrayOfFiles); }); }) // Gets the specific image app.get('/:file', (req, res) => { const filePath = req.params.file res.sendFile(directoryPath + filePath); }) // Saves the image app.put('/file', (req, res) => { let { title, base64 } = req.body; let newTitle = title.split('.')[0] if(fs.existsSync(directoryPath + newTitle + ".png")){ newTitle = `${newTitle}_${Math.floor(Math.random() * 100)}.png` }else{ newTitle = `${newTitle}.png` } if(is_(base64)){ fs.writeFile(directoryPath + newTitle, base64, 'base64', (err) => { if(err) return res.json({"status": "failure... oniiichan messed up >///<"}); res.json({"status": "success... owo"}) }) }else{ res.json({"status": "senpai it's not a base64 image."}) } }) // Starting Application app.listen(port, function (err) { if (err) { return console.error(err); } console.log('Server started! Say hey at http://localhost:' + port + '/') });
import React, { useContext } from 'react'; import { CartContext } from "../../context/CartContext"; import './itemCount.css'; const ItemCount = ({product, min, max, counter, setCounter}) => { const { increase, decrease, itemCount } = useContext(CartContext) const onHandleClick = (sign) => { if (counter < max && sign === '+') setCounter(counter + 1) else if (counter > min && sign === '-') setCounter(counter - 1) } return ( <div> <button className='btn btn-control' onClick={() => onHandleClick('+')}>+</button> <span className='counter'>{counter}</span> <button className='btn btn-control' onClick={() => onHandleClick('-')}>-</button> </div> ); }; export default ItemCount;
'use strict'; import React from 'react'; export default class ResponseViewContextUtil extends React.Component { static propTypes = { response: React.PropTypes.object, children: React.PropTypes.node }; static childContextTypes = { response: React.PropTypes.object }; getChildContext() { return {response: this.props.response}; } render() { return this.props.children; } }
let randomArray = require('../random'); let sort = require('./index'); // random data let n = 10; let {a: input, b: valid} = randomArray(n, 100, 999); // let input = [1, 3, 2, 8, 6, 4, 10]; // let valid = [1, 3, 2, 8, 6, 4, 10]; // sort valid valid.sort((a, b) => a - b); console.log('input =', input); console.log('valid =', valid); let stat = { iterationCount: 0, sort }; // mergeSort let output = stat.sort(input.map(x => x)); // output console.log('output =', output); console.log('\nn = ', n); // console.log('O(n^2) =', (n * n).toFixed(0)); console.log('iterationCount =', stat.iterationCount); // verify require('assert').deepEqual(output, valid);
'use strict'; function UserAccount(){} UserAccount.prototype.expectAccountOptions = function () { element(by.cssContainingText('span.hidden-tablet.ng-scope', 'Account')).click().then(function () { expect(element(by.cssContainingText('span.ng-scope', 'Settings')).isPresent()).toBe(true); expect(element(by.cssContainingText('span.ng-scope', 'Password')).isPresent()).toBe(true); expect(element(by.cssContainingText('span.ng-scope', 'Sessions')).isPresent()).toBe(true); expect(element(by.cssContainingText('span.ng-scope', 'Log out')).isPresent()).toBe(true); }); }; UserAccount.prototype.settingPageFunctions = function () { element(by.cssContainingText('span.hidden-tablet.ng-scope', 'Account')).click().then(function () { element(by.cssContainingText('span.ng-scope', 'Settings')).click(); element(by.model('settingsAccount.firstName')).clear().then(function(){ element(by.model('settingsAccount.firstName')).sendKeys('AdministratorNew'); }); element(by.model('settingsAccount.lastName')).clear().then(function(){ element(by.model('settingsAccount.lastName')).sendKeys('AdministratorNew'); }); element(by.model('settingsAccount.email')).clear().then(function(){ element(by.model('settingsAccount.email')).sendKeys('adminNew@localhost'); }); element(by.xpath("//form//button[text()='Save']")).click(); expect(element(by.xpath("//div/strong[text()='Settings saved!']")).isPresent()).toBe(true); }); }; UserAccount.prototype.expectPasswordPage = function () { element(by.cssContainingText('span.hidden-tablet.ng-scope', 'Account')).click().then(function () { browser.sleep(1000); element(by.cssContainingText('span.ng-scope', 'Password')).click(); element(by.model('password')).clear().then(function(){ element(by.model('password')).sendKeys('admin1'); }); element(by.model('confirmPassword')).clear().then(function(){ element(by.model('confirmPassword')).sendKeys('admin1'); }); element(by.xpath("//form//button[text()='Save']")).click(); expect(element(by.xpath("//div/strong[text()= 'Password changed!']")).isPresent()).toBe(true); }); }; UserAccount.prototype.expectSessionPage = function () { element(by.cssContainingText('span.hidden-tablet.ng-scope', 'Account')).click().then(function () { browser.sleep(1000); element(by.cssContainingText('span.ng-scope', 'Sessions')).click(); expect(element(by.cssContainingText('button.btn','Invalidate')).isPresent()).toBe(true); element(by.cssContainingText('button.btn','Invalidate')).click(); browser.sleep(1000); expect(element(by.cssContainingText('strong','Session invalidated!')).isPresent()).toBe(true); }); }; UserAccount.prototype.expectLogout = function () { element(by.cssContainingText('span.hidden-tablet.ng-scope','Account')).click().then(function(){ expect(element(by.cssContainingText('span.ng-scope', 'Log out')).isPresent()).toBe(true); }); }; module.exports = new UserAccount();
// bootstrap은 프론트엔드 디자인을 쉽게 구현할 수 있도록 도와주는 // html, css, js 등 구현을 위한 layout 프레임워크 입니다. // bootstrap을 React에서 사용할 수 있도록 패키지로 만든 것이 // reactstrap입니다. 여기서, Alerts 패키지는 알림 영역에 대한 // 기능을 제공합니다. 우선, npm을 활용해서 reactstrap을 설치해 줍니다. // C:\reactstart\reactstrap_example>npm install -save reactstrap // reactstrap은 bootsrap css를 포함하고 있지 않기 때문에 // 다음과 같이 bootstrap도 npm으로 설치해 줍니다. // C:\reactstart\reactstrap_example>npm install -save bootstrap // yarn 또는 npm으로 설치시 index.js(또는 App.js)에 다음의 구문을 // 추가해 주시기 바랍니다. // import 'bootstrap/dist/css/bootstrap.css'; import React from "react"; // import './App.css'; import 'bootstrap/dist/css/bootstrap.css'; import ReactstrapFade from "./components/ReactstrapFade"; function App(){ return ( <div> <h1>Start React 2021!</h1> <p>ReactstrapFade 적용하기</p> <ReactstrapFade /> </div> ); }; export default App;
/** * Alexander McCaleb * CMPS 179 - Summer 2013 * Prototype2 - Thumper * * Beat.js * * Beat object * Helps convert between seconds and beats * * Based on code provided by Nathan Whitehead at: * http://nathansuniversity.com/cmps179/presentations/demo/tex9.html * */ var Beat = function(bpm) { this.bpm = bpm; }; /** * Convert time to beatTime */ Beat.prototype.toBeatTime = function(t) { return t * this.bpm / 60.0; }; /** * Convert time to beat value * Beat value is 0 to 1, hits 1 on the beat */ Beat.prototype.toBeat = function(t) { return 1.0 - Math.abs(Math.sin(this.toBeatTime(t) * 3.14159)); }; /** * Determine how synchronized time is with beat * Returns: * -1 for early * 0 for on beat * 1 for late */ Beat.prototype.onBeat = function(prevt, t) { // Compute the recent between beat values var lastBeat = this.toBeat(prevt); var curBeat = this.toBeat(t); // Check whether we're on beat if(curBeat > 0.9 && lastBeat > 0.9) { // We're close enough to the beat return 0; } // Compute the difference between beats var dBeat = curBeat - lastBeat; // Now figure how close we are to the beat if(dBeat > 0) { // We're early return -1; } else { // We're late return 1; } };
import styled from 'styled-components'; const HeaderDiv = styled.div` width: 100%; display: flex; justify-content: space-between; margin-bottom: 3.9rem; .title { font-size: 3rem; text-transform: uppercase; letter-spacing: 1rem; color: white; } .switch-theme-logo { width: 2.5rem; height: 2.5rem; outline: none; cursor: pointer; background-image: ${(props) => `url(${props.src})`}; background-size: cover; } `; const Header = ({ name, toggle }) => { const logo = require(`../../assets/img/${name}.svg`).default; return ( <HeaderDiv src={logo}> <h1 className="title">Todo</h1> <div className="switch-theme-logo" onClick={toggle}></div> </HeaderDiv> ); }; export default Header;
import React from "react"; import { Fontisto } from "@expo/vector-icons"; import styled from "styled-components/native"; import { HEIGHT } from "../../constants/layout"; const MyScreenTabScreen = () => ( <Outline> <IconView> <Icon> <Fontisto name="ticket" size={80} color="#e1e1e1" /> </Icon> <IconText>아직 사용가능한 프립이 없어요</IconText> </IconView> </Outline> ); export default MyScreenTabScreen; const Outline = styled.View` align-items: center; justify-content: center; height: ${HEIGHT / 2.3}; background-color: white; `; const IconView = styled.View` height: 130px; justify-content: space-between; align-items: center; `; const Icon = styled.View``; const IconText = styled.Text` color: #e3e3e3; `;
import { createGlobalStyle } from 'styled-components'; export const GlobalStyle = createGlobalStyle` :root { box-sizing: border-box; font-size: 62.5%; --transition: 300ms ease-in-out; } *, ::before, ::after { box-sizing: inherit; margin: 0; padding: 0; } body { width:100%; font-family: 'Bai Jamjuree', sans-serif; } .download-btn-container { display: flex; flex-direction: column; } .download-btn-container button { height: 5.6rem; border-radius: 2.8rem; border: none; outline: none; color: white; font-family: 'Bai Jamjuree', sans-serif; font-size: 1.8rem; font-weight: 400; letter-spacing: 0.5px; line-height: 3rem; cursor:pointer; transition: var(--transition) transform; } .download-btn-container button:hover{ transform: translateY(-2px); } .ios-btn { background-color: hsl(171, 66%, 44%); margin-bottom: 2.4rem; box-shadow: 0px 10px 20px rgba(137, 229, 199, 0.5); } .ios-btn:hover{ background-color: hsla(171, 66%, 44%,0.7); } .mac-btn { background-color: hsl(233, 100%, 69%); box-shadow: 0px 10px 20px rgba(0, 0, 0, 0.1); } .mac-btn:hover { background-color: hsla(233, 100%, 69%,0.7); } @media screen and (min-width: 700px) { .download-btn-container { flex-direction: row; justify-content: space-between; width:47rem; margin:0 auto; } .download-btn-container button { width:22.7rem; } } `;
module.exports = function () { return context => { if (context.method != 'find' && context.method != 'get') { throw new Error('Blocking access'); } }; };
import React, {useState, useEffect} from 'react'; import Form from "react-bootstrap/Form"; import Container from "react-bootstrap/Container"; import Button from "react-bootstrap/Button"; import { Col } from "react-bootstrap"; import { selectUserHomepage } from '../store/user/selectors'; import {useSelector, useDispatch} from 'react-redux'; import {updateHomepage} from '../store/homeDetails/actions'; export default function EditForm(){ const dispatch = useDispatch(); const homepage = useSelector(selectUserHomepage); const [title, setTitle] = useState(homepage.title); const [description, setDescription] = useState(homepage.description); const [color, setColor] = useState(homepage.color); const [backgroundColor, setBackgroundColor] = useState(homepage.backgroundColor); useEffect(() => { setTitle(homepage.title); setDescription(homepage.description); setColor(homepage.color); setBackgroundColor(homepage.backgroundColor); }, [homepage.color, homepage.title, homepage.description, homepage.backgroundColor]) const submitHandler = (event) => { event.preventDefault(); dispatch(updateHomepage(title, description, color, backgroundColor, homepage.id)); } return ( <div> <Container> <Form as={Col} md={{ span: 8, offset: 2 }} className="mt-5"> <h2 className="mt-5 mb-5">Edit your page</h2> <Form.Group controlId="formBasicTitle"> <Form.Label>Title</Form.Label> <Form.Control value={title} onChange={event => setTitle(event.target.value)} placeholder={homepage.title} required /> </Form.Group> <Form.Group controlId="formBasicDescription"> <Form.Label>Description</Form.Label> <Form.Control onChange={event => setDescription(event.target.value)} value={description} type="text" placeholder={homepage.description} required /> </Form.Group> <Form.Group controlId="formBasicBackgroundColor"> <Form.Label>Background color</Form.Label> <Form.Control value={backgroundColor} onChange={event => setBackgroundColor(event.target.value)} type="color" required /> </Form.Group> <Form.Group controlId="formBasicColor"> <Form.Label>Color</Form.Label> <Form.Control value={color} onChange={event => setColor(event.target.value)} type="color" required /> </Form.Group> <Form.Group className="mt-5"> <Button variant="primary" type="submit" onClick={submitHandler}> Update </Button> </Form.Group> </Form> </Container> </div> ) }
//组件化:就是页面的一部分,把页面的一部分进行组件化写在另一个页面,然后导出,便于维护修改 //引入react和属于react的Compontent函数 import React,{Component,Fragment} from 'react' import TodoList from './pages/todolist/index.js' //子组件的集合组件 class App extends Component{ render(){ return( <TodoList /> ) } } export default App;
import _ from 'underscore'; _.mixin({ isInteger: (n) => { return parseInt(n, 10) === n; }, getRandom: (min, max) => { if (min > max) { let temp = min; min = max; max = temp; } if (min === max) { return(min); } return (min + parseInt(Math.random() * (max - min + 1), 10)); } }); export default _;
/** * Created by Administrator on 2018/4/8. */ import jsonp from 'common/js/jsonp' import {commonParams, options} from './config' export function getSingerList(){ const url='https://c.y.qq.com/v8/fcg-bin/v8.fcg' const data=Object.assign({},commonParams,{ channel: 'singer', page: 'list', key:'all_all_all' , pagesize: 100, pagenum: 1, loginUin: 0, hostUin: 0, platform: 'yqq', needNewCode: 0 }) return jsonp(url,data,options) } export function getSingerDetail(singerId){ const url='https://c.y.qq.com/v8/fcg-bin/fcg_v8_singer_track_cp.fcg' const data=Object.assign({},commonParams,{ loginUin: 0, hostUin: 0, platform: 'yqq', needNewCode: 0, singermid: singerId, order: 'listen', begin: 0, num: 30, songstatus: 1 }) return jsonp(url,data,options) } //export function SongDetail(songmid){ // const url='https://c.y.qq.com/base/fcgi-bin/fcg_music_express_mobile3.fcg' // // const data=Object.assign({},commonParams,{ // loginUin: 0, // hostUin: 0, // platform: 'yqq', // needNewCode: 0, // cid: 205361747, // uin: 0, // songmid: songmid, // filename: 'C40'+songmid, // guid: 5013618820 // }) // return jsonp(url,data,options) //}
var db = require('./db'); var Schema = db.Schema; var schema = new Schema({ name: { type: String, index: {unique: true} }, password: String, privilege: { type: String, default: "user" }, registerDate: {type: Date, default: Date.now }, contact: { studentID: String, phone: String, qq: String, wechat: String, image: String } }); module.exports = db.model('user', schema); module.exports.check = function(name, password, cb) { module.exports.findOne({name: name}, function(err, found) { if (err || !found || found.password !== password) return cb('user not found'); return cb(); }); };
var searchData= [ ['name_5f',['name_',['../class_human.html#aae88b7b47fcb48ae282483b89b753927',1,'Human']]] ];
import React from 'react'; import { connect } from 'react-redux'; import Card from '@material-ui/core/Card'; import CardActions from '@material-ui/core/CardActions'; import CardContent from '@material-ui/core/CardContent'; import Button from '@material-ui/core/Button'; import Typography from '@material-ui/core/Typography'; import CircularProgress from 'material-ui/CircularProgress'; import Avatar from '@material-ui/core/Avatar'; import Chip from '@material-ui/core/Chip'; import LinearProgress from '@material-ui/core/LinearProgress'; import { fetchPokemonDetail } from '../actions/pokemons/fetchDetail'; import Link from 'next/link'; const styles = { card: { minWidth: 345, float: 'left' }, img: { display: 'block', margin: '0 auto' }, progress:{ float: 'left' }, title: { marginBottom: 16, fontSize: 14, } }; class Pokemon extends React.Component { constructor(props){ super(props); this.showPokemon = this.showPokemon.bind(this); } componentDidMount(){ this.props.fetchPokemonDetail(); } getLoader(){ return( <div style={{display: 'flex', justifyContent: 'center'}}> <CircularProgress size={80}/> </div> ) } showPokemon(props) { const {pokemon, fetching} = this.props.pokemon; if (fetching) { return this.getLoader(); } console.log('pokemon detail', pokemon); return ( <div> <Card style={styles.card} raised={true}> <img alt={pokemon.name} title={pokemon.name} src={pokemon.sprites.front_default} style={styles.img}/> <CardContent> <Typography gutterBottom variant="display1" color="primary" > {pokemon.name} </Typography> <Typography gutterBottom variant="headline" color="default"> weight: {pokemon.weight} </Typography> <Typography variant="headline" color="default"> height: {pokemon.height} </Typography> <br/> <Typography gutterBottom variant="headline" color="default"> type: </Typography> {pokemon.types.map( index => { return ( <Chip label={index.type.name} /> ) })} <br/><br/> <Typography gutterBottom variant="headline" color="default"> abilities: </Typography> {pokemon.abilities.map( index => { return ( <Chip label={index.ability.name} /> ) })} <br/><br/> <Typography gutterBottom variant="headline" color="default"> stats: </Typography> {pokemon.stats.map( index => { return ( <div> <Typography gutterBottom variant="subheading" color="default"> {index.stat.name} </Typography> <LinearProgress variant="determinate" value={index.base_stat} /> <br/></div> ) })} </CardContent> <CardActions> <Link href="/"> <Button variant="contained" size="small" color="primary" fullWidth={true}> Back </Button> </Link> </CardActions> </Card> </div> ); } render() { return ( <div> {this.showPokemon()} </div> ); } } // Pokemon.propTypes = { // classes: PropTypes.object.isRequired, // }; const mapStateToProps = ({ pokemon }) => ({ pokemon }); //export default withStyles(styles)(Pokemon); //export default connect(mapStateToProps, { fetchPokemonDetail })(withStyles(styles)(Pokemon)); export default connect(mapStateToProps, { fetchPokemonDetail })(Pokemon);
function validar_form_contato(){ var nome = form_contato.nome.value; var telefone = form_contato.telefone.value; var email = form_contato.email.value; var mensagem = form_contato.mensagem.value; if (nome == ""){ alert("Campo Nome é obrigatório"); form_contato.nome.focus(); return false; } if (telefone == ""){ alert("Campo Telefone é obrigatório"); form_contato.telefone.focus(); return false; } if (email == ""){ alert("Campo Email é obrigatório"); form_contato.email.focus(); return false; } if (mensagem == ""){ alert("Campo Mensagem é obrigatório"); form_contato.mensagem.focus(); return false; } alert("Mensagem eviada com sucesso!") } function validar_form_cad(){ var nome_cad = form_cad.nome_cad.value; var ult_cad = form_cad.ult_cad.value; var email_cad = form_cad.email_cad.value; var senha_cad = form_cad.senha_cad.value; var conf_senha_cad = form_cad.conf_senha_cad.value; var end_cad = form_cad.end_cad.value; var compl_end_cad = form_cad.compl_end_cad.value; var cid_cad = form_cad.cid_cad.value; var esta_cad = form_cad.esta_cad.value; var cep_cad = form_cad.cep_cad.value; if (nome_cad == ""){ alert("Campo Nome é obrigatório"); form_cad.nome_cad.focus(); return false; } if (ult_cad == ""){ alert("Campo Último nome é obrigatório"); form_cad.ult_cad.focus(); return false; } if (email_cad == ""){ alert("Campo Email é obrigatório"); form_cad.email_cad.focus(); return false; } if (senha_cad == ""){ alert("Campo Senha é obrigatório"); form_cad.senha_cad.focus(); return false; } if (conf_senha_cad == ""){ alert("Por favor, confirme sua senha"); form_cad.conf_senha_cad.focus(); return false; } if (end_cad == ""){ alert("Campo Endereço é obrigatório"); form_cad.end_cad.focus(); return false; } if (cid_cad == ""){ alert("Campo Cidade é obrigatório"); form_cad.cid_cad.focus(); return false; } if (esta_cad == ""){ alert("Campo Estado é obrigatório"); form_cad.esta_cad.focus(); return false; } if (cep_cad == ""){ alert("Campo Cep é obrigatório"); form_cad.cep_cad.focus(); return false; } alert("Usuário cadastrado com sucesso!") }
//#1 console.log('Hello World'); //#2 var name=prompt('What is your name?'); console.log("Hi," + name); //#3 if (name=='Alice'||name=='Bob') { console.log('Hi,' + name); } else{ console.log('Who are you?'); } //#4 var n=prompt('Give me a number'); var sum=0; for (var i = 1; i <= n; i++) { var sum=sum+i; } console.log(sum); //#5 var n=prompt('Give me a number'); var sum=0; for (var i = 1; i <= n; i++) { if (i % 3==0 || i %5 ==0 ) { var sum=sum+i; } } console.log(sum); //#6 var n=prompt('Give me a number'); var opr=prompt('Choose an operation add or multiply '); var sum=0; if(opr=='add'){ for (var i = 1; i <= n; i++) { var sum=sum+i; } console.log(sum); } else if(opr=='multiply'){ var sum=1; for (var i = 1; i <= n; i++) { var sum=sum*i; } console.log(sum); }else{ console.log("Please choose add or multiply"); } //#7 var total7=0; var newarray7=[]; for (var i = 1; i <=12; i++) { for(var j=1; j <=12; j++){ total7=i*j; } newarray7.push(total7); } console.log(newarray7); //#8 var number=prompt('Give me a number that you want to see prime number until this number'); for (var counter = 2; counter <= number; counter++) { var notPrime = false; for (var i = 2; i <= counter; i++) { if (counter%i===0 && i!==counter) { notPrime = true; } } if (notPrime === false) { console.log(counter); } } //#9 var guess=prompt('Tell me a number that you guess'); var number9=17; for (var i = 0, rights=1; i <= rights; i++) { if (guess == number9){ alert('You find a hidden number ' + rights +'. tries'); }else if(guess > number9){ guess=prompt('Your guess is too high.Give me another guess'); rights ++; }else if(guess < number9){ guess=prompt('Your guess is too low.Give me another guess'); rights++; } } //#10 var currentyear=2020; var arr10=[]; for (var i = 0; i < 20; i++) { currentyear+=4 arr10[i]=currentyear; } console.log('Leap years: ' + arr10); //#11 function maxItem(){ var arr11 = []; var max = 0; for (var i = 0; i <= 10; i++) { arr11[i]=(Math.random()*100); console.log(Math.floor(arr11[i])); } arr11.forEach(function(scan){ if (scan>max) { max=scan; } }) return max; } console.log('Maximum Number is ' + Math.floor(maxItem())); //#12 function reverseList(){ var arr12=['mazda','lexus','BMW','audi','mercedes']; return console.log(arr12.reverse()); } reverseList(); //#13 var arr13=['mazda','lexus','BMW','audi','mercedes']; var item=prompt('Check your item whether in a list or not'); var result13=''; for (var i = 0; i < arr13.length; i++) { result13=(item + ' is NOT in the list'); if(item==arr13[i]){ result13=('Your item is in the list'); } } alert(result13); //#14 var arr14=[1,2,3,4,5,6,7,8,9,10]; var ar14=[]; for (var i=0; i < arr14.length ; i++){ ar14=arr14[2*i+1]; console.log(arr14); } //#15 var arr15=[1,2,3,4,5,6,7,8,9,10]; total15=0; for (var i = 0; i < arr15.length; i++) { total15+=arr15[i]; } console.log(total15); //#16 function palindrome(){ var word=prompt("Give me a word"); var splitword=word.split(""); var reverseword=splitword.reverse(); var word2=reverseword.join(''); if(word== word2){ alert("It's palindrome "); }else{ alert("It's not a palindrome.") } } palindrome(); //#17 //for-loop var array17=[1,2,3,4,5,6,7,8,9,10]; total17=0; for (var i = 0; i < array17.length; i++) { total17+=array17[i]; } console.log(total17); //while-loop var i=0; var array17a=[1,2,3,4,5,6,7,8,9,10]; total17a=0; while(i<array17a.length){ total17a+=array17a[i]; i++; } console.log(total); //recursion var array_sum = function(my_array) { if (my_array.length === 1) { return my_array[0]; } else { return my_array.pop() + array_sum(my_array); } }; console.log(array_sum([1,2,3,4,5,6])); //#18 function square(){ var array18=[1,2,3,4,5,6]; var ar18=[]; for (var i = 0; i < array18.length; i++) { ar18.push(array18[i]*array18[i]); } console.log(ar18); } square(); //#19 function concatenate(){ var list19=['a','b','c']; var list19a=[1,2,3] for (var i = 0; i < list19a.length; i++) { list1.push(list19a[i]); } return console.log(list19); } concatenate(); //#20 var list20=['a','b','c']; var list20a=[1,2,3]; var list20b=[]; for (var i = 0; i < list20a.length; i++) { list20b[2*i]=list20[i]; list20b[2*i+1]=list20a[i]; } console.log(list); //#21 function merge (){ var list21=[1,4,6]; var list21a=[2,3,5]; list=[]; for (var i = 0; i < list1.length; i++) { list.push(list21[i]); list.push(list21a[i]); } console.log(list.sort()); } merge(); //#22 function rotate_array(a){ var arr22=[1,2,3,4,5,6]; for (var i = 0; i < a; i++) { arr22.unshift(arr22.pop()) } return arr22; } console.log(rotate_array(4)); //#23 function fibonacci(){ var arr23=[]; arr23[0]=1; arr23[1]=1; for (var i = 2; i <100 ; i++) { arr23[i]=arr23[i-2]+arr23[i-1]; } return arr23; } console.log(fibonacci()); //#24 var userinput=prompt('Enter multiple digits number ex.2345'); var splitInput=userinput.toString().split(''); var arr24=splitInput.map(function(a){ return parseInt(a); }) console.log(arr24); //#25 function translate(){ var userSentence=prompt('Give me a sentence that you want to translate from English to Pig Latin'); var splitSentence=userSentence.split(' '); var arr25=splitSentence.map(function(a){ var newarr25=a.split(''); newarr25.push(newarr25.shift()+"ay "); var combine=newarr25.join(''); return combine; }); return arr25.join(''); } console.log(translate());
var width: float; var height: float; function Start() { var mf: MeshFilter = GetComponent.<MeshFilter>(); var mesh = new Mesh(); mf.mesh = mesh; var vertices: Vector3[] = new Vector3[4]; vertices[0] = new Vector3(0, 0, 0); vertices[1] = new Vector3(width, 0, 0); vertices[2] = new Vector3(0, height, 0); vertices[3] = new Vector3(width, height, 0); mesh.vertices = vertices; var tri: int[] = new int[6]; tri[0] = 0; tri[1] = 2; tri[2] = 1; tri[3] = 2; tri[4] = 3; tri[5] = 1; mesh.triangles = tri; var normals: Vector3[] = new Vector3[4]; normals[0] = -Vector3.forward; normals[1] = -Vector3.forward; normals[2] = -Vector3.forward; normals[3] = -Vector3.forward; mesh.normals = normals; var uv: Vector2[] = new Vector2[4]; uv[0] = new Vector2(0, 0); uv[1] = new Vector2(1, 0); uv[2] = new Vector2(0, 1); uv[3] = new Vector2(1, 1); mesh.uv = uv; }
const psm = { padding: ".5rem" }; const pt1 = { paddingTop: "1rem" }; const pt2 = { paddingTop: "2rem" }; const pt3 = { paddingTop: "3rem" }; const pt4 = { paddingTop: "4rem" }; const mt1 = { marginTop: "1rem" }; const mt2 = { marginTop: "2rem" }; const mt3 = { marginTop: "3rem" }; const mt4 = { marginTop: "4rem" }; const mb1 = { marginBottom: "1rem" }; const mb2 = { marginBottom: "2rem" }; const mb3 = { marginBottom: "3rem" }; const mb4 = { marginBottom: "4rem" }; export { psm, pt1, pt2, pt3, pt4, mt1, mt2, mt3, mt4, mb1, mb2, mb3, mb4, }
/** * Standard model component */ Freja.Model = function(url, query) { this.url = url; this.ready = false; this.document = null; this._query = query; }; /** * Returns a single value */ Freja.Model.prototype.getElementById = function(id) { if (this.document) { return this._query.getElementById(this.document, id); } return null; }; /** * Returns a single value */ Freja.Model.prototype.get = function(expression) { if (this.document) { return this._query.get(this.document, expression); } return null; }; /** * Updates a value */ Freja.Model.prototype.set = function(expression, value) { if (this.document) { return this._query.set(this.document, expression, value); } return null; }; /** * Updates the model from a view */ Freja.Model.prototype.updateFrom = function(view) { var values = view.getValues(); for (var i = 0; i < values[0].length; ++i) { // try not to process field names that are not meant to be xpath expressions if(values[0][i].lastIndexOf('/') != -1) { try { this.set(values[0][i], values[1][i]); } catch(x) { // couldn't set the value. // @TODO: Throw new Error. } } } }; /** * Writes the model back to the remote service * @returns Freja._aux.Deferred */ Freja.Model.prototype.save = function() { var url = this.url; var match = /^(file:\/\/.*\/)([^\/]*)$/.exec(window.location.href); if (match) { url = match[1] + url; // local } // since the serialization may fail, we create a deferred for the // purpose, rather than just returning the sendXMLHttpRequest directly. var d = Freja._aux.createDeferred(); var req = Freja.AssetManager.openXMLHttpRequest("POST", url); try { // for some obscure reason exceptions aren't thrown back if I call the // shorthand version of sendXMLHttpRequest in IE6. Freja._aux.sendXMLHttpRequest(req, Freja._aux.serializeXML(this.document)).addCallbacks(Freja._aux.bind(d.callback, d), Freja._aux.bind(d.errback, d)); } catch (ex) { d.errback(ex); } return d; }; /** * Deletes the model from the remote service * @returns Freja._aux.Deferred */ Freja.Model.prototype.remove = function() { var url = this.url; var match = /^(file:\/\/.*\/)([^\/]*)$/.exec(window.location.href); if (match) { url = match[1] + url; // local } var req = Freja.AssetManager.openXMLHttpRequest("DELETE", url); return Freja._aux.sendXMLHttpRequest(req); }; /** * @returns Freja._aux.Deferred */ Freja.Model.prototype.reload = function(url) { if(url) { // Replace old url in cache with new url for (var i=0; i < Freja.AssetManager.models.length; i++) { if (Freja.AssetManager.models[i].url == this.url) { Freja.AssetManager.models[i].url = url; } } this.url = url; } this.ready = false; var onload = Freja._aux.bind(function(document) { this.document = document; this.ready = true; Freja._aux.signal(this, "onload"); }, this); var d = Freja.AssetManager.loadAsset(this.url, true); d.addCallbacks(onload, Freja.AssetManager.onerror); return d; }; /** * DataSource provides a gateway-type interface to a REST service. */ Freja.Model.DataSource = function(createURL, indexURL) { this.createURL = createURL; this.indexURL = indexURL; }; /** * Returns a list of primary-keys to records in the datasource */ Freja.Model.DataSource.prototype.select = function() { return getModel(this.indexURL); }; /** * Creates a new instance of a record * @todo errback to the deferred on errors */ Freja.Model.DataSource.prototype.create = function(values) { var url = this.createURL; var match = /^(file:\/\/.*\/)([^\/]*)$/.exec(window.location.href); if (match) { url = match[1] + url; // local } var req = Freja.AssetManager.openXMLHttpRequest("PUT", url); var payload = {}; for (var i = 0, len = values[0].length; i < len; ++i) { payload[values[0][i]] = values[1][i]; } return Freja._aux.sendXMLHttpRequest(req, Freja._aux.xmlize(payload, 'record')); };
import * as lfo from 'waves-lfo/client'; import * as controllers from 'basic-controllers'; const AudioContext = (window.AudioContext || window.webkitAudioContext); const audioContext = new AudioContext(); let audioStream; try { audioStream = navigator.mediaDevices.getUserMedia({ audio: true }); } catch (err) { const msg = `This navigator doesn't support getUserMedia or implement a deprecated API`; alert(msg); throw new Error(msg); } audioStream .then(init) .catch((err) => console.error(err.stack)); function init(stream) { const source = audioContext.createMediaStreamSource(stream); const audioInNode = new lfo.source.AudioInNode({ sourceNode: source, audioContext: audioContext, }); const signalRecorder = new lfo.sink.SignalRecorder({ duration: Infinity, retrieveAudioBuffer: true, audioContext: audioContext, callback: (buffer) => { const bufferSource = audioContext.createBufferSource(); bufferSource.buffer = buffer; bufferSource.connect(audioContext.destination); bufferSource.start(); } }); const vuMeterDisplay = new lfo.sink.VuMeterDisplay({ canvas: '#vu-meter', }); audioInNode.connect(signalRecorder); audioInNode.connect(vuMeterDisplay); audioInNode.start(); new controllers.TriggerButtons({ label: '', options: ['record', 'stop'], container: '#controllers', callback: (value) => { if (value === 'record') signalRecorder.start(); else signalRecorder.stop(); } }); }
import React from "react"; import { ImageBackground, Image, StyleSheet, Text, SafeAreaView, } from "react-native"; export default function Logo({ navigation }) { return ( <SafeAreaView style={{ alignItems: "center" }}> <Image source={require("../assets/UWMClogo.png")} style={styles.logoContainer} ></Image> <Text style={styles.textContainer}>Volunteer Here</Text> </SafeAreaView> ); } const styles = StyleSheet.create({ logoContainer: { width: 200, height: 200, marginTop: 20, }, textContainer: { color: "cornflowerblue", fontSize: 20, fontWeight: "500", }, });
export const ADD_FRIEND = 'ADD-FRIEND'; export const REMOVE_FRIEND = 'REMOVE-FRIEND'; const SHOW_MORE_FRIENDS = 'SHOW-MORE-FRIENDS'; let initialState = { users: [], page: 1 }; // user: id, isActive, lastLogin, accountStatus, firstName, lastName, imgUrl, intro, country, city, gender, isFriend export function friendsReducer(state = initialState, action) { switch (action.type) { case ADD_FRIEND: let newFriend = { id: action.id, isActive: action.isActive, lastLogin: action.lastLogin, accountStatus: action.accountStatus, firstName: action.firstName, lastName: action.lastName, imgUrl: action.imgUrl, intro: action.intro, country: action.country, city: action.city, gender: action.gender, isFriend: true } return { ...state, users: [...state.users, newFriend] }; case REMOVE_FRIEND: return { ...state, users: state.users.filter(user => { return user.id !== action.id; }) }; case SHOW_MORE_FRIENDS: return { ...state, users: [...state.users, ...action.users], page: action.users.length < 20 ? -1 : state.page + 1 } default: return state; } } export function addNewFriendActionCreator(userInfo) { return { type: ADD_FRIEND, id: userInfo.id, firstName: userInfo.firstName, lastName: userInfo.lastName, imgUrl: userInfo.imgUrl, country: userInfo.country, city: userInfo.city }; } export function removeFriendActionCreator(userId) { return { type: REMOVE_FRIEND, id: userId }; } export function showMoreFriendActionCreator(users) { return { type: SHOW_MORE_FRIENDS, users: users }; }
'use strict'; process.env.NODE_ENV = 'test'; var should = require('should'); var Meatwords = require('../index'); var mw = new Meatwords(); describe('meatwords', function () { it('should return letters', function () { console.log(mw.letters); }); });
var sound1, sound2, sound3, sound4, sond5, sound5FFT, sound1Amp, sound, sound6, sound6FFT, sound7, sound7FFT, sound8, stab3, sound9, sound10, sound11, sound12, sound15; var xpos = []; var ypos = []; var xtarget = []; var ytarget = []; var r, v, b, choose; var fireworks = []; var gravity; var pgfireworks; var n = 0; var c = 3; var points = []; var start = 0; var yoff = 0.0; var yoff2 = 0.0; var drops = []; var system; function preload() { sound1 = loadSound('assets/217.mp3'); sound2 = loadSound('assets/JUST_clap.wav'); sound3 = loadSound('assets/JUST_kick.wav'); sound4 = loadSound('assets/200.mp3'); sound5 = loadSound('assets/elect.mp3'); sound6 = loadSound('assets/JUST_kick_1.wav'); sound7 = loadSound('assets/switch2.mp3'); sound8 = loadSound('assets/JUST_rim.wav'); sound9 = loadSound('assets/1043.mp3'); sound10 = loadSound('assets/Bpm09_1.mp3'); sound11 = loadSound('assets/10432.mp3'); sound12 = loadSound('assets/1.mp3'); sound13 = loadSound('assets/2767.mp3'); sound14 = loadSound('assets/226.mp3'); sound15 = loadSound('assets/cool-sound.mp3') sound16 = loadSound('assets/Bpm095_4.mp3') sound17 = loadSound('assets/JUST_snare_1.wav') sound18 = loadSound('assets/FFL.mp3') sound19 = loadSound('assets/sfx_die.mp3') sound20 = loadSound('assets/LL_.wav') sound21 = loadSound('assets/4.mp3') sound22 = loadSound('assets/231.mp3') sound23 = loadSound('assets/Bpm095_5.mp3') sound24 = loadSound('assets/Bpm095_2.mp3') sound25 = loadSound('assets/3276.mp3') sound26 = loadSound('assets/firework_4.mp3') } function setup() { createCanvas(windowWidth, windowHeight); background(0); sound1Amp = new p5.Amplitude() sound1Amp.setInput(sound1) sound5FFT = new p5.FFT(0.8, 16) sound5FFT.setInput(sound5) sound6FFT = new p5.FFT(0.8, 1024) sound6FFT.setInput(sound6) sound7FFT = new p5.FFT(0.8, 16) sound7FFT.setInput(sound7) sound11FFT = new p5.FFT(0.8, 16) sound11FFT.setInput(sound11) sound14FFT = new p5.FFT(0.8, 16) sound14FFT.setInput(sound14) sound16FFT = new p5.FFT(0.8, 16) sound16FFT.setInput(sound16) sound18FFT = new p5.FFT(0.8, 16) sound18FFT.setInput(sound18) sound22FFT = new p5.FFT(0.8, 16) sound22FFT.setInput(sound22) for (var i = 0; i < 500; i++) { drops[i] = new Drop(); } for (var i = 0; i < 50; i++) { xpos.push(random(0, width)) ypos.push(random(0, -height)) xtarget.push(random(width)) ytarget.push(random(height)) } pgfireworks = createGraphics(windowWidth, windowHeight) console.log(ypos[0]) system = new ParticleSystem(createVector(width / 2, height / 2)); } function draw() { background(0) playSound(sound1, 74); //bulles qui explose du centre vers l'exterieur playSound(sound2, 69); //clap - deux carré du coté vers le milieu playSound(sound3, 90); //rond du centre vers les cotés playSound(sound4, 72); //animation feu d'artifice playSound(sound5, 88); //4 carrés qui tourne et un carré au milieu en fonction du son playSound(sound6, 85); //onde plus grosse playSound(sound7, 82); // carrés et ronds au centre en fonction du son playSound(sound8, 84); //3 balles qui rebondis playSound(sound9, 77); //feu follet qui forme un cercle plusieurs fois playSound(sound10, 89); //forme ciculaire organique playSound(sound11, 81); // plusieurs lignes qui tourne très vite playSound(sound12, 83); // tout petit cercle qui remonte vers le haut playSound(sound13, 68); // multitude d'ellipse qui vont dans la même direction et qui forme une ligne playSound(sound14, 70); // cercle qui tombe du haut et change de taille en fonction du son playSound(sound15, 67); // tombe de la neige avec une musique épique playSound(sound16, 79); // 3 ligne qui vibre playSound(sound17, 73); // forme circulaire qui change de couleur au renouvelement playSound(sound18, 80); // rond et carré + forme au milieu qui bouge playSound(sound19, 65); // sorte d'hélice qui tourne playSound(sound20, 86); // monté vers le haut de petit point playSound(sound21, 71); //explosion de petit point / phyllotaxis playSound(sound22, 75); //3 ronds qui rétrécissent playSound(sound23, 87); //forme organique playSound(sound24, 78); //sorte d'étoile playSound(sound25, 66); //pluie multicolor playSound(sound26, 76); // explosion de la touche 71 // monté vers le haut de petit point if (sound20.isPlaying() == true) { push() pgfireworks.noStroke() pgfireworks.fill(0, 0.05) pgfireworks.rect(0, 0, width, height) pgfireworks.colorMode(HSB); pgfireworks.stroke(255); pgfireworks.strokeWeight(0.2); gravity = createVector(0.1, 0.01); if (random(0.0001) < 0.10) { fireworks.push(new Firework()); } for (var i = fireworks.length - 1; i >= 0; i--) { fireworks[i].update(); fireworks[i].show(pgfireworks); if (fireworks[i].done()) { fireworks.splice(i, 1); } } image(pgfireworks, 0, 0, width, height) pop() }; //forme ciculaire organique if (sound10.isPlaying() == true) { push() var nsegment = 300; var ncurrentsegment = (map(sound10.currentTime(), 0, sound10.duration(), 0, nsegment + 1)); for (var i = 0; i < ncurrentsegment; i++) { fill(255, 0, random(255)); strokeWeight(4); var angle = map(i, 0, nsegment * 1.5, 0, TWO_PI); var x = width * 0.5 + height * 0.45 * cos(angle); var y = height * 0.5 + height * 0.45 * sin(angle); ellipse(width / 2, height / 2, x, y); } pop() } if (keyIsDown(72)) { fireworks = [] } //animation feu d'artifice if (sound4.isPlaying() == true) { push() pgfireworks.noStroke() pgfireworks.fill(0, 0.05) pgfireworks.rect(0, 0, width, height) pgfireworks.colorMode(HSB); pgfireworks.stroke(255); pgfireworks.strokeWeight(4); gravity = createVector(0, 0.12); if (random(1) < 0.13) { fireworks.push(new Firework()); } for (var i = fireworks.length - 1; i >= 0; i--) { fireworks[i].update(); fireworks[i].show(pgfireworks); if (fireworks[i].done()) { fireworks.splice(i, 1); } } image(pgfireworks, 0, 0, width, height) pop() }; //forme organique if (sound23.isPlaying() == true) { push() translate(width / 2, height / 2); var radius = 200; beginShape(); noStroke() var xoff = 0; for (var a = 0; a < TWO_PI; a += 0.001) { var offset = map(noise(xoff, yoff), 0, 1, -50, 100); var r3 = radius + offset; var x3 = r3 * cos(a); var y3 = r3 * sin(a); fill(0, random(99, 105), random(99, 105)); vertex(x3, y3); xoff += 0.01; //ellipse(x3, y3, 4, 4); } endShape(); yoff += 0.01; pop() } //clap - deux carré du coté vers le milieu if (sound2.isPlaying() == true) { push() var ang = map(sound2.currentTime(), 0, sound2.duration(), width, 0) fill(0, 0, 255) rectMode(CENTER); rect(width * 0, height * 0, ang, ang) pop() push() var ang = map(sound2.currentTime(), 0, sound2.duration(), width, 0) fill(0, 0, 255) rectMode(CENTER); rect(width * 1, height * 0, ang, ang) pop() } //bulles qui explose du centre vers l'exterieur if (sound1.isPlaying() == true) { push() system.addParticle(); system.run(); pop() } //rond du centre vers les cotés if (sound3.isPlaying() == true) { push() var rad = map(sound3.currentTime(), 0, sound3.duration(), 50, width) fill(0, 167, 157) ellipse(width * 0.5, height * 0.5, rad, rad) pop() } //4 carrés qui tourne et un carré au milieu en fonction du son if (sound5.isPlaying() == true) { sound5FFT.analyze(); rectMode(CENTER); var nrj1 = sound5FFT.getEnergy("bass") push() fill(0, 200, 255, 50) translate(width * 0.5, height * 0.5) rotate(PI / 4) rect(0, 0, nrj1, nrj1) pop() push() noStroke() fill(0, 200, 255, nrj1) translate(width * 0.36, height * 0.25) var ang = map(sound5.currentTime(), 0, sound5.duration(), 0, PI * 2) rectMode(CENTER); rotate(ang) rect(0, 0, width * 0.2, width * 0.2) pop() push() noStroke() fill(0, 200, 255, nrj1) translate(width * 0.64, height * 0.75) var ang = map(sound5.currentTime(), 0, sound5.duration(), 0, PI * 2) rectMode(CENTER); rotate(ang) rect(0, 0, width * 0.2, width * 0.2) pop() push() noStroke() fill(0, 200, 255, nrj1) translate(width * 0.36, height * 0.75) var ang = map(sound5.currentTime(), 0, sound5.duration(), 0, -PI * 2) rectMode(CENTER); rotate(ang) rect(0, 0, width * 0.2, width * 0.2) pop() push() noStroke() fill(0, 200, 255, nrj1) translate(width * 0.64, height * 0.25) var ang = map(sound5.currentTime(), 0, sound5.duration(), 0, -PI * 2) rectMode(CENTER); rotate(ang) rect(0, 0, width * 0.2, width * 0.2) pop() } //onde plus grosse if (sound6.isPlaying() == true) { push() var waveform = sound6FFT.waveform(); noFill(); beginShape() stroke(150, 255, 255); strokeWeight(10); for (var i = 0; i < waveform.length; i++) { var x = map(i, 0, waveform.length, 0, width * 1.5); var y = map(waveform[i], -1, 1, 0, height); curveVertex(x, y); } endShape(); pop() } // carrés et ronds au centre en fonction du son if (sound7.isPlaying() == true) { sound7FFT.analyze(); rectMode(CENTER); var nrj1 = sound7FFT.getEnergy("bass") var radius = map(nrj1, 0, 255, 0, 450) //permet de changer la limite de 255 à 450 pour notre cas. push() noStroke(); fill(100, random(255), 0, 50) translate(width * 0.5, height * 0.5) rotate(PI / 4) rect(0, 0, radius * 2, radius * 2) pop() push() noStroke(); fill(100, random(255), 0, 50) translate(width * 0.5, height * 0.5) rotate(PI / 4) rect(0, 0, radius * 1.5, radius * 1.5) pop() push() noStroke(); fill(100, random(255), 0, 50) translate(width * 0.5, height * 0.5) rotate(PI / 4) rect(0, 0, radius, radius) pop() push() noStroke(); fill(100, random(255), 0, 50) translate(width * 0.5, height * 0.5) ellipse(0, 0, nrj1 * 1.5, nrj1 * 1.5) pop() push() noStroke(); fill(100, random(255), 0, 50) translate(width * 0.5, height * 0.5) ellipse(0, 0, nrj1, nrj1) pop() push() noStroke(); fill(100, random(255), 0, 50) translate(width * 0.5, height * 0.5) ellipse(0, 0, nrj1 * 0.75, nrj1 * 0.75) pop() } //3 balles qui rebondis if (sound8.isPlaying() == true) { push() noStroke(); fill(0, 255, 255) var theta = map(sound8.currentTime(), 0, sound8.duration(), 0, PI); var ypos1 = height - sin(theta) * height * 0.8; ellipse(width * 0.5, ypos1, 100, 100); pop() push() noStroke(); fill(0, 255, 255) var theta = map(sound8.currentTime(), 0, sound8.duration(), 0, PI); var ypos1 = height - sin(theta) * height * 0.5; ellipse(width * 0.8, ypos1, 100, 100); pop() push() noStroke(); fill(0, 255, 255) var theta = map(sound8.currentTime(), 0, sound8.duration(), 0, PI); var ypos1 = height - sin(theta) * height * 0.4; ellipse(width * 0.2, ypos1, 100, 100); pop() } //feu follet qui forme un cercle plusieurs fois if (sound9.isPlaying() == true) { push() var t = map(sound9.currentTime(), 0, sound9.duration(), 0, 1) for (var i = 0; i < 100; i++) { var x = lerp(xpos[i], xtarget[i], t) var y = lerp(ypos[i], ytarget[i], t) translate(width * 0.7, height * 0.7) var ang = map(sound9.currentTime(), 0, sound9.duration(), 0, 40) rotate(ang) fill(232, random(255), 0) ellipse(x / 3, y / 3, 50, 10) } pop() } // plusieurs lignes qui tourne très vite if (sound11.isPlaying() == true) { sound11FFT.analyze(); var nrj1 = sound11FFT.getEnergy("bass") push() translate(width * 0.5, height * 0.2) var ang = map(sound11.currentTime(), 0, sound11.duration(), 0, 30) rectMode(CENTER); rotate(ang) noStroke(); fill(232, random(255), 0) rect(0, 0, nrj1 / 1.5, height * 0.01) pop() push() translate(width * 0.5, height * 0.2) var ang = map(sound11.currentTime(), 0, sound11.duration(), 30, 0) rectMode(CENTER); rotate(ang) noStroke(); fill(232, random(255), 0) rect(0, 0, nrj1 / 1.5, height * 0.01) pop() push() translate(width * 0.1, height * 0.8) var ang = map(sound11.currentTime(), 0, sound11.duration(), 0, 30) rectMode(CENTER); rotate(ang) noStroke(); fill(232, random(255), 0) rect(0, 0, nrj1 / 1.5, height * 0.01) pop() push() translate(width * 0.1, height * 0.8) var ang = map(sound11.currentTime(), 0, sound11.duration(), 30, 0) rectMode(CENTER); rotate(ang) noStroke(); fill(232, random(255), 0) rect(0, 0, nrj1 / 1.5, height * 0.01) pop() push() translate(width * 0.3, height * 0.65) var ang = map(sound11.currentTime(), 0, sound11.duration(), 0, 30) rectMode(CENTER); rotate(ang) noStroke(); fill(232, random(255), 0) rect(0, 0, nrj1 / 1.5, height * 0.01) pop() push() translate(width * 0.3, height * 0.65) var ang = map(sound11.currentTime(), 0, sound11.duration(), 30, 0) rectMode(CENTER); rotate(ang) noStroke(); fill(232, random(255), 0) rect(0, 0, nrj1 / 1.5, height * 0.01) pop() push() translate(width * 0.6, height * 0.8) var ang = map(sound11.currentTime(), 0, sound11.duration(), 0, 30) rectMode(CENTER); rotate(ang) noStroke(); fill(232, random(255), 0) rect(0, 0, nrj1 / 1.5, height * 0.01) pop() push() translate(width * 0.6, height * 0.8) var ang = map(sound11.currentTime(), 0, sound11.duration(), 30, 0) rectMode(CENTER); rotate(ang) noStroke(); fill(232, random(255), 0) rect(0, 0, nrj1 / 1.5, height * 0.01) pop() push() translate(width * 0.8, height * 0.2) var ang = map(sound11.currentTime(), 0, sound11.duration(), 0, 30) rectMode(CENTER); rotate(ang) noStroke(); fill(232, random(255), 0) rect(0, 0, nrj1 / 1.5, height * 0.01) pop() push() translate(width * 0.8, height * 0.2) var ang = map(sound11.currentTime(), 0, sound11.duration(), 30, 0) rectMode(CENTER); rotate(ang) noStroke(); fill(232, random(255), 0) rect(0, 0, nrj1 / 1.5, height * 0.01) pop() push() translate(width * 0.8, height * 0.8) var ang = map(sound11.currentTime(), 0, sound11.duration(), 0, 30) rectMode(CENTER); rotate(ang) noStroke(); fill(232, random(255), 0) rect(0, 0, nrj1 / 1.5, height * 0.01) pop() push() translate(width * 0.8, height * 0.8) var ang = map(sound11.currentTime(), 0, sound11.duration(), 30, 0) rectMode(CENTER); rotate(ang) noStroke(); fill(232, random(255), 0) rect(0, 0, nrj1 / 1.5, height * 0.01) pop() push() translate(width * 0.5, height * 0.5) var ang = map(sound11.currentTime(), 0, sound11.duration(), 0, 30) rectMode(CENTER); rotate(ang) noStroke(); fill(232, random(255), 0) rect(0, 0, nrj1 / 1.5, height * 0.01) pop() push() translate(width * 0.5, height * 0.5) var ang = map(sound11.currentTime(), 0, sound11.duration(), 30, 0) rectMode(CENTER); rotate(ang) noStroke(); fill(232, random(255), 0) rect(0, 0, nrj1 / 1.5, height * 0.01) pop() push() translate(width * 0.2, height * 0.2) var ang = map(sound11.currentTime(), 0, sound11.duration(), 0, 30) rectMode(CENTER); rotate(ang) noStroke(); fill(232, random(255), 0) rect(0, 0, nrj1 / 1.5, height * 0.01) pop() push() translate(width * 0.2, height * 0.2) var ang = map(sound11.currentTime(), 0, sound11.duration(), 30, 0) rectMode(CENTER); rotate(ang) noStroke(); fill(232, random(255), 0) rect(0, 0, nrj1 / 1.5, height * 0.01) pop() } // tout petit cercle qui remonte vers le haut if (sound12.isPlaying() == true) { push() var t = map(sound12.currentTime(), 0, sound12.duration() * 0.75, 0, 1) noStroke() for (var i = 0; i < 100; i++) { var x = lerp(xpos[i], xtarget[i], t) var y = lerp(ypos[i], ytarget[i], t) fill(255, 0, 255) var ang = map(sound12.currentTime(), 0, sound12.duration(), 1, 0) rectMode(CENTER); rotate(ang) ellipse(y, x, width * 0.005, height * 0.005) } pop() } // multitude d'ellipse qui vont dans la même direction et qui forme une ligne if (sound13.isPlaying() == true) { push() var t = map(sound13.currentTime(), 0, sound13.duration(), 0, 1) noStroke() for (var i = 0; i < 100; i++) { translate(width * 0.5, height * 0.5) var x = lerp(xpos[i], xtarget[i], t) var y = lerp(ypos[i], ytarget[i], t) fill(200, random(255), 255) var ang = map(sound13.currentTime(), 0, sound13.duration(), 1, 0) rectMode(CENTER); rotate(ang) ellipse(height * 0.1, width * 0.1, width * 0.02, height * 0.02) } pop() } // cercle qui tombe du haut et change de taille en fonction du son if (sound14.isPlaying() == true) { sound14FFT.analyze(); var nrj1 = sound14FFT.getEnergy("bass") push() noStroke(); var t = map(sound14.currentTime(), 0, sound14.duration(), 0, 1) for (var i = 0; i < 70; i++) { fill(255, random(255), 0) var x = lerp(xpos[i], xtarget[i], t) var y = lerp(ypos[i], ytarget[i], t) ellipse(x, y, nrj1 / 2.5, nrj1 / 2.5) } pop() } // tombe de la neige avec une musique épique if (keyIsDown(67)) { snowflakes = [] } if (sound15.isPlaying() == true) { push() var t2 = map(sound15.currentTime(), 0, sound15.duration(), 0, 1) let t = frameCount / 20; for (var i = 0; i < random(5); i++) { snowflakes.push(new snowflake()); } for (let flake of snowflakes) { flake.update(t); flake.display(); } pop() } function snowflake() { this.posX = 0; this.posY = random(-50, 0); this.initialangle = random(0, 2 * PI); this.size = random(2, 5); this.radius = sqrt(random(pow(width / 2, 2))); this.update = function (time) { let w = 0.6; let angle = w * time + this.initialangle; this.posX = width / 2 + this.radius * sin(angle); this.posY += pow(this.size, 0.5); if (this.posY > height) { let index = snowflakes.indexOf(this); snowflakes.splice(index, 1); } }; this.display = function () { ellipse(this.posX, this.posY * 1.5, this.size); var grey = map(sound15.currentTime(), sound15.duration() * 0.75, sound15.duration(), 255, 0) t2 = constrain(t, 0, 1) grey = constrain(grey, 0, random(255)) fill(grey); }; } // 3 ligne qui vibre if (sound16.isPlaying() == true) { push() var waveform = sound16FFT.waveform(); noFill(); beginShape(); stroke(255, 0, 255); strokeWeight(4); for (var i = 0; i < waveform.length; i++) { var x = map(i, 0, waveform.length, 0, width); var y = map(waveform[i], -1, 2, 0, height); curveVertex(x, y); } endShape(); pop() push() var waveform = sound16FFT.waveform(); noFill(); beginShape(); stroke(255, 0, 255); strokeWeight(10); for (var i = 0; i < waveform.length; i++) { var x = map(i, 0, waveform.length, 0, width); var y = map(waveform[i], -1, 1, 0, height); curveVertex(x, y); } endShape(); pop() push() var waveform = sound16FFT.waveform(); noFill(); beginShape(); stroke(255, 0, 255); strokeWeight(4); for (var i = 0; i < waveform.length; i++) { var x = map(i, 0, waveform.length, 0, width); var y = map(waveform[i], -1, 0.5, 0, height); curveVertex(x, y); } endShape(); pop() } if (keyIsDown(73) == true) { choose = random(1, 4); if (choose < 2) { r = random(0, 100); v = random(0, 255); b = 255; } if (choose >= 2 && choose < 3) { b = random(0, 100); v = 255; r = random(0, 255); } if (choose >= 3) { v = random(0, 100); r = 255; b = random(0, 255); } } // forme circulaire qui change de couleur au renouvelement if (sound17.isPlaying() == true) { push() var nsegment = 200; var ncurrentsegment = (map(sound17.currentTime(), 0, sound17.duration(), 0, nsegment + 1)); for (var i = 0; i < ncurrentsegment; i++) { fill(r, v, b); noStroke() strokeWeight(4); var angle = map(i, 0, nsegment, 0, TWO_PI); var x = width * 0.5 + height * 0.45 * cos(angle); var y = height * 0.5 + height * 0.45 * sin(angle); ellipse(x, y, 80, 80) } pop() } // rond et carré + forme au milieu qui bouge if (sound18.isPlaying() == true) { sound18FFT.analyze(); rectMode(CENTER); var nrj1 = sound18FFT.getEnergy("bass") push() fill(0, 200, random(255), ) translate(width * 0.35, height * 0.5) rotate(PI / 4) rect(0, 0, nrj1 * 1.3, nrj1 * 1.3) pop() push() fill(0, 200, random(255), ) translate(width * 0.65, height * 0.5) rotate(PI / 4) rect(0, 0, nrj1 * 1.3, nrj1 * 1.3) pop() push() fill(random(255), 0, random(255)) translate(width * 0.2, height * 0.5) rotate(PI / 4) ellipse(0, 0, nrj1 * 0.5, nrj1 * 0.5) pop() push() fill(random(255), 0, random(255)) translate(width * 0.8, height * 0.5) rotate(PI / 4) ellipse(0, 0, nrj1 * 0.5, nrj1 * 0.5) pop() push() fill(random(255), 0, random(255)) translate(width * 0.5, height * 0.2) rotate(PI / 4) ellipse(0, 0, nrj1 * 0.5, nrj1 * 0.5) pop() push() fill(random(255), 0, random(255)) translate(width * 0.5, height * 0.8) rotate(PI / 4) ellipse(0, 0, nrj1 * 0.5, nrj1 * 0.5) pop() push() var nsegment = 300; var ncurrentsegment = (map(sound18.currentTime(), 0, sound18.duration(), 0, nsegment + 1)); for (var i = 0; i < ncurrentsegment; i++) { fill(random(255), 0, random(255)); var angle = map(i, 0, nsegment, 0, TWO_PI / 1.5); var x = width * 0.01 + height * 0.45 * cos(angle); var y = height * 0.01 + height * 0.45 * sin(angle); ellipse(width / 2, height / 2, x, y); } pop() } // sorte d'hélice qui tourne if (sound19.isPlaying() == true) { push() translate(width * 0.5, height * 0.5) var ang = map(sound19.currentTime(), 0, sound19.duration(), 0, PI * 2) rectMode(CENTER); rotate(ang) fill(0, 167, 200) noStroke(); ellipse(0, 0, width * 0.07, height) pop() push() translate(width * 0.5, height * 0.5) var ang = map(sound19.currentTime(), 0, sound19.duration(), 0, PI * 3) rectMode(CENTER); rotate(ang) noStroke(); fill(245, 147, 49) ellipse(0, 0, width * 0.04, height / 1.5) fill(0, 167, 157) ellipse(0, 0, 15, 15) fill(255, 255, 255) noStroke(); rect(0, 0, 7, 7) pop() } //explosion de petits points if (keyIsDown(71)) { n = 0 } if (sound21.isPlaying() == true) { push() translate(width / 2, height / 2); rotate(n * 0.01); for (var i = 0; i < n; i++) { var a = i * 137.5; var r1 = c * sqrt(i); var x = r1 * cos(a); var y = r1 * sin(a); var hu = sin(start + i * 0.5); hu = map(hu, -10, 10, 0, 360); fill(hu, random(255), 255); ellipse(x, y, 2, 2); } n += 150; start += 5; pop() } //3 ronds qui rétrécissent if (sound22.isPlaying() == true) { sound22FFT.analyze(); var nrj1 = sound22FFT.getEnergy("bass") push() var rad = map(sound22.currentTime(), 0, sound22.duration(), width / 4, 10) fill(random(99, 205), 0, 0); ellipse(width * 0.3, height * 0.3, rad, rad) pop() push() var rad = map(sound22.currentTime(), 0, sound22.duration(), width / 4, 10) fill(random(99, 105), random(200, 255), 0); ellipse(width * 0.7, height / 3.6, rad, rad) pop() push() var rad = map(sound22.currentTime(), 0, sound22.duration(), width / 4, 10) fill(random(250, 255), random(230, 255), random(1, 70)) ellipse(width * 0.5, height * 0.7, rad, rad) pop() } //sorte d'étoile if (sound24.isPlaying() == true) { push() translate(width / 2, height / 2); var radius = 200; noStroke() beginShape(); var xoff2 = 0; for (var a = 0; a < TWO_PI; a += 0.01) { var offset = map(noise(xoff2, yoff2), 0, 1, -1050, 1000); var r4 = radius + offset; var x4 = r4 * cos(a); var y4 = r4 * sin(a); fill(0, random(99, 105), random(99, 205)); vertex(x4, y4); xoff2 += 0.1; //ellipse(x4, y4, 4, 4); } endShape(); yoff2 += 0.01; pop() } //pluie multicolor if (sound25.isPlaying() == true) { push() for (var i = 0; i < drops.length; i++) { drops[i].fall(); drops[i].show(); } pop() } // explosion de la touche 71 if (sound26.isPlaying() == true) { push() translate(width * 0.3, height * 0.3); var radius = 200; noStroke() beginShape(); var xoff2 = 0; for (var a = 0; a < TWO_PI; a += 0.001) { var offset = map(noise(xoff2, yoff2), 0, 1, -300, 100); var r4 = radius + offset; var x4 = r4 * cos(a); var y4 = r4 * sin(a); fill(random(99, 205), 0, 0); vertex(x4, y4); xoff2 += 0.1; //ellipse(x4, y4, 4, 4); } endShape(); yoff2 += 0.1; pop() push() translate(width * 0.7, height / 3.6); var radius = 200; noStroke() beginShape(); var xoff2 = 0; for (var a = 0; a < TWO_PI; a += 0.001) { var offset = map(noise(xoff2, yoff2), 0, 1, -305, 300); var r4 = radius + offset; var x4 = r4 * cos(a); var y4 = r4 * sin(a); fill(random(99, 105), random(200, 255), 0); vertex(x4, y4); xoff2 += 0.1; //ellipse(x4, y4, 4, 4); } endShape(); yoff2 += 0.01; pop() push() translate(width * 0.5, height * 0.7); var radius = 20; noStroke() beginShape(); var xoff2 = 0; for (var a = 0; a < TWO_PI; a += 0.001) { var offset = map(noise(xoff2, yoff2), 0, 1, -305, 300); var r4 = radius + offset; var x4 = r4 * cos(a); var y4 = r4 * sin(a); fill(random(250, 255), random(230, 255), random(1, 70)); vertex(x4, y4); xoff2 += 0.1; //ellipse(x4, y4, 4, 4); } endShape(); yoff2 += 0.01; pop() } } function playSound(sound, keyId) { if (keyIsDown(keyId) == true) { if (sound.isPlaying() == false) { sound.play(); } } } function windowResized() { resizeCanvas(windowWidth, windowHeight); } //Classe de l'animation pluie multicolor function Drop() { this.x = random(width); this.y = random(-500, -50); this.z = random(0, 20); this.len = map(this.z, 0, 20, 10, 20); this.yspeed = map(this.z, 0, 20, 1, 20); this.fall = function () { this.y = this.y + this.yspeed; var grav = map(this.z, 0, 10, 0, 0.2); this.yspeed = this.yspeed + grav; if (this.y > height) { this.y = random(-200, -100); this.yspeed = map(this.z, 0, 20, 4, 10); } } this.show = function () { var thick = map(this.z, 0, 20, 1, 3); strokeWeight(thick); stroke(random(1, 255), random(1, 255), random(1, 255)); line(this.x, this.y, this.x, this.y + this.len); } } // CLASSE particle pour la classe fireworks function Particle2(x, y, hu, firework) { this.pos = createVector(x, y); this.firework = firework; this.lifespan = 255; this.hu = hu; this.acc = createVector(0, 0); if (this.firework) { this.vel = createVector(0, random(-12, -8)); } else { this.vel = p5.Vector.random2D(); this.vel.mult(random(2, 15)); } this.applyForce = function (force) { this.acc.add(force); } this.update = function () { if (!this.firework) { this.vel.mult(0.9); this.lifespan -= 4; } this.vel.add(this.acc); this.pos.add(this.vel); this.acc.mult(0); } this.done = function () { if (this.lifespan < 0) { return true; } else { return false; } } this.show = function (pg) { pg.colorMode(HSB); if (!this.firework) { pg.strokeWeight(2); pg.stroke(this.hu, 255, 255, this.lifespan); } else { pg.strokeWeight(4); pg.stroke(this.hu, 255, 255); } pg.point(this.pos.x, this.pos.y); } } //Classe de l'animation feu d'artifice function Firework() { this.hu = random(255); this.firework = new Particle2(random(width), height, this.hu, true); this.exploded = false; this.particles = []; this.done = function () { if (this.exploded && this.particles.length === 0) { return true; } else { return false; } } this.update = function () { if (!this.exploded) { this.firework.applyForce(gravity); this.firework.update(); if (this.firework.vel.y >= 0) { this.exploded = true; this.explode(); } } for (var i = this.particles.length - 1; i >= 0; i--) { this.particles[i].applyForce(gravity); this.particles[i].update(); if (this.particles[i].done()) { this.particles.splice(i, 1); } } } this.explode = function () { for (var i = 0; i < 100; i++) { var p = new Particle2(this.firework.pos.x, this.firework.pos.y, this.hu, false); this.particles.push(p); } } this.show = function (pg) { if (!this.exploded) { this.firework.show(pg); } for (var i = 0; i < this.particles.length; i++) { this.particles[i].show(pg); } } } // Classe de l'animation des des petits points qui explosent // A simple Particle class var Particle = function (position) { var vx = random(-2, 2); var vy = random(-2, 2); var ax = vx * 0.01; var ay = vy * 0.01; this.acceleration = createVector(ax, ay); this.velocity = createVector(vx, vy); this.position = position.copy(); this.lifespan = 255; }; Particle.prototype.run = function () { this.update(); this.display(); }; // Method to update position Particle.prototype.update = function () { this.velocity.add(this.acceleration); this.position.add(this.velocity); this.lifespan -= 2; }; // Method to display Particle.prototype.display = function () { colorMode(HSB); noStroke(); // stroke(200, 255 - this.lifespan); // strokeWeight(2); fill(this.lifespan * 2, min(255 - this.lifespan, 500), max(2000 - this.lifespan, 0)); ellipse(this.position.x, this.position.y, 12, 12); //triangle(this.position.x, //this.position.y, //this.position.x + this.velocity.x * 20, //this.position.y + this.velocity.y * 2, //this.position.x + this.velocity.x * 2, // this.position.y + this.velocity.y * 20, // ); }; // Is the particle still useful? Particle.prototype.isDead = function () { return this.lifespan < 0; }; var ParticleSystem = function (position) { this.origin = position.copy(); this.particles = []; }; ParticleSystem.prototype.addParticle = function () { this.particles.push(new Particle(this.origin)); }; ParticleSystem.prototype.run = function () { for (var i = this.particles.length - 1; i >= 0; i--) { var p = this.particles[i]; p.run(); if (p.isDead()) { this.particles.splice(i, 1); } } };
import React from 'react'; const Vehicle = (props) => ( <div onClick={() => {props.fn(props.vehicle)}} className="vehicle"> { props.vehicle.make } {props.vehicle.model} </div> ) export default Vehicle;
const express = require('express'); const minionsRouter = express.Router(); const dbFunctions = require("./db"); minionsRouter.get('/', (req, res, next) => { res.send(dbFunctions.getAllFromDatabase('minions')); }); minionsRouter.post('/', (req, res, next) => { addToDatabase('minions', req.query); res.status(201).send('Minion Created Successfully'); }); minionsRouter.get('/:minionId', (req, res, next) => { if (dbFunctions.getFromDatabaseById('minions', req.params.minionId)) { res.send(dbFunctions.getFromDatabaseById('minions', req.params.minionId)); } else { res.status(404).send("Minion with that ID does not exist"); } }); minionsRouter.put('/:minionId', (req, res, next) => { if (dbFunctions.getFromDatabaseById('minions', req.params.minionId)) { dbFunctions.getFromDatabaseById('minions', req.params.minionId) = req.query; res.send(`Minion ${req.params.id} updated successfully`); } else { res.status(404).send("Minion with that ID does not exist"); } }); minionsRouter.delete('/:minionId', (req, res, next) => { if (deleteFromDatabasebyId('minions', req.params.minionId)) { res.status(204).send(); } else { res.status(404).send(`Minion with ID ${req.params.minionId} not found`); } }) module.exports = minionsRouter;
import { useState, useEffect, useMemo, useCallback } from "react"; import _ from "underscore"; import * as path from "constants/routes"; import { UNAUTHORIZED } from "constants/index"; export const useActiveLink = (path) => { const [activeLink, setActiveLink] = useState(path); useEffect(() => { if (!activeLink || activeLink === path) return; setActiveLink(path); }, [path]); return [activeLink, setActiveLink]; }; export const useClickOutside = (ref, callback) => { useEffect(() => { window.addEventListener("mousedown", handleClick); return () => { window.removeEventListener("mousedown", handleClick); }; }); const handleClick = (e) => { if (ref.current && !ref.current.contains(e.target)) { callback(); } }; }; export const useDebounce = (value, delay) => { const [debauncedValue, setValue] = useState(value); useEffect(() => { const handle = setTimeout(() => { setValue(value); }, delay); return () => { clearTimeout(handle); }; }, [value, delay]); return debauncedValue; }; export const useInfiniteScroll = ({ delay, callback, skip }) => { const [isFetching, setIsFetching] = useState(false); const throttled = _.throttle((e) => handleScroll(e), delay); useEffect(() => { if (skip) return; const wrapper = document.getElementById("content"); wrapper.addEventListener("scroll", throttled); return () => { wrapper.removeEventListener("scroll", throttled); }; }, [skip]); useEffect(() => { if (!isFetching) return; callback(); }, [isFetching]); const handleScroll = (event) => { const { scrollTop, clientHeight, scrollHeight } = event.target; if (scrollTop + clientHeight >= scrollHeight - 300) { setIsFetching(true); } }; return [isFetching, setIsFetching]; }; export const useQuery = (props) => { const { client, endpoint, variables, entity, fetchPolicy, router } = props; const [state, setState] = useState({ loading: true, data: null, error: null, }); const { loading, data, error } = state; const params = useMemo(() => ({ ...variables }), [variables]); const getData = useCallback( (incomingParams) => { setState({ ...state, loading: true }); client .query({ query: endpoint, variables: { ...params, ...incomingParams, }, fetchPolicy: fetchPolicy || "no-cache", }) .then((response) => { const items = response.data[entity]; setState({ ...state, loading: false, data: items }); }) .catch((error) => { if (error.toString() !== UNAUTHORIZED) { router.push(path.SERVER_ERROR); } setState({ loading: false, data: null, error }); }); }, [endpoint, params, fetchPolicy] ); return { getData, loading, error, data }; }; export const useSelection = () => { const [selected, setSelect] = useState([]); const select = useCallback((id) => setSelect(id), [selected, setSelect]); return [selected, select]; };
let mainCounter = document.getElementById("mainCounter"); mainCounter.innerText = "00:00:00:000"; let startButton = document.getElementById("start"); let pauseButton = document.getElementById("pause"); pauseButton.classList.add("disabled"); let loopButton = document.getElementById("loop"); let resetButton = document.getElementById("reset"); let topFiveButton = document.getElementById("showTopFive"); let loopContainer = document.getElementById("loopContainer"); let topFiveContainer = document.getElementById("topFiveContainer"); let runningTime = 0; let newInterval = null; let cumulativeLoops = null; let loopArray = []; let isPaused = false; startButton.addEventListener("click",function() { if(!startButton.classList.contains("disabled")){ isPaused = false; clearInterval(newInterval) startCounting(); pauseButton.classList.remove("disabled"); }//else do nothing }); function startCounting(){ console.log("came to startCounting"); startButton.classList.add("disabled"); newInterval = setInterval(function(){ if(!isPaused){ runningTime += 100; mainCounter.innerText = milisecondsToTime(runningTime); } },100) } pauseButton.addEventListener("click", function() { if(!pauseButton.classList.contains("disabled")){ isPaused = true; startButton.innerText = "Continue"; startButton.classList.remove("disabled"); pauseButton.classList.add("disabled"); } }); resetButton.addEventListener("click", function(){ mainCounter.innerText = "00:00:00:000"; loopContainer.innerHTML = ""; runningTime = 0; clearInterval(newInterval); newInterval = null; cumulativeLoops = null; loopArray = []; startButton.innerText = "Start"; startButton.classList.remove("disabled"); pauseButton.classList.add("disabled"); }); loopButton.addEventListener("click",makeLoop); function makeLoop(){ let cumulative = null for(let i = 0; i<loopArray.length;i++){ cumulative += loopArray[i]; } let currentLoop = runningTime-cumulative; loopArray.push(currentLoop); setToLocal("top5",findTopFive(loopArray)); console.log(getFromLocal("top5")); arrayToHTML(loopArray,loopContainer); //check on click, if 5 loops have been recorded, then append topFiveButton to document if(loopArray.length >= 5){ topFiveButton.classList.remove("disabled"); } } topFiveButton.addEventListener("click",function(){ if(!topFiveButton.classList.contains("disabled")){ //if not disabled storageArrayToHTML("top5",topFiveContainer); } }) function milisecondsToTime(time) { function pad(n, z) { z = z || 2; return ('00' + n).slice(-z); } let miliseconds = time % 1000; time = (time - miliseconds) / 1000; let seconds = time % 60; time = (time - seconds) / 60; let minutes = time % 60; let hours = (time - minutes) / 60; return pad(hours) + ':' + pad(minutes) + ':' + pad(seconds) + ':' + pad(miliseconds, 3); } function findTopFive(array){ return array.sort((a,b)=>a-b).slice(0,5); //ascending sort, return only first 5 } function getFromLocal(key){ return JSON.parse(localStorage.getItem(key)); } function setToLocal(key,data){ localStorage.setItem(key,JSON.stringify(data)); } function storageArrayToHTML(whatData, container){ arrayToHTML(getFromLocal(whatData),topFiveContainer); } // v HTML en div za rezultate function arrayToHTML(array,container) { container.innerHTML = ""; for(let i=0;i < array.length; i++) { let oneLoop = document.createElement("p"); oneLoop.innerHTML = milisecondsToTime(array[i]); container.appendChild(oneLoop); } } function dataExists(){ return localStorage.length > 0; } function onLoadShowTopFive(){ //runs on page load, checks local storage for best laps and calls appropriate html build function if(dataExists()){ storageArrayToHTML("top5",topFiveContainer); }else{ console.log("no previous data present!"); } } onLoadShowTopFive();
export const SET_USER = "SET_USER"; export const CLEAR_USER = "CLEAR_USER"; export const SET_CHANNEL = "SET_CHANNEL"; export const SET_PRIVATE_CHANNEL = "SET_PRIVATE_CHANNEL"; export const SET_USER_POSTS = "SET_USER_POSTS"; export const SET_COLORS= "SET_COLORS"
function addDots(nStr) { nStr += ''; x = nStr.split('.'); x1 = x[0]; x2 = x.length > 1 ? '.' + x[1] : ''; const rgx = /(\d+)(\d{3})/; while (rgx.test(x1)) { x1 = x1.replace(rgx, '$1' + '.' + '$2'); // changed comma to dot here } return x1 + x2; } export default function rupiah(price) { if (!price) { price = 0 }; return `Rp ${addDots(Math.round(price)).toString()}` }
/** * Created by moritz löser (moritz.loeser@prodyna.com) on 15.06.2015. */ var rootUrl = window.location.protocol + "//" + window.location.host + "/timetracker-backend"; var wsProtocol = "ws:"; if(window.location.protocol == "https:"){ wsProtocol = "wss:"; } var wsRootUrl = wsProtocol + "//" + window.location.host + "/timetracker-backend"; var logOutUrl = window.location.protocol + "//invalid:invalid@" + window.location.host + "/timetracker-backend/timetracker/user/current"; var app = angular.module('timetracker', ['ui.bootstrap', 'ngWebSocket']); // renders current user available before others need it angular.element(document).ready(function () { var initInjector = angular.injector(['ng']); var $http = initInjector.get('$http'); $http.get(rootUrl + '/timetracker/user/current').then(function (response) { app.constant('currentUser', response.data); angular.bootstrap(document, ['timetracker']); }); }); app.controller('timetrackerCtrl', function ($scope, $http, currentUser, $filter, $websocket) { $scope.url = logOutUrl; $scope.currentUser = currentUser; $scope.isManager = ("MANAGER" == currentUser.role) || ("ADMIN" == currentUser.role); $scope.isAdmin = ("ADMIN" == currentUser.role); if ($scope.isManager) { $scope.allBookingsList = {}; var allBookingsWs = $websocket(wsRootUrl + '/allbookings'); allBookingsWs.onMessage(function (event) { $scope.allBookingsList = JSON.parse(event.data); }); var updateAllBookings = function () { //all bookings $http.get(rootUrl + '/timetracker/booking/all').success(function (response) { $scope.allBookingsList = response; }) }; updateAllBookings(); //projects $scope.allProjectsList = {}; var allProjectsWs = $websocket(wsRootUrl + '/allprojects'); allProjectsWs.onMessage(function (event) { $scope.allProjectsList = JSON.parse(event.data); }); var updateAllProjects = function () { $http.get(rootUrl + '/timetracker/project/all').success(function (response) { $scope.allProjectsList = response; }); }; updateAllProjects(); $scope.newProject = {}; //new project $scope.submitCreateProject = function () { var data = $scope.newProject; $http.post(rootUrl + "/timetracker/project", data).success( function (answer, status) { $scope.createProjectResult = status; }).error(function (answer, status) { $scope.createProjectResult = status; }); }; //users projects (register users to projects) var updateAllUsersProjects = function () { $scope.allUsersProjectsList = {}; $http.get(rootUrl + '/timetracker/usersprojects/all').success(function (response) { $scope.allUsersProjectsList = response; }); }; updateAllUsersProjects(); $scope.allUsersList = {}; var allUsersWs = $websocket(wsRootUrl + '/allusers'); allUsersWs.onMessage(function (event) { $scope.allUsersList = JSON.parse(event.data); }); var updateAllUsers = function () { $http.get(rootUrl + '/timetracker/user/all').success(function (response) { for (var i = 0; i < response.length; ++i) $scope.allUsersList[response[i].name] = response[i]; }); }; updateAllUsers(); var updateAllProjects = function () { $scope.allProjectsList = {}; $http.get(rootUrl + '/timetracker/project/all').success(function (response) { for (var i = 0; i < response.length; ++i) $scope.allProjectsList[response[i].name] = response[i]; }); }; updateAllProjects(); $scope.newUsersProject = {}; $scope.submitCreateUsersProject = function () { var data = { "user": $scope.allUsersList[$scope.newUsersProject.user], "project": $scope.allProjectsList[$scope.newUsersProject.project] }; $http.post(rootUrl + "/timetracker/usersprojects", data).success( function (answer, status) { $scope.createUsersProjectResult = status; updateAllUsersProjects(); updateUsersProjects(); }).error(function (answer, status) { $scope.createUsersProjectResult = status; }); }; } if ($scope.isAdmin) { //manage users $scope.newUser = {}; $scope.submitCreateUser = function () { var data = $scope.newUser; $http.post(rootUrl + "/timetracker/user", data).success( function (answer, status) { $scope.createUserResult = status; }).error(function (answer, status) { $scope.createUserResult = status; }); }; } //my bookings //update my bookings list var updateMyBookings = function () { $scope.myBookingsList = []; $http.get(rootUrl + '/timetracker/booking/user/' + currentUser.id).success(function (response) { $scope.myBookingsList = response; }); }; //update on load updateMyBookings(); // //list of projects for current user (usersprojects) var updateUsersProjects = function () { $scope.usersprojectsList = {}; $http.get(rootUrl + '/timetracker/usersprojects/user/' + currentUser.id).success(function (response) { for (var i = 0; i < response.length; ++i) //map users project by projects name $scope.usersprojectsList[response[i].project.name] = response[i]; }) }; //update on load updateUsersProjects(); //opens date picker for start $scope.openStart = function ($event) { $event.preventDefault(); $event.stopPropagation(); $scope.openedStart = true; }; //opens date picker for end $scope.openEnd = function ($event) { $event.preventDefault(); $event.stopPropagation(); $scope.openedEnd = true; }; var initBookingForm = function () { $scope.newBooking = {}; //timepicker values must be initialized $scope.newBooking.startTime = new Date(); //ad 15 minutes to end to get vaild interval on init $scope.newBooking.endTime = new Date(new Date().getTime() + 15*60000); }; initBookingForm(); //either create mode or update mode var switchEditMode = function (isUpdate) { $scope.createDisabled = isUpdate; $scope.updateDisabled = !isUpdate; $scope.deleteDisabled = !isUpdate; } //on init create mode switchEditMode(false); //create new booking $scope.submitCreateBooking = function () { //convert date, time string to epoch time var startDateF = $filter('date')($scope.newBooking.startDate, "MM dd, yyyy"); var startTimeF = $filter('date')($scope.newBooking.startTime, "HH:mm:ss") var endDateF = $filter('date')($scope.newBooking.endDate, "MM dd, yyyy"); var endTimeF = $filter('date')($scope.newBooking.endTime, "HH:mm:ss") var booking = { "usersProjects": $scope.usersprojectsList[$scope.newBooking.project], "start": new Date(startDateF + " " + startTimeF).getTime(), "end": new Date(endDateF + " " + endTimeF).getTime() }; $http.post(rootUrl + "/timetracker/booking", booking).success( function (answer, status) { $scope.createBookingResult = status; updateMyBookings(); }).error(function (answer, status) { $scope.createBookingResult = status; }); } //fill form with booking clicked $scope.bookingClicked = function (booking) { $scope.newBooking = {}; $scope.newBooking.project = {}; $scope.newBooking.project = booking.usersProjects.project.name; $scope.newBooking.id = booking.id; $scope.newBooking.startDate = $filter('date')(booking.start, "yyyy-MM-dd"); $scope.newBooking.startTime = new Date(booking.start); $scope.newBooking.endDate = $filter('date')(booking.end, "yyyy-MM-dd"); $scope.newBooking.endTime = new Date(booking.end); //switch to update switchEditMode(true); }; $scope.resetBooking = function () { initBookingForm(); //switch to create new switchEditMode(false); }; $scope.deleteBooking = function(){ $http.delete(rootUrl + "/timetracker/booking/" + $scope.newBooking.id).success( function (answer, status) { $scope.createBookingResult = status; updateMyBookings(); initBookingForm(); }).error(function (answer, status) { $scope.createBookingResult = status; }); }; $scope.updateBooking = function(){ //convert date, time string to epoch time var startDateF = $filter('date')($scope.newBooking.startDate, "MM dd, yyyy"); var startTimeF = $filter('date')($scope.newBooking.startTime, "HH:mm:ss") var endDateF = $filter('date')($scope.newBooking.endDate, "MM dd, yyyy"); var endTimeF = $filter('date')($scope.newBooking.endTime, "HH:mm:ss") var booking = { "id": $scope.newBooking.id, "usersProjects": $scope.usersprojectsList[$scope.newBooking.project], "start": new Date(startDateF + " " + startTimeF).getTime(), "end": new Date(endDateF + " " + endTimeF).getTime() }; $http.put(rootUrl + "/timetracker/booking/" + $scope.newBooking.id, booking).success( function (answer, status) { $scope.createBookingResult = status; updateMyBookings(); }).error(function (answer, status) { $scope.createBookingResult = status; }); }; });
import { getActiveProjectId } from "../../App"; import { fetchProjectById, updateProject } from "../../Project/api"; /** * @function updateSection * @param {string} sectionIdQuery * @param {Object} sectionUpdates * @param {string} [sectionUpdates.name] * @param {Task[]} [sectionUpdates.tasks] */ const updateSection = (sectionIdQuery, sectionUpdates) => { const targetProjectId = getActiveProjectId(); const targetProject = fetchProjectById(targetProjectId); for (let i = 0; i < targetProject.sections.length; i++) { if (targetProject.sections[i].id === sectionIdQuery) { targetProject.sections[i] = { ...targetProject.sections[i], ...sectionUpdates, }; } } updateProject(targetProjectId, { sections: [...targetProject.sections], }); }; export default updateSection;
import { completeToDos, getTodos } from '../utils.js'; const toDos = document.getElementById('append-here'); export function renderTodo(arrayItem) { const li = document.createElement('li'); const btn = document.createElement('button'); li.append(btn); btn.classList.add('todos'); btn.setAttribute('id', arrayItem.id); btn.textContent = arrayItem.todos; btn.addEventListener('click', () => { completeToDos(arrayItem.id); btn.style.textDecoration = 'line-through'; }); if (arrayItem.completed) { btn.style.textDecoration = 'line-through'; } return li; } export function callRender() { const Todos = getTodos(); for (let Todo of Todos) { const liItem = renderTodo(Todo); toDos.append(liItem); } }
//"TaskId": "T_FCTRCJPFLCVFT_661"
// Задача 1. Вычислить среднее арифметическое значений массива let massiv = [10, 45, 65, 24, 34, 56, 31, 90, 67, 33, 90] function arifm(massiv) { let sum = 0; for(let i = 0; i < massiv.length; i++) { sum = sum + massiv[i]; } let result = sum / massiv.length; return result; } console.log(arifm(massiv))
import React, { Component } from 'react'; import classnames from 'classnames'; class Header extends Component { render() { const className = classnames('modal-custom-header', this.props.className); const { tittle } = this.props; return ( <div className={className}> <h4>{ tittle }</h4> </div> ); } } Header.props = { children: React.PropTypes.node, tittle: React.PropTypes.string.isRequired, className: React.PropTypes.string }; export default Header;
const mongoose = require("mongoose"); const Schema = mongoose.Schema; const Collection = require("../models/collections"); const userSchema = new Schema({ name: { type: String, required: true, }, email: { type: String, required: true, }, password: { type: String, required: true, }, cart: { items: [ { product: { type: Object, required: true, }, quantity: { type: Number, required: true, }, }, ], }, }); userSchema.methods.addToCart = function (addProduct) { const existingProd = this.cart.items.findIndex( (cp) => cp.product._id.toString() === addProduct._id.toString() ); let updatedItems = [...this.cart.items]; let newQuantity = 1; if (existingProd < 0) { updatedItems.push({ product: addProduct, quantity: 1, }); } else { newQuantity = this.cart.items[existingProd].quantity + 1; updatedItems[existingProd].quantity = newQuantity; } let newCart = { items: updatedItems, }; this.cart = newCart; return this.save(); }; userSchema.methods.removeFromCart = function (addProduct) { const existingProd = this.cart.items.findIndex( (cp) => cp.product._id.toString() === addProduct._id.toString() ); let updatedItems = [...this.cart.items]; if (existingProd < 0) { const error = new Error("Product could not found"); error.statusCode = 404; throw error; } if (updatedItems[existingProd].quantity === 1) { updatedItems = updatedItems.filter( (cp) => cp.product._id.toString() !== addProduct._id.toString() ); } else { let newQuantity = this.cart.items[existingProd].quantity - 1; updatedItems[existingProd].quantity = newQuantity; } let updatedCart = { items: updatedItems, }; this.cart = updatedCart; return this.save(); }; userSchema.methods.clearFromCart = function (addProduct) { const existingProd = this.cart.items.findIndex( (cp) => cp.product._id.toString() === addProduct._id.toString() ); let updatedItems = [...this.cart.items]; if (existingProd < 0) { const error = new Error("Product could not found"); error.statusCode = 404; throw error; } else { updatedItems = updatedItems.filter( (cp) => cp.product._id.toString() !== addProduct._id.toString() ); } let updatedCart = { items: updatedItems, }; this.cart = updatedCart; return this.save(); }; module.exports = mongoose.model("User", userSchema);
import Comment from './Comment.component' export { Comment }
/** * templates */ module.exports = [ { "name": "vue-template-mobile", "path": "https://github.com/sufangyu/vue-template-mobile.git#cli", "desc": "移动端项目通用模板" }, { "name": "cli-test", "path": "https://github.com/sufangyu/cli-temp.git#master", "desc": "脚手架功能开发模板" }, ];
import React from "react"; import ClassNames from "classnames"; import { connect } from "react-redux"; import dragging from "../../hoc/dragging"; import { deleteTask } from "../../actions/"; class Card extends React.PureComponent { render() { const { data, dragging, forDragStart } = this.props; const style = ClassNames("card-container-color", data.style); const dragAndDrop = ClassNames({ card: true, "card-dragging": dragging }); return ( <div className={dragAndDrop} draggable="true" onDragStart={forDragStart}> <div className="card__header"> <div className={style}> <div className="card__header-priority">{data.priority}</div> </div> <div onClick={this.handleDelete} className="card__header-clear"> <i className="material-icons">clear</i> </div> </div> <div className="card__text">{data.text}</div> <div className="card__menu"> <div className="card__menu-left"> <div className="comments-wrapper"> <div className="comments-ico"> <i className="material-icons">comment</i> </div> <div className="comments-num">{data.comments}</div> </div> <div className="attach-wrapper"> <div className="attach-ico"> <i className="material-icons">attach_file</i> </div> <div className="attach-num">{data.attach}</div> </div> </div> <div className="card__menu-right"> <div className="add-peoples"> <i className="material-icons">add</i> </div> <div className="img-avatar"> <img src={data.avatar} /> </div> </div> </div> </div> ); } handleDelete = () => { const { data, deleteTask } = this.props; deleteTask(data.id); }; } export default connect( null, { deleteTask } )(dragging(Card));