text
stringlengths
7
3.69M
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Table, Icon, Dropdown } from 'semantic-ui-react'; import { Link } from 'react-router-dom'; import { chatLog, searchChatLog } from '../../Func/actions/ChatLog' const options = [ { key: 0, text: '전체', value: 0 }, { key: 1, text: 'ID', value: 1 }, { key: 2, text: '날짜', value: 2 }, { key: 3, text: '플랫폼', value: 3 }, ] class System2 extends Component { state = { chatLogData: [], page: 0, totalpage: 10, searchWord: '', searchType: { key: 0, text: '전체', value: 0 } }; componentDidMount = () => { this.loadData(); } loadData = () => { this.props.chatLog(0); } componentWillReceiveProps = (nextProps) => { if(nextProps.chatLogData !== this.state.chatLogData) { this.setState({ chatLogData: nextProps.chatLogData }) } if(nextProps.searchedData !== this.state.searchedData) { console.log(nextProps.searchedData) this.setState({ searchedData: nextProps.searchedData }) } if(nextProps.searchedPage !== this.state.searchedPage) { this.setState({ searchedPage: nextProps.searchedPage }) } } handlePage = (page) => { var index; var str; var last; const pagenum = this.state.pagenum; const totalnum = this.state.chatLogData.length; switch(page){ case 'prev': if(pagenum < 10){ this.props.chatLog(0); }else{ index = (Math.floor((pagenum-10)/10)*10)+9 this.props.chatLog(index); } break; case 'next': str = totalnum.toString(); last = str.substr(str.length-1); if((totalnum - pagenum) > last){ index = Math.floor((pagenum+10)/10)*10 this.props.chatLog(index); }else{ this.props.chatLog(totalnum-1); } break; default: this.props.chatLog(page); break; } } makeNormalRow = ({ create_date, platform, client_id, chatbot_count }, i) => { return( <Table.Row key={i}> <Table.Cell textAlign={'center'}>{create_date}</Table.Cell> <Table.Cell textAlign={'center'}> <Link to={`/System/ChatLog/id=${client_id}&date=${create_date}`}>{client_id}</Link> </Table.Cell> <Table.Cell textAlign={'center'}>{platform}</Table.Cell> <Table.Cell textAlign={'center'}>{chatbot_count}</Table.Cell> <Table.Cell textAlign={'center'}><Link to={`/System/ChatLog/id=${client_id}&date=${create_date}`}><Icon name='edit'/></Link></Table.Cell> </Table.Row> ) } changeSearchType = (e, data) => { var target = options[data.value] this.setState({ searchType: target }) } searchChatLog = (value) => { if(value !== ''){ this.setState({ searchWord: value }) this.props.searchChatLog(this.state.searchType.key, value, 0) }else{ this.setState({ searchWord: '', searchedData: [] }) } } render() { const { chatLogData, page, searchWord, searchedData, searchedPage } = this.state; var array = []; var first=0; var last=0; var i; first = (Math.floor(page/10))*10 + 0; if(chatLogData.length/10 < 9){ last = Math.ceil(chatLogData.length/10)-1 }else{ last = (Math.floor(page/10))*10 + 9; } for(i = first; i<(last+1); i++){ array.push(i); } return ( <div className='System1'> <div className='outsideTable'> <div className='ui search searchBox'> <Dropdown selection options={options} value={this.state.searchType.value} text={this.state.searchType.text} onChange={this.changeSearchType} placeholder='Choose an option' /> <div className='ui icon input'> <i className='search link icon' style={{left:"0"}} /> <Icon inverted size='mini' className='removeSearchBtn link' circular name='delete' onClick={() => { this.searchChatLog(''); }} /> <input className='prompt' type='text' placeholder='Search...' onKeyPress={(e)=>{ if(e.key === 'Enter'){ this.searchChatLog(e.target.value) } }} onChange={(e)=>{ this.searchChatLog(e.target.value) }} value={this.state.searchWord} /> </div> </div> </div> <Table size='small' basic='very' className='ScenarioTable'> <Table.Header> <Table.Row> <Table.HeaderCell textAlign={'center'} width={3}>날짜</Table.HeaderCell> <Table.HeaderCell textAlign={'center'} width={3}>아이디</Table.HeaderCell> <Table.HeaderCell textAlign={'center'} width={4}>플랫폼</Table.HeaderCell> <Table.HeaderCell textAlign={'center'} width={3}>대화건수</Table.HeaderCell> <Table.HeaderCell textAlign={'center'} width={3}>상세보기</Table.HeaderCell> </Table.Row> </Table.Header> <Table.Body> {searchWord.length>0 ? searchedData.map(this.makeNormalRow) : chatLogData.map(this.makeNormalRow)} </Table.Body> </Table> <div className='pagebox'> {page > 9 && <div className='pagebtn' onClick={this.handlePage.bind(this, 'prev')}>{'<'}</div>} {array.map((j, i) => { return ( <div key={i} className={page === j ? 'pagebtn active' : 'pagebtn'} onClick={this.handlePage.bind(this, j)}>{j+1}</div> ) }) } {array.length === 10 && <div className='pagebtn' onClick={this.handlePage.bind(this, 'next')}>{'>'}</div>} </div> </div> ); } } const mapStateToProps = (state) => { return { chatLogData: state.ChatLog.chatLogData.data, searchedData: state.ChatLog.searchedChatLog.data, searchedType: state.ChatLog.searchedChatLog.type, searchedValue: state.ChatLog.searchedChatLog.value, searchedPage: state.ChatLog.searchedChatLog.page, }; }; const mapDispatchToProps = (dispatch) => { return { chatLog: (page) => { return dispatch(chatLog(page)); }, searchChatLog: (type, value, page) => { return dispatch(searchChatLog(type, value, page)); }, }; }; export default connect(mapStateToProps, mapDispatchToProps)(System2); // export default System1;
import Header from './index' test('A test test', () => { expect( '2' ).toBe( '2' ) })
import React from 'react'; import PropTypes from 'prop-types'; import styled from '@emotion/styled'; import FollowerIcon from 'assets/icons/FollowerIcon'; import Text from 'components/Text'; const FollowersContainer = styled.div` display: flex; align-items: center; `; const StyledFollowerIcon = styled(FollowerIcon)` width: 20px; height: 20px; margin-right: 4px; color: ${({ color, theme }) => theme.colors[color] ?? theme.colors.primary}; `; const Followers = ({ className, count, color }) => ( <FollowersContainer className={className}> <StyledFollowerIcon color={color} /> <Text as="span" color={color}> <Text weight="medium" as="span" color={color}>{count}</Text> followers </Text> </FollowersContainer> ); Followers.propTypes = { className: PropTypes.string, count: PropTypes.number, color: PropTypes.string, }; Followers.defaultProps = { className: null, count: 0, color: null, }; export default Followers;
import { combineReducers } from 'redux' import auth from './auth' import drawer from './drawer' import ui from './ui' import youtube from './youtube' export default combineReducers({ auth, drawer, ui, youtube })
(function() { // 这些变量和函数的说明,请参考 rdk/app/example/web/scripts/main.js 的注释 var imports = [ 'rd.attributes.Scroll', 'css!base/style' ]; var extraModules = [ ]; var controllerDefination = ['$scope', main]; function main(scope) { } rdk.$ngModule.config(['ScrollConfigProvider',function(ScrollConfigProvider){ ScrollConfigProvider.setOptions( { wheelSpeed:0.5, //鼠标滚轮移动滚动条的速度 minScrollbarLength:100, //滚动条最小长度 maxScrollbarLength:280, //滚动条最大长度 theme:"test" //主题 } ); }]); var controllerName = 'DemoController'; //========================================================================== // 从这里开始的代码、注释请不要随意修改 //========================================================================== define(/*fix-from*/application.import(imports)/*fix-to*/, start); function start() { application.initImports(imports, arguments); rdk.$injectDependency(application.getComponents(extraModules, imports)); rdk.$ngModule.controller(controllerName, controllerDefination); } })();
import { Editor, Raw } from '../..' import React from 'react' import initialState from './state.json' import keycode from 'keycode' /** * Define a set of node renderers. * * @type {Object} */ const NODES = { 'table': props => <table><tbody {...props.attributes}>{props.children}</tbody></table>, 'table-row': props => <tr {...props.attributes}>{props.children}</tr>, 'table-cell': props => <td {...props.attributes}>{props.children}</td> } /** * Define a set of mark renderers. * * @type {Object} */ const MARKS = { bold: { fontWeight: 'bold' } } /** * The tables example. * * @type {Component} */ class Tables extends React.Component { /** * Deserialize the raw initial state. * * @type {Object} */ state = { state: Raw.deserialize(initialState, { terse: true }) }; /** * On backspace, do nothing if at the start of a table cell. * * @param {Event} e * @param {State} state * @return {State or Null} state */ onBackspace = (e, state) => { if (state.startOffset != 0) return e.preventDefault() return state } /** * On change. * * @param {State} state */ onChange = (state) => { this.setState({ state }) } /** * On delete, do nothing if at the end of a table cell. * * @param {Event} e * @param {State} state * @return {State or Null} state */ onDelete = (e, state) => { if (state.endOffset != state.startText.length) return e.preventDefault() return state } /** * On return, do nothing if inside a table cell. * * @param {Event} e * @param {State} state * @return {State or Null} state */ onEnter = (e, state) => { e.preventDefault() return state } /** * On key down, check for our specific key shortcuts. * * @param {Event} e * @param {Object} data * @param {State} state * @return {State or Null} state */ onKeyDown = (e, data, state) => { if (state.startBlock.type != 'table-cell') return switch (data.key) { case 'backspace': return this.onBackspace(e, state) case 'delete': return this.onDelete(e, state) case 'enter': return this.onEnter(e, state) } } /** * Render the example. * * @return {Component} component */ render = () => { return ( <div className="editor"> <Editor state={this.state.state} renderNode={this.renderNode} renderMark={this.renderMark} onKeyDown={this.onKeyDown} onChange={this.onChange} /> </div> ) } /** * Return a node renderer for a Slate `node`. * * @param {Node} node * @return {Component or Void} */ renderNode = (node) => { return NODES[node.type] } /** * Return a mark renderer for a Slate `mark`. * * @param {Mark} mark * @return {Object or Void} */ renderMark = (mark) => { return MARKS[mark.type] } } /** * Export. */ export default Tables
'use strict'; TSManager.controller('ListCtrl', function ($scope, Tasks) { $scope.todos = Tasks.query(); $scope.from = '-done'; $scope.reverse = true; $scope.alerts = []; $scope.modal = { "content": "Hello Modal", "saved": false } $scope.create = function (task) { Tasks.save(task); $scope.todos.push(task); } $scope.remove = function (task) { var position = $scope.todos.indexOf(task); $scope.todos.splice(position,1); // console.log($scope.todos.indexOf(task) + ' - Position de la tach courant'); Tasks.remove({id: task.id}); } $scope.alert = function() { } $scope.submitForm = function (data) { Tasks.update({id: data.id},data); $scope.alerts.push({ "type": "success", "title": "Update success for " + data.name, "content": "Isn't it wonderful ?" }); } });
import Backbone from 'backbone'; const Message = Backbone.Model.extend({ defaults() { return { created: undefined, text: '', }; }, initialize() { let created = this.attributes.created; switch (typeof created) { case 'object': break; case 'string': created = new Date(created); break; case 'undefined': created = new Date(); break; default: break; } if (Object.prototype.toString.call(created) !== '[object Date]' || isNaN(created.getTime())) { throw new Message.InvalidDateException(this.attributes.created); } this.set('created', created); }, }, { InvalidDateException(value) { this.value = value; this.toString = () => { return `Date is ${Object.prototype.toString.call(this.value)}, Date must be a Date object or in UTC format.`; }; }, }); export default Message;
var createError = require('http-errors'); var express = require('express'); var path = require('path'); var cookieParser = require('cookie-parser'); var logger = require('morgan'); const cors=require('cors') const mongoose = require('mongoose') const verify = require('./middleware/verify') var indexRouter = require('./routes/index'); var usersRouter = require('./routes/users'); var momentRouter = require('./routes/moment'); var app = express(); app.use('/uploads',express.static('./upload')) app.use(cors()) app.use(logger('dev')); app.use(express.json()); app.use(express.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.use(express.json({limit: '50mb'})); app.use('/', indexRouter); app.use('/users', usersRouter); app.use('/moment',verify, momentRouter); // catch 404 and forward to error handler app.use(function(req, res, next) { next(createError(404)); }); mongoose.connect('mongodb://localhost:27017/moment') .then(()=>console.log("Connected to MongoDB...")) .catch(err=>console.log("Could not connect to mongodb")) module.exports = app;
import './train.html'; import './train.css'; const TAB_NOTES = [ 'DO_1', 'RE_1', 'MI_1', 'FA_1', 'SOL_1', 'LA_1', 'SI_1', 'DO_2', 'MI_2', 'FA_2', 'SOL_2', 'LA_2', 'SI_2', ]; const NOTES_PATH = '/images/NOTES/FA/'; const NB_SERIES = 15; Template.train.onCreated(function () { this.note = new ReactiveVar(''); this.lastNote = new ReactiveVar(''); this.indexTab = new ReactiveVar(0); this.indexSerie = new ReactiveVar(0); this.responseActive = new ReactiveVar(false); this.response = new ReactiveVar(false); this.score = new ReactiveVar(0); this.end = new ReactiveVar(false); randomNote(); }); Template.train.helpers({ note() { return NOTES_PATH + TAB_NOTES[Template.instance().indexTab.get()] + '.png'; }, nomNote() { return Template.instance().note.get(); }, responseActive() { return Template.instance().responseActive.get(); }, response() { return Template.instance().response.get(); }, end() { return Template.instance().end.get(); //return true; }, indexSerie() { return Template.instance().indexSerie.get(); }, nbSeries() { return NB_SERIES; }, score() { return Template.instance().score.get(); } }); Template.train.events({ 'click .js-note'(event, instance) { event.preventDefault(); const note = event.target.value; if (note.toUpperCase() == Template.instance().note.get()) { Template.instance().score.set(Template.instance().score.get() + 1); Template.instance().response.set(true); } else { Template.instance().response.set(false); } Template.instance().responseActive.set(true); Template.instance().lastNote.set(Template.instance().note.get()) Template.instance().indexSerie.set(Template.instance().indexSerie.get() + 1); if (Template.instance().indexSerie.get() < (NB_SERIES)) { randomNote(); } else { Template.instance().end.set(true); } } }); function entierAleatoire(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } function randomNote() { Template.instance().indexTab.set(entierAleatoire(1, TAB_NOTES.length) - 1); Template.instance().note.set(TAB_NOTES[Template.instance().indexTab.get()].split('_')[0]); if (Template.instance().note.get() == Template.instance().lastNote.get()) { randomNote(); } }
import React from 'react'; import {HeaderWrapper, HeaderWrapper2, HeaderIcons, Contact, Donations, Title, LogoDiv, Nav, NavList, NavListItem, NavLink, HeaderText,HeaderWrapper3, NavList2, NavLink2, NavListItem2, } from './header-styles'; import {Icon, Input} from 'antd'; import Logo from '../../../utils/Logo'; const {Search} = Input const Header = () => { return ( <header> {/* First Header */} <HeaderWrapper> <HeaderIcons> <Icon className="icon_1" type="facebook"/> <Icon className="icon_2" type="twitter"/> <Icon className="icon_3" type="youtube"/> <Icon className="icon_4" type="instagram"/> </HeaderIcons> <Contact> <Title>Contacts</Title> </Contact> <Donations> <Title>Donations</Title> </Donations> </HeaderWrapper> {/* End of first header */} {/* Second Header */} <HeaderWrapper2> <LogoDiv> <Logo link={true} linkTo="/"/> <HeaderText>SJ Football club</HeaderText> </LogoDiv> <Nav> <NavList> <NavListItem> <NavLink to="/">Home</NavLink> </NavListItem> <NavListItem> <NavLink to="/news">News</NavLink> </NavListItem> <NavListItem> <NavLink to="/results">Results</NavLink> </NavListItem> <NavListItem> <NavLink to="/tables">Tables</NavLink> </NavListItem> <NavListItem> <NavLink to="/about">About</NavLink> </NavListItem> </NavList> </Nav> </HeaderWrapper2> {/* End of Second Header */} {/* Third Header */} <HeaderWrapper3> <NavList2> <NavListItem2> <NavLink2 to="/apl">APL</NavLink2> </NavListItem2> <NavListItem2> <NavLink2 to="/uefa">UEFA</NavLink2> </NavListItem2> <NavListItem2> <NavLink2 to="/elc">ELC</NavLink2> </NavListItem2> {/* <NavListItem2> <NavLink2 to="/super_cup">SUPER CUP</NavLink2> </NavListItem2> <NavListItem2> <NavLink2 to="/world_cup">WORLD CUP</NavLink2> </NavListItem2> */} <NavListItem2> <Search placeholder="Search" style={{width: 300, marginTop: '-1.5rem'}} onSearch={value => console.log(value)} /> </NavListItem2> </NavList2> </HeaderWrapper3> {/* End of Third Nav */} </header> ) } export default Header;
'use strict' const mongoose = require('mongoose'); const Schema = mongoose.Schema; const passportLocalMongoose = require('passport-local-mongoose'); const options = { errorMessages: { UserExistsError: 'En användare med det användarnamnet finns redan', IncorrectPasswordError: 'Felaktigt lösenord eller användarnamn', IncorrectUsernameError: 'Felaktigt lösenord eller användarnamn' }, limitAttempts: true, maxAttempts: 10 } const User = new Schema({ local: { username: { type: String, // unique: true //removed - E11000 duplicate key error }, password: { type: String }, isAdmin: { type: Boolean, default: false } } }, { collection: 'users' }) //add the passport-local-mongoose plugin User.plugin(passportLocalMongoose, options); module.exports = mongoose.model('User', User);
import RK4 from './rk4'; export default class Entity extends RK4 { }
let canvas = document.getElementById('canvas') let gl = canvas.getContext("webgl", { premultipliedAlpha: true }) canvas.width = window.innerHeight canvas.height = canvas.width let img = new Image() img.src = 'https://i.ibb.co/hsRMb22/smoke.png' img.crossOrigin = "anonymous" let ismousedown = false let scaleProportionally= true let mousePos let texture img.onload = () => { console.log(img) texture = loadTexture(img) } let settingsSmoke = { rate: 1, color: { r: 0.7, g: 0.7, b: 0.7, a: 0.03 }, scaleMin: { x: 0.001, y: 0.001 }, scaleMax: { x: 0.01, y: 0.01 }, maxVel: { x: 0.00035, y: 0.0025 }, minVel: { x: 0.00015, y: 0.001 }, maxLife: 4000, minLife: 800, minRotVel: 0.006, maxRotVel: 0.01, minScaleVel: { x: 0.00005, y: 0.00005 }, maxScaleVel: { x: 0.00085, y: 0.00085 }, minColorVel: { r: 0, g: 0, b: 0, a: -0.0002 }, maxColorVel: { r: 0.0, g: 0.0, b: 0.0, a: -0.0001 } } let settingsFlame = { rate: 4, color: { r: 1, g: 1, b: 0, a: 0.5 }, scaleMin: { x: 0.004, y: 0.004 }, scaleMax: { x: 0.02, y: 0.02 }, maxVel: { x: 0.00095, y: 0.0055 }, minVel: { x: -0.00095, y: 0.0031 }, maxLife: 500, minLife: 200, minRotVel: 0.0001, maxRotVel: 0.001, minScaleVel: { x: 0.00005, y: 0.00005 }, maxScaleVel: { x: 0.00035, y: 0.00035 }, minColorVel: { r: 0, g: -0.2, b: 0, a: 0 }, maxColorVel: { r: 0.0, g: -0.005, b: 0.0, a: 0 } } let particles = [] let buffer function createPosMat3(pos) { let arr = [ 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, pos.x, -pos.y, 1.0 ] return new Float32Array(arr) } function createScaleMat3(scale) { let arr = [ scale.x, 0.0, 0.0, 0.0, scale.y, 0.0, 0.0, 0.0, 1.0 ] return new Float32Array(arr) } function createRotMat3(angle) { let sin = Math.sin(angle) let cos = Math.cos(angle) let arr = [ cos, -sin, 0.0, sin, cos, 0.0, 0.0, 0.0, 1.0 ] return new Float32Array(arr) } function multMat3(m1, m2) { let arr = new Float32Array(9) for (let i = 0; i < 3; i++) { for (let j = 0; j < 3; j++) { for (let k = 0; k < 3; k++) { arr[i * 3 + j] += m1[i * 3 + k] * m2[k * 3 + j] } } } return arr } function addParticles(pos, settings) { for (let i = 0; i < settings.rate; i++){ let scaleX = Math.random() * (settings.maxScaleVel.x - settings.minScaleVel.x) + settings.minScaleVel.x let obj = { pos: { x: pos.x, y: pos.y }, color: { r: settings.color.r, g: settings.color.g, b: settings.color.b, a: settings.color.a }, rotation: Math.random() * 6.28319, scale: { x: Math.random() * (settings.scaleMax.x - settings.scaleMin.x) + settings.scaleMin.x, y: Math.random() * (settings.scaleMax.y - settings.scaleMin.y) + settings.scaleMin.y}, vel: { x: Math.random() * (settings.maxVel.x - settings.minVel.x) + settings.minVel.x, y: Math.random() * (settings.maxVel.y - settings.minVel.y) + settings.minVel.y }, life: Math.random() * (settings.maxLife - settings.minLife) + settings.minLife, rotVel: Math.random() * (settings.maxRotVel - settings.minRotVel) + settings.minRotVel, scaleVel: { x: scaleX, y: scaleX }, colorVel: { r: Math.random() * (settings.maxColorVel.r - settings.minColorVel.r) + settings.minColorVel.r, g: Math.random() * (settings.maxColorVel.g - settings.minColorVel.g) + settings.minColorVel.g, b: Math.random() * (settings.maxColorVel.b - settings.minColorVel.b) + settings.minColorVel.b, a: Math.random() * (settings.maxColorVel.a - settings.minColorVel.a) + settings.minColorVel.a} } particles.push(obj) } } function loadTexture(image) { let texture = gl.createTexture() gl.bindTexture(gl.TEXTURE_2D, texture) gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true) gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image) gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST) gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST) return texture } function getShader(tieblan, type) { let shader = gl.createShader(type === "fragment" ? gl.FRAGMENT_SHADER : gl.VERTEX_SHADER) gl.shaderSource(shader, tieblan) gl.compileShader(shader) if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { alert(gl.getShaderInfoLog(shader)) return null } return shader } canvas.onmousedown = () => ismousedown = true canvas.onmouseup = () => ismousedown = false canvas.onmousemove = (e) => mousePos = { x: e.clientX / canvas.width * 2 - 1, y: e.clientY / canvas.height * 2 - 1 } vertexShader = getShader(vertexShader, "daniklox") fragmentShader = getShader(fragmentShader, "fragment") let samplerUniform let shaderProgram let lightUniform function initShaders() { shaderProgram = gl.createProgram() gl.attachShader(shaderProgram, vertexShader) gl.attachShader(shaderProgram, fragmentShader) gl.linkProgram(shaderProgram) if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) { alert("Could not initialise shaders") } gl.useProgram(shaderProgram) let vertexPositionAttribute = gl.getAttribLocation(shaderProgram, "a_position") gl.enableVertexAttribArray(vertexPositionAttribute) let texturePositionAttribute = gl.getAttribLocation(shaderProgram, "a_texcoord") gl.enableVertexAttribArray(texturePositionAttribute) gl.bindBuffer(gl.ARRAY_BUFFER, buffer) gl.vertexAttribPointer(vertexPositionAttribute, 2, gl.FLOAT, false, 16, 0) gl.vertexAttribPointer(texturePositionAttribute, 2, gl.FLOAT, false, 16, 8) samplerUniform = gl.getUniformLocation(shaderProgram, "u_texture") lightUniform = gl.getUniformLocation(shaderProgram, "u_light") gl.uniform1i(samplerUniform, 0) } function createBuffer() { vertices = [ 1.0, 1.0, 1.0, 1.0, -1.0, 1.0, 0.0, 1.0, 1.0, -1.0, 1.0, 0.0, -1.0, -1.0, 0.0, 0.0 ] buffer = gl.createBuffer() gl.bindBuffer(gl.ARRAY_BUFFER, buffer) gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW) } let c = 0 function draw(color) { gl.viewport(0, 0, canvas.width, canvas.height) gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT) gl.clearColor(0, 0, 0, 1) gl.blendFunc(gl.SRC_ALPHA, gl.ONE) gl.enable(gl.BLEND) if(ismousedown === true){ addParticles(mousePos, settingsFlame) addParticles({ x: mousePos.x, y: mousePos.y - 0.06}, settingsSmoke) } gl.activeTexture(gl.TEXTURE0) gl.bindTexture(gl.TEXTURE_2D, texture) let pMatrixUniform = gl.getUniformLocation(shaderProgram, "u_matrix") for (let i = 0; i < particles.length; i++) { let p = particles[i] let wMatrix = multMat3(createRotMat3(p.rotation), createScaleMat3({ x: p.scale.x, y: p.scale.y })) wMatrix = multMat3(wMatrix, createPosMat3({ x: p.pos.x, y: p.pos.y })) gl.uniformMatrix3fv(pMatrixUniform, false, new Float32Array(wMatrix)) gl.uniform1i(samplerUniform, 0) gl.uniform4f(lightUniform, p.color.r, p.color.g, p.color.b, p.color.a) gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4) //update p.pos.x += p.vel.x p.pos.y -= p.vel.y p.rotation += p.rotVel p.scale.x += p.scaleVel.x p.scale.y += p.scaleVel.y p.life -= 16 p.color.a += p.colorVel.a p.color.r += p.colorVel.r p.color.g += p.colorVel.g p.color.b += p.colorVel.b if(p.life <= 0){ particles.splice(i, 1) } } } createBuffer() initShaders() setInterval(draw, 16, { r: 1, g: 0, b: 0, a: 1 })
// USER LOGIN, REGISTER, LOADING export const USER_LOADING = 'USER_LOADING'; export const USER_LOADED = 'USER_LOADED'; export const AUTH_ERROR = 'AUTH_ERROR'; export const LOGIN_SUCCESS = 'LOGIN_SUCCESS'; export const LOGIN_FAIL = 'LOGIN_FAIL'; export const LOGOUT_SUCCESS = 'LOGOUT_SUCCESS'; export const LOGOUT_FAIL = 'LOGOUT_FAIL'; export const REGISTER_SUCCESS = 'REGISTER_SUCCESS'; export const REGISTER_FAIL = 'REGISTER_FAIL'; // ERRORS & SUCCESS GETTER AND CLEARERS export const GET_ERRORS = 'GET_ERRORS'; export const CLEAR_ERRORS = 'CLEAR_ERRORS'; export const GET_SUCCESS = 'GET_SUCCESS'; export const CLEAR_SUCCESS = 'CLEAR_SUCCESS'; // EMAIL CONFIRMATION export const CONFIRMATION_SUCCESS = 'CONFIRMATION_SUCCESS'; export const CONFIRMATION_FAIL = 'CONFIRMATION_FAIL'; // FORGOT & RESET PASSWORD export const FORGOT_PASSWORD_SUCCESS = 'FORGOT_PASSWORD_SUCCESS'; export const FORGOT_PASSWORD_FAIL = 'FORGOT_PASSWORD_FAIL'; export const RESET_PASSWORD_SUCCESS = 'RESET_PASSWORD_SUCCESS'; export const RESET_PASSWORD_FAIL = 'RESET_PASSWORD_FAIL'; // DASHBOARD export const DASHBOARD_LOADING = 'DASHBOARD_LOADING'; export const DASHBOARD_LOADED = 'DASHBOARD_LOADED'; // DOGS export const GET_DOGS = 'GET_DOGS'; export const ADD_DOG = 'ADD_DOG'; export const ADD_DOG_FAIL = 'ADD_DOG_FAIL'; export const DELETE_DOG = 'DELETE_DOG'; export const DELETE_DOG_FAIL = 'DELETE_DOG_FAIL'; export const DOGS_LOADING = 'DOGS_LOADING'; export const DOGS_LOADING_FAIL = 'DOGS_LOADING_FAIL'; // FAMILY export const REGISTER_FAMILY_SUCCESS = 'REGISTER_FAMILY_SUCCESS'; export const REGISTER_FAMILY_FAIL = 'REGISTER_FAMILY_FAIL'; export const LEAVE_FAMILY_SUCCESS = 'LEAVE_FAMILY_SUCCESS'; export const LEAVE_FAMILY_FAIL = 'LEAVE_FAMILY_FAIL'; export const INVITE_TO_FAMILY_SUCCESS = 'INVITE_TO_FAMILY_SUCCESS'; export const INVITE_TO_FAMILY_FAIL = 'INVITE_TO_FAMILY_FAIL'; export const HAS_FAMILY = 'HAS_FAMILY'; export const FAMILY_JOIN_SUCCESS = 'FAMILY_JOIN_SUCCESS'; export const FAMILY_JOIN_FAIL = 'FAMILY_JOIN_FAIL'; // WALKS export const WALKS_LOADING = 'WALKS_LOADING'; export const INITIAL_WALKS = 'INITIAL_WALKS'; export const ADD_WALK = 'ADD_WALK'; export const ADD_WALK_FAIL = 'ADD_WALK_FAIL'; export const DELETE_WALK = 'DELETE_WALK'; export const DELETE_WALK_FAIL = 'DELETE_WALK_FAIL';
besgamApp .controller('newsletter', function( $scope, $http, $route, $log, vcRecaptchaService ) { $scope.email = $route.current.params.email; $scope.response = null; $scope.widgetId = null; $scope.model = { key: '6LfuiAgTAAAAABTVAVcs1h1SEtBNTnhAT1gHi3uv' }; $scope.setResponse = function (response) { console.info('Response available'); $scope.response = response; }; $scope.setWidgetId = function (widgetId) { console.info('Created widget ID: %s', widgetId); $scope.widgetId = widgetId; }; $scope.submit = function(form) { /* Inicializamos valores del formulario */ form.captcha.$setValidity('recaptcha', true); form.email.$setValidity('recurrent', true); form.email.$setValidity('unexpected', true); form.email.$setValidity('sessionko', true); /* Controlamos el CaptCha */ if( !$scope.response || form.$error.recaptcha ) form.captcha.$setValidity('recaptcha', false); /* Comprobamos errores */ $scope.$broadcast('validate-form', form.$name ); /* Controlamos la validación del formulario */ if (form.$invalid) return; /* Configuración del envío */ var params = { method: 'POST', url: 'php/newsletter.php', headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' }, data: 'email='+this.email+'&resp='+$scope.response } /* Llamada al modelo */ $http( params ) .success(function(data, status, headers, params) { /* Si nos devuelve un error */ if( data.error || !angular.isDefined( data.error ) ) { /* Dependiendo de la respuesta damos el error */ switch(data.type) { case 'ALREADY-EXISTS': // El email ya ha sido registrado form.email.$setValidity('recurrent', false); break; case 'CAPTCHA-KO': // La respuesta del Captcha no es correcta. form.captcha.$setValidity('recaptcha', false); break; case 'SESSION-KO': // Solo se permite 1 inscripción por sesión form.email.$setValidity('sessionko', false); break; default: // Error por defecto form.email.$setValidity('unexpected', false); } /* Reiniciamos el captCha */ $scope.response = null; vcRecaptchaService.reload(0); /* Creamos los mensajes de error */ $scope.$broadcast('validate-form', form.$name ); } else $scope.respOK = true; /* Recogamos el error, si el estatus no es OK */ if (status != 200) $log.error(data); }) .error(function(data, status, headers, config) { $log.error(data); }); }; $scope.back = function() { $scope.send = 0; }; /* Envio de parametros en un formulario */ var param = function(data) { var returnString = ''; for (d in data) { if (data.hasOwnProperty(d)) returnString += d + '=' + data[d] + '&'; } // Remove last ampersand and return return returnString.slice( 0, returnString.length - 1 ); }; });
import React, { Component } from 'react' import Yearselect from './comp/Yearselect' import Monthselect from './comp/Monthselect' const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] const isEventValid = state => ( state.nazwa.length > 5 && state.dzien.length > 0 && state.miesiac.length > 0 && state.rok.length > 3 && !isNaN(state.dzien) && !isNaN(state.miesiac) && !isNaN(state.rok) ) class App extends Component { state = { today: new Date(), cday: new Date().getDate(), cmonth: new Date().getMonth(), cyear: new Date().getFullYear(), isAddingOpen: false, nazwa: '', opis: '', dzien: '', miesiac: '', rok: '', nazwaError: false, dzienError: false, miesiacError: false, rokError: false, dateError: false, events: [] } componentDidMount() { this.gettingPosts() } checkSoonEvents = () => { let lisy = document.querySelectorAll('.events-list ul li') lisy.forEach( item => { /* if ((new Date(2019, parseInt(months.indexOf(item.innerText.substr(3,3))), parseInt(item.innerText.substr(0,1))).getTime() - new Date().getTime())/(1000*60*60*24) <= 0 ) { item && item.parentElement.removeChild(item) } */ if ((new Date(2019, parseInt(months.indexOf(item.innerText.substr(3,3))), parseInt(item.innerText.substr(0,1))).getTime() - new Date().getTime())/(1000*60*60*24) < 2 ) { item.classList.add('pretty-soon') } }) } checkPastedEvent = () => { if (new Date(this.state.cyear, this.state.cmonth, this.state.cday).getTime() > new Date(this.state.rok, this.state.miesiac, this.state.dzien)) { this.setState({ dateError: true }) } } gettingPosts = () => { fetch('http://localhost:3005/eventy', { method: 'GET' }) .then(response => response.json()) .then(json => { let newjson = json.filter( item => { new Date }) this.setState({ events: json }) this.checkSoonEvents() this.showCalendar(this.state.cmonth, this.state.cyear) }) } showCalendar = (month, year) => { let selectyear = document.getElementById("year") let selectmonth = document.getElementById("month") let tableBody = document.getElementById('calendar-body') let daysInMonth = 32 - new Date(year, month).getDate() let firstDay = new Date(year, month).getDay() tableBody.innerHTML = '' selectyear.value = year selectmonth.value = month let date = 1 for (let i = 0; i < 6; i++) { let row = document.createElement('tr') for (let j = 0; j < 7; j++) { if (date > daysInMonth) { break } else if (i === 0 && j < firstDay) { let cell = document.createElement('td') row.appendChild(cell) } else { let cell = document.createElement('td') if (date === this.state.today.getDate() && year === new Date().getFullYear() && month === new Date().getMonth()) { cell.classList.add('activeDay') } this.state.events.forEach( item => { if (parseInt(item.dzien) === date && parseInt(item.miesiac) === month && parseInt(item.rok) === year) { cell.classList.add('eventDay') cell.dataset.info = item.nazwa /* let newele = document.createElement('div') newele.innerText = cell.dataset.info newele.setAttribute("style", "position: absolute; width: 5rem; height: 5rem; background: black; top: -5rem; left: -5rem") console.log('newele', newele) cell.appendChild(newele) */ } }) cell.innerText = date row.appendChild(cell) date++ } } tableBody.appendChild(row) } } next = () => { this.state.cmonth === 11 ? this.setState({ cyear: this.state.cyear + 1, cmonth: 0 }, () => { this.showCalendar(this.state.cmonth, this.state.cyear) }) : this.setState({ cmonth: this.state.cmonth + 1 }, () => { this.showCalendar(this.state.cmonth, this.state.cyear) }) } previous = () => { this.state.cmonth === 0 ? this.setState({ cyear: this.state.cyear - 1, cmonth: 11 }, () => { this.showCalendar(this.state.cmonth, this.state.cyear) }) : this.setState({ cmonth: this.state.cmonth - 1 }, () => { this.showCalendar(this.state.cmonth, this.state.cyear) }) } jump = () => { let selectyear = document.getElementById("year").value let selectmonth = document.getElementById("month").value this.setState({ cmonth: parseInt(selectmonth), cyear: parseInt(selectyear) }, () => { this.showCalendar(this.state.cmonth, this.state.cyear) }) } handleFormChange = e => { let name = e.target.name let value = e.target.value this.checkPastedEvent() this.setState({ [name]: value }) if (name === 'nazwa' && value.length > 5) { this.setState({ nazwaError: false }) } if (name === 'dzien' && value.length > 0 && !isNaN(value)) { this.setState({ dzienError: false }) } if (name === 'miesiac' && value.length > 0 && !isNaN(value)) { this.setState({ miesiacError: false }) } if (name === 'rok' && value.length > 3 && !isNaN(value)) { this.setState({ rokError: false }) } } handleFormSubmit = e => { e.preventDefault() let obj = { nazwa: this.state.nazwa, opis: this.state.opis, dzien: this.state.dzien, miesiac: this.state.miesiac-1, rok: this.state.rok } this.setState({ events: this.state.events.push({ nazwa: this.state.nazwa, opis: this.state.opis, dzien: this.state.dzien, miesiac: this.state.miesiac-1, rok: this.state.rok }) }) this.postingEvents(obj) this.setState({ nazwa: '', opis: '', dzien: '', miesiac: '', rok: '' }) } postingEvents = events => { fetch('http://localhost:3005/eventy', { headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, method: 'POST', body: JSON.stringify(events) }) .then(response => response.json()) .then(json => { console.log(json) this.gettingPosts() }) } showMe = e => { //document.querySelectorAll('.hidden-content').forEach( item => { // item.classList.remove('slide-down') //}) e.target.nextSibling.nextSibling.classList.toggle('slide-up') e.target.nextSibling.nextSibling.classList.toggle('slide-down') } removeEvent = id => { fetch(`http://localhost:3005/eventy/${id}`, { method: 'DELETE' }) let events = this.state.events.filter(item => item.id !== id) this.setState({ events }) } handleBlur = e => { const { name } = e.target if (name === 'nazwa') { this.setState({ nazwaError: this.state.nazwa.length < 6 }) } if (name === 'dzien') { this.setState({ dzienError: this.state.dzien.length < 1 }) } if (name === 'miesiac') { this.setState({ miesiacError: this.state.miesiac.length < 1 }) } if (name === 'rok') { this.setState({ rokError: this.state.rok.length < 4 }) } } movetohead = () => { this.showCalendar(new Date().getMonth(), new Date().getFullYear()) this.setState({ cmonth: new Date().getMonth(), cyear: new Date().getFullYear() }) } render() { const { isAddingOpen, nazwa, opis, dzien, miesiac, rok, events, cday, cmonth, cyear, dzienError, miesiacError, rokError, nazwaError, dateError } = this.state let eve if (events.length) { eve = events.sort((a, b) => new Date(a.rok, a.miesiac, a.dzien) - new Date(b.rok, b.miesiac, b.dzien)).map(item => { return <li key={item.id}> <div className='event-name' onClick={this.showMe}>{item.dzien}. {months[item.miesiac]} {item.rok === cyear && item.rok} - {item.nazwa}</div><div className='mrx' onClick={() => this.removeEvent(item.id)}><i class="fas fa-times"></i></div> <div className='hidden-content slide-up'>{item.opis || 'Brak opisu'}</div> </li> }) } else { eve = 'Brak informacji' } let enabled = isEventValid(this.state) && dateError return ( <div className="container"> <div className='events-list'> <span className='events-header'>Zbliżające się wydarzenia</span> <ul>{eve}</ul> </div> <div className="card"> <h3 onClick={this.movetohead}className="card-header" id="monthAndYear">{months[cmonth]} {cmonth === new Date().getMonth() && cday + ','} {cyear}</h3> <table className="table" id="calendar"> <thead> <tr> <th>Sun</th> <th>Mon</th> <th>Tue</th> <th>Wed</th> <th>Thu</th> <th>Fri</th> <th>Sat</th> </tr> </thead> <tbody id="calendar-body"> </tbody> </table> <div className="form-inline"> <button className="btn" id="previous" onClick={this.previous}>{'<< Previous'}</button> <button className="btn" id="next" onClick={this.next}>{'Next >>'}</button> </div> <form className="form-inline2"> <label htmlFor="month">Jump To:&nbsp;&nbsp;&nbsp;</label> <Monthselect jump={this.jump} /> <Yearselect jump={this.jump} /> </form> <button className='add-btn' onClick={() => this.setState({ isAddingOpen: !isAddingOpen })}>Wydarzenie</button> {isAddingOpen && ( <form className='event-form' onSubmit={this.handleFormSubmit}> <input type='text' placeholder='Nazwa wydarzenia' name='nazwa' onChange={this.handleFormChange} onBlur={this.handleBlur} value={nazwa} /> {nazwaError && <p> Nazwa nie może być pustym ciągiem znaków </p>} <input type='text' placeholder='Opis wydarzenia' name='opis' onChange={this.handleFormChange} onBlur={this.handleBlur} value={opis} /> <input type='text' placeholder='Dzień miesiąca' name='dzien' onChange={this.handleFormChange} onBlur={this.handleBlur} value={dzien} /> {dzienError && <p> Podaj prawidłowy dzień miesiąca </p>} <input type='text' placeholder='Miesiąc' name='miesiac' onChange={this.handleFormChange} onBlur={this.handleBlur} value={miesiac} /> {miesiacError && <p> Podaj prawidłową liczbę oznaczającą miesiąc </p>} <input type='text' placeholder='Rok' name='rok' onChange={this.handleFormChange} onBlur={this.handleBlur} value={rok} /> {rokError && <p> Podaj 4 cyfrową liczbę reprezentującą rok. Liczba nie może by mnniejsza od {cyear} </p>} <button className='add-btn extradisabled' disabled={!enabled}>Dodaj</button> </form>)} </div> </div> ) } } export default App
import { Container, Row, Col } from 'react-bootstrap'; import '../styles/portifolio.css'; import '../styles/images-portifolio.css'; import { useState, useEffect } from 'react'; import { fs } from '../../../../config/firebase.js' import { PortifolioItemMain } from './portifolio-main-item.js'; import { motion } from "framer-motion"; import '../styles/clouds.css'; const Portifolio = () => { //Vetores de itens da Coluna 1 e Coluna 2 const [items, setitems] = useState([]); const [itemsCol1, setitemsCol1] = useState([]); const [itemsCol2, setitemsCol2] = useState([]); //Atualização dinâmicas de itens da coluna com base em lista do firebase useEffect(() => { //Busca a snapshot da coleção 'Portifolio-item' fs.collection('Portifolio-item').onSnapshot(snapshot => { const newItem = // Variável com vetor de itens do map seguinte: snapshot.docs.map((doc) => ({ //Faz um map na lista de documentos da seleção ID: doc.id, ...doc.data(), })); newItem.map((individualItem) => { //Faz um map no vetor de itens do newItem setitems((prevState) => [...prevState, individualItem]); if (individualItem.checkCol === 'col1') { //Verifica qual coluna pertence o item setitemsCol1((prevState) => [...prevState, individualItem]); } else { setitemsCol2((prevState) => [...prevState, individualItem]); } }) }) }, []) const variants = { hidden: { opacity: 0 }, enter: { opacity: 1 }, exit: { opacity: 0 }, } return ( <Container fluid> <Row className="first-section-detail-main"> <Col className="first-col-detail"> <motion.div variants={variants} // Pass the variant object into Framer Motion initial="hidden" // Set the initial state to variants.hidden animate="enter" // Animated state to variants.enter exit="exit" // Exit state (used later) to variants.exit transition={{ type: "spring", stiffness: 150 }}> <h1 className="first-col-detail-main">Portfólio</h1> <h4 className="first-col-detail-desc">Seja bem vindo(a) ao meu portfólio! Aqui você encontrará os mais recentes trabalhos feitos com muito carinho por mim. Espero que goste e que tenha uma boa experiência! ;)</h4> </motion.div> </Col> </Row> <Row id="linha-fotos"> {/*Linha de referência para a commentSection*/} <Col className="coluna"> {/*O vetor de itens da coluna 1 é maior que 0? Se sim, renderiza os itens presente nele*/} {itemsCol1.length > 0 && ( <PortifolioItemMain items={itemsCol1} /> )} {itemsCol1.length < 1 && ( <div className='container-fluid'>Por favor, espere....</div> )} </Col> <Col className="coluna coluna-dois"> {/*O vetor de itens da coluna 2 é maior que 0? Se sim, renderiza os itens presente nele*/} {itemsCol2.length > 0 && ( <PortifolioItemMain items={itemsCol2} /> )} {itemsCol2.length < 1 && ( <div className='container-fluid'>Por favor, espere....</div> )} </Col> </Row> <Row id="linha-fotos-mobile"> <Col className="coluna"> {/*O vetor de itens da coluna 2 é maior que 0? Se sim, renderiza os itens presente nele*/} {items.length > 0 && ( <PortifolioItemMain items={items} /> )} {items.length < 1 && ( <div className='container-fluid'>Por favor, espere....</div> )} </Col> </Row> </Container> ) } export default Portifolio;
import React, { Component } from "react"; import callAPI from "./../util/callAPI"; class TaskForm extends Component { constructor(props) { super(props); this.state = { name: "", status: false, price: "" }; } handleChange = e => { var target = e.target; var name = target.name; var value = target.type === "checkbox" ? target.checked : target.value; this.setState({ [name]: value }); }; componentDidMount() { var { match } = this.props; if (match) { callAPI(`products/${match.params.id}`, "GET", null).then(res => { var data = res.data; this.setState({ name: data.name, id: data.id, status: data.status, price: data.price }); console.log(this.state); }); } } handleSubmit = e => { e.preventDefault(); var { history } = this.props; var id = this.state.id; if (id) { callAPI(`products/${id}`, "PUT", { name: this.state.name, price: this.state.price, status: this.state.status }).then(res => { history.goBack(); }); } else { callAPI("products", "POST", { name: this.state.name, price: this.state.price, status: this.state.status }).then(res => { history.goBack(); }); } }; render() { return ( <form onSubmit={this.handleSubmit}> <label>Name Product: </label> <input type="text" placeholder="Enter your name product" className="form-control" name="name" value={this.state.name} onChange={this.handleChange} /> <label>Price: </label> <input type="text" placeholder="Enter price" className="form-control" name="price" value={this.state.price} onChange={this.handleChange} /> <label>Status</label> <br /> <label> <input type="checkbox" name="status" onChange={this.handleChange} checked={this.state.status} />{" "} Còn hàng </label> <br /> <button className="btn btn-primary" type="submit"> <i className="fa fa-plus" /> Add Product </button> </form> ); } } export default TaskForm;
const MOCK_SERVER = require('../mocks/mock_server'); let mud; describe('Testing: AGGIE BEHAVIOR', () => { let combatLoop; let cmdLoop; let mockPlayer; let wolf; let wolf2; let wolfRoom; let mockPlayerRoom; let mockPlayerArea; let server; beforeEach((done) => { mud = new MOCK_SERVER(() => { server = mud.server; mud.createNewEntity((playerModel) => { mud.createNewEntity((wolfModel) => { mud.createNewEntity((wolf2Model) => { mockPlayer = playerModel; mockPlayer.refId = 'unit-test-player' mockPlayer.area = 'midgaard'; mockPlayer.originatingArea = mockPlayer.area; mockPlayer.roomid = '1'; mockPlayer.isPlayer = true; mockPlayer.level = 1; mockPlayer.name = 'Bilbo'; mockPlayer.displayName = 'Bilbo'; mockPlayer.combatName = 'Bilbo'; mockPlayer.chp = 100; wolf = wolfModel; wolf.area = 'midgaard'; wolf.originatingArea = mockPlayer.area; wolf.roomid = '2'; // north of player wolf.level = 1; wolf.isPlayer = false; wolf.name = 'wolf'; wolf.displayName = 'Wolf'; wolf.combatName = 'Wolf'; wolf.refId = 'wolf-refid'; wolf.cmv = 100; wolf.mv = 100; wolf.hp = 100; wolf.chp = 1; wolf.refId = 'b'; wolf2 = wolf2Model; wolf2.area = 'midgaard'; wolf2.originatingArea = mockPlayer.area; wolf2.roomid = '2'; // north of player wolf2.level = 1; wolf2.isPlayer = false; wolf2.name = 'wolf2'; wolf2.combatName = 'Wolf2'; wolf2.displayName = 'Wolf2'; wolf2.refId = 'wolf2-refid'; wolf2.cmv = 100; wolf2.mv = 100; wolf2.hp = 100; wolf2.chp = 1; wolf2.refId = 'a'; mockPlayerArea = server.world.getArea(mockPlayer.area); mockPlayerRoom = server.world.getRoomObject(mockPlayer.area, mockPlayer.roomid); mockPlayerRoom.playersInRoom.push(mockPlayer); wolfRoom = server.world.getRoomObject(wolf.area, wolf.roomid); wolfRoom.monsters = []; server.world.players.push(mockPlayer); done(); }, [{ module: 'aggie' }]); }, [{ module: 'aggie' }]); }); }, false, false); }); it('should simulate player walking into a room and being attacked by a wolf', () => { mockPlayer.hitroll = 20; // beats the default entity AC of 10 so we always hit wolfRoom.monsters.push(wolf); wolfRoom.monsters.push(wolf2); server.world.ticks.gameTime(server.world); let cmd = server.world.commands.createCommandObject({ msg: 'move north' }); server.world.addCommand(cmd, mockPlayer); // process move north server.world.ticks.gameTime(server.world); // process kill command given by the aggie behavior server.world.ticks.gameTime(server.world); expect(server.world.battles.length).toBe(1); while (wolf.fighting) { server.world.ticks.gameTime(server.world); } expect(wolf.chp).toBe(0); expect(wolfRoom.monsters.length).toBe(1); expect(server.world.battles.length).toBe(1); expect(server.world.battles[0].positions['0']).toBe(null); expect(server.world.battles[0].positions['1'].attacker.name).toBe('wolf2'); expect(server.world.battles[0].positions['1'].defender.name).toBe('Bilbo'); expect(server.world.battles[0].positions['2']).toBe(undefined); while (wolf2.fighting) { server.world.ticks.gameTime(server.world); } expect(wolf2.chp).toBe(0); expect(wolfRoom.monsters.length).toBe(0); expect(server.world.battles.length).toBe(0); }); });
function _parseUpdateResult(){ window.returnValue = xmlUpdateResult.XMLDocument.documentElement.xml; window.close(); }
// Copyright 2012 Dmitry Monin. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Unit converter. */ goog.provide('morning.ui.UnitConverter'); goog.require('goog.dom.classlist'); goog.require('goog.dom.dataset'); goog.require('goog.string'); goog.require('goog.ui.Component'); goog.require('goog.ui.Tooltip'); goog.require('morning.measure.Length'); goog.require('morning.measure.Temperature'); /** * Unit Converter * * @constructor * @param {string=} opt_unitType * @extends {goog.ui.Component} */ morning.ui.UnitConverter = function(opt_unitType) { goog.base(this); /** * Unit type * * @type {string} * @private */ this.unitType_ = opt_unitType || ''; /** * Number of decimals * * @type {number} * @private */ this.decimals_ = 0; /** * Measure converter * * @type {morning.measure.AbstractMeasure} * @private */ this.measure_ = null; /** * Tooltip component which shows switches * * @type {goog.ui.Tooltip} * @private */ this.tooltip_ = null; /** * @type {Function} * @private */ this.messageProvider_ = null; }; goog.inherits(morning.ui.UnitConverter, goog.ui.Component); /** @inheritDoc */ morning.ui.UnitConverter.prototype.createDom = function() { var domHelper = this.getDomHelper(); var el = domHelper.createDom('div', 'unit-converter'); this.decorateInternal(el); }; /** @inheritDoc */ morning.ui.UnitConverter.prototype.decorateInternal = function(el) { goog.base(this, 'decorateInternal', el); if (typeof this.messageProvider_ != 'function') { throw new Error( 'morning.ui.UnitConverter: Message provider is not specified.'); } var ds = goog.dom.dataset; var unitType = /** @type {string} */ (ds.get(el, 'unittype')) || this.unitType_; var value = parseFloat(ds.get(el, 'value')) || 0; var decimals = parseInt(ds.get(el, 'decimals'), 10) || 0; if (goog.DEBUG && !unitType) { console.warn('UnitConverter: UnitType not specified %o', el); } value = value || 0; this.unitType_ = unitType; this.decimals_ = decimals || 0; this.measure_ = this.measureFactory_(unitType); this.measure_.setValue(value, unitType); var html = [], unitTypes = this.measure_.getUnitTypes(), i = 0, cls = ''; for (; i < unitTypes.length; i++) { cls = unitTypes[i] == unitType ? 'selected' : ''; html.push('<span class="unit-type ' + cls + '" data-unittype="' + unitTypes[i] + '">' + goog.string.trim(this.messageProvider_('unit.' + unitTypes[i])) + '</span>'); } this.tooltip_ = new goog.ui.Tooltip(el); this.tooltip_.setHtml(html.join(' | ')); this.tooltip_.setShowDelayMs(300); this.tooltip_.setHideDelayMs(600); }; /** @inheritDoc */ morning.ui.UnitConverter.prototype.enterDocument = function() { goog.base(this, 'enterDocument'); this.getHandler().listen(this.tooltip_.getElement(), goog.events.EventType.CLICK, this.handleClick_); }; /** * Returns current unit type * * @return {string} */ morning.ui.UnitConverter.prototype.getType = function() { return this.unitType_; }; /** * Handles click event * * @param {goog.events.BrowserEvent} e * @private */ morning.ui.UnitConverter.prototype.handleClick_ = function(e) { if (!goog.dom.classlist.contains(e.target, 'unit-type')) { return; } var ds = goog.dom.dataset; var element = /** @type {Element} */ (e.target); var unitType = /** @type {string} */ (ds.get(element, 'unittype')); this.setType(unitType); }; /** * Returns measure converter by type * * @param {string} unitType * @private * @return {morning.measure.AbstractMeasure} */ morning.ui.UnitConverter.prototype.measureFactory_ = function(unitType) { switch (unitType) { case 'km': case 'mile': return new morning.measure.Length(); case 'celcius': case 'fahrenheit': return new morning.measure.Temperature(); } return null; }; /** * Sets message provider method * * @param {Function} messageProvider function(msg) {return translatedMsg;} */ morning.ui.UnitConverter.prototype.setMessageProvider = function(messageProvider) { this.messageProvider_ = messageProvider; }; /** * Sets measuring type * * @param {string} type */ morning.ui.UnitConverter.prototype.setType = function(type) { this.unitType_ = type; var value = this.measure_.getValue(this.unitType_, this.decimals_); goog.dom.dataset.set(this.getElement(), 'unittype', type); goog.dom.dataset.set(this.getElement(), 'value', String(value)); var tooltipTypes = this.tooltip_.getElement(). querySelectorAll('.unit-type'); var isActive; goog.array.forEach(tooltipTypes, function(tooltipType) { isActive = goog.dom.dataset.get(tooltipType, 'unittype') == type; goog.dom.classlist.enable(tooltipType, 'selected', isActive); }); this.setHtml_(String(value)); this.dispatchEvent({ type: morning.ui.UnitConverter.EventType.TYPE_CHANGE, unitType: type }); }; /** * Displays current value * * @param {string} value * @private */ morning.ui.UnitConverter.prototype.setHtml_ = function(value) { if (typeof this.messageProvider_ != 'function') { throw new Error('morning.ui.UnitConverter: Message provider is not specified.'); } if (!this.getElement()) { return; } this.getElement().innerHTML = value + this.messageProvider_('unit.' + this.unitType_); }; /** * Sets value * * @param {number} value * @param {string=} opt_unitType */ morning.ui.UnitConverter.prototype.setValue = function(value, opt_unitType) { opt_unitType = opt_unitType || this.unitType_; this.measure_.setValue(value, opt_unitType); var html = this.measure_.getValue(this.unitType_, this.decimals_); this.setHtml_(String(html)); }; /** * Sets visibility * * @param {boolean} isVisible */ morning.ui.UnitConverter.prototype.setVisible = function(isVisible) { goog.dom.classlist.enable(this.getElement(), 'visible', isVisible); }; morning.ui.UnitConverter.EventType = { TYPE_CHANGE: 'typechange' };
angular.module("mainModule", []) .filter("removeHtml", function(){ return function(texto){ return texto; } })
import React, { Component } from 'react'; import AddTodo from './Components/AddTodo'; import Todos from './Components/Todos'; import './App.css'; class App extends Component { constructor(props) { super(props); this.state = { todos: [ { id: 1, content: 'buy milk' }, { id: 2, content: 'play games' } ], todo: '', editItem: false, isEmpty: false } } addTodo = (todo) => { let updatedTodos = [...this.state.todos, todo]; this.setState({ todos: updatedTodos }); } editTodo = (id) => { const filteredItems = this.state.todos.filter(item => item.id !== id); const selectedItem = this.state.todos.find(item => item.id === id); this.setState({ todos: filteredItems, todo: selectedItem.content, editItem: true, isEmpty: false }); } handleClearAll = () => { this.setState({ todos: [], isEmpty: false }); }; handleChange = (e) => { this.setState({ todo: e.target.value, isEmpty: false }) } handleSubmit = (e) => { e.preventDefault(); if (this.state.todo === '') { this.setState({ isEmpty: true }); return; } let data = { id: Math.random(), content: this.state.todo } this.addTodo(data); this.setState({ todo: '', editItem: false }) } deleteTodo = (id) => { const updatedTodos = this.state.todos.filter(todo => { return todo.id !== id }); this.setState({ todos: updatedTodos, isEmpty: false }); } render() { let { todos } = this.state; return ( <div className="todo-app container"> <h1 className="center blue-text">Todo's</h1> <Todos todos={todos} onEditTodo={this.editTodo} onDeleteTodo={this.deleteTodo} isEmpty={this.state.isEmpty} /> <AddTodo onFormSubmit={this.handleSubmit} todo={this.state.todo} onInputChange={this.handleChange} editItem={this.state.editItem} /> <button className="clear-all" onClick={this.handleClearAll}>Clear All</button> </div> ) } } export default App;
import React from 'react'; class VoteSubmitted extends React.Component { render() { return( <div> <p>Your vote of {this.props.voteCast} is submitted</p> {!this.props.voteComplete && <button className="btn btn-primary" onClick={()=>{ this.props.onChangeVote()}}>Change Vote</button> } <button className="btn btn-primary" onClick={()=>{ this.props.onResetVote()}}>Reset All Votes</button> </div> ) } } VoteSubmitted.propTypes = { voteCast: React.PropTypes.string.isRequired } export default VoteSubmitted;
const { expect } = require("chai"); let WithoutZK; let withoutZK; before(async () => { WithoutZK = await ethers.getContractFactory("WithoutZK"); }); beforeEach(async () => { withoutZK = await WithoutZK.deploy(); await withoutZK.deployed(); }); describe("WithoutZK", function () { it("should process", async () => { const secret = 42; await withoutZK.process(secret); expect(await withoutZK.greet()).to.equal( "answer to the ultimate question of life, the universe, and everything", ); }); it("should be invalid when secret not equal to 42", async () => { const secret = 42; for (let i = 0; i < 100; i++) { if (i === secret) continue; await expect(withoutZK.process(i)).to.revertedWith("invalid"); } }); });
$(function() { // ヘッダーメニュー $('.menu-trigger').on('click', function() { $(this).toggleClass('active'); }); // スムーススクロール var scroll = new SmoothScroll('a[href*="#"]',{ speed: 1500, }); $('.menu').on('click',function(){ $('.menu__line').toggleClass('active'); $('.gnav').fadeToggle(); }); $('.fade').fadeIn(2000); }); $(function(){ $(window).scroll(function (){ $('.fadein').each(function(){ var elemPos = $(this).offset().top; var scroll = $(window).scrollTop(); var windowHeight = $(window).height(); if (scroll > elemPos - windowHeight + 200){ $(this).addClass('scrollin'); } }); }); });
// ================================================================================ // // Copyright: M.Nelson - technische Informatik // Die Software darf unter den Bedingungen // der APGL ( Affero Gnu Public Licence ) genutzt werden // // weblet: dbadmin/weblet/detail // ================================================================================ { var i; var str = ""; weblet.loadview(); var attr = { hinput : false, nameInput : { checktype : weblet.inChecktype.alphanum }, templateInput : { checktype : weblet.inChecktype.dir }, mysql : {} } weblet.findIO(attr); weblet.showLabel(); weblet.showids = new Array("htmlcomposeid"); weblet.titleString.add = weblet.txtGetText("#mne_lang#neues Weblet"); weblet.titleString.mod = weblet.txtGetText("#mne_lang#Weblet bearbeiten"); weblet.ok = function() { var i; var p = {}; var action; var result; if ( this.okaction == 'add' ) action = "/db/utils/table/insert.xml"; else action = "/db/utils/table/modify.xml"; p = this.addParam(p, "schema", this.initpar.schema); p = this.addParam(p, "table", 'htmlcompose'); p = this.addParam(p, "htmlcomposeidInput.old", this.obj.inputs.htmlcomposeid); p = this.addParam(p, "htmlcomposeid"); p = this.addParam(p, "name"); p = this.addParam(p, "template"); p = this.addParam(p, "custom"); MneAjaxWeblet.prototype.write.call(this, "/db/utils/connect/start.xml", {} ); result = MneAjaxWeblet.prototype.write.call(this, action, p ); if ( result != 'ok') { MneAjaxWeblet.prototype.write.call(this, "/db/utils/connect/end.xml", {rollback: "true"} ); return true; } p = {}; p = this.addParam(p, "schema", this.initpar.schema); p = this.addParam(p, "table", 'htmlcomposenames'); p = this.addParam(p, "htmlcomposeidInput.old", this.act_values.htmlcomposeid); p = this.addParam(p, "htmlcomposeidInput", this.act_values.htmlcomposeid); p = this.addParam(p, "label_en"); p = this.addParam(p, "label_de"); p = this.addParam(p, "sqlend", 1); result = MneAjaxWeblet.prototype.write.call(this, action, p ); if ( result == 'ok' ) { this.showValue(this); this.setDepends('add'); return false; } return true; } weblet.del = function() { var i; var p = {}; var result; if ( this.confirm(this.txtSprintf(this.titleString.del, this.txtFormat.call(this, this.act_values[this.titleString.delid], this.typs[this.ids[this.titleString.delid]]) ) ) != true ) return false; MneAjaxWeblet.prototype.write.call(this, "/db/utils/connect/start.xml", {} ); p = this.addParam(p, "schema", this.initpar.schema); p = this.addParam(p, "table", 'htmlcomposetabslider'); p = this.addParam(p, "htmlcomposeidInput.old", this.act_values.htmlcomposeid); result = MneAjaxWeblet.prototype.write.call(this, "/db/utils/table/delete.xml", p ); if ( result != 'ok') { MneAjaxWeblet.prototype.write.call(this, "/db/utils/connect/end.xml", {rollback: "true"} ); return true; } p.table = 'htmlcomposetabselect'; result = MneAjaxWeblet.prototype.write.call(this, "/db/utils/table/delete.xml", p ); if ( result != 'ok') { MneAjaxWeblet.prototype.write.call(this, "/db/utils/connect/end.xml", {rollback: "true"} ); return true; } p.table = 'htmlcomposetabnames'; result = MneAjaxWeblet.prototype.write.call(this, "/db/utils/table/delete.xml", p ); if ( result != 'ok') { MneAjaxWeblet.prototype.write.call(this, "/db/utils/connect/end.xml", {rollback: "true"} ); return true; } p.table = 'htmlcomposetab'; result = MneAjaxWeblet.prototype.write.call(this, "/db/utils/table/delete.xml", p ); if ( result != 'ok') { MneAjaxWeblet.prototype.write.call(this, "/db/utils/connect/end.xml", {rollback: "true"} ); return true; } p.table = 'htmlcomposenames'; result = MneAjaxWeblet.prototype.write.call(this, "/db/utils/table/delete.xml", p ); if ( result != 'ok') { MneAjaxWeblet.prototype.write.call(this, "/db/utils/connect/end.xml", {rollback: "true"} ); return true; } p.table = 'htmlcompose'; p = this.addParam(p, "sqlend", 1); result = MneAjaxWeblet.prototype.write.call(this, "/db/utils/table/delete.xml", p ); if ( result == 'ok' ) { this.add(); this.setDepends('del'); return false; } return true; } weblet.export = function() { var ajax = new MneAjaxData(this.win); var p = {}; var i; var str = ''; var mysql = this.frame.mysql.checked; var format; p = this.addParam(p, "htmlcomposeidInput.old", this.act_values.htmlcomposeid); p = this.addParam(p, "schema", this.initpar.schema); p = this.addParam(p, "sqlend", "1"); p = this.addParam(p, "table", 'htmlcompose'); p = this.addParam(p, "cols", "createdate,createuser,modifydate,modifyuser,htmlcomposeid,name,template,custom"); ajax.read("/db/utils/table/data.xml", p); for ( i = 0; i < ajax.values.length; i++ ) { if ( mysql ) format = "INSERT INTO mne_application_htmlcompose( createdate, createuser, modifydate, modifyuser, htmlcomposeid, name, template, custom) VALUES ($1, '$2', $3, '$4', '$5', '$6', '$7', $8);"; else format = "INSERT INTO mne_application.htmlcompose( createdate, createuser, modifydate, modifyuser, htmlcomposeid, name, template, custom) VALUES ($1, E'$2', $3, E'$4', E'$5', E'$6', E'$7', $8);"; str = this.txtSprintf(format, this.txtMascarade_single(ajax.values[i][0],"'", "\\'"), this.txtMascarade_single(ajax.values[i][1],"'", "\\'"), this.txtMascarade_single(ajax.values[i][2],"'", "\\'"), this.txtMascarade_single(ajax.values[i][3],"'", "\\'"), this.txtMascarade_single(ajax.values[i][4],"'", "\\'"), this.txtMascarade_single(ajax.values[i][5],"'", "\\'"), this.txtMascarade_single(ajax.values[i][6],"'", "\\'"), (ajax.values[i][7])[0] != 'f' ) + '\n'; } p.table = 'htmlcomposenames'; p.cols = "createdate,createuser,modifydate,modifyuser,htmlcomposeid,label_de,label_en"; ajax.read("/db/utils/table/data.xml", p); for ( i = 0; i < ajax.values.length; i++ ) { if ( mysql ) format = "INSERT INTO mne_application_htmlcomposenames ( createdate, createuser, modifydate, modifyuser, htmlcomposeid, label_de, label_en) VALUES ($1, '$2', $3, '$4', '$5', '$6', '$7');"; else format = "INSERT INTO mne_application.htmlcomposenames ( createdate, createuser, modifydate, modifyuser, htmlcomposeid, label_de, label_en) VALUES ($1, E'$2', $3, E'$4', E'$5', E'$6', E'$7');"; str += this.txtSprintf(format, this.txtMascarade_single(ajax.values[i][0],"'", "\\'"), this.txtMascarade_single(ajax.values[i][1],"'", "\\'"), this.txtMascarade_single(ajax.values[i][2],"'", "\\'"), this.txtMascarade_single(ajax.values[i][3],"'", "\\'"), this.txtMascarade_single(ajax.values[i][4],"'", "\\'"), this.txtMascarade_single(ajax.values[i][5],"'", "\\'"), this.txtMascarade_single(ajax.values[i][6],"'", "\\'")) + '\n'; } p.table = 'htmlcomposetab'; p.cols = "createdate,createuser,modifydate,modifyuser,htmlcomposeid,htmlcomposetabid,path,id,subposition,position,initpar,owner,depend,loadpos,ugroup,custom"; ajax.read("/db/utils/table/data.xml", p); for ( i = 0; i < ajax.values.length; i++ ) { if ( mysql ) format = "INSERT INTO mne_application_htmlcomposetab( createdate, createuser, modifydate, modifyuser, htmlcomposeid, htmlcomposetabid, path, id, subposition, position, initpar, owner, depend, loadpos, ugroup, custom) VALUES ($1, '$2', $3, '$4', '$5', '$6', '$7', '$8', '$9', $10, '$11', '$12', '$13', '$14', $15, $16);"; else format = "INSERT INTO mne_application.htmlcomposetab( createdate, createuser, modifydate, modifyuser, htmlcomposeid, htmlcomposetabid, path, id, subposition, \"position\", initpar, owner, depend, loadpos, ugroup, custom) VALUES ($1, E'$2', $3, E'$4', E'$5', E'$6', E'$7', E'$8', E'$9', $10, E'$11', E'$12', E'$13', E'$14', $15, $16);"; str += this.txtSprintf(format, this.txtMascarade_single(ajax.values[i][0],"'", "\\'"), this.txtMascarade_single(ajax.values[i][1],"'", "\\'"), this.txtMascarade_single(ajax.values[i][2],"'", "\\'"), this.txtMascarade_single(ajax.values[i][3],"'", "\\'"), this.txtMascarade_single(ajax.values[i][4],"'", "\\'"), this.txtMascarade_single(ajax.values[i][5],"'", "\\'"), this.txtMascarade_single(ajax.values[i][6],"'", "\\'"), this.txtMascarade_single(ajax.values[i][7],"'", "\\'"), this.txtMascarade_single(ajax.values[i][8],"'", "\\'"), this.txtMascarade_single(ajax.values[i][9],"'", "\\'"), this.txtMascarade_single(ajax.values[i][10],"'","\\'"), this.txtMascarade_single(ajax.values[i][11],"'","\\'"), this.txtMascarade_single(ajax.values[i][12],"'","\\'"), this.txtMascarade_single(ajax.values[i][13],"'","\\'"), this.txtMascarade_single(ajax.values[i][14],"'","\\'"), (ajax.values[i][15])[0] != 'f') + '\n'; } p.table = 'htmlcomposetabnames'; p.cols = "createdate,createuser,modifydate,modifyuser,htmlcomposeid,label_de,label_en,htmlcomposetabid,custom"; ajax.read("/db/utils/table/data.xml", p); for ( i = 0; i < ajax.values.length; i++ ) { if ( mysql ) format = "INSERT INTO mne_application_htmlcomposetabnames ( createdate, createuser, modifydate, modifyuser, htmlcomposeid, label_de, label_en, htmlcomposetabid, custom) VALUES ($1, '$2', $3, '$4', '$5', '$6', '$7', '$8', $9);"; else format = "INSERT INTO mne_application.htmlcomposetabnames ( createdate, createuser, modifydate, modifyuser, htmlcomposeid, label_de, label_en, htmlcomposetabid, custom) VALUES ($1, E'$2', $3, E'$4', E'$5', E'$6', E'$7', E'$8', $9);"; str += this.txtSprintf(format, this.txtMascarade_single(ajax.values[i][0],"'", "\\'"), this.txtMascarade_single(ajax.values[i][1],"'", "\\'"), this.txtMascarade_single(ajax.values[i][2],"'", "\\'"), this.txtMascarade_single(ajax.values[i][3],"'", "\\'"), this.txtMascarade_single(ajax.values[i][4],"'", "\\'"), this.txtMascarade_single(ajax.values[i][5],"'", "\\'"), this.txtMascarade_single(ajax.values[i][6],"'", "\\'"), this.txtMascarade_single(ajax.values[i][7],"'", "\\'"), (ajax.values[i][8])[0] != 'f') + '\n'; } p.table = 'htmlcomposetabselect'; p.cols = "createdate,createuser,modifydate,modifyuser,id,element,htmlcomposeid,htmlcomposetabid,htmlcomposetabselectid,schema,query,tab,wop,wcol,wval,scols,showcols,cols,weblet,showdynpar,custom,selval"; ajax.read("/db/utils/table/data.xml", p); for ( i = 0; i < ajax.values.length; i++ ) { if ( mysql ) format = "INSERT INTO mne_application_htmlcomposetabselect( createdate, createuser, modifydate, modifyuser, id, element, htmlcomposeid, htmlcomposetabid, htmlcomposetabselectid, schema, query, tab, wop, wcol, wval, scols, showcols, cols, weblet, showdynpar, custom, selval) VALUES ($1, '$2', $3, '$4', '$5', '$6', '$7', '$8', '$9', '$10', '$11', '$12', '$13', '$14', '$15', '$16', '$17', '$18', $19, '$20', $21, E'$22');"; else format = "INSERT INTO mne_application.htmlcomposetabselect( createdate, createuser, modifydate, modifyuser, id, element, htmlcomposeid, htmlcomposetabid, htmlcomposetabselectid, schema, query, tab, wop, wcol, wval, scols, showcols, cols, weblet, showdynpar, custom, selval) VALUES ($1, E'$2', $3, E'$4', E'$5', E'$6', E'$7', E'$8', E'$9', E'$10', E'$11', E'$12', E'$13', E'$14', E'$15', E'$16', E'$17', E'$18', E'$19', E'$20', $21, E'$22');"; str += this.txtSprintf(format, this.txtMascarade_single(ajax.values[i][0],"'", "\\'"), this.txtMascarade_single(ajax.values[i][1],"'", "\\'"), this.txtMascarade_single(ajax.values[i][2],"'", "\\'"), this.txtMascarade_single(ajax.values[i][3],"'", "\\'"), this.txtMascarade_single(ajax.values[i][4],"'", "\\'"), this.txtMascarade_single(ajax.values[i][5],"'", "\\'"), this.txtMascarade_single(ajax.values[i][6],"'", "\\'"), this.txtMascarade_single(ajax.values[i][7],"'", "\\'"), this.txtMascarade_single(ajax.values[i][8],"'", "\\'"), this.txtMascarade_single(ajax.values[i][9],"'", "\\'"), this.txtMascarade_single(ajax.values[i][10],"'","\\'"), this.txtMascarade_single(ajax.values[i][11],"'","\\'"), this.txtMascarade_single(ajax.values[i][12],"'","\\'"), this.txtMascarade_single(ajax.values[i][13],"'","\\'"), this.txtMascarade_single(ajax.values[i][14],"'","\\'"), this.txtMascarade_single(ajax.values[i][15],"'","\\'"), this.txtMascarade_single(ajax.values[i][16],"'","\\'"), this.txtMascarade_single(ajax.values[i][17],"'","\\'"), this.txtMascarade_single(ajax.values[i][18],"'","\\'"), this.txtMascarade_single(ajax.values[i][19],"'","\\'"), ajax.values[i][20], this.txtMascarade_single(ajax.values[i][21],"'","\\'") ) + '\n'; } p.table = 'htmlcomposetabslider'; p.cols = "createdate,createuser,modifydate,modifyuser,htmlcomposeid,slidername,sliderpos,custom"; ajax.read("/db/utils/table/data.xml", p); for ( i = 0; i < ajax.values.length; i++ ) { if ( mysql ) format = "INSERT INTO mne_application.htmlcomposetabslider ( createdate, createuser, modifydate, modifyuser, htmlcomposeid, slidername, sliderpos, custom) VALUES ($1, '$2', $3, '$4', '$5', '$6', '$7', $8);"; else format = "INSERT INTO mne_application.htmlcomposetabslider ( createdate, createuser, modifydate, modifyuser, htmlcomposeid, slidername, sliderpos, custom) VALUES ($1, E'$2', $3, E'$4', E'$5', E'$6', E'$7', $8);"; str += this.txtSprintf(format, this.txtMascarade_single(ajax.values[i][0],"'", "\\'"), this.txtMascarade_single(ajax.values[i][1],"'", "\\'"), this.txtMascarade_single(ajax.values[i][2],"'", "\\'"), this.txtMascarade_single(ajax.values[i][3],"'", "\\'"), this.txtMascarade_single(ajax.values[i][4],"'", "\\'"), this.txtMascarade_single(ajax.values[i][5],"'", "\\'"), this.txtMascarade_single(ajax.values[i][6],"'", "\\'"), (ajax.values[i][7])[0] != 'f') + '\n'; } var s = str.split('\n'); for ( i = (s.length - 1); i >= 0; i--) this.message(s[i], true) return false; } }
import { expect } from 'chai'; import { parseAgentAndProcess } from './queryString'; describe('queryString', () => { describe('parseAgentAndProcess', () => { it('parses the agent and process from a path', () => { [ { path: '/agent/process', expected: { agent: 'agent', process: 'process' } }, { path: '/agent/process/', expected: { agent: 'agent', process: 'process' } }, { path: '/agent/process/bar', expected: { agent: 'agent', process: 'process' } }, { path: 'agent/process', expected: { agent: 'agent', process: 'process' } }, { path: '/agent', expected: { agent: undefined, process: undefined } }, { path: '//process', expected: { agent: undefined, process: undefined } }, { path: '//', expected: { agent: undefined, process: undefined } } ].forEach(({ path, expected }) => { expect(parseAgentAndProcess(path)).to.deep.equal(expected, path); }); }); }); });
/*======================================================================= * FILE: Navigation.js * AUTHOR: Kyler Ashby * DATE: Winter 2021 * * DESCRIPTION: Navigation module (for volumes, books) * IS 542, Winter 2021, BYU. */ /*jslint browser, long, for */ /*-------------------------------------------------------------- * IMPORTS */ import {books} from "./MapScripApi.js"; import {volumes} from "./MapScripApi.js"; import Api from "./MapScripApi.js"; import Html from "./HtmlHelper.js"; import injectBreadcrumbs from "./Breadcrumbs.js"; import MapHelper from "./MapHelper.js"; import navigateChapter from "./Chapter.js"; /*-------------------------------------------------------------- * CONSTANTS */ const BOTTOM_PADDING = "<br /><br />"; const CLASS_BOOKS = "books"; const CLASS_BUTTON = "btn"; const CLASS_CHAPTER = "chapter"; const CLASS_VOLUME = "volume"; const DIV_SCRIPTURES = "scriptures"; const DIV_SCRIPTURES_NAVIGATOR = "scripnav"; const TAG_HEADER5 = "h5"; /*-------------------------------------------------------------- * PRIVATE VARIABLES */ /*-------------------------------------------------------------- * PRIVATE METHODS */ const bookChapterValid = function (bookId, chapter) { let book = books[bookId]; if (book === undefined || chapter < 0 || chapter > book.numChapters) { return false; } if (chapter === 0 && book.numChapters > 0) { return false; } return true; }; const booksGrid = function (volume) { return Html.div({ classKey: CLASS_BOOKS, content: booksGridContent(volume) }); }; const booksGridContent = function (volume) { let gridContent = ""; volume.books.forEach(function (book) { gridContent += Html.link({ classKey: CLASS_BUTTON, id: book.id, href: `#${volume.id}:${book.id}`, content: book.gridName }); }); return gridContent; }; const chaptersGrid = function (book) { return Html.div({ classKey: CLASS_VOLUME, content: Html.element(TAG_HEADER5, book.fullName) }) + Html.div({ classKey: CLASS_BOOKS, content: chaptersGridContent(book) }); }; const chaptersGridContent = function (book) { let gridContent = ""; let chapter = 1; while (chapter <= book.numChapters) { gridContent += Html.link({ classKey: `${CLASS_BUTTON} ${CLASS_CHAPTER}`, id: chapter, href: `#${book.parentBookId}:${book.id}:${chapter}`, content: chapter }); chapter += 1; } return gridContent; }; const changeHash = function (volumeId, bookId, chapterId) { window.location.hash = `#${( volumeId === undefined ? "" : volumeId )}${( bookId === undefined ? "" : ":" + bookId )}${( chapterId === undefined ? "" : ":" + chapterId )}`; }; const navigateBook = function (bookId) { MapHelper.clearMarkers(); let book = books[bookId]; if (book.numChapters <= 1) { navigateChapter(bookId, book.numChapters); } else { document.getElementById(DIV_SCRIPTURES).innerHTML = Html.div({ id: DIV_SCRIPTURES_NAVIGATOR, content: chaptersGrid(book) }); injectBreadcrumbs(Api.volumeForId(book.parentBookId), book); } }; const navigateHome = function (volumeId) { document.getElementById(DIV_SCRIPTURES).innerHTML = Html.div({ id: DIV_SCRIPTURES_NAVIGATOR, content: volumesGridContent(volumeId) }); injectBreadcrumbs(Api.volumeForId(volumeId)); }; const onHashChanged = function () { // homeVolumeChapterButtons(); let ids = []; if (location.hash !== "" && location.hash.length > 1) { ids = location.hash.slice(1).split(":"); } if (ids.length <= 0) { navigateHome(); } else if (ids.length === 1) { let volumeId = Number(ids[0]); if (volumeId < volumes[0].id || volumeId > volumes.slice(-1)[0].id) { navigateHome(); } else { navigateHome(volumeId); } } else { let bookId = Number(ids[1]); if (books[bookId] === undefined) { navigateHome(); } else { if (ids.length === 2) { navigateBook(bookId); } else { let chapter = Number(ids[2]); if (bookChapterValid(bookId, chapter)) { navigateChapter(bookId, chapter); } else { navigateHome(); } } } } }; const volumesGridContent = function (volumeId) { let gridContent = ""; volumes.forEach(function (volume) { if (volumeId === undefined || volumeId === volume.id) { gridContent += Html.div({ classKey: CLASS_VOLUME, content: Html.anchor(volume) + Html.element(TAG_HEADER5, volume.fullName) }); gridContent += booksGrid(volume); } }); return gridContent + BOTTOM_PADDING; }; /*-------------------------------------------------------------- * PUBLIC API */ const Navigation = { onHashChanged, changeHash }; export default Object.freeze(Navigation);
const GET_PRICE = "transactions/GET_PRICE"; export const BUY_STOCK = "transactions/BUY_STOCK"; const getPrice = (transactionPriceDict) => ({ type: GET_PRICE, transactionPriceDict }); const buyStock = (transaction) => ({ type: BUY_STOCK, payload: transaction }) export const getPriceShares = (ticker_symbol) => async (dispatch) => { const res = await fetch(`/api/transactions/${ticker_symbol}`); if (res.ok) { let data = await res.json(); dispatch(getPrice(data)); } }; export const stockTransaction = (data, ticker_symbol) => async (dispatch) => { const res = await fetch(`/api/transactions/${ticker_symbol}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ data, ticker_symbol }), }); if (res.ok) { const transactionInfo = await res.json(); dispatch(buyStock(transactionInfo)); dispatch(getPriceShares(ticker_symbol)); } }; let initialState = { transactionPrice: {}, transactionData: {} }; export default function reducer(state = initialState, action) { switch (action.type) { case GET_PRICE: return { ...state, transactionPrice: action.transactionPriceDict }; case BUY_STOCK: return { ...state, transactionData: action.payload } default: return state; } }
import Product from "../models/Product.js"; import ErrorResponse from "../helpers/errorResponse.js"; import asyncHandler from "../middlewares/async.js"; import slugify from "slugify"; /** * @desc Get all Products * @route GET /api/products * @route GET /api/categories/:categoryId/products /// products belongs To a Category * @access Public(No Auth) */ export const getProducts = asyncHandler(async (req, res, next) => { let query; // categoryId parametresi gönderildiyse /api/categories/:categoryId/products if (req.params.categoryId) { // Basically it means select * from products where category=categoryId query = Product.find({ category: req.params.categoryId }); } else { // eğer categoryId parametresi yoksa tüm productları çekiyoruz; // populate ile category bilgilerini alıyoruz; query = Product.find(); } const products = await query; res.status(200).json({ success: true, count: products.length, data: products, }); }); /** * @desc Get single Product * @route GET /api/products/:id * @access Public(No Auth) */ export const getProduct = asyncHandler(async (req, res, next) => { const product = await Product.findById(req.params.id); if (!product) { return next(new ErrorResponse(`Product not found`, 404)); } res.status(200).json({ success: true, data: product, }); }); /** * @desc Get Featured Products * @route GET /api/products/featured * @access Public(No Auth) */ export const getFeaturedProducts = asyncHandler(async (req, res, next) => { const featuredProducts = await Product.find({ isFeatured: true, }); res.status(200).json({ success: true, data: featuredProducts, }); }); /** * @desc Create Product * @route POST /api/products * @access Private */ export const createProduct = asyncHandler(async (req, res, next) => { const product = await Product.create(req.body); res.status(201).json({ success: true, data: product, }); }); /** * @desc Update Product * @route PUT /api/products/:id * @access Private */ export const updateProduct = asyncHandler(async (req, res, next) => { let product = await Product.findById(req.params.id); if (!product) { return next(new ErrorResponse(`Product not found`, 404)); } if (req.body.name && req.body.name != product.name) { product.slug = slugify(req.body.name, { lower: true }); product.name = req.body.name; await product.save(); } product = await Product.findByIdAndUpdate(req.params.id, req.body, { useFindAndModify: false, new: true, runValidators: true, }); res.status(200).json({ success: true, data: product, }); }); /** * @desc Delete Product * @route Delete /api/products/:id * @access Private */ export const deleteProduct = asyncHandler(async (req, res, next) => { const product = await Product.findById(req.params.id); if (!product) { return next(new ErrorResponse(`Product not found`, 404)); } product.remove(); res.status(200).json({ success: true, data: {}, }); });
var salmin = 1045 var precokw = (salmin/7)/100 var kw var rs = require('readline-sync') var kw = rs.questionInt('Quantos KWH voce gastou esse mes? ') while (kw <= 0){ var kw = rs.questionInt('Quantos KWH voce gastou esse mes? ') } kwdesc = (precokw*kw)*0.9 if (kw > 100){ console.log('Esta na media do consumo brasileiro e ira pagar RS'+kwdesc+ ' Pois tem 10% de desconto') }else { console.log('Esta acima do consumo brasileiro e ira pagar RS' +(precokw*kw)+ ' Pois nao tem 10% de desconto') }
const expect = require('expect'); const {generateMessage,generateLocationMessage } = require('./message'); describe('Generate message', () => { it('it should generate correct message object', () => { let from = 'jen'; let text = 'some message'; let message = generateMessage(from,text); expect(message.createdAt).toBeA('number'); expect(message).toInclude({ from, text, }); }); }); describe('Generate Location Message', () => { it('should generate correct location object', () => { let from = 'abhi'; let longitude = 75.123123129312; let latitude = -42.454353453453; const url = `https://www.google.com/maps?q=${latitude},${longitude}`; const message = generateLocationMessage(from,latitude,longitude); console.log(message); expect(message.createdAt).toBeA('number'); expect(message).toInclude({from,url}); }) });
var inquirer = require('inquirer'); var isLetter = require('is-letter'); var Word = require('./foodword.js'); var Game = require('./randomFood.js'); //set the maxListener require('events').EventEmitter.prototype._maxListeners = 100; var hangman = { wordBank: Game.newFood.foodList, guessesRemaining: 10, //empty array to hold letters guessed by user. And checks if the user guessed the letter already guessedLetters: [], display: 0, currentWord: null, //asks user if they are ready to play startGame: function() { var that = this; //clears guessedLetters before a new game starts if it's not already empty. if(this.guessedLetters.length > 0){ this.guessedLetters = []; } inquirer.prompt([{ message: "Ready to play?" }]) }} hangman.startGame();
import { useEffect, useState } from "react" import ContactUs from "../components/contactUs" import NavBar from "../components/navbar" const Contact = () => { return ( <> <NavBar /> <ContactUs /> </> ) } export default Contact
/* *author:秦浩 *Create date: 2009-05-19 *Description: 发货记录单表单验证 */ function ValidateInput() { // var IsAllCheck = 0; // var ddlCompanyName = $.trim($("#ddlCompanyName").val()); //物 流 公 司 // var txtGoodsOrderNO = $.trim($("#txtGoodsOrderNO").val());//发 货 单 号 // var chkBox = $("input[type='checkbox']"); //复选框集合 // // function FocusCompanyName(){$("#ddlCompanyName").focus();} // function FocusGoodsOrderNO(){$("#txtGoodsOrderNO").focus();} // // if(txtGoodsOrderNO == "") // { // $.prompt('请输入发货单号!!', {callback:FocusGoodsOrderNO}); // return false; // } // // if(ddlCompanyName == "0") // { // $.prompt('请选择物流公司!!', {callback:FocusCompanyName}); // return false; // } // // for(var i = 0; i < chkBox.length; i++) // { // if(chkBox[i].checked) // IsAllCheck ++ // } // // if(IsAllCheck == 0) // { // $.prompt('请选择POP信息!!'); // return false; // } // return true; }
app.controller("MainController",function($rootScope,$scope,$window,$location){ $rootScope.last ="Austira"; $rootScope.go = function(path){ $location.path(path); } $rootScope.back = function(){ $window.history.back(); } });
// ajax the delete button AND update graph function ajaxDelete() { // ajaxify crud functions $('.delete-form').on("submit", function(event) { event.preventDefault(); var $target = $(event.target); console.log($target); $.ajax({ url: $target.attr('action'), type: 'DELETE' }).done(function(response) { ajaxLineGraph(); ajaxPieGraph(); $target.parent().parent().hide(); }); }); } // ajax the get started button function ajaxSignup() { $('#signupButton').on("click", function(event) { event.preventDefault(); $.ajax({ url: '/signup', type: "GET" }).done(function(response) { $('.splash-head').replaceWith(response); }); }); } // grab data from db to use with graphs function ajaxLineGraph() { $.ajax({ url: "/data/line", type: "GET", dataType: 'JSON' }).done(function(response) { var r = response; var lineChartData = { labels: response['labels'], datasets: [{ strokeColor: "#27ae60", pointColor: "rgba(220,220,220,1)", pointStrokeColor: "green", data: r["data"].deadlifts }, { strokeColor: "#2980b9", pointColor: "rgba(151,187,205,1)", pointStrokeColor: "#fff", data: r["data"].squats }, { strokeColor: "#8e44ad", pointColor: "rgba(151,187,205,1)", pointStrokeColor: "#fff", data: r["data"].benchpresses }, { strokeColor: "#c0392b", pointColor: "rgba(151,187,205,1)", pointStrokeColor: "#fff", data: r["data"].overheadpresses }, { strokeColor: "#95a5a6", pointColor: "rgba(151,187,205,1)", pointStrokeColor: "#fff", data: r["data"].powercleans }] }; createLineChart(lineChartData); }); } function ajaxPieGraph() { $.ajax({ url: "/data/pie", type: "GET", dataType: 'JSON' }).done(function(response) { var r = response; var pieChartData = [{ value: r['dead lift'], color: "#27ae60" }, { value: r['squat'], color: "#2980b9" }, { value: r['bench press'], color: "#8e44ad" }, { value: r['power cleans'], color: "#c0392b" }, { value: r['overhead press'], color: "#95a5a6" }]; createPieChart(pieChartData); }); }
import { createStore, applyMiddleware, combineReducers } from 'redux'; import thunk from 'redux-thunk'; import { persistStore } from 'redux-persist'; import auth from './auth'; const rootReducer = combineReducers({ auth }); // Add the thunk middleware to our store const store = createStore(rootReducer, applyMiddleware(thunk)); //Enable persistence persistStore(store); export default store;
(function() { 'use strict'; const endpoint = 'https://api.ipify.org/?format=json'; const platformInfo = navigator.platform; const isOnline = navigator.onLine; const publicIpText = document.getElementById('public-ip'); const localIpText = document.getElementById('local-ip'); const platformText = document.getElementById('platform-info'); const connectionText = document.getElementById('connection-status'); axios.get(endpoint) .then(response => { const publicIp = response.data.ip; publicIpText.textContent = publicIp; }) .catch(error => { publicIpText.textContent = error.toString(); }); platformText.textContent = platformInfo; connectionText.textContent = isOnline ? 'Connected' : 'Disconnected'; window.RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection; const pc = new RTCPeerConnection({iceServers: []}); const noop = () => {}; pc.createDataChannel(''); pc.createOffer(pc.setLocalDescription.bind(pc), noop); pc.onicecandidate = ice => { if (!ice || !ice.candidate || !ice.candidate.candidate) return; const localIp = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/.exec(ice.candidate.candidate)[1]; localIpText.textContent = localIp; pc.onicecandidate = noop; }; })();
/** * Created by ntban_000 on 4/27/2017. */ 'use strict' const mongoose = require('mongoose'); const bcrypt = require('bcrypt-nodejs'); const Schema = mongoose.Schema; const UserSchema = new Schema({ username: { type:String, lowercase:true, required: true, unique:true }, password: { type: String, required:true }, name: { type:String, required:true }, email: { type:String, lowercase: true, required: true, unique:true }, permission: { type:String, required:true, default:'user' } }) UserSchema.pre('save',function(next){ var user = this; bcrypt.hash(user.password, null, null, function(err,hash){ if(err) return next(err); user.password = hash; next(); }) }) UserSchema.methods.comparePassword = function(password){ return bcrypt.compareSync(password,this.password); } module.exports = mongoose.model('User', UserSchema);
function Sphere() {} Sphere.prototype = { setCenter: function(vector) { this.center = vector; return this; }, setRadius: function(r) { this.radius = r; return this; }, setDiffuseMaterialColors: function(colorVec) { this.DiffMatColor = colorVec; return this; }, setAmbientMaterialColors: function(colorVec) { this.AmbientMatColor = colorVec; return this; }, setSpecularMaterialColors: function(colorVec) { this.SpecularMatColor = colorVec; return this; }, setSpecularExponent: function(exp) { this.SpecularExponent = exp; return this; }, setRefractionIndex: function(index) { this.RefractionIndex = index; return this; }, getRefractionIndex: function() { return this.RefractionIndex; }, getSpecularMaterialColors: function() { return this.SpecularMatColor; }, getSpecularExponent: function() { return this.SpecularExponent; }, getAmbientMaterialColors: function() { return this.AmbientMatColor; }, getDiffuseMaterialColors: function() { return this.DiffMatColor; }, getCenter: function() { return this.center; }, getRadius: function() { return this.radius; }, //TODO add the Specular material color and Specular exponent // Returns a copy of the sphere dup: function() { return Sphere.create(this.center,this.radius); } }; // Constructor function Sphere.create = function(center,radius) { var S = new Sphere(); S.setCenter(center); S.setRadius(radius) return S; }; // Utility functions var $S = Sphere.create;
var WorldBound = { setpos: function (x, y) { this.x = x this.y = y }, draw: function () { UFX.draw("t", this.x*100, this.y*100) }, } var Stands = { think: function (dt) { if (this.parent) { if (!this.parent.supports(this)) { this.drop() this.kjump = 1 this.y += 0.002 } } else { if (this.upward) { var d = Math.min(settings.vyup * dt, this.dup) this.y += d this.dup -= d if (this.dup == 0) { this.drop() } } else if (this.hover) { this.hover = Math.max(this.hover - dt, 0) } else { this.oldy = this.y if (this.hanging) { var a = -settings.ahang this.hanging = Math.max(this.hanging - dt, 0) } else { var a = this.ay } this.y += dt * this.vy + 0.5 * dt * dt * a this.vy += dt * a } } }, drop: function () { this.upward = false this.hover = settings.hover this.y -= 0.001 this.vy = 0 this.ay = -settings.aydown this.parent = null }, land: function (parent) { this.kjump = 0 this.parent = parent this.y = this.parent.y this.vy = 0 this.upward = false this.hover = false }, } var HasHealth = { init: function (maxhp) { this.maxhp = maxhp || 1 this.alive = true }, heal: function (dhp) { if (dhp === undefined) { this.hp = this.maxhp } else { this.hp = Math.min(this.hp + dhp, this.maxhp) } }, takedamage: function (dhp) { if (this.hp <= 0) return this.hp = Math.max(this.hp - dhp, 0) if (this.hp <= 0) { this.die() } }, die: function () { this.alive = false }, } var SplatsOnDeath = { takedamage: function () { new Splat(this.x, this.y, 1) }, } var GivesMoney = { init: function (amt) { this.amt = amt || 1 }, die: function () { playsound("pickup") state.gp += this.amt }, } var MercyInvulnerable = { takedamage: function () { this.tmercy = settings.tmercy }, think: function (dt) { this.tmercy = Math.max(this.tmercy - dt, 0) }, draw: function () { if (!this.tmercy) return UFX.draw("alpha", this.tmercy * 20 % 2 >= 1 ? 0.1 : 0.9) }, } var MovesHorizontal = { hmove: function (dx) { this.vx = (dx || 0) * settings.vx }, think: function (dt) { this.x += this.vx * dt }, } var IsSurface = { supports: function (obj) { return obj.x >= this.x && obj.x <= this.x + this.dx }, catches: function (obj) { return obj.y < this.y && obj.oldy >= this.y && this.supports(obj) }, } var MultiLeaper = { leap: function () { playsound("jump") this.kjump += 1 this.parent = null this.upward = true this.dup = settings.dup this.hanging = settings.hangtimes[state.jhang] if (state.jhang > 0) { new Slash(this.x, this.y + 0.3, settings.slashsizes[state.jhang]) } }, } var DrawLine = { init: function (color) { this.color = color || "white" }, draw: function () { var color = this.ischeck ? "yellow" : this.color UFX.draw("ss", color, "lw 8 b m 0 0 l", this.dx*100, "0 s") }, } var DrawDebugLine = { init: function (color) { this.color = color || "white" }, draw: function () { if (!DEBUG) return var color = this.ischeck ? "yellow" : this.color UFX.draw("ss", color, "lw 8 b m 0 0 l", this.dx*100, "0 s") }, } var DrawPlacable = { think: function (dt) { this.color = state.canplace(this) ? "white" : "red" }, } var FliesLissajous = { init: function (dx, dy, omegax, omegay) { this.dx = dx || 3 this.dy = dy || 1 this.omegax = omegax || 1.1 this.omegay = omegay || 1.6 }, settrack: function (x0, y0) { this.tfly = 0 this.x0 = x0 this.y0 = y0 }, think: function (dt) { this.tfly += dt this.x = this.x0 + this.dx * Math.sin(this.tfly * this.omegax) this.y = this.y0 + this.dy * Math.sin(this.tfly * this.omegay) }, } var LissajousPulses = { init: function () { this.tpulse = 0 this.dx0 = this.dx this.dy0 = this.dy }, think: function (dt) { this.tpulse += dt this.dx = (1 + 0.4 * Math.sin(2 * this.tpulse)) * this.dx0 this.dy = (1 + 0.4 * Math.cos(2 * this.tpulse)) * this.dy0 }, } var FliesToroidal = { init: function (r0, dr, omegar, omegap) { this.r0 = r0 || 1 this.dr = dr || 0.8 this.omegar = omegar || 5 this.omegap = omegap || 1 }, settrack: function (x0, y0) { this.tfly = 0 this.x0 = x0 this.y0 = y0 }, think: function (dt) { this.tfly += dt var r = this.r0 + this.dr * Math.sin(this.tfly * this.omegar) var phi = this.tfly * this.omegap this.x = this.x0 + 2 * r * Math.sin(phi) this.y = this.y0 + 0.6 * r * Math.cos(phi) }, } var FliesErratic = { init: function (dx, dy, v) { this.dx = dx || 1 this.dy = dy || 1 this.v = v || 3 }, settrack: function (x0, y0) { this.tfly = 0 this.x0 = x0 this.y0 = y0 this.x = this.x0 this.y = this.y0 }, think: function (dt) { this.tfly += dt if (!this.target) { this.target = [ this.x0 + this.dx * UFX.random(-1, 1), this.y0 + this.dy * UFX.random(-1, 1), ] } var dx = this.target[0] - this.x, dy = this.target[1] - this.y var d = Math.sqrt(dx * dx + dy * dy) if (d < this.v * dt) { this.x = this.target[0] this.y = this.target[1] this.target = null return } this.x += (this.v * dt) * dx / d this.y += (this.v * dt) * dy / d }, } var HitZone = { init: function (r) { this.r = r || 0 }, hits: function (x, y, r) { return Math.abs(x - this.x) < r + this.r && Math.abs(y - this.y) < r + this.r }, } var CheckBoss = { die: function () { state.checkbosses() }, } var WithinSector = { settrack: function (x0, y0) { var sx = Math.floor(x0 / settings.sectorsize) var sy = Math.floor(y0 / settings.sectorsize) this.sectorkey = sx + "," + sy }, } function You(x, y) { this.setpos(x, y) this.parent = null this.kjump = 999 this.drop() this.heal() } You.prototype = UFX.Thing() .addcomp(WorldBound) .addcomp(Stands) .addcomp(MultiLeaper) .addcomp(MovesHorizontal) .addcomp(HasHealth, 3) .addcomp(MercyInvulnerable) .addcomp({ draw: function () { if (state.jhang) { var a = this.upward || this.hover ? -0.9 : this.parent || this.hanging ? 0.15 : 0.8 UFX.draw("fs white [ t 0 50 r", a, "( m 0 0 l 80 0 l 40 20 ) f ]") UFX.draw("fs white [ t 0 50 r", -a, "( m 0 0 l -80 0 l -40 20 ) f ]") } UFX.draw("fs green ( m -25 0 l -15 60 l 15 60 l 25 0 ) f") }, land: function (parent) { state.lastlanding = parent if (parent.ischeck) state.savegame() }, takedamage: function () { playsound("hurt") }, }) function Platform(x, y, dx) { this.setpos(x, y) this.dx = dx state.claimtiles(this) var c = UFX.random.rand(100,120) + "," + UFX.random.rand(100,120) + "," + UFX.random.rand(100,120) this.grad = UFX.draw.lingrad(0, 0, 0, -100, 0, "rgb(" + c + ")", 1, "rgba(" + c + ",0)") } Platform.prototype = UFX.Thing() .addcomp(WorldBound) .addcomp(IsSurface) .addcomp({ draw: function () { UFX.draw("fs", this.grad, "fr 0 -100", this.dx*100, 100) }, }) .addcomp(DrawDebugLine, "#266") function VirtualPlatform(x, y, dx) { this.setpos(x, y) this.dx = dx } VirtualPlatform.prototype = UFX.Thing() .addcomp(WorldBound) .addcomp(DrawLine, "white") .addcomp(DrawPlacable) function House(x, y, name) { this.setpos(x, y) this.name = name this.r = 3 } House.prototype = UFX.Thing() .addcomp(WorldBound) .addcomp({ draw: function () { UFX.draw("fs #424 ss #848 lw 8 ( m -85 0 q -85 100 0 200 q 85 100 85 0 ) f s") UFX.draw("fs #242 ss #484 lw 8 ( m -20 0 c -20 100 -100 100 -60 180 c -50 100 50 100 60 180 c 100 100 20 100 20 0 ) f s") UFX.draw("fs #224 ss #448 lw 8 ( m -100 0 q 0 -20 100 0 q 100 15 90 30 q 0 18 -90 30 q -100 15 -100 0 ) f s") // UFX.draw("fs #026 fr -100 0 200 240") }, }) function Bat(x0, y0) { this.setpos(x0, y0) this.settrack(x0, y0) this.tfly = UFX.random(1000) this.heal() state.monsters.push(this) } Bat.prototype = UFX.Thing() .addcomp(WorldBound) .addcomp(WithinSector) .addcomp(FliesLissajous, 3, 1, 0.7, 0.4) .addcomp(HitZone, 0.2) .addcomp(HasHealth, 1) .addcomp(GivesMoney, 1) .addcomp(SplatsOnDeath) .addcomp({ draw: function () { var h = 20 * [0, 1, 0, -1][Math.floor(this.tfly * 20 % 4)] UFX.draw("ss #B00 lw 5 b m -50", h, "l 0 0 l 50", h, "s") UFX.draw("fs #700 fr -20 -20 40 40") }, }) function Zat(x0, y0) { this.setpos(x0, y0) this.settrack(x0, y0) this.tfly = UFX.random(1000) this.heal() state.monsters.push(this) } Zat.prototype = UFX.Thing() .addcomp(WorldBound) .addcomp(WithinSector) .addcomp(FliesLissajous, 5, 3, 0.7, 1.2) .addcomp(HitZone, 0.3) .addcomp(HasHealth, 1) .addcomp(GivesMoney, 2) .addcomp(SplatsOnDeath) .addcomp({ draw: function () { var h = 20 * [0, 1, 0, -1][Math.floor(this.tfly * 20 % 4)] UFX.draw("z 1.5 1.5 ss #BB0 lw 5 b m -50", h, "l 0 0 l 50", h, "s") UFX.draw("fs #770 fr -20 -20 40 40") }, }) function Wat(x0, y0) { this.setpos(x0, y0) this.settrack(x0, y0) this.tfly = UFX.random(1000) this.heal() state.monsters.push(this) } Wat.prototype = UFX.Thing() .addcomp(WorldBound) .addcomp(WithinSector) .addcomp(FliesLissajous, 5, 3, 0.7, 1.2) .addcomp(HitZone, 0.4) .addcomp(HasHealth, 1) .addcomp(GivesMoney, 3) .addcomp(SplatsOnDeath) .addcomp({ draw: function () { var h = 20 * [0, 1, 0, -1][Math.floor(this.tfly * 20 % 4)] UFX.draw("z 2 2 ss #0BB lw 5 b m -50", h, "l 0 0 l 50", h, "s") UFX.draw("fs #077 fr -20 -20 40 40") }, }) function Lance(x0, y0, tfrac) { this.setpos(x0, y0) this.settrack(x0, y0) this.tfly = tau * tfrac this.heal() state.monsters.push(this) } Lance.prototype = UFX.Thing() .addcomp(WorldBound) .addcomp(WithinSector) .addcomp(FliesLissajous, 2, 1, 1, 2) .addcomp(LissajousPulses) .addcomp(HitZone, 0.4) .addcomp(HasHealth, 1) .addcomp(SplatsOnDeath) .addcomp(CheckBoss) .addcomp({ draw: function () { UFX.draw("r", this.tfly * 5 % tau) UFX.draw("ss #B00 lw 5 b m -80 0 l 80 0 m 0 -80 l 0 80 s") UFX.draw("fs #700 fr -30 -30 60 60") }, die: function () { playsound("explosion") }, }) function Wilson(x0, y0, tfrac) { this.setpos(x0, y0) this.settrack(x0, y0) this.tfly = tau * tfrac this.heal() state.monsters.push(this) } Wilson.prototype = UFX.Thing() .addcomp(WorldBound) .addcomp(WithinSector) .addcomp(FliesToroidal) .addcomp(HitZone, 0.4) .addcomp(HasHealth, 1) .addcomp(SplatsOnDeath) .addcomp(CheckBoss) .addcomp({ draw: function () { UFX.draw("r", this.tfly * 5 % tau) UFX.draw("ss #B00 lw 5 b m -80 0 l 80 0 m 0 -80 l 0 80 s") UFX.draw("fs #700 fr -30 -30 60 60") }, die: function () { playsound("explosion") }, }) function Percy(x0, y0) { this.setpos(x0, y0) this.settrack(x0, y0) this.tfly = UFX.random(100) this.heal() state.monsters.push(this) } Percy.prototype = UFX.Thing() .addcomp(WorldBound) .addcomp(WithinSector) .addcomp(FliesErratic, 5, 2, 5) .addcomp(HitZone, 0.4) .addcomp(HasHealth, 1) .addcomp(SplatsOnDeath) .addcomp(CheckBoss) .addcomp({ draw: function () { UFX.draw("r", this.tfly * 5 % tau) UFX.draw("ss #B00 lw 5 b m -80 0 l 80 0 m 0 -80 l 0 80 s") UFX.draw("fs #700 fr -30 -30 60 60") }, die: function () { playsound("explosion") }, })
import { combineReducers } from "redux"; import { messages } from "./reducers/messages" import { options } from "./reducers/options" import { loading } from "./reducers/loading" import { language } from "./reducers/language" import { auth } from "./reducers/auth" export const reducer = combineReducers({ messages, options, loading, language, auth, })
// Konstruktor klasy tworzacej liste // na wejscie otrzymuje wektor danych, z ktorych tworzy liste <ul/> // autor: Patryk Jar jar dot patryk at gmail dot com // data : 28 marca 2010 r. var yList = function() { return { }; };
const Arbre=require('../Modele/arbreModel') exports.create=(req,res)=>{ const newArbre=new Arbre({ name:req.body.name, ImageArbre:req.file.originalname, categori:req.body.categori, prix:req.body.prix, quantite:req.body.quantite }) newArbre.save() .then(result=>res.status(200).json({ message:"Arbre added" })) .catch(er=>console.log(er)) } exports.findArbre=(req,res)=>{ Arbre.find() .then(result=>res.send(result)) .catch(er=>console.log(er)) } exports.SortArbre=(req,res)=>{ Arbre.find() .sort({name:1}) .exec((err, data) => err ? console.log(err) : res.send(data)); }; exports.SortArbrepri=(req,res)=>{ Arbre.find() .sort({prix:1}) .exec((err,data) =>err ? console.log(err):res.send(data)); }; exports.DeleteArbre=(req,res)=>{ let id=req.params.id Arbre.findByIdAndDelete({_id:id}) .then(result=>res.send(result)) .catch(er=>console.log(er)) } ; exports.findArbreId=(req,res)=>{ let id=req.params.id Arbre.findById({_id:id}) .then(result=>res.send(result)) .catch(er=>console.log(er)) }; exports.EditArbre=(req,res)=>{ let id=req.params.id Arbre.findByIdAndUpdate({_id:id},req.body) .then(result=>res.send(result)) .catch(er=>console.log(er)) }
/*/ --------------------------------------------// * ┌─────────────────────────────────────────┐ * │ |> Serverless API - Lambda Functions │ * └─────────────────────────────────────────┘ * /*/ const db = require("../db"); const { GetItemCommand, PutItemCommand, UpdateItemCommand, DeleteItemCommand, ScanCommand } = require("@aws-sdk/client-dynamodb"); const { marshall, unmarshall } = require("@aws-sdk/util-dynamodb"); // GET_POST const getPost = async (event) => { const response = { "body": "", "statusCode": 200 } try { const params = { TableName: process.env.DYNAMODB_TABLE_NAME, Key: marshall({ postId: event.pathParameters.postId }) }; const { Item } = await db.send(new GetItemCommand(params)); console.log({ Item }); response.body = JSON.stringify({ "message": "Successfully fetched post data.", "data": (Item) ? unmarshall(Item) : {}, "rawData": Item }); } catch (err) { console.error(err); response.statusCode = 500; response.body = JSON.stringify({ "message": "Failed to fetch post", "errorMsg": err.message, "errorStack": err.stack }); } return response; }; // CREATE_POST const createPost = async (event) => { const response = { "body": "", "statusCode": 200 } try { const body = JSON.parse(event.body); const params = { TableName: process.env.DYNAMODB_TABLE_NAME, Item: marshall(body || {}) }; const createResult = await db.send(new PutItemCommand(params)); response.body = JSON.stringify({ "message": "Successfully created post.", createResult }); } catch (err) { console.error(err); response.statusCode = 500; response.body = JSON.stringify({ "message": "Failed to create post", "errorMsg": err.message, "errorStack": err.stack }); } return response; }; // UPDATE_POST // NOTE: The expression props inside `params` are specific to DynamoDB which contains reserved key words // ---- Any instance of a `DynamoDB` reserved word can be escaped by the prepending # character const updatePost = async (event) => { const response = { "body": "", "statusCode": 200 } try { const body = JSON.parse(event.body); const objKeys = Object.keys(body); const params = { TableName: process.env.DYNAMODB_TABLE_NAME, Key: marshall({ postId: event.pathParameters.postId }), UpdateExpression: `SET ${objKeys.map((_, index) => `#key${index} = :value${index}`).join(", ")}`, ExpressionAttributeNames: objKeys.reduce((acc, key, index) => ({ ...acc, [`#key${index}`]: key, }), {}), ExpressionAttributeValues: marshall(objKeys.reduce((acc, key, index) => ({ ...acc, [`:value${index}`]: body[key], }), {})), }; const updateResult = await db.send(new UpdateItemCommand(params)); response.body = JSON.stringify({ "message": "Successfully updated post.", updateResult }); } catch (err) { console.error(err); response.statusCode = 500; response.body = JSON.stringify({ "message": "Failed to create post", "errorMsg": err.message, "errorStack": err.stack }); } return response; }; // DELETE_POST const deletePost = async (event) => { const response = { "body": "", "statusCode": 200 } try { const body = JSON.parse(event.body); const params = { TableName: process.env.DYNAMODB_TABLE_NAME, Key: marshall({ postId: event.pathParameters.postId }) } const deleteResult = await db.send(new DeleteItemCommand(params)); response.body = JSON.stringify({ "message": "Successfully updated post.", deleteResult }); } catch (err) { console.error(err); response.statusCode = 500; response.body = JSON.stringify({ "message": "Failed to create post", "errorMsg": err.message, "errorStack": err.stack }); } return response; }; // GET_ALL_POSTS const getPost = async (event) => { const response = { "body": "", "statusCode": 200 } try { const { Items } = await db.send(new ScanCommand({ TableName: process.env.DYNAMODB_TABLE_NAME })); console.log({ Items }); response.body = JSON.stringify({ message: "Successfully fetched post data.", data: Items.map((item) => unmarshall(item)), Items }); } catch (err) { console.error(err); response.statusCode = 500; response.body = JSON.stringify({ "message": "Failed to fetch post", "errorMsg": err.message, "errorStack": err.stack }); } return response; }; module.exports = { getPost, createPost, updatePost, deletePost }
$(function(){ attachEvent(); }); function addGene(){ var gn = $('#gene_name').val(); var gf = $('#gene_f_gene').val(); var gm = $('#gene_m_gene').val(); $.ajax({ url: "/genes/add_gene/", type: "get", dataType: "script", data: {gene: {name: gn, f_gene: gf, m_gene: gm}} }); } function attachEvent(){ $(".cow-delete-button").click(function(event){ var ans = confirm('삭제하시겠습니까?'); if (ans){ return true; } else { return false; } }); }
"use strict"; /** * @class * @classdesc a test mock to represent an abstract module class * @implements {EquivalentJS.Manager.Module.class} * @typedef {Object} EquivalentJS.mock.AbstractModule * @constructs */ EquivalentJS.define('EquivalentJS.mock.AbstractModule', new function () { /** * @description bind public properties or methods * @memberOf EquivalentJS.mock.AbstractModule * @private * @alias {EquivalentJS.mock.AbstractModule} */ var _ = this; /** * @description test a property * @memberOf EquivalentJS.mock.AbstractModule * @type {number} * @default */ _.aProperty = 1; /** * @description test b property * @memberOf EquivalentJS.mock.AbstractModule * @type {number} * @default */ _.bProperty = 1; });
import React, {useState} from 'react'; import { Pressable, SectionList, StyleSheet, Text, TouchableOpacity, View, } from 'react-native'; import Ionicons from 'react-native-vector-icons/Ionicons'; import {screenBackgroundColor, tintColor, headerTextColor} from '../stylesheets/color-sheme'; import {createStackNavigator} from 'react-navigation-stack'; import {tabStylesheet} from '../stylesheets/tab-stylesheet'; import {createAppContainer} from 'react-navigation'; import SettingsScreen from '../components/settings-screen'; import {Button} from 'react-native-elements'; // <TouchableOpacity style={{marginRight: 10}} onPress={() => alert('TODO: delete list')}> // <Ionicons name={'trash-outline'} size={24} color={headerTextColor}/> // </TouchableOpacity> const fakeIngredients = [ {name: 'Beef', quantity: '26oz'}, {name: 'Bell Peppers', quantity: '4'} ]; const screens = { GroceryList: { screen: GroceryListScreen, navigationOptions: ({navigation}) => ({ title: 'Grocery List', headerRight: () => ( <TouchableOpacity style={{marginRight: 10, alignItems: 'center', display: 'flex', flexDirection: 'row'}} onPress={() => alert('TODO: delete list')}> <Ionicons name={'trash-outline'} size={24} color={headerTextColor}/> </TouchableOpacity> ), headerLeft: () => ( <TouchableOpacity style={{marginLeft: 10}} onPress={() => navigation.navigate('Settings')}> <Ionicons name={'settings-outline'} size={24} color={headerTextColor}/> </TouchableOpacity> ) }) }, Settings: { screen: SettingsScreen, navigationOptions: { headerTintColor: headerTextColor } } } const GroceryStack = createStackNavigator(screens, { defaultNavigationOptions: { headerStyle: tabStylesheet.header, headerTitleStyle: tabStylesheet.headerTitle } }) const GroceryContainer = createAppContainer(GroceryStack) function MyCheckbox() { const [checked, onChange] = useState(false); function onCheckmarkPress() { onChange(!checked); } return ( <Pressable style={[groceryStyles.checkboxBase, checked && groceryStyles.checkboxChecked]} onPress={onCheckmarkPress}> {checked && <Ionicons name="checkmark" size={24} color="white" />} </Pressable> ); } function IngredientItem(props) { return ( <View style={groceryStyles.ingredient}> <MyCheckbox /> <Text style={{marginLeft: 10, fontSize: 16}}>{props.name}</Text> <View style={{flex: 1}} /> <Text style={{marginLeft: 10}}>{props.quantity}</Text> </View> ) } function clearList() { // TODO: make clear list function } function GroceryListScreen() { return ( <View style={{alignItems: 'center', width: '100%', flex: 1, backgroundColor: screenBackgroundColor}}> <SectionList sections={[{title: 'Plan Title', data: fakeIngredients}, { title: 'Pantry', data: fakeIngredients }, {title: 'Other Items', data: fakeIngredients}]} style={{width: '100%'}} renderSectionHeader={({section: {title}}) => ( <View style={{alignItems: 'center', backgroundColor: screenBackgroundColor}}> <Text style={groceryStyles.headerLabel}>{title}</Text> <View style={{ backgroundColor: '#C5C5C5', width: '80%', height: 3, marginBottom: 15, borderRadius: 1.5 }}/> </View> )} renderItem={({item}) => ( <IngredientItem name={item.name} quantity={item.quantity}/> )} renderSectionFooter={({section: {title}}) => { if (title !== 'Other Items') { return; } return ( <View style={{display: 'flex', flexDirection: 'row', marginLeft: 30}}> <Button icon={<Ionicons name='add' size={24} />} title='Add Item' type='clear' onPress={() => alert('TODO: add new grocery item')}/> </View> ) }} keyExtractor={(item, index) => index.toString()} /> </View> ) } const groceryStyles = StyleSheet.create({ planTitle: { fontSize: 36, padding: 10 }, headerLabel: { fontSize: 24, padding: 10, marginTop: 25, textAlign: 'right', width: '85%' }, ingredientList: { width: '100%', }, ingredient: { height: 30, width: '80%', marginLeft: '10%', display: 'flex', flexDirection: 'row', marginBottom: 5 }, checkboxBase: { width: 24, height: 24, justifyContent: 'center', alignItems: 'center', borderRadius: 4, borderWidth: 2, borderColor: tintColor, backgroundColor: 'transparent', }, checkboxChecked: { backgroundColor: tintColor, } }) export default class GroceryListTab extends React.Component { render() { return ( <GroceryContainer/> ) } }
/* global google */ import React, {useState, useEffect} from 'react'; //// for integration with python import axios from 'axios'; import Street from './Street.jsx'; import MapDirectionsRenderer from './DirectionRenderer.jsx'; import PersistentDrawerRight from './Drawer.jsx'; import Button from '@material-ui/core/Button'; import { withGoogleMap, withScriptjs,GoogleMap, LoadScript, Marker, InfoWindow, StreetViewPanorama, DirectionsRenderer } from '@react-google-maps/api'; import './App.css'; function App() { const defaultCenter = { lat: 42.35, lng: -83.0457538 } const [center, setCenter] = useState(defaultCenter); const [url, setUrl] = useState(''); const [selected, setSelected] = useState({}); const [locationArray, setLocationArray] = useState([]); const mapStyles = { height: "100vh", width: "100%" }; const locations = [ { name: "Cadillac Square, Detroit, Wayne County, Michigan, 48226, USA", location: {lat: 42.331427, lng: -83.0457538}, mapKey : "Ui2edZ5tTmv06LZmZTbJEA", }, { name: "4662, Heck, Poletown East, Detroit, Wayne County, Michigan, 48207, USA", location: {lat: 42.367350, lng: -83.026907}, mapKey : "CVujV7TFQUvpAXHUcso7_A", }, { name: "4159, Lincoln, Woodbridge, Detroit, Wayne County, Michigan, 48208, USA", location: {lat: 42.346911, lng: -83.074396}, mapKey : "37wFuSBQC3Gul0NOJBvtdg", }, ]; function onSelect(item) { setSelected({name: "display", location: item}); setCenter({lat: item.lat, lng: item.lng}); console.log('item:', item); console.log('setCentered'); } function displayMarkers(){ return locations.map((item) => { return ( <Marker key = {item.name} position = {{lat: item.location.lat, lng: item.location.lng}} onClick = {() => onSelect(item)} /> ) }) } function displayRoadSegments(){ return locationArray.map((item) =>{ var latitude = item[0]; var longitude = item[1]; var myLatLng = { lat : latitude, lng: longitude } console.log('myLatLng', myLatLng); return ( <div> <Marker position = {myLatLng} onClick = {() => onSelect(myLatLng)} /> </div> ) }) } async function makeArray(latLon){ let temp = []; for (var i = 0; i < latLon.length; ++i){ temp.push(latLon[i]); } // console.log("TEMP:", temp); setLocationArray(latLon); } const handleSubmit = e => { console.log("handling submit:", url); axios .post("m_dice", url) .then(res => { let latLon = res.data; console.log("LatLon",latLon); makeArray(latLon); }) .catch(function (error) { console.log(error); }) e.preventDefault(); }; return ( <div className="App"> {<PersistentDrawerRight/>} <LoadScript googleMapsApiKey='AIzaSyAEthE8cXJYTabbM5WNNkbE1J3jWIvMDoU'> <GoogleMap mapContainerStyle={mapStyles} zoom={14} center={center} options={{streetViewControl: true}} > {/*displayMarkers()*/} { (locationArray.length !== undefined) ? (displayRoadSegments()): ""} {/*MapDirectionsRenderer(locationArray)*/} {/* <InfoWindow position = {selected.location} clickable = {true} onCloseClick ={() => setSelected({})} > <div> <Street mapKey = {selected}/> <p>{selected.name}</p> <StreetViewPanorama position={selected.location} visible={true} fullscreenControl={false} enableCloseButton={true} > </StreetViewPanorama> <Button variant="contained" color="primary" onClick={() => console.log("SAVED!")}>SAVE</Button> </div> </InfoWindow> */} { (selected.location) && ( <StreetViewPanorama position={selected.location} visible={true} fullscreenControl={false} enableCloseButton={false} > </StreetViewPanorama> ) } </GoogleMap> </LoadScript> <form onSubmit = {handleSubmit}> <input type = "submit" value = "Trigger Backend" /> </form> </div> ); } export default App;
import _ from 'underscore'; import d3 from 'd3'; import RiskOfBiasScore from 'riskofbias/RiskOfBiasScore'; import D3Visualization from './D3Visualization'; import RoBLegend from './RoBLegend'; class RoBBarchartPlot extends D3Visualization { constructor(parent, data, options){ // stacked-bars of risk of bias information. Criteria are on the y-axis, // and studies are on the x-axis super(...arguments); this.setDefaults(); } render($div){ this.plot_div = $div.html(''); this.processData(); if(this.dataset.length === 0){ return this.plot_div.html('<p>Error: no studies with risk of bias selected. Please select at least one study with risk of bias.</p>'); } this.get_plot_sizes(); this.build_plot_skeleton(true); this.add_axes(); this.draw_visualizations(); this.resize_plot_dimensions(); this.trigger_resize(); this.build_labels(); this.add_menu(); this.build_legend(); } resize_plot_dimensions(){ // Resize plot based on the dimensions of the labels. var xlabel_width = this.vis.select('.y_axis').node().getBoundingClientRect().width; if (this.padding.left < this.padding.left_original + xlabel_width) { this.padding.left = this.padding.left_original + xlabel_width; this.render(this.plot_div); } } get_plot_sizes(){ this.h = this.row_height * this.metrics.length; var menu_spacing = 40; this.plot_div.css({'height': (this.h + this.padding.top + this.padding.bottom + menu_spacing) + 'px'}); } setDefaults(){ _.extend(this, { firstPass: true, included_metrics: [], padding: {}, x_axis_settings: { domain: [0, 1], scale_type: 'linear', text_orient: 'bottom', axis_class: 'axis x_axis', gridlines: true, gridline_class: 'primary_gridlines x_gridlines', axis_labels: true, label_format: d3.format('.0%'), }, y_axis_settings: { scale_type: 'ordinal', text_orient: 'left', axis_class: 'axis y_axis', gridlines: true, gridline_class: 'primary_gridlines x_gridlines', axis_labels: true, label_format: undefined, }, color_scale: d3.scale.ordinal() .range(_.values(RiskOfBiasScore.score_shades)), }); } processData(){ var included_metrics = this.data.settings.included_metrics, stack_order = ['N/A', '--', '-', '+', '++'], metrics, stack, dataset; dataset = _.chain(this.data.aggregation.metrics_dataset) .filter(function(d){ var metric_id = d.rob_scores[0].data.metric.id; return _.contains(included_metrics, metric_id); }).map(function(d){ var vals = { 'label': d.rob_scores[0].data.metric.name, 'N/A':0, '--':0, '-':0, '+':0, '++':0, }, weight = 1/d.rob_scores.length; d.rob_scores.forEach(function(rob){ vals[rob.data.score_text] += weight; if(rob.data.score_text==='NR'){ vals['-'] += weight; } }); return vals; }) .value(); metrics = _.chain(dataset) .map(function(d){return d.label;}) .uniq() .value(); stack = d3.layout.stack()( _.map(stack_order, function(score){ return _.map(dataset, function(d){ return {x: d.label, y: d[score]}; }); }) ); if(this.firstPass){ _.extend(this.padding, { top: this.data.settings.padding_top, right: this.data.settings.padding_right, bottom: this.data.settings.padding_bottom, left: this.data.settings.padding_left, left_original: this.data.settings.padding_left, }); this.firstPass = false; } _.extend(this,{ w: this.data.settings.plot_width, row_height: this.data.settings.row_height, dataset, metrics, stack_order, stack, title_str: this.data.settings.title, x_label_text: this.data.settings.xAxisLabel, y_label_text: this.data.settings.yAxisLabel, }); } add_axes(){ _.extend(this.x_axis_settings, { rangeRound: [0, this.w], number_ticks: 5, x_translate: 0, y_translate: this.h, }); _.extend(this.y_axis_settings, { domain: this.metrics, number_ticks: this.metrics.length, rangeRound: [0, this.h], x_translate: 0, y_translate: 0, }); this.build_y_axis(); this.build_x_axis(); } draw_visualizations(){ var x = this.x_scale, y = this.y_scale, colors = this.color_scale, fmt = d3.format('%'), groups; this.bar_group = this.vis.append('g'); // Add a group for each score. groups = this.vis.selectAll('g.score') .data(this.stack) .enter().append('svg:g') .attr('class', 'score') .style('fill', function(d, i){return colors(i);}) .style('stroke', function(d, i){return d3.rgb(colors(i)).darker();}); // Add a rect for each score. groups.selectAll('rect') .data(Object) .enter().append('svg:rect') .attr('x', function(d) { return x(d.y0); }) .attr('y', function(d) { return y(d.x)+5; }) .attr('width', function(d) { return x(d.y); }) .attr('height', 20); if(this.data.settings.show_values){ groups.selectAll('text') .data(Object) .enter().append('text') .attr('class', 'centeredLabel') .style('fill', '#555') .attr('x', function(d){return (x(d.y0) + x(d.y)/2);}) .attr('y', function(d){return (y(d.x)+20);}) .text(function(d){return (d.y>0) ? fmt(d.y) : '';}); } } build_labels(){ var svg = d3.select(this.svg), x, y; x = parseInt(this.svg.getBoundingClientRect().width / 2, 10); y = 25; svg.append('svg:text') .attr('x', x) .attr('y', y) .text(this.title_str) .attr('text-anchor', 'middle') .attr('class','dr_title'); x = this.w / 2; y = this.h + 30; this.vis.append('svg:text') .attr('x', x) .attr('y', y) .attr('text-anchor', 'middle') .attr('class','dr_axis_labels x_axis_label') .text(this.x_label_text); x = -this.padding.left + 15; y = this.h / 2; this.vis.append('svg:text') .attr('x', x) .attr('y', y) .attr('text-anchor', 'middle') .attr('transform','rotate(270, {0}, {1})'.printf(x, y)) .attr('class', 'dr_axis_labels x_axis_label') .text(this.y_label_text); } build_legend(){ if (this.legend || !this.data.settings.show_legend) return; let options = { dev: this.options.dev || false, collapseNR: true, }; this.legend = new RoBLegend( this.svg, this.data.settings, options ); } } export default RoBBarchartPlot;
const expect = require("chai").expect; const sinon = require("sinon"); const Plugins = require("eslint/lib/config/plugins"); const ModuleResolver = require("eslint/lib/util/module-resolver"); const eslintPatch = require("../lib/eslint-patch"); describe("eslint-patch", function() { describe("patch", function() { let loadAll; before(function() { loadAll = Plugins.loadAll; }); after(function() { Plugins.loadAll = loadAll; }); it("intercepts plugins", function() { eslintPatch(); expect(loadAll).to.not.equal(Plugins.loadAll, "Plugins.loadAll is not patched"); }); }); describe("Plugins.loadAll", function() { before(function() { eslintPatch(); }); it("delegates each plugin to be loaded", function () { Plugins.load = sinon.spy(); Plugins.loadAll([ "jasmine", "mocha" ]); expect(Plugins.load.calledWith("jasmine")).to.be.true; expect(Plugins.load.calledWith("mocha")).to.be.true; }); it("only warns not supported once", function () { console.error = sinon.spy(); Plugins.load = sinon.stub().throws(); Plugins.loadAll([ "node" ]); Plugins.loadAll([ "node" ]); sinon.assert.calledOnce(console.error); sinon.assert.calledWith(console.error, "Module not supported: eslint-plugin-node"); }); it("does not raise exception for unsupported plugins", function() { Plugins.getAll = sinon.stub().returns([]); Plugins.load = sinon.stub().throws(); function loadPlugin() { Plugins.loadAll([ "unsupported-plugin" ]); } expect(loadPlugin).to.not.throw(); }); }); describe("loading extends configuration", function() { it("patches module resolver", function() { const resolve = ModuleResolver.prototype.resolve; eslintPatch(); expect(ModuleResolver.prototype.resolve).to.not.eql(resolve); }); it("returns fake config for skipped modules", function() { eslintPatch(); Plugins.loadAll(['invalidplugin']); expect(new ModuleResolver().resolve('eslint-plugin-invalidplugin')).to.match(/.+empty-plugin.js/); }); it("does not warn user repeatedly about not supported modules", function() { console.error = sinon.spy(); eslintPatch(); for(var i=0; i<3; i++) { new ModuleResolver().resolve('eslint-plugin-bogus'); } expect(console.error.callCount).to.eql(1); }); }); });
import React, { Component } from 'react'; import css from './styles.scss'; import {} from 'prop-types'; import NavBarItems from 'assets/fr/navbar.json'; import {TweenMax} from 'gsap'; import MainNavButton from './components/MainNavButton'; import Link from '../components/Link' class NavBarMobile extends Component { isMenuOpen = false; constructor(props) { super(); } /** * display or Hide the Full screen mobile menu */ handleClick = () => { this.$mainNavButton.toggleDisplayButton(); if( !this.isMenuOpen ){ this.isMenuOpen = true; TweenMax.fromTo( this.$menu, .7, { css:{ display: 'flex', top: "-100%" }}, { css: { top: "0%" } } ) } else { this.isMenuOpen = false; TweenMax.to( this.$menu, .7, { css: { top: "-100%", display: 'none'} } ) } } /** * Handle the hide of the full screen mobile menu * @return {[type]} [description] */ handleHideMenu = () => { this.$mainNavButton.toggleDisplayButton(); this.isMenuOpen = false; TweenMax.to( this.$menu, .7, { css: { top: "-100%", display: 'none'} } ) } render() { return ( <div className={css.component}> <MainNavButton ref={ (el) => this.$mainNavButton = el} handleClick={this.handleClick}/> <nav ref={ (el) => this.$menu = el}> { NavBarItems.navbar.map( (dataItem, index) => ( <Link key={index} index={index} {...dataItem} handleHideMenu={this.handleHideMenu}/> ))} </nav> </div> ); } } export default NavBarMobile
var LocalStrategy = require('passport-local').Strategy, SL = require(process.cwd() + '/lib/happy/sqllib.js'); module.exports = { initialize : function(server, Passport) { },addlang : function(pgClient, data, cb){ var sql = 'INSERT INTO translates.lang_t (lang,name) VALUES ($1,$2)'; pgClient.query(sql, [data.lang,data.name], function(err, user){ if(err){ cb(err || 'no user with this userName', false); } else { if(data.lang_of_name){ var translateData = { key : '_' + data.name.toLowerCase(), desc : data.name, lang : data.lang_of_name } module.exports.addtranslate(pgClient, translateData, function(err2, outdata){ if(outdata){ var sqlUpdate = 'UPDATE translates.lang_t SET link=$1 WHERE lang=$2'; pgClient.query(sqlUpdate, [outdata.link, data.lang], function(err3, data2){ cb(err3, user.rows[0]); }); } else { cb(err2, null); } }); } else { cb(null, user.rows[0]); } } }); },updatedesc : function(pgClient, data, cb){ var SQL = SL.SqlLib('translates.link_t'); SQL.whereAnd('link=' + data.link); //var sql = SQL.generateUpsert({'link':data.link,data:data.desc,'lang':data.lang},['link']); var updateDATA = { '"desc"':data.desc, 'changed':'now()' }; if(!isNaN(data.group)){ updateDATA['"group"'] = data.group; } if(data.key){ updateDATA['key'] = data.key; } SQL.update(pgClient, updateDATA, function(err, res){ cb(err, res); }); },addtranslate : function(pgClient, data, cb){ if(isNaN(data.group)){ data.group = 0; } if(!data.desc){ cb('missing column desc'); return; } if(!data.key){ data.key = null; } //var sql = 'INSERT INTO translates.link_t ("key","desc","group") VALUES ($1,E\''+data.desc+'\',$2) RETURNING link,"desc","key","group"'; //pgClient.query(sql, [data.key,data.group], function(err, user){ var sql = 'INSERT INTO translates.link_t ("key","desc","group") VALUES ($1,$2,$3) RETURNING link,"desc","key","group"'; pgClient.query(sql, [data.key,data.desc, data.group], function(err, user){ if(err){ cb(err || 'no user with this userName', false); } else { var row = user.rows[0]; data.link = row.link; data.data = row.desc; data.desc = row.desc; data.group = row.group; module.exports.translate(pgClient, data, cb); } }); },translate : function(pgClient, data, cb){ if(!data.lang){ data.lang = 'en'; } var SQL = SL.SqlLib('translates.translate_t'); SQL.whereAnd('link=' + data.link + ' AND lang=\'' +data.lang +'\''); //var sql = SQL.generateUpsert({'link':data.link,data:data.desc,'lang':data.lang},['link']); SQL.upsert(pgClient,{'link':data.link,data:data.data,'lang':data.lang},['link','data'], function(err, res){ var out = null; if(!err){ out = { link : res[0].link, data : res[0].data }; // from add translate - in this table doesnt if(data.key){ out.key = data.key; } if(data.desc){ out.desc = data.desc; } if(!isNaN(data.group)){ out.group = data.group; } } cb(err, out); }); },getlangs : function(pgClient, fields, data, cb){ var sql = 'SELECT lang,name FROM translates.lang_t (key,description) VALUES ($1,$2) RETURNING link'; var indexOfTranslate = fields.indexOf("translate"); if(indexOfTranslate > -1){ if(!data.lang_of_names){ cb('field \'translate\' is preset but not specified lang (data.lang_of_names)'); return; } fields[indexOfTranslate] = 'translates.translate_t.data as translate'; } var indexOfLang = fields.indexOf("lang"); if(indexOfLang > -1){ fields[indexOfLang] = 'translates.lang_t.lang as lang'; } var SQL = SL.SqlLib('translates.lang_t', fields); if(indexOfTranslate > -1){ var join = 'translates.lang_t.link=translates.translate_t.link AND translates.translate_t.lang=\'' + data.lang_of_names + '\''; SQL.join('translates.translate_t',join); } SQL.select(pgClient, cb); } ,getUserByName : function(pgClient, userName, cb){ var sql = 'SELECT id, name, full_name, pass,admin FROM usr WHERE name = $1'; console.log(sql) ; pgClient.query(sql, [userName], function(err, user){ if(err || user.rows.length < 1){ cb(err || 'no user with this userName', false); } else { cb(null, user.rows[0]); } }); },getUserById : function(pgClient, id, cb){ var sql = 'SELECT id, name, full_name,admin FROM usr WHERE id = $1'; console.log(sql) ; pgClient.query(sql, [id], function(err, user){ if(err || user.rows.length < 1){ cb(err || 'no user with this id', false); } else { cb(null, user.rows[0]); } }); },setLastLogin : function(pgClient, userId, cb){ console.log('ahoj now()'); var sql = new SL.SqlLib('usr'); sql.whereAnd('id='+userId); sql.update(pgClient, {last_login:'now()'}, function(err, data){ console.log(err ? err : data); cb(err, data); }) },get: function(pgClient, fields, data, cb){ // example data // var data = { // lang : 'cz', // page : 0, // second: 'en', // lastUpdateFirst: true - for editor first show the last updated, // group : number - select just the translates from group // }; if(!data.lang){ cb('data.lang missing!'); return ; } // in fields could be desc instead description var indexOfDesc = fields.indexOf("desc"); if(indexOfDesc > -1){ fields[indexOfDesc] = '"desc"'; } var indexOfGroup = fields.indexOf("group"); if(indexOfGroup > -1){ fields[indexOfGroup] = '"group"'; } var indexOfLink = fields.indexOf("link"); if(indexOfLink > -1){ fields[indexOfLink] = 'translates.link_t.link as link'; } var indexOfData = fields.indexOf("data"); if(indexOfData > -1){ if(data.second){ fields[indexOfData] = 'COALESCE(tt.data,tt2.data) as data'; } else { // simple way without merge data fields[indexOfData] = 'tt.data as data'; } } var indexOfKey = fields.indexOf("key"); var sql = new SL.SqlLib('translates.link_t', fields); if(indexOfData > -1 || indexOfKey > -1){ var join = 'tt.link=translates.link_t.link AND (tt.lang=\''+data.lang +'\')'; // !!!! with OR doesn't work sometime could put priority second // even the primar lang is present (example with new intro) // the czech translation is missing , even is present // for selecting and the language is not there use second lang // in most cases will be en because is base //if(data.second){ // join += ' OR translates.translate_t.lang=\''+data.second +'\''; // } sql.join('translates.translate_t tt',join); if(data.second){ var join2 = 'tt2.link=translates.link_t.link AND (tt2.lang=\''+data.second +'\')'; sql.join('translates.translate_t tt2',join2); } } // TODO: page moving // var size=100; //sql.offset(data.page * size); //sql.limit((data.page+1) * size); // for normal purpose if(data.lastUpdateFirst){ sql.addOrderBy('link_t.changed DESC'); } else if(data.byLinkId){ sql.addOrderBy('link_t.link'); } if(!isNaN(data.group)){ sql.whereAnd('"group"='+data.group.toString()); } sql.select(pgClient, cb); },delete:function(pg, dataContainer, cb){ if(!dataContainer.link){ cb('missing link'); return; } pg.query("DELETE FROM translates.translate_t USING translates.link_t WHERE translates.link_t.link = "+ dataContainer.link+" AND translates.translate_t.link = translates.link_t.link;" + ";DELETE FROM translates.link_t WHERE translates.link_t.link=" + dataContainer.link , [], function(err, data){ cb(err, dataContainer); }); } }
const router = require('express').Router() const {Product, User} = require('../db/models') module.exports = router router.get('/', async (req, res, next) => { try { const products = await Product.findAll() res.json(products) } catch (err) { next(err) } }) router.post('/', async (req, res, next) => { if (req.user.userType === 'ADMIN') { try { const existingProduct = await Product.findOne({ where: { name: req.body.name } }) if (existingProduct === null) { const createdProduct = await Product.create(req.body) res.status(201).send(createdProduct) } else { res.sendStatus(409) } } catch (err) { next(err) } } else { res.sendStatus(404) } }) router.get('/:productId', async (req, res) => { try { const id = req.params.productId const product = await Product.findByPk(id) res.json(product) } catch (error) { res.sendStatus(error) } }) router.delete('/:productId', async (req, res, next) => { if (req.user.userType === 'ADMIN') { try { if (!Number.isInteger(parseInt(req.params.productId))) { res.sendStatus(400) } const deleted = await Product.findOne({ where: { id: parseInt(req.params.productId) } }) if (deleted) { await Product.destroy({ where: { id: parseInt(req.params.productId) } }) res.sendStatus(204) } else { res.sendStatus(404) } } catch (err) { next(err) } } else { res.sendStatus(404) } }) router.put('/:productId', async (req, res, next) => { if (req.user.userType === 'ADMIN') { try { const updatedProduct = await Product.findOne({ where: { id: req.params.productId } }) if (updatedProduct) { await updatedProduct.update(req.body) res.status(200).send(updatedProduct) } else { res.sendStatus(404) } } catch (err) { next(err) } } else { res.sendStatus(404) } }) //two ways of doing this - first way create a route that is linked to products - clicking on a link should prodive the correct ID which will be put into the axios url //second way is to create a separate link to each product without :productId and send the id as a req in axios
const formToJSON = elements => [].reduce.call(elements, (data, element) => { data[element.name] = element.value; return data; }, {}); function submitForm(form, url) { document.querySelectorAll('button').forEach(btn => btn.disabled = true); const opt = { timeOut: 2000 }; const postData = { linkList: [] }; for (let el of form.elements) if (el.name.includes('linkList[]')) postData.linkList.push(el.value); fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(postData) }) .then(res => res.json()) .then(res => { let msg = res.msg.replace(/\n/g, '<br/>'); if (res.code === 200) toastr.success(msg, "Success", opt); else toastr.error(msg, "Error", opt); setTimeout(() => { if (res.code === 200) window.location.replace('/'); else document.querySelectorAll('button').forEach(btn => btn.disabled = false); }, opt.timeOut); }); return false; }
import React, { Component } from 'react'; import './App.css'; import ReactMapboxGl, { Popup } from "react-mapbox-gl"; const Map = ReactMapboxGl({ accessToken: "pk.eyJ1IjoiYmxpc2h0ZW4iLCJhIjoiMEZrNzFqRSJ9.0QBRA2HxTb8YHErUFRMPZg" }); const INITIAL_CENTER = [20, -2]; const INITIAL_ZOOM = [9]; class App extends Component { constructor(props) { super(props); this.state = { text: "wibble", center: INITIAL_CENTER }; } onMouseMove(e) { var features = e.target.queryRenderedFeatures(e.point); features && features.length && this.setState({ text: features["0"].properties.class }); this.setState({ center: [e.lngLat.lng, e.lngLat.lat] }); } render() { return ( <Map style="mapbox://styles/mapbox/streets-v9" onMouseMove={(map,e)=>this.onMouseMove(e)} center={INITIAL_CENTER} zoom={INITIAL_ZOOM} containerStyle={{ height: "100vh", width: "100vw" }}> <Popup coordinates={this.state.center} offset={{'bottom-left': [12, -38], 'bottom': [0, -38], 'bottom-right': [-12, -38]}}> <h1>{this.state.text}</h1> </Popup> </Map> ); } } export default App;
hvar fs = require('fs'); var fd = fs.openSync('veggie.txt', 'r'); var veggie = ""; do{ var buf = new Buffer(5); buf.fill(); var bytes = fs.readSync(fd, buf, null, 5); console.log('read %d bytes', bytes); veggie += buf.toString(); }while(bytes>0); fs.closeSync(fd); console.log('Veggies: ' + veggie);
import css from './index.css' import React, { Component } from 'react'; import Logo from '../logo'; export default class NavBar extends Component { constructor(props) { super(props); } render() { return ( <div id = 'nav-bar'><Logo/></div> ) } }
//make SVG compatibility SVGElement.prototype.getTransformToElement = SVGElement.prototype.getTransformToElement || function (toElement) { return toElement.getScreenCTM().inverse().multiply(this.getScreenCTM()); }; $(function () { // split pane $('div.split-pane').splitPane(); //add nano scroll to pages $(".nano").nanoScroller(); }); //create left pane items var projectAssets = $('#project-assets'); var projectAssetsGraph = new joint.dia.Graph, projectAssetsPaper = new joint.dia.Paper({ el: projectAssets, height: projectAssets.height(), width: projectAssets.width(), model: projectAssetsGraph, interactive: false }); var participant = new joint.shapes.sequence.Participant({ position: {x: 60, y: 10} }); var frame = new joint.shapes.sequence.frame({ position: {x: 5, y: 200} }); //add to cells projectAssetsGraph.addCells([participant, frame]); //main editor var mainEditor = $('#editor-main'); var graph = new joint.dia.Graph, paper = new joint.dia.Paper({ defaultLink: new joint.shapes.sequence.Link, el: mainEditor, width: mainEditor.width(), height: mainEditor.height(), model: graph, gridSize: 10 }); projectAssetsPaper.on('cell:pointerdown', function (cellView, e, x, y) { $('body').append('<div id="invisiblePaper" style="position:fixed;z-index:100;opacity:.8;pointer-event:none;"></div>'); var flyGraph = new joint.dia.Graph, invisiblePaper = new joint.dia.Paper({ el: $('#invisiblePaper'), model: flyGraph, interactive: false }), flyShape = cellView.model.clone(), pos = cellView.model.position(), offset = { x: x - pos.x, y: y - pos.y }; flyShape.position(0, 0); flyGraph.addCell(flyShape); $("#invisiblePaper").offset({ left: e.pageX - offset.x, top: e.pageY - offset.y }); $('body').on('mousemove.fly', function (e) { $("#invisiblePaper").offset({ left: e.pageX - offset.x, top: e.pageY - offset.y }); }); $('body').on('mouseup.fly', function (e) { var x = e.pageX, y = e.pageY, target = paper.$el.offset(); if (x > target.left && x < target.left + paper.$el.width() && y > target.top && y < target.top + paper.$el.height()) { var s = flyShape.clone(); s.position(x - target.left - offset.x, y - target.top - offset.y); graph.addCell(s); } $('body').off('mousemove.fly').off('mouseup.fly'); flyShape.remove(); $('#invisiblePaper').remove(); }); }); function setGrid(paper, gridSize, color) { // Set grid size on the JointJS paper object (joint.dia.Paper instance) paper.options.gridSize = gridSize; // Draw a grid into the HTML 5 canvas and convert it to a data URI image var canvas = $('<canvas/>', {width: gridSize, height: gridSize}); canvas[0].width = gridSize; canvas[0].height = gridSize; var context = canvas[0].getContext('2d'); context.beginPath(); context.rect(1, 1, 1, 1); context.fillStyle = color || '#AAAAAA'; context.fill(); // Finally, set the grid background image of the paper container element. var gridBackgroundImage = canvas[0].toDataURL('image/png'); paper.$el.css('background-image', 'url("' + gridBackgroundImage + '")'); } // Example usage: setGrid(paper, 10, 'rgba(106, 115, 124, 0.7)'); //handle mouse transform paper.on('cell:pointerup', function (cellView) { //to avoid trigger on links if (cellView.model instanceof joint.dia.Link) return; var freeTransform = new joint.ui.resize({cellView: cellView}); freeTransform.render(); var cell = cellView.model; var cellViewsBelow = paper.findViewsFromPoint(cell.getBBox().center()); if (cellViewsBelow.length) { // Note that the findViewsFromPoint() returns the view for the `cell` itself. var cellViewBelow = _.find(cellViewsBelow, function (c) { return c.model.id !== cell.id }); // Prevent recursive embedding. if (cellViewBelow && cellViewBelow.model.get('parent') !== cell.id) { cellViewBelow.model.embed(cell); } } }); // First, un-embed the cell that has just been grabbed by the user. paper.on('cell:pointerdown', function (cellView, evt, x, y) { var cell = cellView.model; if (!cell.get('embeds') || cell.get('embeds').length === 0) { // Show the dragged element above all the other cells (except when the // element is a parent). cell.toFront(); } if (cell.get('parent')) { graph.getCell(cell.get('parent')).unembed(cell); } });
import React from "react" import styled from "styled-components" import BodyBurnLogo from "../../svgs/BodyBurnLogo" import WhatIsBodyBurnCopy from "./Copy/WhatIsBodyBurnCopy" import Fourteen from "../Shared/FourteenDayTrialHeader" import { above } from "../../styles/Theme" const HeadlineContent = () => { return ( <ContentContainer> <LogoWrapper> <Logo /> <WhatIsBodyBurnCopy /> </LogoWrapper> <Fourteen> Come try Body Burn for 14 days of unlimited classes. Click here now! </Fourteen> </ContentContainer> ) } export default HeadlineContent const ContentContainer = styled.div` grid-column: 1 / -1; grid-row: 1 / -1; margin: 80px 0 40px 0; padding: 0 16px; display: flex; flex-direction: column; justify-content: space-between; width: 100%; z-index: 1; ${above.mobile` margin: 80px 0 40px 80px; justify-content: space-around; width: 60%; `} ` const LogoWrapper = styled.div` width: 100%; /* ${above.mobile` margin: 0 0 60px 0; `} */ ` const Logo = styled(BodyBurnLogo)` width: 100%; `
// 第一个动画效果 function animate(element){ element.onmouseover=function(){ this.style.color= " #efb336"; this.children[1].style.display = 'block'; } element.onmouseout = function(){ this.style.color= "#666"; this.children[1].style.display = 'none'; } } // // 商品展示页 动画效果 function anim(elements,obj){ // elements.onmouseover = function(){ //清除上一个定时器 clearInterval(elements.timerId) //开启一个新的定时器 elements.timerId = setInterval(function(){ // 假设成立 var flag=true; // 遍历 对象 for(var key in obj){ var atter = key; var getart = obj[key]; //动画三步走 // 获取当前位置 var current = window.getComputedStyle(elements)[atter]; var current = parseInt(current); // 累加小碎步 var setp = (getart - current)/10 setp = setp > 0 ? Math.ceil(setp) : Math.floor(setp);; current += setp; // 重新赋值 elements.style[atter]= current + "px"; // 第二步 找打脸的 if(current != getart){ flag =false } } // 判断 if(false == true){ clearInterval(elements.timerId) } },20) // } } // elements.onmouseout=function(){ // // dai.style.display="none"; // }
import React from 'react' import Paper from 'material-ui/Paper' import {List, ListItem} from 'material-ui/List' import Divider from 'material-ui/Divider' import Subheader from 'material-ui/Subheader' import Avatar from 'material-ui/Avatar' import {grey400, darkBlack, lightBlack} from 'material-ui/styles/colors' import IconButton from 'material-ui/IconButton' import MoreVertIcon from 'material-ui/svg-icons/navigation/more-vert' import IconMenu from 'material-ui/IconMenu' import MenuItem from 'material-ui/MenuItem' import Thing from './thing.js' import {Tabs, Tab} from 'material-ui/Tabs' import TextField from 'material-ui/TextField' import CreatetThings from './createthings.js' const style = { height: '800', width: '400', margin: 20, display: 'inline-block' }; const desStyle = { height: '800', width: '300', margin: 20, display: 'inline-block' }; const iconButtonElement = ( <IconButton touch={true} tooltip="more" tooltipPosition="bottom-left"> <MoreVertIcon color={grey400}/> </IconButton> ); const rightIconMenu = ( <IconMenu iconButtonElement={iconButtonElement}> <MenuItem>Reply</MenuItem> <MenuItem>Forward</MenuItem> <MenuItem>Delete</MenuItem> </IconMenu> ); const ThingList = ({things,sceneId}) => ( <div> <Paper style={style} zDepth={2}> <List> <Tabs> <Tab label="待处理的事" value={0}/> <Tab label="需要协同的事" value={1}/> <Tab label="已关注的事" value={2}/> </Tabs> <TextField hintText="搜索" fullWidth={true}/> {things.map((thing) => ( <div key={thing._id}> <ListItem rightIconButton={rightIconMenu} primaryText={thing.owner} secondaryText={< p > <span style={{ color: darkBlack }}>{thing.title}</span> < br/> { thing.describe } < /p>} secondaryTextLines={2}/> <Divider inset={true}/> </div> ))} </List> <List> <Subheader>添加一个事情</Subheader> <CreatetThings sceneId = {sceneId}/> </List> </Paper> <Thing/> </div> ); export default ThingList;
import axios from './axios' const Csrf = { getCookie() { axios.get("/csrf-cookie"); } } export default Csrf
import React from "react"; import { Container, Grid, Header } from "semantic-ui-react"; import styled from "styled-components"; import SearchForm from "./SearchForm/SearchFormContainer"; const StyledContainer = styled(Container)` &&& { height: 100%; min-height: 440px; display: flex; padding-top: 4em; @media only screen and (min-width: 768px) { padding-top: 12em; display: block; } } `; const Subtitle = styled.p` &&& { color: #fff; font-size: 2em; margin-bottom: 0.5em; @media only screen and (min-width: 768px) { font-size: 40px; } } `; const Title = styled(Header)` &&& { color: #fff; font-size: 2.2em; font-weight: 700; margin: 0; @media only screen and (min-width: 768px) { font-size: 45px; } } `; const FormTitle = styled(Header)` &&& { color: #4f4b65; font-size: 2em; font-weight: 300; @media only screen and (min-width: 768px) { color: #fff; font-size: 2em; } } `; const StyledColumn = styled(Grid.Column)` &&& { -webkit-box-shadow: 0px 4px 5px 0px rgba(0, 0, 0, 0.47); -moz-box-shadow: 0px 4px 5px 0px rgba(0, 0, 0, 0.47); box-shadow: 0px 4px 5px 0px rgba(0, 0, 0, 0.47); background-color: #fafafe; padding: 1.2em; @media only screen and (min-width: 768px) { -webkit-box-shadow: 0px 4px 5px 0px rgba(0, 0, 0, 0.47); -moz-box-shadow: 0px 4px 5px 0px rgba(0, 0, 0, 0.47); box-shadow: 0px 4px 5px 0px rgba(0, 0, 0, 0.47); background-color: #00000040; padding: 1.2em; } } `; const HomePageHeading = () => ( <StyledContainer> <Grid stretched> <Grid.Row> <Grid.Column computer={8} mobile={16} textAlign="left" verticalAlign="top" > <Title as="h1">Pandora.</Title> <Subtitle> Lorem ipsum dolor sit amet, consectetur adipiscing. </Subtitle> </Grid.Column> <StyledColumn floated="right" mobile={16} computer={6} verticalAlign="bottom" > <FormTitle className="searchForm__header" as="h1" textAlign="left" > Encuentra lugares para entrenar cerca de ti. </FormTitle> <SearchForm /> </StyledColumn> </Grid.Row> </Grid> </StyledContainer> ); export default HomePageHeading;
const loggedUser = JSON.parse(localStorage.getItem("user")); const initState = loggedUser ? { loggedIn: true, authError: null, loggedUser } : {}; const authReducer = (state = initState, action) => { switch(action.type) { case "LOGIN_SUCCESS": console.log("login success"); return { ...state, loggedIn: true, loggedUser: action.loggedUser, authError: null } case "LOGIN_ERROR": console.log("login error"); return { ...state, loggedIn: false, authError: action.authError } case "SIGNOUT_SUCCESS": console.log("signout success"); return { ...state, loggedIn: false, authError: null } case "SIGNOUT_ERROR": console.log("signout error"); return { ...state, loggedIn: true, authError: action.authError } default: return state; } } export default authReducer;
import {createStore, combineReducers, applyMiddleware} from 'redux'; import movielistReducer from './reducers/movielistReducer'; import userReducer from './reducers/userReducer'; import thunk from 'redux-thunk'; import {composeWithDevTools} from 'redux-devtools-extension' const middleware = [thunk]; const allReducers = combineReducers({movies: movielistReducer, users: userReducer}); const initialState = { users: [], movies: {name: "TERMINATOR 2"} }; const store = createStore(allReducers, initialState, ( applyMiddleware(...middleware), window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__())); export default store;
class DashboardInjector { constructor(app) { this.app = app; this.subscriptions = {}; app.worker.addHandler("dashboard_update", (c, m) => this._onUpdate(c, m)); } _onUpdate(ctx, msg) { if (this.subscriptions[msg.id] === undefined) { console.warn("No dashboard subscription for ", msg.id); return; } this.subscriptions[msg.id].forEach((f) => f.callback(msg.data)); } subscribe(id, key, callback) { if (this.subscriptions[id] === undefined) { this.subscriptions[id] = []; } this.subscriptions[id].push({ callback: callback, key: key }); this.app.worker.postMessage("dashboard_subscribe", { id: id }); } unsubscribe(id, key) { this.app.worker.postMessage("dashboard_unsubscribe", { id: id }); if (this.subscriptions[id] === undefined) { return; } this.subscriptions[id] = this.subscriptions[id].filter((e) => e.key != key); if (this.subscriptions[id].length == 0) { delete this.subscriptions[id]; } } addType(type, component) { this.app.store.commit("addDashboardType", { type: type, component: component, }); } } export default DashboardInjector;
import urlWithParams from '../../src/common/urlwithparams'; export default function localOrHive(src, params) { src = src.toLowerCase(); if (window.location.hostname === '127.0.0.1') { return urlWithParams(`${window.location.origin}/assets?path=${src}`, params); } else { // if (params && (params.reforged || params.sc2)) { return `https://www.hiveworkshop.com/casc-contents?path=${src}`; // } else { //return `https://www.hiveworkshop.com/data/static_assets/mpq/tft/${src}`; // } } }
(function ($) { const password = $("#password"); let isChecked = false; $("#show-password-btn").on("click", function () { isChecked = !isChecked; password.attr("type", isChecked ? "text" : "password"); $(this).text((isChecked ? "Hide" : "Reveal") + " Password"); }); })(window.jQuery);
module.exports={ api_secret_key:'metin' };
const express = require("express"); const path = require("path"); const auth = require("http-auth"); const { body, validationResult } = require("express-validator/check"); var thesaurus = require("thesaurus-synonyms"); var natural = require("natural"); var tokenizer = new natural.WordTokenizer(); const router = express.Router(); const basic = auth.basic({ file: path.join(__dirname, "../users.htpasswd") }); function sayNothing(blah) { console.log(blah); } function splitSentences(paragraph) { console.log(paragraph); sentences = tokenizer.tokenize(paragraph); console.log(sentences); return sentences; } function splitWords(sentence) { console.log(sentence); words = tokenizer.tokenize(sentence); console.log(words); return words; } async function findThesaurus(word) { console.log("finding thesaurus for word: " + word); // use cortical.io, as of Mar 22, 2019 10:20pm Thesaurus.com API is not responding // with any results // very intellegent algorithm, ALWAYS use the first word returned :) var response = await thesaurus.similar(word).then(function(result) { return result[0]; }); return response; } function sanitizeParagragh(json) { value = json["paragraph"]; var content = JSON.stringify(value); return content; } async function convertParagraph(input) { console.log("input to be converted " + input); var output = input; var sanitizedParagraph = sanitizeParagragh(input); var words = splitWords(sanitizedParagraph); var kidParagraph = ""; for (const word of words) { translatedWord = await findThesaurus(word); kidParagraph += " " + translatedWord; } output["insights"] = kidParagraph; console.log("Final output = " + JSON.stringify(output)); return output; } // temporarily disable authentication due to Heroku https router.get("/", auth.connect(basic), (req, res) => { res.render("form", { title: "translation form" }); }); router.get("/", (req, res) => { res.render("form", { title: "translation form" }); }); router.post( "/", [ body("paragraph") .isLength({ min: 1 }) .withMessage("Please enter at least a word") ], async (req, res) => { const errors = validationResult(req); if (errors.isEmpty()) { var response_data = req.body; const wisdom = await convertParagraph(req.body).then( result => result.insights ); console.log("Final response data: " + wisdom); // put insights data // response_data["insights"] = "Sample Response"; response_data["insights"] = wisdom; res.render("form", { title: "translation form", errors: errors.array(), data: response_data }); } else { res.render("form", { title: "translation form", errors: errors.array(), data: req.body }); } } ); module.exports = router;
"use strict"; // require the express module const express = require("express"); // require the router object (with all the defined routes) to be used in this file const questionsRoutes = require("./questions.api"); const scoreRoutes = require("./scores.api") // require the cors module const cors = require("cors"); // create an instance of an express server const app = express(); // Enable Cross Origin Resource Sharing so this API cam be used from web apps on other domains app.use(cors()); // allow POST and PUT requests to use JSON bodies app.use(express.json()); // use thee router object (with all the defined routes) app.use("/", questionsRoutes); app.use("/", scoreRoutes); // define the port const port = 3001; // run the server app.listen(port, () => { console.log(`Listening on port ${port}`); });
import axios from 'axios'; import { formatListing } from '../helpers/formatValues'; import { FETCH_EVENTS } from './types'; import { SUBMIT_EVENT } from './types'; import { JOIN_EVENT } from './types'; import { FETCH_SINGLE_EVENT } from './types'; import { QUIT_EVENT } from './types'; import { REMOVE_EVENT } from './types'; import { EXPIRED_EVENTS } from './types'; export const submitEvent = (values) => { // const options = formatListing(values); // console.log(options) will return empty object becasue formatData not stringifyable return async dispatch => { try { const res = await axios.post('/api/event', values); dispatch({ type: SUBMIT_EVENT, payload: res.data }); } catch (err) { console.log(err); } }; } export const fetchEvents = () => async dispatch => { try { const res = await axios.get('/api/event'); dispatch({ type: FETCH_EVENTS, payload: res.data }); } catch (err) { console.log(err); } }; export const showEvent = (id) => async dispatch => { try { const res = await axios.get(`/api/event/${id}`); dispatch({ type: FETCH_SINGLE_EVENT, payload: res.data }); } catch (err) { console.log(err); } }; export const joinEvent = (id) => async dispatch => { try { const res = await axios.post(`/api/event/join/${id}`); dispatch({ type: JOIN_EVENT, payload: res.data }); } catch (err) { console.log(err); } }; export const quitEvent = (id) => async dispatch => { try { const res = await axios.post(`/api/event/quit/${id}`); dispatch({ type: QUIT_EVENT, payload: res.data }); } catch (err) { console.log(err); } } //from user info export const removeEvent = (id) => async dispatch => { try { const res = await axios.post(`/api/event/remove/${id}`); dispatch({ type: REMOVE_EVENT, payload: res.data }); } catch (err) { console.log(err); } } export const expiredEvents = (id) => async dispatch => { try { const res = await axios.post(`/api/event/expired/${id}`); dispatch({ type: EXPIRED_EVENTS, payload: res.data }); } catch (err) { console.log(err); } }
// components/pannel-box/pannel-box.js Component({ /** * 组件的属性列表 */ properties: { title: String, content: String, imgPath: String }, /** * 组件的初始数据 */ data: { }, /** * 组件的方法列表 */ methods: { itemClick() { this.triggerEvent('itemClick', {}, {}) } } })
import React, { Component } from "react"; import Typewriter from "typewriter-effect"; import { Link } from "react-router-dom"; import "./Home.css"; class Home extends Component { constructor(props) { super(props); this.state = { type: "", showBorder: true, }; } render() { const style = { color: "black", backgroundColor: "rgba(163, 159, 220,0.5)", }; return ( <div className="container mainss"> <div className="row mt-3 mr-3 ml-1"> <h2 className="pt-3"> {" "} <strong> Hey, I'm Yash</strong> </h2> <img src={require("../../assets/Images/lng.png")} alt="Me" width="70px" /> </div> <div style={{ justifyContent: "center" }} className="row mt-5 mb-5 mr-3 ml-3" > <div className="row"> <h2>I'm</h2> &nbsp; <h2> <Typewriter options={{ strings: [ " a Student", " Web Developer", " Continuous Learner", " Frontend Developer", ], autoStart: true, loop: true, }} /> </h2> </div> </div> <div className="mt-5 "> <p>I am a full stack javascript developer from India.</p> <p> I have developed some cool projects and have hosted them on {" "} <a style={style} target="_blank" rel="noopener noreferrer" href="https://github.com/yashgandhi876" > github. </a>{" "} I can help you with your projects, drop a mail at{" "} yashgandhi876@gmail.com </p> <p> Most of the time, I talk about web development and some other cool stuff on{" "} <a style={style} target="_blank" rel="noopener noreferrer" href="https://twitter.com/yashgandhi876" > twitter. </a> </p> <p> You can read more{" "} <Link style={style} to="/aboutme"> about me. </Link> </p> <p> If you like this website don't forget to hit{" "} <a style={style} target="_blank" rel="noopener noreferrer" href="https://github.com/yashgandhi876/yashgandhi.tech" > star button on github. </a> </p> </div> </div> ); } } export default Home;
BEER.MyStockMasterViewModel = function (data) { var self = this; self.Yeasts = new BEER.ViewModels.Yeast(); self.Malts = new BEER.ViewModels.Malt(); self.Hops = new BEER.ViewModels.Hop(); self.myMalts = new BEER.ViewModels.MyMalts(); self.myHops = new BEER.ViewModels.MyHops(); self.myYeasts = new BEER.ViewModels.MyYeasts(); self.updateStock = function () { if (localStorage) { localStorage.setItem('myMalts', JSON.stringify(self.myMalts.malts())); localStorage.setItem('myHops', JSON.stringify(self.myHops.hops())); localStorage.setItem('myYeasts', JSON.stringify(self.myYeasts.yeasts())); } } self.myMalts.getMyMalts(self.Malts.queryLoaded); self.myHops.getMyHops(self.Hops.queryLoaded); self.myYeasts.getMyYeasts(self.Yeasts.queryLoaded); console.log('hello') } ko.applyBindings(new BEER.MyStockMasterViewModel());
import React, { Component } from 'react'; import { Card, CardImg, CardText, CardBody, CardTitle } from 'reactstrap'; import { DISHES } from './../shared/dishes.js'; //CardImgOverlay, class DishDetail extends Component { componentDidMount(){ console.log('Dishdetail Component componentDidMount is Invoked'); } componentDidUpdate() { console.log('Dishdetail Component componentDidUpdate is Invoked'); } constructor(props) { super(props); this.state = { dish: null } this.state = { dishes: DISHES }; } dateFormat(datestring) { var split = datestring.split("-") const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] const year = split[0] const month = months[parseInt(split[1]) - 1] const day = split[2].split("T")[0] return month + " " + day + ", " + year } renderComments(commentArray) { if (commentArray != null) { const commentsDisplay = commentArray.map((comment) => { return( <div key={comment.id}> <p>{comment.comment}</p> <p>-- {comment.author}, {new Intl.DateTimeFormat('en-US', { year: 'numeric',month:'short',day:'2-digit'}).format(new Date(Date.parse(comment.date)))} </p> </div> ); }); // <p>-- {comment.author}, {this.dateFormat(comment.date)} return( <div> <h4>Comments</h4> {commentsDisplay} </div> ); } else { return( <div></div> ); } } renderDish(dish) { return( <Card> <CardImg top src={dish.image} alt={dish.name} /> <CardBody> <CardTitle>{dish.name}</CardTitle> <CardText>{dish.description}</CardText> </CardBody> </Card> ) } render() { console.log('Dishdetail Component render is Invoked'); const dish = this.props.dish if (dish != null) { return( <div className='container'> <div className="row"> <div className="col-12 col-md-5 m-1"> {this.renderDish(dish)} </div> <div className="col-12 col-md-5 m-1"> {this.renderComments(dish.comments)} </div> </div> </div> ); } else { return( <div></div> ); } } } export default DishDetail;
import request from 'supertest'; import cheerio from 'cheerio'; import { createTestHarness } from '../../testUtils/testHarness'; const macroWrapper = `{% from './components/view-expandable-section/macro.njk' import viewExpandableSection %} {{ viewExpandableSection(params) }}`; describe('view-expandable-section', () => { it('should render title of the expandable section', (done) => { const context = { params: { dataTestId: 'some-data-identifier', title: 'Some section title', }, }; const dummyApp = createTestHarness(macroWrapper, context); request(dummyApp) .get('/') .then((res) => { const $ = cheerio.load(res.text); expect($('[data-test-id="some-data-identifier"]').text().trim()).toEqual('Some section title'); done(); }); }); it('should render innerComponent of the expandable section', (done) => { const context = { params: { dataTestId: 'some-data-identifier', title: 'Some section title', innerComponent: '<p>Some inner component</p>', }, }; const dummyApp = createTestHarness(macroWrapper, context); request(dummyApp) .get('/') .then((res) => { const $ = cheerio.load(res.text); expect($('[data-test-id="some-data-identifier"] p').text().trim()).toEqual('Some inner component'); done(); }); }); it('should add classes provided within the params', (done) => { const context = { params: { dataTestId: 'some-data-identifier', title: 'Some title', classes: 'new-class another-class', }, }; const dummyApp = createTestHarness(macroWrapper, context); request(dummyApp) .get('/') .then((res) => { const $ = cheerio.load(res.text); expect($('div[data-test-id="some-data-identifier"]').hasClass('new-class')).toEqual(true); expect($('div[data-test-id="some-data-identifier"]').hasClass('another-class')).toEqual(true); done(); }); }); });
import {SERVICE_URLS} from '../constants/serviceUrl'; import * as types from '../constants/actiontypes'; import axios from 'axios'; import toastr from 'toastr'; let uploadFile = (token, acceptedFiles) =>{ const url = SERVICE_URLS.ACCOUNT_SETTINGS; var config = { headers: {'Authorization':'Token '+token} }; const apiuploadImageRequest = axios.post(url, { image: acceptedFiles[0] }, config); return(dispatch)=>{ return apiuploadImageRequest.then(({data})=>{ toastr.success("Profile image uploaded successfully"); }).catch((error)=>{ throw(error); }); } } let getAccountProfileDetails = (token) =>{ return axios.get(SERVICE_URLS.ACCOUNTS_SETTING_PROFILE, token); } let getAccountPrivateSettingsDetails = (token) =>{ return axios.get(SERVICE_URLS.ACCOUNTS_SETTING_PRIVATE, token); } let getAccountNotificationsDetails = (token) =>{ return axios.get(SERVICE_URLS.ACCOUNTS_SETTING_NOTIFICATION, token); } let getEmailSettingsDetails = (token) =>{ return axios.get(SERVICE_URLS.ACCOUNTS_SETTING_EMAIL, token); } let getAccountSettingsDetails = (token) =>{ var config = { headers: {'Authorization':'Token '+token} }; const apiRequest = axios.all([getAccountProfileDetails(config), getAccountPrivateSettingsDetails(config), getAccountNotificationsDetails(config),getEmailSettingsDetails(config)]); return(dispatch)=>{ return apiRequest.then(axios.spread(function (profileDetails, privateDetails, notificationDetails, emailDetails) { dispatch({type:types.GET_ACCOUNT_PROFILE_DETAILS,apiResult:profileDetails.data}); dispatch({type:types.GET_ACCOUNT_PRIVATE_DETAILS,apiResult:privateDetails.data}); dispatch({type:types.GET_ACCOUNT_NOTIFICATIONS_DETAILS,apiResult:notificationDetails.data}); dispatch({type:types.GET_ACCOUNT_EMAIL_DETAILS,apiResult:emailDetails.data}); })).catch((error)=>{ throw(error); }); } } let saveProfileDetails = (formData, token) =>{ var config = { headers: {'Authorization':'Token '+token} }; const url = SERVICE_URLS.ACCOUNTS_SETTING_PROFILE; const apiSaveProfileRequest = axios.post(url, formData, config); return(dispatch)=>{ return apiSaveProfileRequest.then(({data})=>{ toastr.success("Profile details saved successfully"); dispatch({type:types.GET_ACCOUNT_PROFILE_DETAILS,apiResult: data}); }).catch((error)=>{ toastr.error(error); throw(error); }); } } let savePrivateDetails = (formData, token) =>{ var config = { headers: {'Authorization':'Token '+token} }; const url = SERVICE_URLS.ACCOUNTS_SETTING_PRIVATE; const apiSaveProfileRequest = axios.post(url, formData, config); return(dispatch)=>{ return apiSaveProfileRequest.then(({data})=>{ toastr.success("Password changed successfully"); dispatch({type:types.GET_ACCOUNT_PRIVATE_DETAILS,apiResult: data}); }).catch((error)=>{ toastr.warning(error.response.data.error); throw(error); }); } } let saveNotificationDetails = (formData, token) =>{ var config = { headers: {'Authorization':'Token '+token} }; const url = SERVICE_URLS.ACCOUNTS_SETTING_NOTIFICATION; const apiSaveProfileRequest = axios.post(url, formData, config); return(dispatch)=>{ return apiSaveProfileRequest.then(({data})=>{ toastr.success("Notification settings saved successfully"); dispatch({type:types.GET_ACCOUNT_NOTIFICATIONS_DETAILS,apiResult: data}); }).catch((error)=>{ toastr.error(error); throw(error); }); } } let saveEmailDetails = (formData, token) =>{ var config = { headers: {'Authorization':'Token '+token} }; const url = SERVICE_URLS.ACCOUNTS_SETTING_EMAIL; const apiSaveProfileRequest = axios.post(url, formData, config); return(dispatch)=>{ return apiSaveProfileRequest.then(({data})=>{ toastr.success("Email settings saved successfully"); dispatch({type:types.GET_ACCOUNT_EMAIL_DETAILS,apiResult: data}); }).catch((error)=>{ toastr.error(error); throw(error); }); } } let getSkillset = (token) =>{ const url = SERVICE_URLS.GOLFER_SKILLS; var config = { headers: {'Authorization':'Token '+token} }; const apiSkillRequest = axios.get(url,config); return(dispatch) => { return apiSkillRequest.then(({data})=>{ dispatch({type:types.GET_SKILLS ,apiResult:data}); }).catch((error)=>{ if(error != "Error: Request failed with status code 401"){ toastr.error(error); } throw(error); }); } } let updateUserProfileImage = (image) => { return(dispatch) => { let _activeUser = JSON.parse(sessionStorage.getItem('userDetails')); _activeUser.profile_image_url = image; sessionStorage.setItem('userDetails', JSON.stringify(_activeUser)); return dispatch({type: types.UPDATE_PROFILE_IMAGE, activeUser: _activeUser}); } } export {getAccountSettingsDetails, saveProfileDetails, savePrivateDetails, saveNotificationDetails, saveEmailDetails, uploadFile, getSkillset, updateUserProfileImage};
const net = require('net'); const chat = require('./chat'); const chatRoom = new chat(); const server = net.createServer(client => { client.setEncoding('utf-8'); chatRoom.add(client); client.on('data', message => { chatRoom.send(client, message); }); client.on('close', () => { chatRoom.remove(client); }); }); const port = 65000; server.listen(port, err => { if (err) console.log('error', err); else console.log('server listening on port', port); });
import React, { useContext } from 'react' import UserAvatar from './UserAvatar' import { UserContext } from '../App' function useStates() { const user = useContext(UserContext) return ( <div className = 'user-states'> <div> <UserAvatar user={ user}/> {user.name} </div> <div className = 'states'> <p>{ user.followers} ta followers</p> <p>{ user.following} ta followinglar bor</p> </div> </div> ) } export default useStates
//Importer fastifer const fastify = require('fastify')({ logger: true }); // Import Os pour pouvoir recuper le hostname qui nous seras utile par la suite. const os = require("os"); // Creation du enpoint rest qui renvoie l'objet json ci-dessous fastify.get('/', async (request, reply) => { reply.type('application/json').code(200); return { 'name': 'Simple NodeJs App', 'deploy_type': 'Cloud Native', 'deploy_on': os.hostname(), 'Author': 'mombe090' } }); //Demarrer le serveur fastify. fastify.listen(3000, '0.0.0.0', (err, address) => { if (err) throw err fastify.log.info(`Server a bien demarrer sur l'adresse suivante ${address}`) });
const express = require("express"); const router = express.Router(); /** * Express router for /logout * * clear session and redirect to home page */ const logout = router.get('/logout',(req, res)=> { req.logout(); //req.session.destroy(); req.session = null; res.redirect('/'); }); module.exports = logout;
import React from 'react'; import {Button, ButtonGroup, Icon, Slider} from '@blueprintjs/core'; import {formatTime} from '../common/utils'; export default function (bundle) { bundle.use( 'recorderStart', 'recorderStop', 'recorderPause', 'recorderResume', 'playerStart', 'playerPause', 'playerSeek', 'getRecorderState', 'getPlayerState', 'Menu', 'StepperControls' ); bundle.defineView('RecorderControls', RecorderControlsSelector, RecorderControls); }; function RecorderControlsSelector (state, props) { const {getRecorderState, getPlayerState, StepperControls, Menu} = state.get('scope'); const {recorderStart, recorderPause, recorderResume, recorderStop, playerStart, playerPause, playerSeek} = state.get('actionTypes'); const getMessage = state.get('getMessage'); const recorder = getRecorderState(state); const recorderStatus = recorder.get('status'); const isPlayback = recorderStatus === 'paused'; let canRecord, canPlay, canPause, canStop, canStep, position, duration, playPause; if (isPlayback) { const player = getPlayerState(state); const isReady = player.get('isReady'); const isPlaying = player.get('isPlaying'); canPlay = canStop = canRecord = canStep = isReady && !isPlaying; canPause = isReady && isPlaying; playPause = isPlaying ? 'pause' : 'play'; position = player.get('audioTime'); duration = player.get('duration'); } else { canRecord = /ready|paused/.test(recorderStatus); canStop = /recording|paused/.test(recorderStatus); canPlay = recorderStatus === 'paused'; canPause = canStep = recorderStatus === 'recording'; position = duration = recorder.get('elapsed') || 0; playPause = 'pause'; } return { getMessage, recorderStatus, isPlayback, playPause, canRecord, canPlay, canPause, canStop, canStep, position, duration, StepperControls, Menu, recorderStart, recorderPause, recorderResume, recorderStop, playerStart, playerPause, playerSeek, }; } class RecorderControls extends React.PureComponent { render () { const { getMessage, canRecord, canPlay, canPause, canStop, canStep, isPlayback, playPause, position, duration, StepperControls, Menu } = this.props; return ( <div> <div className='hbox' style={{marginTop: '3px'}}> <div className="controls controls-main" style={{flexGrow: '3'}}> <ButtonGroup> <Button onClick={this.onStartRecording} disabled={!canRecord} title={getMessage('START_RECORDING')} icon={<Icon icon='record' color='#a01'/>}/> <Button onClick={this.onStopRecording} disabled={!canStop} icon='stop' title={getMessage('STOP_RECORDING')} /> {playPause === 'play' ? <Button onClick={this.onStartPlayback} disabled={!canPlay} title={getMessage('START_PLAYBACK')} icon='play' /> : <Button onClick={this.onPause} disabled={!canPause} title={getMessage('PAUSE_PLAYBACK')} icon='pause' />} </ButtonGroup> <div className='ihbox' style={{margin: '7px 0 0 10px'}}> <Icon icon='time'/> <span style={{marginLeft: '4px'}}> {formatTime(position)} {isPlayback && ' / '} {isPlayback && formatTime(duration)} </span> </div> </div> <div className='text-center' style={{flexGrow: '7'}}> <StepperControls enabled={canStep}/> </div> <div className='text-right' style={{flexGrow: '2'}}> <Menu/> </div> </div> {isPlayback && <div className='row' style={{marginTop: '3px'}}> <Slider value={position} onChange={this.onSeek} stepSize={100} labelStepSize={30000} min={0} max={duration} labelRenderer={formatTime} /> </div>} </div> ); } onStartRecording = () => { const {recorderStatus} = this.props; if (recorderStatus === 'ready') { this.props.dispatch({type: this.props.recorderStart}); } else { this.props.dispatch({type: this.props.recorderResume}); } }; onPause = () => { const {recorderStatus} = this.props; if (recorderStatus === 'recording') { this.props.dispatch({type: this.props.recorderPause}); } else { this.props.dispatch({type: this.props.playerPause}); } }; onStartPlayback = () => { this.props.dispatch({type: this.props.playerStart}); }; onStopRecording = () => { this.props.dispatch({type: this.props.recorderStop}); }; onSeek = (audioTime) => { this.props.dispatch({type: this.props.playerSeek, payload: {audioTime}}); }; }
import BaseView from './base'; export default class ItemView extends BaseView {}
import React from 'react' import {useSelector} from 'react-redux' import {currencyFormatter} from '../../actions/currencyFormatter' const CashBalance = () => { const balance = useSelector(state => state.currentUserReducer.currentUser.attributes.balance) return ( <span id ='balance'> {'CASH BALANCE: USD '} <strong>{currencyFormatter(balance)}</strong> </span> ) } export default CashBalance
const layer = layui.layer const form = layui.form const laypage = layui.laypage let q = { pagenum: 1, // 页码值,默认请求第一页的数据 pagesize: 2, // 每页显示几条数据,默认每页显示2条 cate_id: '', // 文章分类的 Id state: '' // 文章的发布状态 } // 渲染表格 function initTable() { $.ajax({ method: 'GET', data: q, url: '/my/article/list', success(res) { if (res.status !== 0) { return layer.msg(res.message) } console.log(res); // layer.msg(res.message) const htmlStr = template('articleHtml', res) $("tbody").html(htmlStr) renderPage(res.total) } }) } initTable() // 格式化时间 template.defaults.imports.dataFormat = function (date) { const dt = new Date(date) const y = dt.getFullYear(); const m = padZero(dt.getMonth() + 1); const d = padZero(dt.getDate()); const hour = padZero(dt.getHours()); const min = padZero(dt.getMinutes()); const sec = padZero(dt.getSeconds()); return `${y}-${m}-${d} ${hour}:${min}:${sec}` } function padZero(num) { return num >= 10 ? num : '0' + num } // 渲染分类列表 function initCate() { $.ajax({ type: 'GET', url: '/my/article/cates', success(res) { if (res.status !== 0) { return layer.msg(res.message) } console.log(res); const cateHtml = template('cateHtml', res); $('[name=cate_id]').html(cateHtml) form.render() } }) } initCate() // 实现筛选功能 $('#form-search').on('submit', function (e) { e.preventDefault(); const cate_id = $("[name=cate_id]").val() const state = $("[name=state]").val() q.cate_id = cate_id q.state = state console.log(cate_id, state); initTable() }) // 实现分页效果 function renderPage(total) { laypage.render({ elem: 'pageBox', count: total, limit: q.pagesize, limits: [2, 3, 5, 10], curr: q.pagenum, layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip'], jump: function (obj, first) { q.pagenum = obj.curr q.pagesize = obj.limit if (!first) { initTable() } } }) } // 删除文章 $("tbody").on('click', '.btnDel', function () { const id = $(this).attr('data-id') layer.confirm('确认删除?', { icon: 3, title: '提示' }, function (index) { $.ajax({ method: 'GET', url: '/my/article/delete/' + id, success(res) { if (res.status !== 0) { return layer.msg(res.message) } if ($('.btnDel').length === 1 && q.pagenum !== 1) { q.pagenum = q.pagenum - 1 } initTable() } }) layer.close(index) }) })
#!/usr/bin/env node const yargs = require('yargs'); const { argv } = yargs; const fs = require('fs'); const chalk = require('chalk'); yargs .usage('Usage: $0 <command> [options]') .example( '$0 --template="./templatest/sample.tsx" --output="components/Form/"', 'Write sample.tsx with strings replaced to output components directory' ) .nargs('template', 1) .nargs('output', 1) .describe('template', 'Load a template file') .describe('output', 'Ouput file location') .demandOption(['template', 'output']) .help('h') .alias('h', 'help') .epilog('Powered by Devzstudio').argv; const startProcess = async () => { await fs.readFile(argv.template, 'utf8', async function (err, data) { if (err) throw err; const ignoreCommandsList = ['template', 'output']; let fileContents = await data; Object.keys(argv).map((key) => { if (!ignoreCommandsList.includes(key)) { const slug = `{{${key}}}`; const regEx = new RegExp(slug, 'g'); fileContents = fileContents.replace(regEx, argv[key]); } }); await fs.writeFile(argv.output, fileContents, function (err) { if (err) { return console.log(err); } chalk.blue('The file was saved!'); }); }); }; startProcess();
import React from "react"; import { Link } from "react-router-dom"; export const MailButton = () => { return ( <Link to="/contact" > <button className="social-media-icon contact-icon"> <svg xmlns="http://www.w3.org/2000/svg" height="64" width="64" viewBox="0 0 64 64"><title>letter</title><g fill="#212121" className="nc-icon-wrapper"><path d="M33.933,37.5a4.006,4.006,0,0,1-3.867,0L2,22.017V51a6.006,6.006,0,0,0,6,6H56a6.006,6.006,0,0,0,6-6V22.017Z" fill="#212121"></path><path data-color="color-2" d="M56,7H8a6.006,6.006,0,0,0-6,6v5a1,1,0,0,0,.517.876l29,16a1,1,0,0,0,.966,0l29-16A1,1,0,0,0,62,18V13A6.006,6.006,0,0,0,56,7Z"></path></g></svg> </button> </Link > ) }
(global.webpackJsonp = global.webpackJsonp || []).push([ [ "pages/consultants/headimgs/main" ], { "07af": function(n, t, e) { function a(n) { return n && n.__esModule ? n : { default: n }; } Object.defineProperty(t, "__esModule", { value: !0 }), t.default = void 0; var o = a(e("8e44")), i = e("ccf5"), u = { mixins: [ a(e("327a")).default ], data: function() { return { per: 50, support_open_data: wx.canIUse("open-data") }; }, onLoad: function() { this.getData(); }, onShareAppMessage: function() { return this.getShareInfo({ title: "访问用户", path: "/pages/consultants/headimgs/main?id=".concat(this.$root.$mp.query.id) }); }, methods: { getData: function() { var n = this; this.items.length >= 500 && retrun; var t = this.page, e = this.$root.$mp.query.id; this.loading = !0, o.default.getConsultantViewers(e, { page: t, per: this.per }).then(function(t) { t.items = t.items.map(function(n) { return n || i.DEFAULT_HEADIMG; }), n.handleData(t); }); } }, components: { Loading: function() { e.e("components/views/loading").then(function() { return resolve(e("7756")); }.bind(null, e)).catch(e.oe); } } }; t.default = u; }, "16f7": function(n, t, e) { e.d(t, "b", function() { return a; }), e.d(t, "c", function() { return o; }), e.d(t, "a", function() {}); var a = function() { var n = this; n.$createElement; n._self._c; }, o = []; }, "1beb": function(n, t, e) { e.r(t); var a = e("07af"), o = e.n(a); for (var i in a) [ "default" ].indexOf(i) < 0 && function(n) { e.d(t, n, function() { return a[n]; }); }(i); t.default = o.a; }, "49f9": function(n, t, e) { (function(n) { function t(n) { return n && n.__esModule ? n : { default: n }; } e("6cdc"), t(e("66fd")), n(t(e("57f93")).default); }).call(this, e("543d").createPage); }, "57f93": function(n, t, e) { e.r(t); var a = e("16f7"), o = e("1beb"); for (var i in o) [ "default" ].indexOf(i) < 0 && function(n) { e.d(t, n, function() { return o[n]; }); }(i); e("fdcc"); var u = e("f0c5"), f = Object(u.a)(o.default, a.b, a.c, !1, null, "9d1748fc", null, !1, a.a, void 0); t.default = f.exports; }, f612: function(n, t, e) {}, fdcc: function(n, t, e) { var a = e("f612"); e.n(a).a; } }, [ [ "49f9", "common/runtime", "common/vendor" ] ] ]);
import React from "react"; function SubTestimonial(props) { return ( <div className="subTest-wrapper"> <div className="subTest-icon"> <i class="fas fa-quote-left"></i> </div> <div className="subTest-quote">{props.quote}</div> <div className="subTest-img"> <img src={props.image} alt="testimonial portrait" /> </div> <div className="subTest-name">{props.name}</div> </div> ); } export default SubTestimonial;
import clsx from 'clsx'; const KPI = ({ className }) => { return ( <div className={clsx( className, 'p-12 shadow-xl rounded-md flex justify-center items-center' )}> <div className="h-17 w-17 rounded-full bg-icoBlue-200 mr-5"></div> <div> <p className="font-extrabold text-4xl">47.2k</p> <span className="text-icoGray-500 font-bold">Total followers</span> </div> </div> ); }; export default KPI;
var AWS = require('aws-sdk'); AWS.config.update({region: 'us-east-1'}); var dynamodb = new AWS.DynamoDB(); var fs = require('fs'); var obj = JSON.parse(fs.readFileSync('import.json', 'utf8')); var crypto = require('crypto'); var toadd = []; obj.forEach(function(data) { for(var obj in data.questions) { var uid = hash(data.questions[obj].question); //toadd.push({'uid': uid, 'question': data.questions[obj]}); toadd.push({'uid': uid, 'question': data.questions[obj]}); } }); for(var i in toadd) { console.log(toadd[i]); var params = { Item: { "uid": { "S": toadd[i].uid }, "question": { "S": toadd[i].question.question }, "choices": { "L": [ { "S": toadd[i].question.choices[0] }, { "S": toadd[i].question.choices[1] }, { "S": toadd[i].question.choices[2] }, { "S": toadd[i].question.choices[3] } ] }, "correct": { "S": toadd[i].question.correct } }, TableName: 'Questions' } dynamodb.putItem(params, function(err, data) { if(err) { console.log(err); } else { console.log(data); } }); } function hash(pwd) { return crypto.createHash('sha512').update(pwd).digest('base64'); }
/** * @param {number[][]} graph * @param {number[]} initial * @return {number} */ let DSU = function(n) { this.size = []; this.root = []; this.infected = []; for (let i = 0; i < n; i++) { root[i] = i; } this.find = function(x) { if (root[x] != x) { root[x] = find(root[x]); } return root[x]; }; }; var minMalwareSpread = function(graph, initial) { // 1 - 2 - 3 // 0. find the disjoint set, which only one node is infected. // 1. choose the disjoint set which has largest nodes // 2. return the smallest index };
/* * Copyright 2017 PhenixP2P Inc. Confidential and Proprietary. All Rights Reserved. * Please see the LICENSE file included with this distribution for details. */ import React from 'react'; import {PropTypes} from 'prop-types'; import styles from '../../styles/controls.css'; const LatencyText = ({lag}) => ( <div className={`${styles.streamStatusMessage}`}> {lag < .5 ? 'Real-Time': `Latency: ${lag}`} </div> ); LatencyText.propTypes = { lag: PropTypes.number.isRequired }; export default LatencyText;
const request = require('request'); const config = require('../config'); const defaultClient = request.defaults({ headers: { Accept: 'application/json', }, timeout: config.rest.timeout, }); exports.defaultClient = defaultClient;
//функция столкновения астероида с элементом переданным в функции function crashAsteroid(getAsteroid, element) { //если положение астероида заходит на переданный элемент if (getAsteroid.offsetTop + getAsteroid.offsetWidth > element.offsetTop && getAsteroid.offsetLeft + getAsteroid.offsetWidth > element.offsetLeft && getAsteroid.offsetLeft < element.offsetLeft + element.offsetWidth) { //если элемент - корабль if(element.className == 'ship') { getAsteroid.remove(); //отнимаем жизнь quantityLifes--; //если жизни закончились if (quantityLifes == 0) { //вызываем функция завершения игры over(); } //обновляем блок с жизнями lifes.remove(); creatureLifes(); //вызываем функцию создания взрыва на корабле creatureBum(); //если элемент - пуля } else if (element.className == "shot") { //вызываем функцию взрыва explode(getAsteroid, "explode", 8); //удаляем элемент element.remove(); //перебираем массив с пулями shots.forEach(function(value, i) { //если id пули с массива = id элемента if (value.id == element.id) { //удаляем с массива 1 ячейку начиная с позиции i shots.splice(i, 1); } }); } } }