text
stringlengths
7
3.69M
import React from 'react'; import { useFormik } from 'formik'; import * as Yup from 'yup'; import {useDispatch, useSelector} from "react-redux"; import {addUser, usernameChange, roleChange} from "../../../store/actions/app"; import { useHistory } from 'react-router-dom'; const Registration = () => { let users = useSelector((state) => state.appReducer.users) let dispatch = useDispatch() const history = useHistory(); const { handleChange, handleSubmit, values, touched, errors } = useFormik({ initialValues: { firstName: '', lastName: '', email: '', password: '', confirmPassword: '', }, validationSchema: Yup.object({ firstName: Yup.string() .max(15, 'Must be 15 characters or less') .required('Required'), lastName: Yup.string() .max(20, 'Must be 20 characters or less') .required('Required'), email: Yup.string().email('Invalid email address').required('Required'), password: Yup.string() .min(6, 'Password should be longer 6 characters') .required(), confirmPassword: Yup.string().oneOf( [Yup.ref('password'), null], 'Passwords must match' ), }), onSubmit: (values) => { const name = values.firstName const email = values.email const password = values.password let ifIn = users.filter(el => el.email === email) if(ifIn.length > 0){ alert('User is found, sign up') } else { dispatch(addUser({ name: name, password: password, role: "user", email: email })) dispatch(usernameChange(name)) dispatch(roleChange('user')) history.push('/'); } }, }); return ( <div> <form onSubmit={handleSubmit}> <label htmlFor="name">Enter you name</label> <input id="user_name" name="firstName" type="name" minlength="6" placeholder="Name" onChange={handleChange} value={values.firstName} /> <label htmlFor="surname">Enter you surname</label> <input id="user_surname" name="lastName" type="name" minlength="6" placeholder="Surname" onChange={handleChange} value={values.lastName} /> <label htmlFor="password">Enter you password</label> <input id="password" name="password" type="password" placeholder="Password" onChange={handleChange} value={values.password} /> {touched.password && errors.password ? <p>{errors.password}</p> : null} <label htmlFor="password">Confirm password</label> <input id="confirm_password" name="confirmPassword" type="password" placeholder="Confirm password" value={values.confirmPassword} onChange={handleChange} /> {touched.confirmPassword && errors.confirmPassword && ( <p className={'error'}>{errors.confirmPassword}</p> )} <span className="confirm"></span> <label htmlFor="mail">Enter you email</label> <input id="email" type="email" placeholder="email" onChange={handleChange} value={values.email} /> {touched.email && errors.email ? <div>{errors.email}</div> : null} <input id="submit" className="btn-input" type="submit" value="Sing Up" /> <input type="reset" value="Clear" /> </form> </div> ); }; export default Registration;
'use strict' angular.module('soniaSpaApp').factory('articleFactory', function ($http){ var getAll = function(){ return $http({ method: 'GET', url: '/api/article/' }); } return { getAll: getAll } });
game.LoadingScreen = me.ScreenObject.extend({ init : function() { this.parent(true); this.invalidate = false; this.loadPercent = 0; me.loader.onProgress = this.onProgressUpdate.bind(this); this.logo = null; }, onResetEvent: function() { if (this.logo == null) { // init stuff if not yet done this.logo = me.loader.getImage("logo"); } }, onProgressUpdate : function(progress) { this.loadPercent = progress; this.invalidate = true; }, update : function() { if (this.invalidate === true) { this.invalidate = false; return true; } return false; }, onDestroyEvent : function() { this.logo = null; }, draw : function(context) { console.log("draw loading") me.video.clearSurface(context, "#efefef"); context.drawImage(this.logo, 95,0); var width = Math.floor(this.loadPercent * context.canvas.width); /*context.strokeStyle = "#fff200"; context.strokeRect(0, (context.canvas.height / 2) + 40, context.canvas.width, 20); context.fillStyle = "#89b002"; context.fillRect(2, (context.canvas.height / 2) + 42, width - 4, 18);*/ context.strokeStyle = "#fff200"; context.strokeRect(0, (me.video.getHeight() / 2) + 40, me.video.getWidth(), 6); context.fillStyle = "#f47920"; context.fillRect(2, (me.video.getHeight() / 2) + 42, width-4, 2); } });
module.exports = { siteMetadata: { title: `Shreya Shankar`, author: `Shreya Shankar`, description: `Making machine learning work in the real world.`, siteUrl: `http://shreya-shankar.com/`, social: { twitter: `sh_reya`, }, }, plugins: [ { resolve: `gatsby-transformer-remark`, options: { plugins: [ `gatsby-remark-emoji`, // <-- this line adds emoji ] } }, { resolve: `gatsby-source-filesystem`, options: { path: `${__dirname}/content/blog`, name: `blog`, }, }, { resolve: `gatsby-source-filesystem`, options: { path: `${__dirname}/content/assets`, name: `assets`, }, }, { resolve: `gatsby-transformer-remark`, options: { plugins: [ { resolve: `gatsby-remark-table-of-contents`, options: { exclude: "Table of Contents", tight: true, fromHeading: 1, toHeading: 6, className: "table-of-contents", }, }, `gatsby-remark-autolink-headers`, { resolve: `gatsby-remark-images`, options: { maxWidth: 590, }, }, { resolve: `gatsby-remark-responsive-iframe`, options: { wrapperStyle: `margin-bottom: 1.0725rem`, }, }, { resolve: `gatsby-remark-highlight-code`, }, `gatsby-remark-prismjs`, `gatsby-remark-copy-linked-files`, `gatsby-remark-smartypants`, `gatsby-remark-reading-time`, ], }, }, `gatsby-transformer-sharp`, `gatsby-plugin-sharp`, { resolve: `gatsby-plugin-google-analytics`, options: { trackingId: 'UA-137597884-1', }, }, `gatsby-plugin-feed`, { resolve: `gatsby-plugin-manifest`, options: { name: `Gatsby Starter Blog`, short_name: `GatsbyJS`, start_url: `/`, background_color: `#ffffff`, theme_color: `#0B3C5D`, display: `minimal-ui`, icon: `content/assets/gatsby-icon.png`, }, }, `gatsby-plugin-offline`, `gatsby-plugin-react-helmet`, { resolve: `gatsby-plugin-typography`, options: { pathToConfigModule: `src/utils/typography`, }, }, { resolve: 'gatsby-plugin-mailchimp', options: { endpoint: 'https://gmail.us20.list-manage.com/subscribe/post?u=076f3389d8d753915c5285ef4&amp;id=4733e9a320', // see instructions section below }, }, ], }
var name = "John"; var talk = function () { var name = "Sandy"; console.log("My name is", name); } talk(); var walk = function () { console.log(name, "is walking."); } walk();
import React from 'react'; import { Container, ContentListas, ContentListMovies, ContentMovie } from './styles'; export function LinhaDeFilmes({title, items}) { return ( <Container> <h2>{title}</h2> <ContentListas> <ContentListMovies> {items.results.length > 0 && items.results.map((item, key) => ( <ContentMovie key={key}> <img src={`https://image.tmdb.org/t/p/w300${item.poster_path}`} alt={item.original_title}/> </ContentMovie> ))} </ContentListMovies> </ContentListas> </Container> ) }
//获取cookie export function getCookie(name) { let cookieStr = document.cookie; if(cookieStr.length==0)return; let arr; let res = null; if (cookieStr.indexOf(';') > -1) { arr = cookieStr.split(';'); arr.forEach((cookie, index) => { let tmp_arr = cookie.split('='); if (tmp_arr[0] == name) { res = tmp_arr[1] } }) } else { let tmp_arr = cookieStr.split('='); if (tmp_arr[0] == name) { res = tmp_arr[1] } } return res } //jsonp跨域封装 //动态创建script标签, 添加到body src 指定接口地址,准备callback name export function loginput(){ let t=new Date(); t.setTime(t.getTime()-1) document.cookie='token='+getCookie('token')+';expirse='+t.toUTCString() }
WinJS.Namespace.define('malfiGlobals', { session: [], gridView: true, displayedItemsArray: [], searchedItemsArray: [], searchHistoryArray: [], invokedDiv: null, activeUser: '', activeHost: '', loadingInProgress: false, rootFolder: [], selecteditemsArray: [], currentObject: { id: "", name: "" }, operations: { operations: [], properties: []}, uploadedItems: 0, currentLocation: { name: 'Views', id: 'defaultViews', type: 'defaultFolder', }, currentPath: { path: [], history: 0, backSteps: -1 }, isLoggedArr: [], //Used to store custom theme objects customTheme: [], //Used to store custom theme CSS strings customizationReady: {background: false, logo: false, theme: false, language: false}, customThemeCSS: [], backgroundImage: [], companyLogo: [], strings: [], sites: [ {name: 'Favorite sites', id:'favoriteSites', objectTypeId: 'sitesFolder'}, {name: 'My sites', id:'mySites', objectTypeId: 'sitesFolder'}, {name: 'All sites', id:'allSites', objectTypeId: 'sitesFolder'} ], toastNotification: function (msg, duration) { if (document.visibilityState === 'hidden') { var notifications = Windows.UI.Notifications; var template = notifications.ToastTemplateType.toastImageAndText02; var toastXml = notifications.ToastNotificationManager.getTemplateContent(template); var toastTextElements = toastXml.getElementsByTagName("text"); toastTextElements[0].appendChild(toastXml.createTextNode(msg)); var toastNode = toastXml.selectSingleNode("/toast"); toastNode.setAttribute("duration", duration); var launchAttribute = toastXml.createAttribute("launch"); launchAttribute.value = true toastNode.attributes.setNamedItem(launchAttribute); var toast = new notifications.ToastNotification(toastXml); var toastNotifier = notifications.ToastNotificationManager.createToastNotifier(); toastNotifier.show(toast); } }, passwordVault: new Windows.Security.Credentials.PasswordVault(), popupQueue: { currentAlert: null, queue: [], showSync: function (alert) { malfiGlobals.popupQueue.queue.push(alert); malfiGlobals.popupQueue.showNext(); }, showNext: function () { if (malfiGlobals.popupQueue.currentAlert !== null) { return; } if (malfiGlobals.popupQueue.queue.length > 0) { malfiGlobals.popupQueue.currentAlert = malfiGlobals.popupQueue.queue.shift(); malfiGlobals.popupQueue.currentAlert.showAsync().done( function (){ malfiGlobals.popupQueue.currentAlert = null; malfiGlobals.popupQueue.showNext(); }, function (){ malfiGlobals.popupQueue.currentAlert = null; malfiGlobals.popupQueue.showNext(); }) } } }, defaultViews: [], allDefaultViews: [ { name: 'Activities', id: 'activities', objectTypeId: 'defaultFolder' }, { name: 'Repository', id: 'repository', objectTypeId: 'defaultFolder' }, { name: 'Shared Files', id: 'sharedFiles', objectTypeId: 'defaultFolder' }, { name: 'Sites', id: 'sites', objectTypeId: 'defaultFolder' }, { name: 'My Files', id: 'myFiles', objectTypeId: 'defaultFolder' }, { name: 'My Tasks', id: 'tasks', objectTypeId: 'defaultFolder' }, { name: 'Favorites', id: 'favorites', objectTypeId: 'defaultFolder' } ] });
$(document).ready(function() { $ludyTrigger = $('.ludy-trigger'); $ludyWrapper = $('.ludy-wrapper'); $ludyTrigger.on('click', function() { $(this).slideUp(400, function() { $ludyWrapper.slideDown(400); }); }); });
// Conceito "chave/valor" const saudacao = 'Opa!'; function exec() { const saudacao = "Diz aí!!!!" return saudacao } // Objetos são grupos aninhados de chaves/valores const cliente = { nome:'Pedro', idade:'32', peso: '76', endereço: { rua: 'Rua dos bobos', numero: 0, } } console.log(saudacao); console.log(exec()); console.log(cliente); console.log(cliente.nome);
/*************************** * BUSCA BINÁRIA * * Requer um conjunto de dados ORDENADO. * Atua dividindo o vetor sucessivamente em metades aproximadas, * até que o valor de busca seja localizado, ou que o ponteiro * de fim acabe antes do ponteiro de início. Essa última situação * indica que o valor de busca não existe no conjunto. */ let comps function buscaBinaria(vetor, valorBusca) { comps = 0 let ini = 0 let fim = vetor.length - 1 while(fim >= ini) { comps++ // Math.floor() retira as casas decimais de um número let meio = Math.floor((ini + fim) / 2) // Se o valor de busca for igual ao valor do vetor // na posição do meio, encontramos o que procuramos // e retornamos a posição onde encontramos if(valorBusca === vetor[meio]) { comps++ return meio } // Senão, se o valor de busca for maior que o valor // do meio do vetor, descartamos a metade esquerda // do vetor trazendo o ponteiro ini para meio + 1 else if(valorBusca > vetor[meio]) { comps += 2 ini = meio + 1 } // Por fim, caso o valor de busca seja menor que o // valor do meio do vetor, descartamos a metade direita // do vetor trazendo o ponteiro fim para meio - 1 else { comps += 2 fim = meio - 1 } } // Se chegamos até aqui, significa que fim < ini e, portanto, // o valor de busca não existe no vetor. Para indicar isso, // retornamos o valor convencional -1 return -1 } let nums = [0, 11, 22, 33, 44, 55, 66, 77, 88, 99] console.log('Posição de 33:', buscaBinaria(nums, 33), 'comps:', comps) console.log('Posição de 77:', buscaBinaria(nums, 77), 'comps:', comps) console.log('Posição de 81:', buscaBinaria(nums, 81), 'comps:', comps) /****************************************************************/ import { nomes } from './data/vetor-nomes.mjs' console.log(`Posição de FAUSTO: ${buscaBinaria(nomes, 'FAUSTO')}, comps: ${comps}`) console.log(`Posição de ADAMASTOR: ${buscaBinaria(nomes, 'ADAMASTOR')}, comps: ${comps}`) console.log(`Posição de ZULEIDE: ${buscaBinaria(nomes, 'ZULEIDE')}, comps: ${comps}`) console.log(`Posição de INSTAGRAMILDA: ${buscaBinaria(nomes, 'INSTAGRAMILDA')}, comps: ${comps}`) console.log(`Posição de JERDERSON: ${buscaBinaria(nomes, 'JERDERSON')}, comps: ${comps}`)
import React, {Component} from 'react' import { connect } from 'react-redux' import { resetAuthedUser } from '../actions/authedUser' import { NavLink, withRouter } from 'react-router-dom' class Navbar extends Component { state = {showLogout: true}; constructor(props) { super(props); this.state = {showLogout: false}; this.handleClick = this.handleClick.bind(this); } componentWillMount() { document.addEventListener('mousedown', this.handleDropdownClick, false); } componentWillUnmount() { document.removeEventListener('mousedown', this.handleDropdownClick, false); } handleDropdownClick = (e) => { const { resetAuthedUser } = this.props if (this.state.showLogout === true) { if (this.node.contains(e.target)) { resetAuthedUser() this.setState(() => ({showLogout: !this.state.showLogout})) this.props.history.push('/') return; } this.setState(() => ({showLogout: !this.state.showLogout})) } } handleClick() { this.setState(() => ({showLogout: !this.state.showLogout})) } render() { const { authedUser, user } = this.props return ( <div className='navbar navbar-expand-md navbar-light'> <ul className='navbar-nav'> <li className='nav-item active'> <NavLink to='/' exact activeClassName='active' className='nav-link'>Home</NavLink> </li> <li className='nav-item'> <NavLink to='/add' exact activeClassName='active' className='nav-link'>New Question</NavLink> </li> <li className='nav-item'> <NavLink to='/leaderboard' exact activeClassName='active' className='nav-link'>Leaderboard</NavLink> </li> </ul> {authedUser !== null && <div className='nav-item'> {user !== null && <div className='dropdown'> <div className='row'> <p className='username'>{user.name}</p> <button className='btn btn-default dropdown-toggle' onClick={this.handleClick}> <img src={user.avatarURL} className='avatar' alt={`Avatar of ${authedUser}`} /> </button> </div> {this.state.showLogout && <ul className='logout' ref={ node => this.node = node }> <p role='menuitem' className='logout-link' onClick={(e) => this.handleDropdownClick(e)}>Log Out</p> </ul> } </div> } </div> } </div> ) } } function mapStateToProps ({ authedUser, users, dispatch }) { return { authedUser, user: users[authedUser], dispatch, } } function mapDispatchToProps (dispatch) { return { resetAuthedUser: () => { dispatch(resetAuthedUser()) } } } export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Navbar))
$(function () { $("button[name='submit']").click(function (){ //获取注册信息 var username = $("input[name='username']").val().trim(); var password = $("input[name='password'").val().trim(); var gender = $("input[name='gender'").val(); var age = $("input[name='age']").val().trim(); var city = $("select[name='city']").val(); var hobbies = new Array(); $("input[name='hobby']:checked").each(function () { hobbies.push($(this).val()); }); var introduction = $("textarea[name='introduction']").val(); //传递数组时传递参数的名字用 *[],后台获取时也用 *[] 的名字获取 if (username != "") { if (password != "") { if (age != "") { var args = { username : username, password : password, gender : gender, age : age, city : city, "hobbies[]" : hobbies, introduction : introduction } $.post("register", args, function (data) { if (data == "1") { //条用 blockUI 插件,实现动态效果,信息持续5秒 $.blockUI({ message: '<h4>注册成功,将在5秒后跳转到聊天室!</h3>' }); setTimeout($.unblockUI, 5000); //5秒后跳转 setTimeout("window.location.href='index'", 5000); } }) } else { alert("年龄不得为空"); } } else { alert("密码不得为空!"); } } else { alert("用户名不得为空!"); } return false; }) })
'use strict'; module.exports = (sequelize, DataTypes) => { const PrductColor = sequelize.define('PrductColor', { imagepath: DataTypes.TEXT }, {}); PrductColor.associate = function(models) { // associations can be defined here PrductColor.belongsTo(models.Products,{foreignKey:'ProductId'}); PrductColor.belongsTo(models.Colors,{foreignKey:'ColorId'}); }; return PrductColor; };
import React from 'react'; import styled from 'styled-components'; const StyledLogo = styled.svg` width: 27px; height: 40px; position: fixed; left: 50%; top: 50%; transform: translate(-50%, -50%); animation: 500ms ease-in-out infinite alternate pulse; @keyframes pulse { from { transform: translate(-50%, -50%) scale(1); } to { transform: translate(-50%, -50%) scale(1.3); } } `; const Diagonal = styled.path` fill: #1E1D1D; `; const Vertical = styled.path` fill: #303535 `; const Logo = () => { return ( <StyledLogo viewBox="0 0 27 40"> <Diagonal d="M19.9641 0.00930016L3.07421 24.5245C2.79973 24.9244 2.35141 25.1569 1.87564 25.1569H0V26.6915H1.58285H2.69908H7.53914L25.9387 0L19.9641 0.00930016Z"/> <Vertical d="M22.041 16.322V36.4569L27 40.0002V13.4482H22.041H19.3511V14.9828H20.7235C21.4554 14.9828 22.041 15.5873 22.041 16.322Z"/> </StyledLogo> ); }; export default Logo;
'use strict'; var repos = require('./github/githubRepos'); var issues = require('./github/githubIssues'); var filter = require('./filter/randomFilterStrategy.js'); exports.findIssue = function(req, res) { repos.select(req.params.language, filter.get).then(function (repoName) { return issues.select(repoName, filter.get); }).then(function (issueUrl) { res.json({issueUrl: issueUrl}); }).fail(function (error) { res.json({ issueUrl: 'Find and fix me, bitch!', errorMsg: error.message}); }); };
// The implementation is based on the code in Filament Engine: https://github.com/google/filament // specifically, shaders here: https://github.com/google/filament/tree/24b88219fa6148b8004f230b377f163e6f184d65/filament/src/materials/ssao // --------------- POST EFFECT DEFINITION --------------- // /** * @class * @name SSAOEffect * @classdesc Implements the SSAOEffect post processing effect. * @description Creates new instance of the post effect. * @augments PostEffect * @param {GraphicsDevice} graphicsDevice - The graphics device of the application. * @param {any} ssaoScript - The script using the effect. */ function SSAOEffect(graphicsDevice, ssaoScript) { pc.PostEffect.call(this, graphicsDevice); this.ssaoScript = ssaoScript; this.needsDepthBuffer = true; var fSsao = [ pc.shaderChunks.screenDepthPS, "", "varying vec2 vUv0;", "", "//uniform sampler2D uColorBuffer;", "uniform vec4 uResolution;", "", "uniform float uAspect;", "", "#define saturate(x) clamp(x,0.0,1.0)", "", "// Largely based on 'Dominant Light Shadowing'", "// 'Lighting Technology of The Last of Us Part II' by Hawar Doghramachi, Naughty Dog, LLC", "", "const float kSSCTLog2LodRate = 3.0;", "", "highp float getWFromProjectionMatrix(const mat4 p, const vec3 v) {", " // this essentially returns (p * vec4(v, 1.0)).w, but we make some assumptions", " // this assumes a perspective projection", " return -v.z;", " // this assumes a perspective or ortho projection", " // return p[2][3] * v.z + p[3][3];", "}", "", "highp float getViewSpaceZFromW(const mat4 p, const float w) {", " // this assumes a perspective projection", " return -w;", " // this assumes a perspective or ortho projection", " // return (w - p[3][3]) / p[2][3];", "}", "", "", "const float kLog2LodRate = 3.0;", "", "vec2 sq(const vec2 a) {", " return a * a;", "}", "", "uniform float uInvFarPlane;", "", "vec2 pack(highp float depth) {", "// we need 16-bits of precision", " highp float z = clamp(depth * uInvFarPlane, 0.0, 1.0);", " highp float t = floor(256.0 * z);", " mediump float hi = t * (1.0 / 256.0); // we only need 8-bits of precision", " mediump float lo = (256.0 * z) - t; // we only need 8-bits of precision", " return vec2(hi, lo);", "}", "", "// random number between 0 and 1, using interleaved gradient noise", "float random(const highp vec2 w) {", " const vec3 m = vec3(0.06711056, 0.00583715, 52.9829189);", " return fract(m.z * fract(dot(w, m.xy)));", "}", "", "// returns the frag coord in the GL convention with (0, 0) at the bottom-left", "highp vec2 getFragCoord() {", " return gl_FragCoord.xy;", "}", "", "highp vec3 computeViewSpacePositionFromDepth(highp vec2 uv, highp float linearDepth) {", " return vec3((0.5 - uv) * vec2(uAspect, 1.0) * linearDepth, linearDepth);", "}", "", "highp vec3 faceNormal(highp vec3 dpdx, highp vec3 dpdy) {", " return normalize(cross(dpdx, dpdy));", "}", "", "// Compute normals using derivatives, which essentially results in half-resolution normals", "// this creates arifacts around geometry edges.", "// Note: when using the spirv optimizer, this results in much slower execution time because", "// this whole expression is inlined in the AO loop below.", "highp vec3 computeViewSpaceNormal(const highp vec3 position) {", " return faceNormal(dFdx(position), dFdy(position));", "}", "", "// Compute normals directly from the depth texture, resulting in full resolution normals", "// Note: This is actually as cheap as using derivatives because the texture fetches", "// are essentially equivalent to textureGather (which we don't have on ES3.0),", "// and this is executed just once.", "highp vec3 computeViewSpaceNormal(const highp vec3 position, const highp vec2 uv) {", " highp vec2 uvdx = uv + vec2(uResolution.z, 0.0);", " highp vec2 uvdy = uv + vec2(0.0, uResolution.w);", " highp vec3 px = computeViewSpacePositionFromDepth(uvdx, -getLinearScreenDepth(uvdx));", " highp vec3 py = computeViewSpacePositionFromDepth(uvdy, -getLinearScreenDepth(uvdy));", " highp vec3 dpdx = px - position;", " highp vec3 dpdy = py - position;", " return faceNormal(dpdx, dpdy);", "}", "", "// Ambient Occlusion, largely inspired from:", "// 'The Alchemy Screen-Space Ambient Obscurance Algorithm' by Morgan McGuire", "// 'Scalable Ambient Obscurance' by Morgan McGuire, Michael Mara and David Luebke", "", "uniform vec2 uSampleCount;", "uniform float uSpiralTurns;", "", "#define PI (3.14159)", "", "vec3 tapLocation(float i, const float noise) {", " float offset = ((2.0 * PI) * 2.4) * noise;", " float angle = ((i * uSampleCount.y) * uSpiralTurns) * (2.0 * PI) + offset;", " float radius = (i + noise + 0.5) * uSampleCount.y;", " return vec3(cos(angle), sin(angle), radius * radius);", "}", "", "highp vec2 startPosition(const float noise) {", " float angle = ((2.0 * PI) * 2.4) * noise;", " return vec2(cos(angle), sin(angle));", "}", "", "uniform vec2 uAngleIncCosSin;", "", "highp mat2 tapAngleStep() {", " highp vec2 t = uAngleIncCosSin;", " return mat2(t.x, t.y, -t.y, t.x);", "}", "", "vec3 tapLocationFast(float i, vec2 p, const float noise) {", " float radius = (i + noise + 0.5) * uSampleCount.y;", " return vec3(p, radius * radius);", "}", "", "uniform float uMaxLevel;", "uniform float uInvRadiusSquared;", "uniform float uMinHorizonAngleSineSquared;", "uniform float uBias;", "uniform float uPeak2;", "", "void computeAmbientOcclusionSAO(inout float occlusion, float i, float ssDiskRadius,", " const highp vec2 uv, const highp vec3 origin, const vec3 normal,", " const vec2 tapPosition, const float noise) {", "", " vec3 tap = tapLocationFast(i, tapPosition, noise);", "", " float ssRadius = max(1.0, tap.z * ssDiskRadius);", // at least 1 pixel screen-space radius "", " vec2 uvSamplePos = uv + vec2(ssRadius * tap.xy) * uResolution.zw;", "", " float level = clamp(floor(log2(ssRadius)) - kLog2LodRate, 0.0, float(uMaxLevel));", " highp float occlusionDepth = -getLinearScreenDepth(uvSamplePos);", " highp vec3 p = computeViewSpacePositionFromDepth(uvSamplePos, occlusionDepth);", "", " // now we have the sample, compute AO", " vec3 v = p - origin; // sample vector", " float vv = dot(v, v); // squared distance", " float vn = dot(v, normal); // distance * cos(v, normal)", "", " // discard samples that are outside of the radius, preventing distant geometry to", " // cast shadows -- there are many functions that work and choosing one is an artistic", " // decision.", " float w = max(0.0, 1.0 - vv * uInvRadiusSquared);", " w = w*w;", "", " // discard samples that are too close to the horizon to reduce shadows cast by geometry", " // not sufficiently tessellated. The goal is to discard samples that form an angle 'beta'", " // smaller than 'epsilon' with the horizon. We already have dot(v,n) which is equal to the", " // sin(beta) * |v|. So the test simplifies to vn^2 < vv * sin(epsilon)^2.", " w *= step(vv * uMinHorizonAngleSineSquared, vn * vn);", "", " occlusion += w * max(0.0, vn + origin.z * uBias) / (vv + uPeak2);", "}", "", "uniform float uProjectionScaleRadius;", "uniform float uIntensity;", "", "float scalableAmbientObscurance(highp vec2 uv, highp vec3 origin, vec3 normal) {", " float noise = random(getFragCoord());", " highp vec2 tapPosition = startPosition(noise);", " highp mat2 angleStep = tapAngleStep();", "", " // Choose the screen-space sample radius", " // proportional to the projected area of the sphere", " float ssDiskRadius = -(uProjectionScaleRadius / origin.z);", "", " float occlusion = 0.0;", // webgl1 does not handle non-constant loop, work around it graphicsDevice.webgl2 ? ( " for (float i = 0.0; i < uSampleCount.x; i += 1.0) {" ) : ( " const float maxSampleCount = 256.0;" + " for (float i = 0.0; i < maxSampleCount; i += 1.0) {" + " if (i >= uSampleCount.x) break;" ), " computeAmbientOcclusionSAO(occlusion, i, ssDiskRadius, uv, origin, normal, tapPosition, noise);", " tapPosition = angleStep * tapPosition;", " }", " return sqrt(occlusion * uIntensity);", "}", "", "uniform float uPower;", "", "void main() {", " highp vec2 uv = vUv0; //variable_vertex.xy; // interpolated to pixel center", "", " highp float depth = -getLinearScreenDepth(vUv0);", " highp vec3 origin = computeViewSpacePositionFromDepth(uv, depth);", " vec3 normal = computeViewSpaceNormal(origin, uv);", "", " float occlusion = 0.0;", "", " if (uIntensity > 0.0) {", " occlusion = scalableAmbientObscurance(uv, origin, normal);", " }", "", " // occlusion to visibility", " float aoVisibility = pow(saturate(1.0 - occlusion), uPower);", "", " vec4 inCol = vec4(1.0, 1.0, 1.0, 1.0); //texture2D( uColorBuffer, uv );", "", " gl_FragColor.r = aoVisibility; //postProcess.color.rgb = vec3(aoVisibility, pack(origin.z));", "}", "", "void main_old()", "{", " vec2 aspectCorrect = vec2( 1.0, uAspect );", "", " float depth = getLinearScreenDepth(vUv0);", " gl_FragColor.r = fract(floor(depth*256.0*256.0)),fract(floor(depth*256.0)),fract(depth);", "}" ].join("\n"); var fblur = [ pc.shaderChunks.screenDepthPS, "", "varying vec2 vUv0;", "", "uniform sampler2D uSSAOBuffer;", "uniform vec4 uResolution;", "", "uniform float uAspect;", "", "uniform int uBilatSampleCount;", "uniform float uFarPlaneOverEdgeDistance;", "uniform float uBrightness;", "", "float random(const highp vec2 w) {", " const vec3 m = vec3(0.06711056, 0.00583715, 52.9829189);", " return fract(m.z * fract(dot(w, m.xy)));", "}", "", "float bilateralWeight(in float depth, in float sampleDepth) {", " float diff = (sampleDepth - depth) * uFarPlaneOverEdgeDistance;", " return max(0.0, 1.0 - diff * diff);", "}", "", "void tap(inout float sum, inout float totalWeight, float weight, float depth, vec2 position) {", " // ambient occlusion sample", " float ssao = texture2D( uSSAOBuffer, position ).r;", " float tdepth = -getLinearScreenDepth( position );", "", " // bilateral sample", " float bilateral = bilateralWeight(depth, tdepth);", " bilateral *= weight;", " sum += ssao * bilateral;", " totalWeight += bilateral;", "}", "", "void main() {", " highp vec2 uv = vUv0; // variable_vertex.xy; // interpolated at pixel's center", "", " // we handle the center pixel separately because it doesn't participate in bilateral filtering", " float depth = -getLinearScreenDepth(vUv0); // unpack(data.gb);", " float totalWeight = 0.0; // float(uBilatSampleCount*2+1)*float(uBilatSampleCount*2+1);", " float ssao = texture2D( uSSAOBuffer, vUv0 ).r;", " float sum = ssao * totalWeight;", "", // webgl1 does not handle non-constant loop, work around it graphicsDevice.webgl2 ? ( " for (int x = -uBilatSampleCount; x <= uBilatSampleCount; x++) {" + " for (int y = -uBilatSampleCount; y < uBilatSampleCount; y++) {" ) : ( " for (int x = -4; x <= 4; x++) {" + " for (int y = -4; y < 4; y++) {" ), " float weight = 1.0;", " vec2 offset = vec2(x,y)*uResolution.zw;", " tap(sum, totalWeight, weight, depth, uv + offset);", " }", " }", "", " float ao = sum / totalWeight;", "", " // simple dithering helps a lot (assumes 8 bits target)", " // this is most useful with high quality/large blurs", " // ao += ((random(gl_FragCoord.xy) - 0.5) / 255.0);", "", " ao = mix(ao, 1.0, uBrightness);", " gl_FragColor.a = ao;", "}" ].join("\n"); var foutput = [ "varying vec2 vUv0;", "uniform sampler2D uColorBuffer;", "uniform sampler2D uSSAOBuffer;", "", "void main(void)", "{", " vec4 inCol = texture2D( uColorBuffer, vUv0 );", " float ssao = texture2D( uSSAOBuffer, vUv0 ).a;", " gl_FragColor.rgb = inCol.rgb * ssao;", " gl_FragColor.a = inCol.a;", "}" ].join("\n"); var attributes = { aPosition: pc.SEMANTIC_POSITION }; this.ssaoShader = pc.createShaderFromCode(graphicsDevice, pc.PostEffect.quadVertexShader, fSsao, 'SsaoShader', attributes); this.blurShader = pc.createShaderFromCode(graphicsDevice, pc.PostEffect.quadVertexShader, fblur, 'SsaoBlurShader', attributes); this.outputShader = pc.createShaderFromCode(graphicsDevice, pc.PostEffect.quadVertexShader, foutput, 'SsaoOutputShader', attributes); // Uniforms this.radius = 4; this.brightness = 0; this.samples = 20; this.downscale = 1.0; } SSAOEffect.prototype = Object.create(pc.PostEffect.prototype); SSAOEffect.prototype.constructor = SSAOEffect; SSAOEffect.prototype._destroy = function () { if (this.target) { this.target.destroyTextureBuffers(); this.target.destroy(); this.target = null; } if (this.blurTarget) { this.blurTarget.destroyTextureBuffers(); this.blurTarget.destroy(); this.blurTarget = null; } }; SSAOEffect.prototype._resize = function (target) { var width = Math.ceil(target.colorBuffer.width / this.downscale); var height = Math.ceil(target.colorBuffer.height / this.downscale); // If no change, skip resize if (width === this.width && height === this.height) return; // Render targets this.width = width; this.height = height; this._destroy(); var ssaoResultBuffer = new pc.Texture(this.device, { format: pc.PIXELFORMAT_RGBA8, minFilter: pc.FILTER_LINEAR, magFilter: pc.FILTER_LINEAR, addressU: pc.ADDRESS_CLAMP_TO_EDGE, addressV: pc.ADDRESS_CLAMP_TO_EDGE, width: this.width, height: this.height, mipmaps: false }); ssaoResultBuffer.name = 'SSAO Result'; this.target = new pc.RenderTarget({ name: "SSAO Result Render Target", colorBuffer: ssaoResultBuffer, depth: false }); var ssaoBlurBuffer = new pc.Texture(this.device, { format: pc.PIXELFORMAT_RGBA8, minFilter: pc.FILTER_LINEAR, magFilter: pc.FILTER_LINEAR, addressU: pc.ADDRESS_CLAMP_TO_EDGE, addressV: pc.ADDRESS_CLAMP_TO_EDGE, width: this.width, height: this.height, mipmaps: false }); ssaoBlurBuffer.name = 'SSAO Blur'; this.blurTarget = new pc.RenderTarget({ name: "SSAO Blur Render Target", colorBuffer: ssaoBlurBuffer, depth: false }); }; Object.assign(SSAOEffect.prototype, { render: function (inputTarget, outputTarget, rect) { this._resize(inputTarget); var device = this.device; var scope = device.scope; var sampleCount = this.samples; var spiralTurns = 10.0; var step = (1.0 / (sampleCount - 0.5)) * spiralTurns * 2.0 * 3.141; var radius = this.radius; var bias = 0.001; var peak = 0.1 * radius; var intensity = (peak * 2.0 * 3.141) * 0.125; var projectionScale = 0.5 * device.height; var cameraFarClip = this.ssaoScript.entity.camera.farClip; scope.resolve("uAspect").setValue(this.width / this.height); scope.resolve("uResolution").setValue([this.width, this.height, 1.0 / this.width, 1.0 / this.height]); scope.resolve("uBrightness").setValue(this.brightness); scope.resolve("uInvFarPlane").setValue(1.0 / cameraFarClip); scope.resolve("uSampleCount").setValue([sampleCount, 1.0 / sampleCount]); scope.resolve("uSpiralTurns").setValue(spiralTurns); scope.resolve("uAngleIncCosSin").setValue([Math.cos(step), Math.sin(step)]); scope.resolve("uMaxLevel").setValue(0.0); scope.resolve("uInvRadiusSquared").setValue(1.0 / (radius * radius)); scope.resolve("uMinHorizonAngleSineSquared").setValue(0.0); scope.resolve("uBias").setValue(bias); scope.resolve("uPeak2").setValue(peak * peak); scope.resolve("uIntensity").setValue(intensity); scope.resolve("uPower").setValue(1.0); scope.resolve("uProjectionScaleRadius").setValue(projectionScale * radius); // Render SSAO this.drawQuad(this.target, this.ssaoShader, rect); scope.resolve("uSSAOBuffer").setValue(this.target.colorBuffer); scope.resolve("uFarPlaneOverEdgeDistance").setValue(1); scope.resolve("uBilatSampleCount").setValue(4); // Perform the blur this.drawQuad(this.blurTarget, this.blurShader, rect); // Finally output to screen scope.resolve("uSSAOBuffer").setValue(this.blurTarget.colorBuffer); scope.resolve("uColorBuffer").setValue(inputTarget.colorBuffer); this.drawQuad(outputTarget, this.outputShader, rect); } }); // ----------------- SCRIPT DEFINITION ------------------ // var SSAO = pc.createScript('ssao'); SSAO.attributes.add('radius', { type: 'number', default: 4, min: 0, max: 20, title: 'Radius' }); SSAO.attributes.add('brightness', { type: 'number', default: 0, min: 0, max: 1, title: 'Brightness' }); SSAO.attributes.add('samples', { type: 'number', default: 16, min: 1, max: 256, title: 'Samples' }); SSAO.attributes.add('downscale', { type: 'number', default: 1, min: 1, max: 4, title: "Downscale" }); SSAO.prototype.initialize = function () { this.effect = new SSAOEffect(this.app.graphicsDevice, this); this.effect.radius = this.radius; this.effect.brightness = this.brightness; this.effect.samples = this.samples; this.effect.downscale = this.downscale; this.on('attr', function (name, value) { this.effect[name] = value; }, this); var queue = this.entity.camera.postEffects; queue.addEffect(this.effect); this.on('state', function (enabled) { if (enabled) { queue.addEffect(this.effect); } else { queue.removeEffect(this.effect); } }); this.on('destroy', function () { queue.removeEffect(this.effect); this.effect._destroy(); }); };
// eslint-disable-next-line import/named import { NEWSLETTER_SUBSCRIPTION_SUCCESS, NEWSLETTER_SUBSCRIPTION_FAILURE } from './actions'; const initialState = {}; export default function (state = initialState, action) { switch (action.type) { case NEWSLETTER_SUBSCRIPTION_SUCCESS: return action.payload; case NEWSLETTER_SUBSCRIPTION_FAILURE: return action.payload; default: return state; } }
import React, { Component } from 'react'; import { inject, observer } from 'mobx-react'; import qs from 'query-string'; import { Redirect } from 'react-router-dom'; @inject('store') @observer export class AuthPage extends Component { componentWillMount() { const parsed = qs.parse(this.props.history.location.hash) let state; if (parsed.state) { state = JSON.parse(atob(parsed.state)); } let { page, ...query } = state; this.setState({ page, query }); } render() { const query = this.state.query? qs.stringify(this.state.query) : ''; return ( <div> Authenticating... {this.state.page && this.props.store.authenticated && <Redirect to={{ pathname: this.state.page, search: `?${query}` }} />} </div> ) } } export default AuthPage;
const shadow = extend(UnitType, "shadow", { draw(unit) { this.super$draw(unit); Draw.rect("basement-shadow-spinner", unit.x, unit.y, Time.time * 10); Draw.rect("basement-shadow-spinner-outline", unit.x, unit.y, Time.time * 10); Draw.rect("basement-shadow-glow", unit.x, unit.y, Time.time * -10); } }); shadow.constructor = () => extend(UnitEntity, {});
var dir_e0b72804fc6af7ff2a40eccee45fe58a = [ [ "Options", "dir_4b8906d65f34608a697cf4d1b25db375.html", "dir_4b8906d65f34608a697cf4d1b25db375" ], [ "Responses", "dir_47d4e96897544e1c4e9e5c2c5a482c79.html", "dir_47d4e96897544e1c4e9e5c2c5a482c79" ], [ "C1ConnectorContractor.h", "_c1_connector_contractor_8h_source.html", null ], [ "C1ConnectorElement.h", "_c1_connector_element_8h_source.html", null ], [ "C1ConnectorEntitlement.h", "_c1_connector_entitlement_8h_source.html", null ], [ "C1ConnectorGetUserInfoForServiceResponsePublic.h", "_c1_connector_get_user_info_for_service_response_public_8h_source.html", null ], [ "C1ConnectorOffer.h", "_c1_connector_offer_8h_source.html", null ], [ "C1ConnectorOfferGroup.h", "_c1_connector_offer_group_8h_source.html", null ], [ "C1ConnectorOptIn.h", "_c1_connector_opt_in_8h_source.html", null ], [ "C1ConnectorProduct.h", "_c1_connector_product_8h_source.html", null ], [ "C1ConnectorPublicInterface.h", "_c1_connector_public_interface_8h_source.html", null ], [ "C1ConnectorResult.h", "_c1_connector_result_8h_source.html", null ], [ "C1ConnectorSettings.h", "_c1_connector_settings_8h_source.html", null ], [ "C1ConnectorStoreOffer.h", "_c1_connector_store_offer_8h_source.html", null ], [ "C1ConnectorUser.h", "_c1_connector_user_8h_source.html", null ], [ "C1ConnectorUserGroupAction.h", "_c1_connector_user_group_action_8h_source.html", null ], [ "C1ConnectorUserMasterData.h", "_c1_connector_user_master_data_8h_source.html", null ] ];
var t = require('./talk') function constructor () { // A function, the same as any other this.blah = 'Aargh' } constructor.prototype.hrm = 'Yeah...' // So what happend? var obj = new constructor // New created an object that inherited from constructor.prototype // Then magically executed constructor in it's context // and then returned that object for some reason. var other = Object.create(constructor.prototype) constructor.call(other) t.l( obj , obj.hrm , other , other.hrm )
import KeyCodes from 'keycodes-enum'; import AccessibilityModule from '../../index'; describe('ScrollBarData', () => { describe('register role', () => { let cjsScrollBar; let scrollBarEl; let orientationVal; let shouldEnableKeyEvents; beforeEach(() => { cjsScrollBar = new createjs.Shape(); // dummy object orientationVal = 'horizontal'; shouldEnableKeyEvents = false; AccessibilityModule.register({ accessibleOptions: { enableKeyEvents: shouldEnableKeyEvents, orientation: orientationVal, }, displayObject: cjsScrollBar, parent: container, role: AccessibilityModule.ROLES.SCROLLBAR, }); stage.accessibilityTranslator.update(); scrollBarEl = parentEl.querySelector('div[role=scrollbar]'); }); describe('rendering', () => { it('creates div[role=scrollbar] element', () => { expect(scrollBarEl).not.toBeNull(); }); it('sets "aria-orientation" attribute', () => { expect(scrollBarEl.getAttribute('aria-orientation')).toEqual( orientationVal ); }); describe('superclass defaults', () => { it('sets "aria-valuemax" attribute', () => { expect(scrollBarEl.getAttribute('aria-valuemax')).toEqual('100'); }); it('sets "aria-valuemin" attribute', () => { expect(scrollBarEl.getAttribute('aria-valuemin')).toEqual('0'); }); it('sets "aria-valuenow" attribute', () => { expect(scrollBarEl.getAttribute('aria-valuenow')).toEqual('50'); }); }); }); describe('accessible options getters and setters', () => { it('can read and set "orientation" property [for "aria-orientation"]', () => { expect(cjsScrollBar.accessible.orientation).toEqual(orientationVal); const newVal = 'vertical'; cjsScrollBar.accessible.orientation = newVal; expect(cjsScrollBar.accessible.orientation).toEqual(newVal); }); }); describe('other options getters and setters', () => { it('can read and set "enableKeyEvents" property', () => { expect(cjsScrollBar.accessible.enableKeyEvents).toEqual( shouldEnableKeyEvents ); const newVal = true; cjsScrollBar.accessible.enableKeyEvents = newVal; expect(cjsScrollBar.accessible.enableKeyEvents).toEqual(newVal); }); }); describe('onKeyDown event listener', () => { let scrollListener; let prevValue; beforeEach(() => { scrollListener = jest.fn(); cjsScrollBar.on('scroll', scrollListener); prevValue = cjsScrollBar.accessible.value; }); it('can emit "scroll" event when orientation is "horizontal" and "left" key is pressed', () => { const keyCode = KeyCodes.left; scrollBarEl.dispatchEvent(new KeyboardEvent('keydown', { keyCode })); expect(scrollListener).toBeCalledTimes(1); const eventData = scrollListener.mock.calls[0][0]; expect(eventData.scrollLeft).toBeLessThan(prevValue); }); it('can emit "scroll" event when orientation is "horizontal" and "right" key is pressed', () => { const keyCode = KeyCodes.right; scrollBarEl.dispatchEvent(new KeyboardEvent('keydown', { keyCode })); expect(scrollListener).toBeCalledTimes(1); const eventData = scrollListener.mock.calls[0][0]; expect(eventData.scrollLeft).toBeGreaterThan(prevValue); }); it('can emit "scroll" event when orientation is "vertical" and "up" key is pressed', () => { cjsScrollBar.accessible.orientation = 'vertical'; const keyCode = KeyCodes.up; scrollBarEl.dispatchEvent(new KeyboardEvent('keydown', { keyCode })); expect(scrollListener).toBeCalledTimes(1); const eventData = scrollListener.mock.calls[0][0]; expect(eventData.scrollTop).toBeLessThan(prevValue); }); it('can emit "scroll" event when orientation is "vertical" and "down" key is pressed', () => { cjsScrollBar.accessible.orientation = 'vertical'; const keyCode = KeyCodes.down; scrollBarEl.dispatchEvent(new KeyboardEvent('keydown', { keyCode })); expect(scrollListener).toBeCalledTimes(1); const eventData = scrollListener.mock.calls[0][0]; expect(eventData.scrollTop).toBeGreaterThan(prevValue); }); it('"keydown" events are not emitted if enableKeyEvents is false', () => { const keydownListener = jest.fn(); cjsScrollBar.on('keydown', keydownListener); const keyCode = KeyCodes.left; scrollBarEl.dispatchEvent(new KeyboardEvent('keydown', { keyCode })); expect(scrollListener).toBeCalledTimes(1); expect(keydownListener).not.toBeCalled(); }); it('"keydown" events are emitted if enableKeyEvents is true', () => { const keydownListener = jest.fn(); cjsScrollBar.accessible.enableKeyEvents = true; cjsScrollBar.on('keydown', keydownListener); const keyCode = KeyCodes.left; scrollBarEl.dispatchEvent(new KeyboardEvent('keydown', { keyCode })); expect(scrollListener).toBeCalledTimes(1); expect(keydownListener).toBeCalledTimes(1); }); it('"scroll" events are not emitted if enableKeyEvents is true and default is prevented', () => { const keydownListener = jest.fn(); cjsScrollBar.accessible.enableKeyEvents = true; cjsScrollBar.on('keydown', keydownListener); const keyCode = KeyCodes.left; const keydownEvent = new KeyboardEvent('keydown', { keyCode }); Object.defineProperty(keydownEvent, 'defaultPrevented', { value: true, }); scrollBarEl.dispatchEvent(keydownEvent); expect(scrollListener).not.toBeCalled(); expect(keydownListener).toBeCalledTimes(1); }); it('"scroll" event is not emitted if "up"/"down" keys are not pressed when orientation is "vertical"', () => { cjsScrollBar.accessible.orientation = 'vertical'; const keyCode = KeyCodes.left; scrollBarEl.dispatchEvent(new KeyboardEvent('keydown', { keyCode })); expect(scrollListener).not.toBeCalled(); }); it('"scroll" event is not emitted if "left"/"right" keys are not pressed when orientation is "horizontal"', () => { cjsScrollBar.accessible.orientation = 'horizontal'; const keyCode = KeyCodes.up; scrollBarEl.dispatchEvent(new KeyboardEvent('keydown', { keyCode })); expect(scrollListener).not.toBeCalled(); }); }); }); });
import { Link } from '@reach/router' import React from 'react' const Game3 = props => { const { loaded, allPlayers, updateStatus } = props; const clickHandler = (player,index,setStatus) => { updateStatus(player,index,setStatus); } return ( <div> <table className="table table-dark text-center"> <thead> <tr> <th scope="col">#</th> <th scope="col">Player Name</th> <th scope="col">Position</th> <th scope="col">Status</th> <th scope="col">Change Status</th> </tr> </thead> <tbody> { loaded ? allPlayers.map((player, i) => <tr key={i}> <th scope="row">{player.jerseyNumber}</th> <td>{player.name}</td> <td>{player.position}</td> { player.active ? <div> { player.active[2] === 0 ? <td>Unassigned</td> : player.active[2] === 1 ? <td>Starting</td> : player.active[2] === 2 ? <td>Benched</td> : "" } </div> : console.log(player) } <td> <button className="btn btn-success" onClick={() => clickHandler(player, 2, 1)}>Start</button> | <button className="btn btn-danger" onClick={() => clickHandler(player, 2, 2)}>Bench</button> | <button className="btn btn-warning" onClick={() => clickHandler(player, 2, 0)}>Unassign</button> </td> </tr> ) : "" } </tbody> </table> </div> ) } export default Game3
// DETERMINE LOCATION CENTERING function centerFinder(obj) { obj.addEventListener('touchstart', function(e) { this.offset_x = e.x; this.offset_y = e.y; if (typeof this.origin == 'undefined') { this.origin = this.center; } this.zIndex = 50; }); obj.addEventListener('touchmove', function(e) { this.center = { x:this.center.x + (e.x - this.offset_x), y:this.center.y + (e.y - this.offset_y) }; Ti.API.debug('Center: ' + this.center.x + ', ' + this.center.y ); }); }
import React from "react"; import { Field, reduxForm } from "redux-form"; import renderField from "components/FormInputs/renderField"; import authLib from '../../../config/authlib'; class HandoverForm extends React.Component { constructor(props) { super(props); console.log(props); this.state = { loading: false, registerPostmen: [], registerPostmenObj: [], thePackage: {}, items: [], id: props.match.params.orderid }; this.handleSubmit = this.handleSubmit.bind(this); this.options = authLib.getFetchOptions(); } getPostmenId(email) { var postman = this.state.registerPostmenObj.filter((postman) => { if (postman.Email.toLowerCase() == email.toLowerCase()) return true; }); return postman[0].ID; } handleSubmit(event) { event.preventDefault(); //verify if it is a valid postman email address if (event.target.length > 0 && this.state.registerPostmen.indexOf(event.target[0].value) === -1) { alert('Please provide correct email address'); return; } var todayDate = authLib.getTodayDate(); var email = event.target[0].value; var postmanid = this.getPostmenId(email); //set the state to loading of the view this.setState({ loading: true }); fetch("http://localhost:8000/OrderHistory", { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-access-token': this.options.headers['x-access-token'] }, body: JSON.stringify({ "orderId": this.state.orderid, "handoverDate": todayDate, "status": "In-Transit", "postmanId": postmanid }) }) .then(res => res.json()) .then( (data) => { alert('Package has been assigned'); console.log(data); //TODO: redirect to home page }); fetch("http://localhost:8000/package/" + this.state.orderid, { method: 'PUT', headers: { 'Content-Type': 'application/json', 'x-access-token': this.options.headers['x-access-token'] }, body: JSON.stringify({ "orderId": this.state.orderid, "Status": "In-Transit" }) }) } componentDidMount() { //component is still loading this.setState({ loading: true }); //Fetch the data from the persons to see if he is valid postman, only get postman fetch(global.backendURL + "persons", this.options) .then(function (response) { if (response.ok) return response.json(); else[].json(); }) .then((data) => { this.registerPostmen = data; data.forEach(elemnt => { this.state.registerPostmenObj.push(elemnt); this.state.registerPostmen.push(elemnt.Email); }) this.setState({ loading: false }); }); } render() { return ( <div className="card"> <div className="header"> <h4>Handover Package</h4> </div> <h4 className="text-center">Package ID: {this.state.id}</h4> <div className="content"> <form onSubmit={this.handleSubmit} className="form-horizontal"> <legend>Details of receiving postman</legend> <div className="form-group"> <label className="control-label col-md-3">Email</label> <div className="col-md-9"> <Field name="postmanEmail" placeholder="Receiving Postman" type="text" component={renderField} // helpText="postman receiving the package" /> </div> </div> <button type="submit" className="btn btn-fill btn-info"> Submit </button> </form> </div> </div> ); } } export default reduxForm({ form: "formElements" })(HandoverForm);
// Main navigation menu function ShowSection(nav_id) { // Button press command differentiation from the URL // INTENDENT USAGE www.shmulman.co.il/index.html?Cost // var Command = URL_Command(); // document.getElementById("Output4").innerHTML = "Command = " + Command; // if (Command == 'Home') {nav_id = 'Home';} // if (Command == 'About') {nav_id = 'About';} // if (Command == 'Cost') {nav_id = 'Cost';} // if (Command == 'Contacts') {nav_id = 'Contacts';} document.getElementById("Home").style.display="none"; document.getElementById("About").style.display="none"; document.getElementById("Cost").style.display="none"; document.getElementById("Contacts").style.display="none"; document.getElementById(nav_id).style.display = "block"; } // 'Cost' button initiation from external URL function URL_Command() { var FullURL = window.location.search.substring(1); var ParameterArray = FullURL.split('?'); // Slits one string into words and removes & sign var ParameterValue = ParameterArray[0]; if (ParameterValue == 'About' || ParameterValue == 'Cost' || ParameterValue == 'Contacts') { return ParameterValue; } else { ParameterValue = 'Home'; return ParameterValue; } } // Questions workflow functions *********************** // OnLoad sequence for Home Terms & Questions function ClearText_ru() { document.getElementById("t1").style.display="none"; document.getElementById("t2").style.display="none"; document.getElementById("t3").style.display="none"; document.getElementById("t4").style.display="none"; document.getElementById("q1").style.display="none"; document.getElementById("q2").style.display="none"; document.getElementById("q3").style.display="none"; document.getElementById("q4").style.display="none"; document.getElementById("q5").style.display="none"; document.getElementById("q6").style.display="none"; } function ClearText_he() { document.getElementById("q1").style.display="none"; document.getElementById("q2").style.display="none"; document.getElementById("q3").style.display="none"; } // Choose Home Terms & Questions ******************************** function ShowQuery_ru(nav_id) { document.getElementById("t1").style.display="none"; document.getElementById("t2").style.display="none"; document.getElementById("t3").style.display="none"; document.getElementById("t4").style.display="none"; document.getElementById("q1").style.display="none"; document.getElementById("q2").style.display="none"; document.getElementById("q3").style.display="none"; document.getElementById("q4").style.display="none"; document.getElementById("q5").style.display="none"; document.getElementById("q6").style.display="none"; document.getElementById(nav_id).style.display = "block"; } function ShowQuery_he(nav_id) { document.getElementById("q1").style.display="none"; document.getElementById("q2").style.display="none"; document.getElementById("q3").style.display="none"; document.getElementById(nav_id).style.display = "block"; }
/* eslint-disable no-plusplus */ /* eslint-disable guard-for-in */ const obj = { name: 'мечник', health: 10, level: 2, attack: 80, defence: 40, } export default function orderByProps(object, order) { const arr = [] for (const prop in object) { arr.push({ key: prop, value: object[prop] }) } arr.sort((a, b) => (a.key > b.key ? 1 : -1)); if (order) { for (let i = order.length - 1; i >= 0; i--) { const index = arr.findIndex((item) => item.key === order[i]) const item = arr[index] arr.splice(index, 1) arr.unshift(item) } } return arr } orderByProps(obj, ['name', 'defence', 'level'])
import BaseModel from './BaseModel'; import cards from '../cards'; import AnaliticsCounter from './AnaliticsCounter'; export default class HackerSpaceModel extends BaseModel { constructor() { super('Hacker Space'); this.categories = cards[0].map((name) => ({ name })); this.categoriesStatistics = cards[0].map((name) => new AnaliticsCounter(name)); this.cards = cards.slice(1).map((categoryCards, categoryIndex) => { const statistic = this.categoriesStatistics[categoryIndex]; return categoryCards.map((card) => { const cardStatistics = statistic.getWordData(card.word); const percent = (cardStatistics.gameErrorClicks / (cardStatistics.gameErrorClicks + cardStatistics.gameSuccessClicks)) * 100; return { word: card.word, translation: card.translation, trainClicks: cardStatistics.trainClicks, gameSuccessClicks: cardStatistics.gameSuccessClicks, gameErrorClicks: cardStatistics.gameErrorClicks, percent: (percent || 0).toFixed(2), }; }); }); } }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const THREE = SupEngine.THREE; class SelectionRenderer extends SupEngine.ActorComponent { constructor(actor) { super(actor, "SelectionRenderer"); this.meshes = []; } setIsLayerActive(active) { for (const mesh of this.meshes) mesh.visible = active; } setup(width, height, start, end, frameOrder, framesPerDirection) { this.clearMesh(); for (let i = start; i <= end; i++) { const geometry = new THREE.PlaneBufferGeometry(width, height); const material = new THREE.MeshBasicMaterial({ color: 0x900090, alphaTest: 0.1, transparent: true, opacity: 0.5 }); const mesh = new THREE.Mesh(geometry, material); this.meshes.push(mesh); let x, y; if (frameOrder === "rows") { x = i % framesPerDirection; y = Math.floor(i / framesPerDirection); } else { x = Math.floor(i / framesPerDirection); y = i % framesPerDirection; } mesh.position.setX((x + 0.5) * width); mesh.position.setY(-(y + 0.5) * height); mesh.updateMatrixWorld(false); this.actor.threeObject.add(mesh); } } clearMesh() { for (const mesh of this.meshes) { mesh.geometry.dispose(); mesh.material.dispose(); this.actor.threeObject.remove(mesh); } this.meshes.length = 0; } _destroy() { this.clearMesh(); super._destroy(); } } exports.default = SelectionRenderer;
import React from 'react'; import {Image, Text, View} from 'react-native'; import styles from './styles'; export default class MovieCard extends React.Component { render() { const {movie, imageUri} = this.props; return ( <View style={styles.card}> <View style={styles.posterContainer}> <Image resizeMode="cover" resizeMethod="resize" source={{uri: imageUri}} style={styles.poster} /> </View> <View style={styles.cardCaption}> <Text style={styles.cardTitle} numberOfLines={1} ellipsizeMode="tail"> {movie.title} </Text> </View> </View> ); } }
function func() { var x = document.getElementById('name').value; numx = parseInt(x); numx = numx + 1; document.getElementById('answer').innerHTML = numx; }
const catchAsync = require('../utils/catchAsync'); const AppError = require('../utils/appError'); const User = require('../models/userModel'); exports.getAllUsers = catchAsync(async (req, res, next) => { const users = await User.find(); if (!users) { return next(new AppError(`There is no User in DataBase!`, 400)); } res.status(200).json({ status: 'success', results: users.length, data: { users, }, }); }); exports.updateMe = catchAsync(async (req, res, next) => { if (req.body.password || req.body.passwordConfirm) { return next( new AppError( `You are not allowed to change your password here! use /updatePassword Route!`, 400 ) ); } const filterObj = (obj, ...role) => { const newObj = {}; Object.keys(obj).forEach((el) => { if (role.includes(el)) { newObj[el] = obj[el]; } }); return newObj; }; const filterBody = filterObj(req.body, 'name', 'family', 'email'); const updatedUser = await User.findByIdAndUpdate(req.user.id, filterBody, { new: true, runValidators: true, }); res.status(200).json({ status: 'success', data: { updatedUser, }, }); }); exports.deleteMe = catchAsync(async (req, res, next) => { await User.findByIdAndUpdate(req.user.id, { active: false }); res.status(204).json({ status: 'success', message: `User Successfuly deleted!`, }); });
var mumble = require('mumble'); var fs = require('fs'); // var scream = fs.createReadStream('scream.wav'); //fs.readFileSync('scream.wav'); var options = { key: fs.readFileSync( 'key.pem' ), cert: fs.readFileSync( 'crt.pem' ) } /* To generate certificates: key: openssl pkcs12 -in MumbleCertificate.p12 -out key.pem -nocerts -nodes cert: openssl pkcs12 -in MumbleCertificate.p12 -out crt.pem -clcerts -nokeys */ // scream.on('end', function() { // console.log('stream ended'); // scream.unpipe(); // }); console.log( 'Connecting' ); mumble.connect( 'mumble://benhen.zzzz.io', options, function ( error, connection ) { if( error ) { throw new Error( error ); } console.log( 'Connected' ); connection.authenticate( 'e' ); // THiS CODE DOESN'T WORK FOR SOME REASON // for (var i = 0; i < oneWordCommands.length; i++) { // var word = oneWordCommands[i][1]; // var identifier = oneWordCommands[i][0] // console.log(word+'from ' + oneWordCommands[i][0]); // var newCommand = new Object(); // newCommand.identifier = identifier; // newCommand.minLength = 0; // newCommand.action = function(connection, keyString, keyArray) { // sendMessage(connection, word); // console.log('index of ' + i); // } // // var newItem = { // // identifier: identifier, // // minLength: 0, // // action: function(connection, keyString, keyArray) { // // sendMessage(connection, word); // // } // // }; // commands.push(newCommand); // }; connection.on( 'initialized', function() { //gotta add that parameter onInit(connection); }); connection.on( 'message', function(message, actor) { //gotta add that parameter again onMessage(connection, message, actor); }); connection.on('user-connect', function(user) { sendMessage('Hello ' + user.name + '!'); }); // connection.on( 'voice', onVoice ); }); var onInit = function(connection) { console.log( 'Connection initialized' ); // Connection is authenticated and usable. //Print out a list of users (you can comment this out) var users = connection.users(); console.log(JSON.stringify(users[0].name)); for (var i = 0; i < users.length; i++) { console.log('Hi ' + users[i].name + '!'); } //Connect to Elliptical Madness if it exists //I added timeouts to account for connection delays //There is probably a better way, but whatever setTimeout(function() { //look for channel var channel = connection.channelByName("Elliptical Madness"); if (channel) { console.log("Autoconnect channel found."); channel.join(); setTimeout(function() { sendMessage(connection, "Autoconnected. Hi!"); }, 1000); } else { console.log("Autoconnected channel not found"); } }, 500); }; var playing = false; var onMessage = function(connection, message, actor) { if (actor.name === 'e') { //don't respond to yourself return; } //Ignore message if it doesn't contain "!" if (message.indexOf("!") === -1) return; //Take away all html elements - from this: //http://stackoverflow.com/questions/17164335/how-to-remove-only-html-tags-in-a-string-using-javascript var messageText = message.replace(/<\/?(p|i|b|br)\b[^<>]*>/g, ''); messageArray = messageText.split(' '); for (var i = 0; i < messageArray.length; i++) { //convert to lower case to make easier to parse messageArray[i] = messageArray[i].toLowerCase(); }; //ignore message if it doesn't meet certain criteria if (!messageArray || messageArray.length === 0 || messageArray[0].length === 1 || messageArray[0].substring(0, 1) !== '!') return; //first word is the keyword (after the '!') var keyWord = messageArray[0].substring(1); if (messageArray.length > 0) { //take away command from beginning to make easier to parse messageText = messageText.substring(messageArray[0].length+1); } messageArray.shift(); //remove first element (e.g. '!hi') performCommand(connection, keyWord, messageText, messageArray, actor) }; var onVoice = function( event ) { console.log( 'Mixed voice' ); var pcmData = voice.data; } var sendMessage = function(connection, message, actor) { //if you include a user, send it to him if (actor) { actor.sendMessage(message); } else { if (connection.user) { connection.user.channel.sendMessage(message); } } } var performCommand = function(connection, keyWord, commandText, commandArray, actor) { var foundCommand = false; for (var i = 0; i < oneWordCommands.length; i++) { if (oneWordCommands[i][0] === keyWord) { console.log('Received command: ' + oneWordCommands[i][0]); sendMessage(connection, oneWordCommands[i][1]); foundCommand = true; break; } } if (!foundCommand) { for (var i = 0; i < commands.length; i++) { var command = commands[i]; //TODO: array identifiers //This looks for a command with a matching keyword if (command.identifier === keyWord) { console.log('Received command: ' + command.identifier); //execture if found command.action(connection, commandText, commandArray, actor); foundCommand = true; break; } } } if (!foundCommand) { sendMessage(connection, 'Command not found'); } } var playSound = function(connection, sound) { if (playing) return; // scream.pipe(connection.inputStream()); // scream = fs.readFileSync(sound); scream = fs.createReadStream(sound); scream.on('end', function() { scream.unpipe(); }); // if (keyArray.length >= 1) { // var user = connection.userByName(keyArray[0]); // if (user) { // // user.inputStream() // while (user.inputStream().write(scream)) { } // } else { // console.log('user ' + keyArray[0] + ' not found'); // } // } else { // while (connection.inputStream().write(scream)) { } // } scream.pipe(connection.inputStream()); // connection.sendVoice(scream); } var oneWordCommands = [ ['hi', 'Hello!'], ['lenny', '( ͡° ͜ʖ ͡°)'], ['dong', 'ヽ༼ຈل͜ຈ༽ノ raise your dongers ヽ༼ຈل͜ຈ༽ノ'], ['hecomes', 'Ḫ̵͇Ẹ ̢̥̰̥̻̘̙̠C̺̙̠͠O̠̗M̺̭E̵S͖͓͜'], ['meh', '¯\\_(ツ)_/¯'], ['flipthetable', '(╯°□°)╯︵ ┻━┻'], ['putitdown', '┬─┬ノ( º _ ºノ) chill out bro'] ]; var commands = [{ identifier: 'doge', minLength: 0, //how much additional information you need action: function(connection) { var words = ['amaze', 'wow', 'such mumble', 'so bot', 'such auto']; sendMessage(connection, words[Math.floor(Math.random()*words.length)]); } }, { identifier: 'curse', minLength: 1, //how much additional information you need action: function(connection, keyString) { sendMessage(connection, 'Screw you, ' + keyString + '!'); } }, { identifier: 'help', minLength: 1, //how much additional information you need action: function(connection, keyString, keyArray, actor) { sendMessage(connection, 'Here is a list of all commands:', actor); var text = ''; for (var i = 0; i < commands.length; i++) { //don't want anyone else to know if (commands[i].identifier === 'scream' || commands[i].identifier === 'blackYeah') continue; text += commands[i].identifier + ', '; } for (var i = 0; i < oneWordCommands.length; i++) { text += oneWordCommands[i][0] + ', '; }; sendMessage(connection, text); } }, { identifier: 'move', minLength: 1, //how much additional information you need action: function(connection, keyString) { //get rest of command without '!move ' var newChannel = keyString; if (newChannel === 'root') { connection.rootChannel.join(); console.log("Moved to Channel: root"); } else { var channel = connection.channelByName(newChannel); if (channel) { channel.join(); console.log("Moved to Channel: " + newChannel); } else { sendMessage(connection, 'Channel ' + newChannel + ' not found'); } } } }, { identifier: 'printuserlist', minLength: 0, //how much additional information you need action: function(connection) { sendMessage(connection, "User List Requested"); var users = connection.users(); var text = ""; for (var i = 0; i < users.length; i++) { text += users[i].name + ', '; } sendMessage(connection, text); } }, { identifier: 'msg', minLength: 1, //how much additional information you need action: function(connection, keyString, keyArray, actor) { console.log("sending message to " + actor.name); sendMessage(connection, "Thanks for your request, " + actor.name, actor); sendMessage(connection, keyString); } }, { identifier: 'scream', minLength: 0, //how much additional information you need action: function(connection, keyString, keyArray) { // if (keyArray.length >= 1) { // var user = connection.userByName(keyArray[0]); // if (user) { // // user.inputStream() // while (user.inputStream().write(scream)) { } // } else { // console.log('user ' + keyArray[0] + ' not found'); // } // } else { // while (connection.inputStream().write(scream)) { } // } playSound(connection, 'scream.wav'); } }, { identifier: 'blackyeah', minLength: 0, //how much additional information you need action: function(connection, keyString, keyArray) { playSound(connection, 'blackYeah.wav'); } }];
/* * dar o npm init, instalar o gulp localmente, fazer o require * não precisa ficar dando npm init ou instal quando instalar mó- *los nas dependências. */ var gulp = require('gulp'); var browserSync = require('browser-sync').create(); const autoprefixer = require('gulp-autoprefixer'); gulp.task('default', function() { //Ok browserSync.init({ server: { baseDir: './' }, port: 8080, ui: { port: 8081 } }); gulp.watch("./*.*").on('change', browserSync.reload); gulp.watch("js/*.*").on('change', browserSync.reload); gulp.watch("css/*.*").on('change', browserSync.reload); }); gulp.task('prefix', () => gulp.src('css/*.css') .pipe(autoprefixer({ browsers: ['last 5 versions'], cascade: false })) .pipe(gulp.dest('style')) );
import moment from "moment"; const getYearsAgo = (diff) => Number( moment() .subtract(diff, "years") .format("YYYY"), ); export default getYearsAgo;
const assert = require('assert') const mybase64 = require('../index.js') describe('encode',() => { it('ABCDEF',() => { assert.equal(mybase64.encode('ABCDEF'),'QUJDREVG') }) it('12345',() => { assert.equal(mybase64.encode('12345'),'MTIzNDU=') }) }) describe('decode',() => { it('QUJDREVG',() => { assert.equal(mybase64.decode('QUJDREVG'),'ABCDEF') }) it('MTIzNDU=',() => { assert.equal(mybase64.decode('MTIzNDU='),'12345') }) })
window.onload = function(){ console.log("hello","World"); var table_body = document.getElementsByTagName("tbody"); for(var i=0;i<10;i++){ var tr=document.createElement("tr"); for(var j=0;j<3;j++){ var td=document.createElement("td"); var inp=document.createElement("inp"); td.appendChild(inp); tr.appendChild(td); inp.innerHTML="88"; inp.addEventListener("click",function(e){ var val=e.text; console.log("Value ",val); }); } table_body[0].appendChild(tr); } }
import React from "react" import { connect } from "react-redux" import playlist from '../../store/actions/general'; import Link from "../../components/Link/index"; import Image from "../Image/Index" import UserTitle from "../User/Title" import axios from "../../axios-orders" class Player extends React.Component { constructor(props) { super(props) this.state = { audios:props.audios, width:props.isMobile ? props.isMobile : 993, song_id:props.song_id, minimizePlayer:false, pausesong_id:props.pausesong_id, currentTime: null, playCount:[], passwords:props.pageInfoData && props.pageInfoData.audioPassword ? props.pageInfoData.audioPassword : [] } this.audioChange = this.audioChange.bind(this) this.updateWindowDimensions = this.updateWindowDimensions.bind(this); this.audioTag = new React.createRef() this.toggleLoop = this.toggleLoop.bind(this); this.audioSeekSet = this.audioSeekSet.bind(this) } updateWindowDimensions() { this.setState({localUpdate:true, width: window.innerWidth }); } componentWillUnmount() { window.removeEventListener('resize', this.updateWindowDimensions); } componentDidMount(){ this.updateWindowDimensions(); window.addEventListener('resize', this.updateWindowDimensions); } closePlayer = (e) => { e.preventDefault() this.props.updateAudioData([],0,0,"","") return swal({ title: this.state.title, text: this.state.message, icon: "warning", buttons: true, dangerMode: true, }) .then((willDelete) => { if (willDelete) { this.props.updateAudioData([],0,0,"","") } else { } }); } getItemIndex(item_id) { const audios = [...this.props.audios]; const itemIndex = audios.findIndex(p => p["audio_id"] == item_id); return itemIndex; } ended = () => { let song_id = this.props.song_id let itemIndex = 0 itemIndex = this.getItemIndex(song_id) if (itemIndex > -1) { const items = [...this.props.audios] if(itemIndex+2 <= this.props.audios.length){ itemIndex = itemIndex + 1 }else{ itemIndex = 0 } this.props.updateAudioData(this.props.audios,items[itemIndex].audio_id,0,this.props.submitText,this.props.passwordText) } } audioChange = (song_id,e) => { e.preventDefault(); if(song_id != this.state.song_id){ let itemIndex = this.getItemIndex(song_id) if (itemIndex > -1) { const items = [...this.state.audios] this.setState({localUpdate:true, song_id: items[itemIndex].audio_id,current_time:0 }) } } } previous = () => { let song_id = this.props.song_id let itemIndex = 0 itemIndex = this.getItemIndex(song_id) if (itemIndex > -1) { const items = [...this.props.audios] if(itemIndex == 0){ itemIndex = this.props.audios.length - 1 }else{ itemIndex = itemIndex - 1 } this.props.updateAudioData(this.props.audios,items[itemIndex].audio_id,0,this.props.submitText,this.props.passwordText) } } updateProgress () { this.setState({ currentTime: this.audioTag.currentTime }) } formatDuration(duration){ if(isNaN(duration)){ return "00:00" } duration = Math.floor(duration) let d = Number(duration); var h = Math.floor(d / 3600).toString(); var m = Math.floor(d % 3600 / 60).toString(); var s = Math.floor(d % 3600 % 60).toString(); var hDisplay = h.length > 0 ? (h.length < 2 ? "0" + h : h) : "00" var mDisplay = m.length > 0 ? ":" + (m.length < 2 ? "0" + m : m) : ":00" var sDisplay = s.length > 0 ? ":" + (s.length < 2 ? "0" + s : s) : ":00" return (hDisplay != "00" ? hDisplay+mDisplay : mDisplay.replace(":",'')) + sDisplay } playSong = () => { this.props.updateAudioData(this.props.audios, this.props.song_id,0,this.props.submitText,this.props.passwordText) this.audioTag.play(); } pauseSong = () => { this.props.updateAudioData(this.props.audios,this.props.song_id, this.props.song_id,this.props.submitText,this.props.passwordText) this.audioTag.pause(); } toggleLoop () { this.audioTag.loop = !this.audioTag.loop; } playStart = () => { let currentPlayingSong = this.getItemIndex(this.props.song_id) let audio = this.props.audios[currentPlayingSong]; let sessionPassword = this.props.pageInfoData && this.props.pageInfoData.audioPassword ? this.props.pageInfoData.audioPassword : [] if(audio.view_privacy == "password" && sessionPassword.indexOf(this.props.song_id) == -1 && !audio.passwords && ( !this.props.pageInfoData.levelPermissions || this.props.pageInfoData.levelPermissions["audio.view"] != 2 ) && (!this.props.pageInfoData.loggedInUserDetails || this.props.pageInfoData.loggedInUserDetails.user_id != audio.owner_id) ){ this.audioTag.pause(); this.setState({showPassword:true,localUpdate:true,popup_song_id:audio.audio_id}) return; } if(this.state.playCount[this.props.song_id]){ return } let counts = [...this.state.playCount] counts[this.props.song_id] = this.props.song_id this.setState({localUpdate:true,playCount:counts}) const formData = new FormData() formData.append('id', this.props.song_id) const url = "/audio/play-count" axios.post(url, formData) .then(response => { }).catch(err => { }); } changeVolume = (e) => { let value = e.target.value this.audioTag.volume= parseInt(value)/10; } closePopup = (e) => { this.setState({localUpdate:true, showPassword: false}) } formSubmit = (e) => { e.preventDefault() if (!this.state.password || this.state.submitting) { return } let password = this.state.password const formData = new FormData(); formData.append("password", password); const config = { headers: { 'Content-Type': 'multipart/form-data', } }; let currentPlayingSong = this.getItemIndex(this.props.song_id) let audio = this.props.audios[currentPlayingSong]; let url = '/audio/password/' + audio.custom_url this.setState({localUpdate:true, submitting: true, error: null }); axios.post(url, formData, config) .then(response => { if (response.data.error) { this.setState({localUpdate:true, error: response.data.error[0].message, submitting: false }); } else { let passwords = this.state.passwords ? this.state.passwords : [] passwords[this.props.song_id] = this.props.song_id this.setState({localUpdate:true, submitting: false, error: null,password:"",showPassword:false,passwords:passwords }) } }).catch(err => { this.setState({localUpdate:true, submitting: false, error: err }); }); } passwordValue = (e) => { this.setState({localUpdate:true, password: e.target.value }) } audioSeekSet = (e) => { this.audioTag.currentTime = e.target.value } render() { if(!this.props.audios.length && !this.props.audios.length && !this.props.song_id){ return null } let currentPlayingSong = this.getItemIndex(this.props.song_id) let audio = this.props.audios[currentPlayingSong]; let isS3 = true if (audio.audio_file) { const splitVal = audio.audio_file.split('/') if (splitVal[0] == "http:" || splitVal[0] == "https:") { isS3 = false } } if(this.props.song_id == this.props.pausesong_id){ try{ this.audioTag.pause(); }catch(err){ } }else{ if(this.audioTag && this.audioTag.paused && !this.state.showPassword){ if(audio.view_privacy != "password" || this.state.popup_song_id != audio.audio_id){ this.audioTag.play(); } } } let password = null if(this.state.showPassword){ password = <div className="popup_wrapper_cnt"> <div className="popup_cnt"> <div className="comments"> <div className="VideoDetails-commentWrap"> <div className="popup_wrapper_cnt_header"> <h2>{this.props.passwordText}</h2> <a onClick={this.closePopup} className="_close"><i></i></a> </div> <div className="user_wallet"> <div className="row"> <form onSubmit={this.formSubmit}> <div className="form-group"> <input type="text" className="form-control" value={this.state.password ? this.state.password : ""} onChange={this.passwordValue} /> { this.state.error ? <p className="error"> { this.state.error } </p> : null } </div> <div className="form-group"> <label htmlFor="name" className="control-label"></label> <button type="submit">{this.props.submitText}</button> </div> </form> </div> </div> </div> </div> </div> </div> } return ( <React.Fragment> { password } <div className="playbar"> <a href="#" className="close-mini-player" onClick={this.closePlayer}><span className="material-icons" data-icon="clear"></span></a> <ul className="controller"> { this.props.audios.length > 1 ? <li onClick={this.previous.bind(this)}> <i className="fa fa-step-backward"></i> </li> : null } <li> { this.props.pausesong_id == audio.audio_id ? <i className="fas fa-play" onClick={this.playSong.bind(this)}></i> : <i className="fas fa-pause" onClick={this.pauseSong.bind(this)}></i> } </li> { this.props.audios.length > 1 ? <li onClick={this.ended.bind(this)}> <i className="fa fa-step-forward"></i> </li> : null } <li className="volume" onClick={ this.toggleLoop }> <input className="volume-bar" type="range" min="0" max="10" onChange={(e) => this.changeVolume(e)} /> </li> <li className={ this.audioTag && this.audioTag.loop == true ? "active" : "" } onClick={ this.toggleLoop }> <i className="fas fa-redo"></i> </li> </ul> <audio id="audio" autoPlay preload="auto" ref={ (tag) => this.audioTag = tag } src={(isS3 ? this.props.pageInfoData.imageSuffix : "") + audio.audio_file} type="audio/mpeg" style={{display:"none"}} onTimeUpdate={ this.updateProgress.bind(this) } onEnded={ this.ended.bind(this) } onPlay={this.playStart.bind(this)}></audio> <ul className="progress"> <li className="currentTime">{this.formatDuration(this.audioTag ? this.audioTag.currentTime : 0)}</li> {/* <progress value={this.audioTag ? this.audioTag.currentTime : 0} max={audio.duration}></progress> */} <input type="range" max={audio.duration} name="rng" value={this.audioTag && this.audioTag.currentTime ? this.audioTag.currentTime : 0} min="0" step="0.25" onChange={this.audioSeekSet}></input> <li>{this.formatDuration(Math.floor(audio.duration))}</li> </ul> <div className="track-info"> <div className="img"> <Link href="/audio" customParam={`audioId=${audio.custom_url}`} as={`/audio/${audio.custom_url}`}> <a className="trackName"> <Image image={audio.image} imageSuffix={this.props.pageInfoData.imageSuffix} /> </a> </Link> </div> <div className="userTrackName"> <UserTitle childPrepend={true} className="username" data={audio} ></UserTitle> <Link href="/audio" customParam={`audioId=${audio.custom_url}`} as={`/audio/${audio.custom_url}`}> <a className="trackName"> { audio.title } </a> </Link> </div> </div> </div> </React.Fragment> ) } } const mapStateToProps = state => { return { song_id: state.audio.song_id, audios: state.audio.audios, pausesong_id:state.audio.pausesong_id, pageInfoData: state.general.pageInfoData, passwordText:state.audio.passwordText, submitText:state.audio.submitText }; }; const mapDispatchToProps = dispatch => { return { updateAudioData:(audios,song_id,pausesong_id,submit,password) => dispatch(playlist.updateAudioData(audios,song_id,pausesong_id,submit,password)) }; }; export default connect(mapStateToProps, mapDispatchToProps)(Player);
angular.module('app') .directive('listItem', function($timeout) { var template = angular.my.funcs.template('./blocks/list/list__list-item/list__list-item.html'); template.link = function(scope, elem, attrs) { // for textarea autosize .. scope.$watch('tasks', function() { autosize($(elem.find('textarea')[0])); }); elem.bind('keypress focusout', function(event) { if (event.keyCode === 13 || event.type === 'focusout') { event.preventDefault(); elem.find('textarea').attr('disabled', ''); /** * hack: set transparent color to hide caret, then reset * issue: after setting 'disabled' attribute at the moment caret is visible => caret still shows after * */ elem.find('textarea')[0].style.color = 'transparent'; elem.find('textarea')[0].style.color = ''; } }); }; template.controller = function($scope, $element, selectedFilter, $compile) { $scope.removeTask = function(index) { $scope.tasks.splice(index, 1); // for textarea autosize .. $timeout(function() { var tasks = $element.parent().find('textarea'); for (let i = 0; i < tasks.length; i++) { autosize.update($(tasks[i])); } }); }; $scope.editTask = function(index) { $element.find('textarea').removeAttr('disabled'); $element.find('textarea')[0].focus(); }; $scope.completeTask = function(index) { $scope.tasks[index].completed = !$scope.tasks[index].completed; }; $scope.visibleByFilter = function(index) { var task = $scope.tasks[index]; var selected = selectedFilter.states.selected; return selected === 0 || selected === 1 && !task.completed || selected === 2 && task.completed; }; }; return template; });
import React from 'react'; import {NavLink} from "react-router-dom"; import {Banner} from "../Banner/Banner"; import {Background} from "../Background/Background"; import {Services} from "../Services/Services"; import FeaturedRooms from "../FeaturedRooms/FeaturedRooms"; export const Home = () => { return ( <div> <Background> <Banner title="luxurious rooms" subtitle="deluxe rooms starting at $299"> <NavLink to="/rooms" className="btn-primary"> our rooms </NavLink> </Banner> </Background> <Services/> <FeaturedRooms /> </div> ) }
import BaseForm from './BaseForm' export default class ASlider extends BaseForm { constructor(h, formData, obj, vm, type) { super(h, formData, obj, vm, type) return this.initialize } get props() { const { key, obj } = this return { value: this.formData[key] || 0, ...obj.props } } get initialize() { const { type } = this const el = { props: { ...this.props }, style: { ...this.style, width: '100%' }, on: { ...this.on } } return this.h('ElSlider', el) } }
import configureMockStore from "redux-mock-store"; import thunk from "redux-thunk"; import mockAxios from "axios"; import {fetchTodos, addTodo,updateTodo, deleteTodo} from "./actionCreator"; const middleware = [thunk]; const mockStore = configureMockStore(middleware); const store = mockStore(); jest.mock('axios'); describe("Todos actions", () => { it("dispatches FETCH_TODOS action and returns data on success", async () => { mockAxios.get.mockImplementationOnce(() => Promise.resolve({ data: { result: [{ item: "item1" }, { item: "item2" }] } }) ); await store.dispatch(fetchTodos()); const actions = store.getActions(); expect(actions[0].type).toEqual("FETCH_TODOS"); }); it("dispatche ADD_TODO action and returns data on success", async () => { mockAxios.post.mockImplementationOnce(() => Promise.resolve({ data: { result: [{ item: "item1" }] } }) ); await store.dispatch(addTodo()); const actions = store.getActions(); expect(actions[1].type).toEqual("ADD_TODO"); }); it("dispatche UPDATE_TODO action and returns data on success", async () => { mockAxios.put.mockImplementationOnce(() => Promise.resolve({ data: { result: [{ item: "item1" }] } }) ); await store.dispatch(updateTodo()); const actions = store.getActions(); expect(actions[2].type).toEqual("UPDATE_TODO"); }); it("dispatche DELETE_TODO action and returns data on success", async () => { mockAxios.delete.mockImplementationOnce(() => Promise.resolve({ data: {} }) ); await store.dispatch(deleteTodo()); const actions = store.getActions(); expect(actions[3].type).toEqual("DELETE_TODO"); }); });
import Api from './Api'; import { Calling } from './constants'; export default{ GetThread(instaAccount, threadId, limit){ return Api(true, instaAccount).get(Calling["messaging_thread"]+threadId+'/'+limit) }, SendDM(instaAccount, type, message){ return Api(true,instaAccount).post(Calling["messaging_post_text"]+type, message); }, DeleteComment(instaAccount, media, comment){ return Api(true, instaAccount).delete(Calling["messaging_delete_comment"]+media+'/'+comment) }, LikeComment(instaAccount, comment){ return Api(true,instaAccount).post(Calling["messaging_like_comment"]+comment) }, UnLikeComment(instaAccount, comment){ return Api(true,instaAccount).put(Calling["messaging_unlike_comment"]+comment) }, ReplyComment(instaAccount, media, comment, message){ return Api(true,instaAccount).post(Calling["messaging_reply_comment"]+media+'/'+comment, message) }, CreateComment(instaAccount, media, message){ return Api(true,instaAccount).post(Calling["messaging_create_comment"]+media, message) } }
import React from 'react'; import {HashRouter as Router, Redirect, Route, Switch,} from 'react-router-dom'; import Dashboard from './containers/Dashboard'; export default class AppRouter extends React.Component { render() { return ( <Router> <Switch> <Redirect exact from="/" to="/dashboard"/> <Route path="/dashboard" exact component={Dashboard} /> </Switch> </Router> ); } }
import React from "react"; import ReactDom from "react-dom"; import "./index.scss"; import Display from "./Display"; import DrumPad from "./DrumPad"; class DrumMachine extends React.Component { constructor(props) { super(props); this.state = { drums: [ { letter: "Q", keyCode: 81, id:"heater1", audio: process.env.PUBLIC_URL + "/assets/drums/Heater-1.mp3" }, { letter: "W", keyCode: 87, id:"heater2", audio: process.env.PUBLIC_URL + "/assets/drums/Heater-2.mp3" }, { letter: "E", keyCode: 69, id:"heater3", audio: process.env.PUBLIC_URL + "/assets/drums/Heater-3.mp3" }, { letter: "A", keyCode: 65, id:"heater4", audio: process.env.PUBLIC_URL + "/assets/drums/Heater-4_1.mp3" }, { letter: "S", keyCode: 83, id:"clap", audio: process.env.PUBLIC_URL + "/assets/drums/Heater-6.mp3" }, { letter: "D", keyCode: 68, id:"open-high-hat", audio: process.env.PUBLIC_URL + "/assets/drums/Dsc_Oh.mp3" }, { letter: "Z", keyCode: 90, id:"kick-hat", audio: process.env.PUBLIC_URL + "/assets/drums/Kick_n_Hat.mp3" }, { letter: "X", keyCode: 88, id:"kick", audio: process.env.PUBLIC_URL + "/assets/drums/RP4_KICK_1.mp3" }, { letter: "C", keyCode: 67, id:"closed-high-hat", audio: process.env.PUBLIC_URL + "/assets/drums/Cev_H2.mp3" }, ], activeSound: "Here we go!" } } displayUpdate = (d) => { this.setState({ activeSound: d }); } render() { return ( <div id="drum-machine"> <Display active={this.state.activeSound} /> {this.state.drums.map((item, index) => { return ( <DrumPad key={index} id={item.id} drum={item.audio} letter={item.letter} keyCode={item.keyCode} updateDisplay={this.displayUpdate}/> ) })} </div> ); } } ReactDom.render(<DrumMachine />, document.getElementById('root'));
$(function() { // close the overlay navigation when header links are clicked $(".overlay-nav .nav-toc a.header, .overlay-nav .nav-toc a.active.page").attr("data-toggle", "underlay overlay"); // TOCs support three styles: // - box: wrap in a shadowed box and apply TOC styling // - blocks: section TOCs in boxes in a block grid with equal heights // - list: regular list of links var tocs = $(".page-content .toc"); tocs.each(function() { var toc = $(this); // if there's no style already set then add .box for TOCs of depth 1 otherwise .blocks if (!(toc.hasClass("blocks") || toc.hasClass("box") || toc.hasClass("list"))) { toc.addClass((toc.children("ul").children("li").has("ul").length == 0) ? "box" : "blocks"); } if (toc.hasClass("blocks")) { var list = toc.children("ul"); list.addClass("row medium-up-2 large-up-3 toc-grid"); list.children("li").addClass("column column-block toc-block").attr("data-equalizer-watch", "").wrapInner("<div class='toc-box'></div>"); new Foundation.Equalizer(list, { equalizeByRow: true, equalizeOn: "medium" }); } else if (toc.hasClass("box")) { toc.wrapInner("<div class='toc-box'></div>"); } }); });
import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, TextInput, Button, View } from 'react-native'; const PatientSchema = { name: 'Patients', properties: { name: 'string', bp: 'string' , weight: 'string', temperature: 'string', } }; const Realm = require('realm'); let realm = new Realm({ path:'PMA.realm', schema: [PatientSchema] }); export default class ReactNative_Realm extends Component { constructor(props) { super(props); this.state = { name: '', bp: '', weight: '', temperature: '' } } retrieve= () =>{ var name =this.state.name; var result = realm.objects('Patients').filtered('name=\"' + name + '\"'); for (var i = 0; i < result.length; i++) { this.setState({ name: result[i].name, bp: result[i].bp, weight: result[i].weight, temperature: result[i].temperature }); } }; submit = () => { realm.write(() => { realm.create('Patients', {name:this.state.name ,bp: this.state.bp ,weight: this.state.weight,temperature: this.state.temperature}); }); }; render() { return ( <View style={styles.container}> <Text style={styles.welcome}> Patient Details </Text> <View style={{ flexDirection: 'row' }}> <Text>Name: </Text> <TextInput style={{ height: 40, width: 200, borderColor: 'gray', borderWidth: 2 }} value={this.state.name} onChangeText={(name) => this.setState({ name })} /> </View> <View style={{ flexDirection: 'row' }}> <Text>BP: </Text> <TextInput style={{ height: 40, width: 200, borderColor: 'gray', borderWidth: 2 }} placeholder='Enter Blood Pressure' value={this.state.bp} onChangeText={(bp) => this.setState({ bp })} /> </View> <View style={{ flexDirection: 'row' }}> <Text>Weight: </Text> <TextInput style={{ height: 40, width: 200, borderColor: 'gray', borderWidth: 2 }} placeholder='Enter Weight' value={this.state.weight} onChangeText={(weight) => this.setState({ weight })} /> </View> <View style={{ flexDirection: 'row' }}> <Text>Temperature: </Text> <TextInput style={{ height: 40, width: 200, borderColor: 'gray', borderWidth: 2 }} placeholder='Enter Temperature' value={this.state.temperature} onChangeText={(temperature) => this.setState({ temperature })} /> </View> <View style={{ flexDirection: 'row' }}> <Button onPress={() => this.submit()} title="Submit !" color="blue" accessibilityLabel="Save data to database"> Submit ! </Button> <Button onPress={() => this.retrieve()} title="Retrieve !" color="green" accessibilityLabel="Retrieve data from database"> Submit ! </Button> </View> <View> <Text>Name: {this.state.name} BP: {this.state.bp} Temp:{this.state.temperature} Weight:{this.state.weight}</Text> </View> <Text style={styles.welcome}> Number of Patients in Realm db : {realm.objects('Patients').length} </Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, }); AppRegistry.registerComponent('ReactNative_Realm', () => ReactNative_Realm);
(function(){ 'use strict'; angular.module('platanus.palletBundle',['ngFileUpload', 'platanus.pallet', 'platanus.docPreview', 'platanus.progress']); })();
export { default as ListBox } from './ListBox';
import React, {useState} from "react"; import {Link, Redirect } from "react-router-dom"; import axios from "axios"; import {rootUrl} from "../utilities/constants"; import {confirmEmailEndpoint} from "../utilities/endpoints"; import {useParams} from "react-router-dom"; import {useForm} from "react-hook-form"; import {Container,Image} from "react-bootstrap"; export default function VerifyEmail (props){ const { register, handleSubmit, errors,getValues } = useForm( ); const Verify =(item)=>{ setIsError(false); setIsLoading(true); axios.post(`${rootUrl}${confirmEmailEndpoint}${key}/`,item,).then( resp=>{ if(resp.status === 200){ setConfirmed(true); }} ) .catch(error=>{ setIsLoading(false); setIsError(true); }); }; const {key} = useParams(); const [isConfirmedEmail, setConfirmedEmail] = useState(false); const [isError, setIsError] = useState(false); const [isLoading, setIsLoading] = useState(false); const [isConfirmed, setConfirmed] = useState(false); if(isConfirmed){ return <Redirect push to = {{pathname:"/login"}} />; } else{ return( <Container> {isLoading&&<Image className="loadingspinner" src="/Iphone-spinner-2.gif"/>} {isError&&<div><p>Error occured, retry</p></div>} {isConfirmed&&<div><span>Email confirmation was succesful</span></div>} <form onSubmit={handleSubmit(Verify)}> <input type="hidden" name ="key" value= {key}/> <input type="submit" disabled = {isLoading} className = "verifyemail-btn" value ="Click to confirm your email"/> </form> </Container> ); }}
import { makeActionCreator } from '../../../utils/helpers/redux'; const ORDERS_REQUEST = 'orders/ORDERS_REQUEST'; const ORDERS_SUCCESS = 'orders/ORDERS_SUCCESS'; const ADD_ORDER = 'orders/ADD_ORDER'; const UPDATE_ORDER = 'orders/UPDATE_ORDER'; const DELETE_ORDER = 'orders/DELETE_ORDER'; const FILTER_VIEW_ORDER = 'orders/FILTER_VIEW_ORDER'; const ordersRequest = makeActionCreator(ORDERS_REQUEST, 'request'); const ordersSuccess = makeActionCreator(ORDERS_SUCCESS, 'response'); const addOrder = makeActionCreator(ADD_ORDER, 'order'); const updateOrder = makeActionCreator(UPDATE_ORDER, 'order'); const deleteOrder = makeActionCreator(DELETE_ORDER, 'key'); const filterOrders = makeActionCreator(FILTER_VIEW_ORDER, 'index'); export const ActionsTypes = { ORDERS_REQUEST, ORDERS_SUCCESS, ADD_ORDER, UPDATE_ORDER, DELETE_ORDER, FILTER_VIEW_ORDER }; export const Actions = { ordersRequest, ordersSuccess, addOrder, updateOrder, deleteOrder, filterOrders };
"use strict"; const path = require('path') const sqlite3 = require('sqlite3').verbose() const reverse = require('./reverse') function Geocoder(options) { var geocoder = function(options) { this.options = options || {} if (this.options.database === undefined) { this.options.database = path.join(__filename, '../../data/db.sqlite') } this.db = new sqlite3.Database(this.options.database) } geocoder.prototype.reverse = function(latitude, longitude, callback) { return reverse(this, latitude, longitude, callback) } return new geocoder(options) } module.exports = Geocoder;
var _ = require('lodash'); var debug = require('debug')('tipbot:user'); var async = require('async'); var blocktrail = require('blocktrail-sdk'); var pbkdf2 = require('pbkdf2-compat').pbkdf2Sync; var User = function(tipbot, userId, userName, isAdmin) { var self = this; self.tipbot = tipbot; self.id = userId; self.name = userName; self.is_admin = isAdmin || false; self.handle = self.getSlackHandle(); }; User.prototype.updateFromMember = function(member) { var self = this; self.name = member.name; self.is_admin = member.is_admin; self.handle = self.getSlackHandle(); }; User.prototype.getWallet = function(cb, retry) { var self = this; if (typeof retry === "undefined") { retry = false; } if (!self.wallet) { var walletIdentifier = "SLACK-" + self.id, walletPassphrase = pbkdf2("SLACK-" + self.id, self.tipbot.SECRET, 2048, 64, 'sha512').toString('hex'); self.tipbot.client.initWallet(walletIdentifier, walletPassphrase, function(err, wallet) { if (err && err.statusCode == 404) { self.tipbot.client.createNewWallet(walletIdentifier, walletPassphrase, function(err, wallet) { self.wallet = wallet; cb(self.wallet, true); }); } else if (err) { debug('ERROR', err); if (!retry) { setTimeout(function() { self.getWallet(cb, true); }, 3000); } else { cb(); } } else { self.wallet = wallet; cb(self.wallet); } }); } else { cb(self.wallet); } }; User.prototype.tellBalance = function(channel) { var self = this; self.getBalanceLine(function(err, line) { channel.send(line); }); }; User.prototype.getBalanceLine = function(cb) { var self = this; self.getWallet(function(wallet) { wallet.getBalance(function(err, confirmed, unconfirmed) { if (err) { return debug('ERROR', err); } cb(null, self.handle + " confirmed; " + blocktrail.toBTC(confirmed) + " " + self.tipbot.TICKER + " | unconfirmed; " + blocktrail.toBTC(unconfirmed) + " " + self.tipbot.TICKER); }); }); }; User.prototype.tellDepositeAddress = function(channel) { var self = this; self.getWallet(function(wallet) { wallet.getNewAddress(function(err, address) { if (err) { return debug('ERROR', err); } channel.send(self.handle + " you can deposite to; " + address); }); }); }; User.prototype.withdraw = function(channel, value, address) { var self = this; self.getWallet(function(wallet) { wallet.getBalance(function(err, confirmed, unconfirmed) { if (err) { console.log(err); channel.send(err.message); } else if (confirmed >= value) { // EVERYTHING if (value == confirmed) { value -= blocktrail.toSatoshi(0.0002); // some random fee because we don't have a swipe function yet } var pay = {}; pay[address] = value; wallet.pay(pay, null, false, true, self.tipbot.OPTIONS.FEE_STRATEGY || blocktrail.Wallet.FEE_STRATEGY_OPTIMAL, function(err, txHash) { if (err) { console.log(err); channel.send(err.message); return; } var url = self.tipbot.explorerBaseUrl + "/tx/" + txHash; channel.send("Withdrawl of " + blocktrail.toBTC(value) + " " + self.tipbot.TICKER + " to " + address + " transaction; " + url); }); } else if (confirmed + unconfirmed >= value) { channel.send("Sorry " + self.handle + " you have to wait for your previous transactions to be confirmed before you can do this ..."); } else { channel.send("Sorry " + self.handle + " you do not have enough balance to do this ..."); } }); }); }; User.prototype.send = function(channel, user, value) { var self = this; // do self and user in parallel to speed things up a bit async.parallel({ self: function(cb) { self.getWallet(function(wallet) { wallet.getBalance(function(err, confirmed, unconfirmed) { if (err) { cb(err); } else if (confirmed == value) { cb(new Error("Sorry " + self.handle + " you can't send your full balance, need to account for the fee ...")); } else if (confirmed >= value) { cb(null, true); } else if (confirmed + unconfirmed >= value) { cb(new Error("Sorry " + self.handle + " you have to wait for your previous transactions to be confirmed before you can do this ...")); } else { cb(new Error("Sorry " + self.handle + " you do not have enough balance to do this ...")); } }); }); }, user: function(cb) { user.getWallet(function(wallet) { wallet.getNewAddress(wallet.changeChain, function(err, address) { cb(err, address); }); }); } }, function(err, results) { if (err) { console.log(err); channel.send(err.message); return; } self.getWallet(function(wallet) { var send = {}; send[results.user] = value; wallet.pay(send, null, false, true, self.tipbot.OPTIONS.FEE_STRATEGY || blocktrail.Wallet.FEE_STRATEGY_OPTIMAL, function(err, txHash) { if (err) { console.log(err); channel.send(err.message); return; } var url = self.tipbot.explorerBaseUrl + "/tx/" + txHash; channel.send("Sent " + blocktrail.toBTC(value) + " " + self.tipbot.TICKER + " from " + self.handle + " to " + user.handle + " transaction; " + url); }); }); }) }; User.prototype.getSlackHandle = function() { var self = this; return "<@" + self.id + "|" + self.name + ">"; }; User.fromMember = function(tipbot, member) { var user = new User(tipbot, member.id, member.name, member.is_admin); return user; }; module.exports = User;
module.exports = [ { "first_name": "Timothy", "last_name": "Robinson", "job": "Illustrator", "address": "450 Ryan Mountain Apt. 359\nDanielhaven, GU 39375-2283", "image_url": "https://placeholdit.imgix.net/~text?txtsize=55&txt=681x635&w=681&h=635" }, { "first_name": "Michael", "last_name": "Mendoza", "job": "Catering manager", "address": "PSC 1692, Box 6104\nAPO AE 15778", "image_url": "https://dummyimage.com/806x708" }, { "first_name": "Alison", "last_name": "Clements", "job": "Advertising art director", "address": "498 Edwards Forges\nNorth Patrickchester, OR 07516", "image_url": "https://www.lorempixel.com/268/83" }, { "first_name": "Douglas", "last_name": "Wells", "job": "Water quality scientist", "address": "Unit 8298 Box 3485\nDPO AE 45215-9914", "image_url": "https://www.lorempixel.com/212/719" }, { "first_name": "Raymond", "last_name": "Lee", "job": "Radiographer, diagnostic", "address": "1986 Joshua Road Suite 903\nEast Maureenland, AZ 04022-3391", "image_url": "https://placeholdit.imgix.net/~text?txtsize=55&txt=394x823&w=394&h=823" }, { "first_name": "Manuel", "last_name": "Anderson", "job": "Librarian, public", "address": "7119 Harris River Apt. 843\nSouth Willie, AZ 53852", "image_url": "https://placeholdit.imgix.net/~text?txtsize=55&txt=669x384&w=669&h=384" }, { "first_name": "Carol", "last_name": "Gibbs", "job": "Horticultural therapist", "address": "1031 Moore Ports Suite 201\nNew Kathy, MS 77776", "image_url": "https://dummyimage.com/144x322" }, { "first_name": "Jennifer", "last_name": "Roach", "job": "Scientist, audiological", "address": "006 Dylan Glens\nStephaniemouth, AZ 18667", "image_url": "https://www.lorempixel.com/368/241" }, { "first_name": "Thomas", "last_name": "Wright", "job": "Agricultural consultant", "address": "64013 Tiffany Mews\nSouth Ashleyview, MP 87796", "image_url": "https://www.lorempixel.com/547/855" }, { "first_name": "Courtney", "last_name": "Johnson", "job": "Chief Operating Officer", "address": "17267 Theresa Lodge\nDavidberg, MN 79077", "image_url": "https://placeholdit.imgix.net/~text?txtsize=55&txt=5x1023&w=5&h=1023" }, { "first_name": "Joseph", "last_name": "Silva", "job": "Holiday representative", "address": "568 Mahoney Pass Suite 254\nNew Samuelfort, MS 53496", "image_url": "https://placeholdit.imgix.net/~text?txtsize=55&txt=289x492&w=289&h=492" }, { "first_name": "Justin", "last_name": "Austin", "job": "Interior and spatial designer", "address": "Unit 2286 Box 7304\nDPO AP 69248-5085", "image_url": "https://dummyimage.com/624x698" }, { "first_name": "Angela", "last_name": "Jackson", "job": "Government social research officer", "address": "61432 Pitts Wall Apt. 095\nPort Jamesbury, NH 25547-4657", "image_url": "https://www.lorempixel.com/891/548" }, { "first_name": "Michael", "last_name": "Lewis", "job": "Operational investment banker", "address": "953 Jordan Spur Apt. 153\nShelbyshire, MO 76776-1418", "image_url": "https://www.lorempixel.com/628/869" }, { "first_name": "Ryan", "last_name": "Johnson", "job": "Architect", "address": "149 Klein Views\nGoldenshire, AZ 45621", "image_url": "https://dummyimage.com/1008x385" }, { "first_name": "Jennifer", "last_name": "Smith", "job": "Sales executive", "address": "8177 Hess Heights\nWest Justin, MS 73814", "image_url": "https://www.lorempixel.com/219/506" }, { "first_name": "Jason", "last_name": "Rodriguez", "job": "Financial planner", "address": "Unit 4415 Box 9340\nDPO AA 50128-2879", "image_url": "https://www.lorempixel.com/854/370" }, { "first_name": "William", "last_name": "Johnson", "job": "Chief of Staff", "address": "3121 Clark Stream Suite 095\nReevesstad, AZ 37825-8290", "image_url": "https://www.lorempixel.com/131/790" }, { "first_name": "Amanda", "last_name": "Brock", "job": "Special educational needs teacher", "address": "64385 Valerie Loop Suite 542\nSouth Jenniferchester, CA 35547", "image_url": "https://placeholdit.imgix.net/~text?txtsize=55&txt=396x901&w=396&h=901" }, { "first_name": "James", "last_name": "Mason", "job": "Fast food restaurant manager", "address": "7475 Erickson Ranch\nLake Susantown, GA 90191-4726", "image_url": "https://www.lorempixel.com/957/882" }, { "first_name": "Timothy", "last_name": "Rivera", "job": "Engineer, drilling", "address": "81401 Rachel Alley Apt. 193\nEast Bethany, LA 20432", "image_url": "https://placeholdit.imgix.net/~text?txtsize=55&txt=204x605&w=204&h=605" }, { "first_name": "Joseph", "last_name": "Roberts", "job": "Producer, radio", "address": "Unit 7282 Box 3780\nDPO AA 12835-9050", "image_url": "https://www.lorempixel.com/33/707" }, { "first_name": "Anthony", "last_name": "Hernandez", "job": "Scientist, research (maths)", "address": "0444 Clarke Bypass Suite 426\nNorth Martin, KY 40856", "image_url": "https://www.lorempixel.com/780/162" }, { "first_name": "Crystal", "last_name": "White", "job": "Accountant, chartered management", "address": "3783 Berry Green\nHendersonberg, OR 86841", "image_url": "https://dummyimage.com/425x489" }, { "first_name": "Stephen", "last_name": "Allen", "job": "Actuary", "address": "040 Delgado Ville\nNorth Nicholasfort, FM 32951", "image_url": "https://www.lorempixel.com/565/552" }, { "first_name": "Joanne", "last_name": "Thomas", "job": "Counsellor", "address": "8844 Larsen Wells\nPort Lee, FL 69042", "image_url": "https://placeholdit.imgix.net/~text?txtsize=55&txt=75x57&w=75&h=57" }, { "first_name": "Kelly", "last_name": "Nichols", "job": "Nurse, learning disability", "address": "16109 Davila Lock Suite 653\nPort David, HI 33648-7543", "image_url": "https://www.lorempixel.com/895/617" }, { "first_name": "Joseph", "last_name": "Williams", "job": "Geologist, engineering", "address": "USNV Torres\nFPO AA 43700-3915", "image_url": "https://dummyimage.com/727x561" }, { "first_name": "Shane", "last_name": "Briggs", "job": "Civil Service administrator", "address": "1997 Kimberly Stravenue\nEast Joshuaborough, OK 14067-6773", "image_url": "https://placeholdit.imgix.net/~text?txtsize=55&txt=128x631&w=128&h=631" }, { "first_name": "Stephen", "last_name": "Khan", "job": "Designer, multimedia", "address": "30092 Nicole Circle Apt. 501\nPort James, MP 19556-6771", "image_url": "https://placeholdit.imgix.net/~text?txtsize=55&txt=653x724&w=653&h=724" }, { "first_name": "Joseph", "last_name": "Lopez", "job": "Oceanographer", "address": "40109 Barker Cliffs\nMunozstad, NM 21018-5494", "image_url": "https://www.lorempixel.com/248/91" }, { "first_name": "James", "last_name": "Johnson", "job": "Lecturer, higher education", "address": "30994 Brown Brook Suite 354\nKarenberg, PA 04849-3427", "image_url": "https://dummyimage.com/795x95" }, { "first_name": "Lisa", "last_name": "Ayala", "job": "Production engineer", "address": "11901 Christopher Avenue Suite 429\nLake Jessica, OH 79161-9595", "image_url": "https://dummyimage.com/253x776" }, { "first_name": "Sara", "last_name": "Weeks", "job": "Corporate treasurer", "address": "284 Torres Mountain Apt. 261\nWest Williamport, WA 41153-6173", "image_url": "https://placeholdit.imgix.net/~text?txtsize=55&txt=630x290&w=630&h=290" }, { "first_name": "Michael", "last_name": "Petty", "job": "Sports development officer", "address": "395 Sarah Highway Apt. 394\nLake Wendy, IN 82816-9576", "image_url": "https://dummyimage.com/752x447" }, { "first_name": "Brian", "last_name": "Peterson", "job": "Forensic scientist", "address": "098 Simmons Divide\nNew Brianhaven, SC 30744", "image_url": "https://placeholdit.imgix.net/~text?txtsize=55&txt=308x891&w=308&h=891" }, { "first_name": "Jennifer", "last_name": "Woodward", "job": "Gaffer", "address": "2970 Thompson Mall\nHuberstad, PW 39350", "image_url": "https://placeholdit.imgix.net/~text?txtsize=55&txt=529x329&w=529&h=329" }, { "first_name": "Marc", "last_name": "Cook", "job": "Wellsite geologist", "address": "299 Baker Mill\nNew Jason, PW 61103-2759", "image_url": "https://placeholdit.imgix.net/~text?txtsize=55&txt=328x761&w=328&h=761" }, { "first_name": "Cameron", "last_name": "Benjamin", "job": "Dramatherapist", "address": "985 James Key\nNew Isabella, MH 57079", "image_url": "https://dummyimage.com/526x367" }, { "first_name": "Ashley", "last_name": "Vargas", "job": "Presenter, broadcasting", "address": "189 Andrew Courts\nDorseyland, MT 33492", "image_url": "https://placeholdit.imgix.net/~text?txtsize=55&txt=82x82&w=82&h=82" }, { "first_name": "Brian", "last_name": "Mann", "job": "Secondary school teacher", "address": "6750 Julia Mountain\nWest Sarah, RI 90827-9052", "image_url": "https://dummyimage.com/136x858" }, { "first_name": "David", "last_name": "Garcia", "job": "Barista", "address": "68198 Dickson Ridge\nEast Paul, SC 60149-2600", "image_url": "https://www.lorempixel.com/711/588" }, { "first_name": "Billy", "last_name": "Ward", "job": "Software engineer", "address": "1813 Orozco Shores Apt. 661\nEast David, UT 36201", "image_url": "https://dummyimage.com/734x636" }, { "first_name": "Ashley", "last_name": "Shelton", "job": "Information systems manager", "address": "53884 Robert Club Apt. 282\nTerrellbury, WV 38930", "image_url": "https://dummyimage.com/167x103" }, { "first_name": "Dana", "last_name": "Johnson", "job": "Microbiologist", "address": "293 Mark Springs\nPort Amandafurt, AL 37339-1639", "image_url": "https://placeholdit.imgix.net/~text?txtsize=55&txt=398x529&w=398&h=529" }, { "first_name": "Rodney", "last_name": "Vargas", "job": "Chief Financial Officer", "address": "478 Carlos Terrace\nEast Craigtown, SC 37385-5526", "image_url": "https://dummyimage.com/215x240" }, { "first_name": "Michael", "last_name": "Hanson", "job": "Research scientist (medical)", "address": "5829 Miller Oval\nBuckville, NE 14418", "image_url": "https://dummyimage.com/566x996" }, { "first_name": "Brandi", "last_name": "Ward", "job": "Restaurant manager, fast food", "address": "47425 Copeland Forks Suite 598\nWilliamsbury, IA 01855-3258", "image_url": "https://placeholdit.imgix.net/~text?txtsize=55&txt=101x560&w=101&h=560" }, { "first_name": "Aaron", "last_name": "Edwards", "job": "Conservation officer, nature", "address": "PSC 0547, Box 3224\nAPO AE 21825-8371", "image_url": "https://www.lorempixel.com/794/25" }, { "first_name": "Angela", "last_name": "Miller", "job": "Charity fundraiser", "address": "996 Jim Ford Suite 004\nCastilloside, ME 87043", "image_url": "https://placeholdit.imgix.net/~text?txtsize=55&txt=71x178&w=71&h=178" }, { "first_name": "Stephanie", "last_name": "Robertson", "job": "Immunologist", "address": "349 Natalie Land\nKyleside, MT 65929", "image_url": "https://placeholdit.imgix.net/~text?txtsize=55&txt=556x587&w=556&h=587" }, { "first_name": "David", "last_name": "White", "job": "Surveyor, commercial/residential", "address": "174 Stanley Orchard\nTomton, WA 15456-9716", "image_url": "https://www.lorempixel.com/10/209" }, { "first_name": "Kenneth", "last_name": "Martinez", "job": "Financial risk analyst", "address": "476 Thomas Drive Suite 110\nPort Megan, AK 52589", "image_url": "https://www.lorempixel.com/404/955" }, { "first_name": "Benjamin", "last_name": "Smith", "job": "Civil engineer, contracting", "address": "654 Robertson Village Suite 882\nPort Walterborough, VA 92906", "image_url": "https://dummyimage.com/34x993" }, { "first_name": "Christian", "last_name": "Williams", "job": "Horticulturist, amenity", "address": "3492 Dawson Trail\nPort Elizabethstad, FL 09421", "image_url": "https://dummyimage.com/263x72" }, { "first_name": "David", "last_name": "Austin", "job": "Education officer, museum", "address": "168 Elizabeth Mount\nPort Heather, MA 40169", "image_url": "https://dummyimage.com/892x747" }, { "first_name": "Charles", "last_name": "Allison", "job": "Geochemist", "address": "6035 Edwards Bridge Suite 221\nLake Lukemouth, MA 47489", "image_url": "https://www.lorempixel.com/824/203" }, { "first_name": "Oscar", "last_name": "Hickman", "job": "Sound technician, broadcasting/film/video", "address": "659 Ashley Shores Suite 006\nJamesfurt, MO 71966-0575", "image_url": "https://placeholdit.imgix.net/~text?txtsize=55&txt=242x389&w=242&h=389" }, { "first_name": "Johnny", "last_name": "Evans", "job": "Artist", "address": "723 Beard Circles\nFeliciaborough, WI 70922-8273", "image_url": "https://placeholdit.imgix.net/~text?txtsize=55&txt=554x291&w=554&h=291" }, { "first_name": "Benjamin", "last_name": "Snyder", "job": "Surveyor, hydrographic", "address": "2175 Schultz Circles\nLoganport, ID 84195", "image_url": "https://placeholdit.imgix.net/~text?txtsize=55&txt=889x511&w=889&h=511" }, { "first_name": "Kelsey", "last_name": "Howard", "job": "Licensed conveyancer", "address": "8303 Charles Walks\nAnthonyborough, NH 00458-0300", "image_url": "https://placeholdit.imgix.net/~text?txtsize=55&txt=584x400&w=584&h=400" }, { "first_name": "Joe", "last_name": "Mccoy", "job": "Office manager", "address": "33306 Katherine Pines Apt. 527\nTinahaven, IA 97698-0522", "image_url": "https://placeholdit.imgix.net/~text?txtsize=55&txt=942x34&w=942&h=34" }, { "first_name": "Matthew", "last_name": "Lee", "job": "Forest/woodland manager", "address": "38624 Daniels Coves\nNew Chrisland, PA 04851-1685", "image_url": "https://dummyimage.com/462x47" }, { "first_name": "James", "last_name": "Koch", "job": "Surveyor, land/geomatics", "address": "09252 Randy Haven Apt. 595\nNorth Elizabethshire, HI 48516-6426", "image_url": "https://placeholdit.imgix.net/~text?txtsize=55&txt=422x0&w=422&h=0" }, { "first_name": "Mary", "last_name": "Cook", "job": "Administrator, charities/voluntary organisations", "address": "USCGC Lopez\nFPO AA 76386", "image_url": "https://dummyimage.com/456x691" }, { "first_name": "Matthew", "last_name": "Johnston", "job": "Heritage manager", "address": "581 Linda Vista\nNew Kimberlystad, HI 28940", "image_url": "https://www.lorempixel.com/694/303" }, { "first_name": "Roberto", "last_name": "Snyder", "job": "Marine scientist", "address": "USS Kim\nFPO AP 56434-4868", "image_url": "https://dummyimage.com/177x352" }, { "first_name": "Jessica", "last_name": "Hall", "job": "Clinical research associate", "address": "69977 Sheila Drive Apt. 346\nWest Steven, NV 20245", "image_url": "https://dummyimage.com/966x306" }, { "first_name": "Patrick", "last_name": "Branch", "job": "Radio broadcast assistant", "address": "86021 Victoria Bridge\nJeremychester, CT 42762", "image_url": "https://www.lorempixel.com/457/160" }, { "first_name": "Tommy", "last_name": "Moore", "job": "Drilling engineer", "address": "50249 Jill Ford\nPhillipschester, PA 24447", "image_url": "https://www.lorempixel.com/491/96" }, { "first_name": "Joshua", "last_name": "Miller", "job": "Advertising account planner", "address": "2163 Steele Streets Suite 384\nNorth Andrew, KY 13868", "image_url": "https://dummyimage.com/502x843" }, { "first_name": "Susan", "last_name": "Jones", "job": "Accommodation manager", "address": "108 Denise Streets\nLopezmouth, MT 76842-2066", "image_url": "https://dummyimage.com/744x747" }, { "first_name": "Alicia", "last_name": "Brooks", "job": "Optician, dispensing", "address": "302 Gray Passage\nNew Calebland, MP 64438", "image_url": "https://www.lorempixel.com/108/654" }, { "first_name": "April", "last_name": "Frey", "job": "Insurance broker", "address": "4372 Holly Burgs Suite 609\nNorth Aliciafurt, NE 50653-0114", "image_url": "https://www.lorempixel.com/608/401" }, { "first_name": "Tammy", "last_name": "Chen", "job": "Volunteer coordinator", "address": "375 Fitzpatrick Forks\nNew Timothy, AK 40741-9050", "image_url": "https://www.lorempixel.com/447/287" }, { "first_name": "Lisa", "last_name": "Moore", "job": "Designer, furniture", "address": "0923 Bell Radial\nJeffreyfurt, VA 76202-2584", "image_url": "https://www.lorempixel.com/294/294" }, { "first_name": "Christopher", "last_name": "Hernandez", "job": "Data processing manager", "address": "9192 Mercer Shore Apt. 295\nLanceland, VI 28033-5674", "image_url": "https://www.lorempixel.com/482/791" }, { "first_name": "Taylor", "last_name": "Perez", "job": "Therapist, sports", "address": "79991 Cynthia Islands\nMarshallshire, AL 08132", "image_url": "https://www.lorempixel.com/434/1008" }, { "first_name": "Daniel", "last_name": "Herrera", "job": "Metallurgist", "address": "879 Freeman View\nLake Tiffany, IA 28771", "image_url": "https://www.lorempixel.com/236/683" }, { "first_name": "Heather", "last_name": "Dickson", "job": "Commercial horticulturist", "address": "02905 Phillips Groves\nJohnsonport, IA 90861-7834", "image_url": "https://www.lorempixel.com/285/59" }, { "first_name": "Holly", "last_name": "Spencer", "job": "Teacher, English as a foreign language", "address": "47828 Kaitlyn Court\nSouth Angelaburgh, AL 68059-4796", "image_url": "https://placeholdit.imgix.net/~text?txtsize=55&txt=467x24&w=467&h=24" }, { "first_name": "Larry", "last_name": "Wright", "job": "Higher education careers adviser", "address": "80345 Gonzales Road\nSouth Josephtown, DC 41174-8937", "image_url": "https://placeholdit.imgix.net/~text?txtsize=55&txt=665x342&w=665&h=342" }, { "first_name": "Leslie", "last_name": "Hill", "job": "Art therapist", "address": "2288 Roger Extension Suite 317\nNorth Tyrone, PW 10978", "image_url": "https://placeholdit.imgix.net/~text?txtsize=55&txt=109x318&w=109&h=318" }, { "first_name": "Ashley", "last_name": "Grant", "job": "Secretary, company", "address": "045 Brian Path\nNorth Karenport, MD 43435-1633", "image_url": "https://dummyimage.com/504x11" }, { "first_name": "Andrew", "last_name": "Perez", "job": "Geographical information systems officer", "address": "737 Erickson Wall Apt. 844\nPort Robert, TN 66930-4259", "image_url": "https://dummyimage.com/980x13" }, { "first_name": "Jon", "last_name": "Kennedy", "job": "Aeronautical engineer", "address": "5484 Sarah Grove Apt. 660\nNew Aliciafurt, DC 49169", "image_url": "https://www.lorempixel.com/270/658" } ]
function isPalindrome(value){ var value = value.replace(/\W/g, '').toLowerCase(), valueArray = [], palindrome = false; for (i=0; i<value.length; i++) valueArray.push(value.charAt(i)); if (value === valueArray.reverse().join('')) palindrome = true; return palindrome } console.log(isPalindrome("sample text")); console.log(isPalindrome("race car"));
orange_10_interval_name = ["真理<br />大學","北勢寮","麻豆","寮廍里","西庄","隆田","二鎮","六甲","嘉南里","烏山頭<br />水庫","臺南藝<br />術大學"]; orange_10_interval_stop = [ ["大地莊園","真理大學"], // 真理大學 ["四角仔","北勢寮","北勢國小","北勢里"], // 北勢寮 ["油車里","小埤頭","新樓醫院","麻豆轉運站","圓環","電姬戲院","一商前","興中民生路口","麻豆區公所","南勢里","曾文農工","總爺糖廠","臺灣首府大學宿舍","臺灣首府大學"], // 麻豆 ["寮廍里"], // 寮廍里 ["西庄","東庄"], // 西庄 ["隆西街","隆本里","官田區公所","隆田火車站","隆田","南廍里","南廍牌樓"], // 隆田 ["官田工業區","官田服務中心","勞動力發展署","二鎮","瓦窯(六甲)"], // 二鎮 ["七甲里","六甲衛生所","六甲"], // 六甲 ["赤山巖","龍潭寺","嘉南里"], // 嘉南里 ["烏山頭水庫","八田路、171路口"], // 烏山頭水庫 ["大崎","臺南藝術大學(西側門)","臺南藝術大學"] // 臺南藝術大學 ]; orange_10_fare = [ [26], [26,26], [29,26,26], [48,42,26,26], [53,46,26,26,26], [62,56,33,26,26,26], [82,76,54,35,30,26,26], [90,84,62,43,38,28,26,26], [98,91,69,50,45,36,26,26,26], [100,94,71,52,47,38,26,26,26,26], [113,107,85,66,61,52,31,26,26,26,26] ]; // format = [time at the start stop] or // [time, other] or // [time, start_stop, end_stop, other] orange_10_main_stop_name = ["大地<br />莊園","真理<br />大學","麻豆<br />轉運站","總爺<br />糖廠","臺灣<br />首府大學","隆田<br />火車站","官田<br />工業區","六甲","烏山頭<br />水庫","臺南<br />藝術大學"]; orange_10_main_stop_time_consume = [0, 5, 20, 30, 33, 45, 57, 65, 72, 80]; orange_10_important_stop = [0, 2, 5, 7, 9]; // 大地莊園, 麻豆轉運站, 隆田火車站, 六甲, 臺南藝術大學 var Dadi_Manor = 0; // 大地莊園 var TRA_Longtian = 5; // 隆田火車站 var Guantian_Industrial_Park = 6; var Lioujia = 7; orange_10_time_go = [["06:55",Dadi_Manor,Lioujia,['直',[Guantian_Industrial_Park,-5]]],["08:00"],["09:20"],["12:50"],["16:45",Dadi_Manor,TRA_Longtian],["18:25"]]; orange_10_time_return = [["07:55",Lioujia,Dadi_Manor,['直',[TRA_Longtian,-5]]],["09:25"],["10:40"],["14:25"],["17:30",TRA_Longtian,Dadi_Manor],["19:55"]];
import React, { Component } from 'react'; import Gif from './Gif'; import 'emoji-mart/css/emoji-mart.css' import { Picker} from 'emoji-mart' import { Smile , Heart} from 'react-feather'; import ContentEditable from 'react-contenteditable' //import ReactTextareaAutocomplete from '@webscopeio/react-textarea-autocomplete'; // emoji autocomplete(:) or for @ mentions (tag people) class Create extends Component { constructor(props) { super(props); this.initialState = { showEmoji:false, showGif:false, name:'', url: '', }; this.state = this.initialState; } /* Consume as many input fields you want with one single method handleChange, [name]:value , It's dynamic key assigment Main point-> We no longer have any individual handleChage function for each type of input change. Long way: Create two different handleChange() functions for the two inputs ... 1)... const name = event.target.value this.setState({name: name}) 2)... const value = event.target.value this.setState({value:value}) */ handleChange = event => { /*const { name, value } = event.target this.setState({ [name]: value, }) */ //Doesnt work for more than 1 space if(event.target.value === '&nbsp;'){ return event.target.value.replace(/&nbsp;/g, ' ') } this.setState({ name: event.target.value//textContent }) //this.state.name.replace(/&nbsp;/g, '') } submitForm = (event) => { event.preventDefault(); this.props.handleSubmit(this.state) // Whole State is send to handleSubmit this.setState(this.initialState); // Reset evyerthing to initialState again; } pasteAsPlainText = event => { event.preventDefault() const text = event.clipboardData.getData('text/plain') document.execCommand('insertHTML', false, text) } keyPressChange = event => { const keyCode = event.keyCode || event.which if(keyCode === 32){ console.log("space"); } } /*disableNewlines = event => { const keyCode = event.keyCode || event.which if (keyCode === 13) { event.returnValue = false if (event.preventDefault) event.preventDefault() } }*/ showEmoji = () =>{ this.setState({ showEmoji:!this.state.showEmoji }) } showGif = () =>{ this.setState({ showGif:!this.state.showGif, }) } handleClick = () => { this.refs.fileUploader.click() // Open Browser File var file = this.refs.fileUploader.files[0]; console.log(file); } addEmoji = (emoji) =>{ const e = emoji.native; this.setState({ name: this.state.name + e, showEmoji: false, }); } addGif= (gif) =>{ var url = gif.fixed_height_small.url; this.setState({ url : url, name: this.state.name, // + gif showGif: false, }); } render() { return ( <div className="App"> <form onSubmit={this.submitForm}> <label>Create Post</label> <div> <button type="button" className="divCursor toggle-emoji" onClick={this.showEmoji}><Smile /></button> <button type="button" className="divCursor toggle-emoji" onClick={this.showGif}><Heart /></button> <ContentEditable className="message-input" //contentEditable="true" //type=text html={this.state.name} onPaste={this.pasteAsPlainText} // Function to paste the text not the format //onKeyPress={this.disableNewlines} onKeyPress = {this.keyPressChange} //aria-multiline="true" placeholder={"What's in your mind?"} //suppressContentEditableWarning={true} //name="name" disabled={false} //value={this.state.name} //onClick={this.handleChange} onChange = {this.handleChange} // Change the state value on every input field style={{width:"70%",height:"300px"}} > </ContentEditable> </div> {/* <div className="divCursor" onClick={() => this.handleClick()}> <Emoji symbol="🖼️" label="sheep"/> <span> Photo/Video</span> <input type="file" id="file" accept="image/png, image/jpeg, video/*" ref="fileUploader" style={{display: "none"}}></input> </div> */} <button className="post" type="submit">Post</button> </form> {this.state.showEmoji ? (<span style={{position:"absolute",top:10,right:0}} ><Picker emojiTooltip={true}title='Pick your emoji…' set="emojione" onSelect={this.addEmoji} /> </span>): null } {/*When select a emoji, call addemoji() */} {this.state.showGif ? (<span style={{position:"absolute",top:10,right:0}} ><Gif url={this.state.url} addGif={this.addGif} /> </span>): null } {/*When select a emoji, call addGif() */} </div> ); } } export default Create;
import React, { useCallback, useEffect, useState } from 'react'; import styled from 'styled-components'; import { useDispatch, useSelector } from 'react-redux'; import { setPlaylistId } from '../reducer'; import spotifyIcon from '../assets/spotify_icon.png'; import Button from './Button'; import { login } from '../apiUtils'; const getHeaders = (accessToken) => ({ Authorization: 'Bearer ' + accessToken, 'Content-Type': 'application/json', }); const populatePlaylist = async (playlistId, tracks, accessToken) => { const populatePlaylistUrl = `https://api.spotify.com/v1/playlists/${playlistId}/tracks`; await fetch(populatePlaylistUrl, { method: 'PUT', headers: getHeaders(accessToken), body: JSON.stringify({ uris: tracks.map((track) => track.uri), }), }); //TODO handle error }; const createPlaylist = async (accessToken, userId) => { const url = `https://api.spotify.com/v1/users/${userId}/playlists`; const res = await fetch(url, { method: 'POST', headers: getHeaders(accessToken), body: JSON.stringify({ name: 'My Moodify Playlist', }), }).then((res) => res.json()); //TODO handle error return res.id; }; const SpotifyIcon = styled.img` height: 1.2rem; width: 1.2rem; margin-left: 0.5rem; `; export default ({ tracks }) => { const dispatch = useDispatch(); const accessToken = useSelector((state) => state.accessToken); let playlistId = useSelector((state) => state.playlistId); const openPlaylist = useCallback(async () => { if (!accessToken) { window.localStorage.setItem('tracks', JSON.stringify(tracks)); login(); return; } const getUserId = async () => { const res = await fetch('https://api.spotify.com/v1/me', { headers: getHeaders(accessToken), }).then((res) => res.json()); //TODO: handle error return res.id; }; const userId = await getUserId(); if (!playlistId) { playlistId = await createPlaylist(accessToken, userId); dispatch(setPlaylistId(playlistId)); } await populatePlaylist(playlistId, tracks, accessToken); const playlistUrl = `https://open.spotify.com/playlist/${playlistId}`; window.open(playlistUrl); }, [tracks, accessToken, playlistId, dispatch]); useEffect(() => { if (window.localStorage.getItem('tracks')) { window.localStorage.removeItem('tracks'); openPlaylist(); } }, [openPlaylist]); return ( <Button onClick={openPlaylist}> Create Playlist <SpotifyIcon src={spotifyIcon} alt="Spotify Logo" /> </Button> ); };
var sensationApp = angular.module('sensationApp'); // Home Data: Home page configuration sensationApp.factory('Data', function(){ var data = {}; data.items = [ { title: 'View Menu', icon: 'search', page: 'food-menu-search.html' } //, // //{ // title: 'Order Online', // icon: 'th', // page: 'modal.html'} // //{ // title: 'Reservation', // icon: 'envelope-o', // page: 'rsvp.html' //} //{ // title: 'Gallery', // icon: 'camera', // page: 'gallery.html' //}, //{ // title: 'Food Menu', // icon: 'calendar', // page: 'food-menu.html' //}, //{ // title: 'Drinks Menu', // icon: 'calendar', // page: 'drinks-menu.html' //}, //{ // title: 'Side & Dessert Menu', // icon: 'calendar', // page: 'sides-menu.html' //}, //{ // title: 'Map', // icon: 'map-marker', // page: 'map.html' //} ]; return data; }); // Menu Data: Menu configuration sensationApp.factory('MenuData', function(){ var data = {}; data.items = [ { title: 'Home', icon: 'home', page: 'home.html' }, { title: 'Menu', icon: 'search', page: 'food-menu-search.html' }, //{ // title: 'Order Online', // icon: 'th', // //page: 'modal.html' // page: 'https://tabachines.staging.wpengine.com/order-now/' //}, //{ // title: 'Contact', // icon: 'envelope-o', // page: 'contact.html' //}, { title: 'Map & Directions', icon: 'map-marker', page: 'map.html' } //{ // title: 'Connect With Us', // icon: 'social', // page:'social-media.html' //} ]; return data; }); // Map Data: Map configuration sensationApp.factory('MapData', function(){ var data = {}; data.map = { zoom: 16, center: { latitude: 34.0469942, longitude: -118.2502639 }, markers: [ { id: 1, icon: 'img/blue_marker.png', latitude: 34.0469942, longitude: -118.2502639, title: 'The Restaurant' }] }; return data; }); // Gallery Data: Gallery configuration //sensationApp.factory('GalleryData', function(){ // var data = {}; // // data.items = [ // { // label: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.', // src: 'img/gallery-1.jpg', // location: 'New York, June 2014' // }, // { // label: 'Ut enim ad minim veniam, quis nostrud exercitation ullamco.', // src: 'img/gallery-2.jpg', // location: 'Athens, August 2013' // }, // { // label: 'Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.', // src: 'img/gallery-3.jpg', // location: 'Tokyo, May 2013' // } // ]; // // return data; //}); // //// Products Data: JSON Products configuration //sensationApp.factory('ProductsData', function(){ // // var data = { url: 'json/products.json', letterLimit: 20 }; // // return data; //}); // //// News Data: JSON News configuration //sensationApp.factory('NewsData', function(){ // // var data = { url: 'json/news.json', letterLimit: 20 }; // // return data; //}); // FoodMenu Data: JSON FoodMenu configuration sensationApp.factory('FoodMenuData', function(){ var data = { url: 'json/loop.json' }; return data; }); //// DrinkMenu Data: JSON FoodMenu configuration //sensationApp.factory('DrinkMenuData', function(){ // // var data = { url: 'json/drinks.json', letterLimit: 20 }; // // return data; //}); // //// sideMenu Data: JSON FoodMenu configuration //sensationApp.factory('SideMenuData', function(){ // // var data = { url: 'json/sides.json', letterLimit: 20 }; // // return data; //}); // //// Posts Data: JSON Wordpress Posts configuration //sensationApp.factory('PostsData', function(){ // // /* (For DEMO purposes) Local JSON data */ // //var data = { url: 'json/wordpress.json' }; // // /* Set your URL as you can see in the following example */ // // var data = { url: 'https://tabachines.staging.wpengine.com/?json=get_recent_posts' }; // // /* With user-friendly permalinks configured */ // var data = { url: 'http://tabachines.staging.wpengine.com/api/get_recent_posts' }; // // return data; //}); // //// Server Posts Data (Server side pagination with AngularJS) //sensationApp.factory('ServerPostsData', function(){ // // /* (For DEMO purposes) Local JSON data */ // //var data = { url: 'json/serverposts&' }; // // /* Set your URL as you can see in the following example */ // /* NOTE: In case of the default permalinks, you should add '&' at the end of the url */ // //var data = { url: 'http://tabachines.staging.wpengine.com/?json=get_recent_posts&' }; // // /* With user-friendly permalinks configured */ // /* NOTE: In case of the user-friendly permalinks, you should add '?' at the end of the url */ // var data = { url: 'http://tabachines.staging.wpengine.com/api/get_recent_posts?' }; // // return data; //}); // //// Categories Data: JSON Categories configuration //sensationApp.factory('CategoriesData', function(){ // // /* (For DEMO purposes) Local JSON data */ // var data = { url: 'json/categories.json', // category_url: 'json/category' }; // // /* Set your URL as you can see in the following example */ // // var data = { url: 'YourWordpressURL/?json=get_category_index', // // category_url: 'YourWordpressURL/?json=get_category_posts&' }; // // /* With user-friendly permalinks configured */ // // var data = { url: 'YourWordpressURL/api/get_category_index', // // category_url: 'YourWordpressURL/api/get_category_posts?' }; // // return data; //}); // //// About Data: JSON News configuration //sensationApp.factory('AboutData', function(){ // // var data = { url: 'json/about.json' }; // // return data; //}); // NVD3Data Data: JNVD3Data configuration sensationApp.factory('NVD3Data', function(){ var data = {}; data.options = { chart: { type: 'discreteBarChart', margin : { top: 20, right: 20, bottom: 40, left: 65 }, x: function(d){return d.label;}, y: function(d){return d.value;}, showValues: true, valueFormat: function(d){ return d3.format(',.4f')(d); }, transitionDuration: 500, xAxis: { axisLabel: 'X Axis' }, yAxis: { axisLabel: 'Y Axis', axisLabelDistance: 30 } } }; data.data = [ { key: "Cumulative Return", values: [ { "label" : "A" , "value" : -29.765957771107 } , { "label" : "B" , "value" : 0 } , { "label" : "C" , "value" : 32.807804682612 } , { "label" : "D" , "value" : 196.45946739256 } , { "label" : "E" , "value" : 0.19434030906893 } , { "label" : "F" , "value" : -98.079782601442 } , { "label" : "G" , "value" : -13.925743130903 } , { "label" : "H" , "value" : -5.1387322875705 } ] } ]; return data; }); // Plugins Data: Mobile Plugins configuration sensationApp.factory('PluginsData', function(){ var data = {}; data.items = [ { title: 'Device Plugin', icon: 'mobile', page: 'device.html' }, { title: 'Notifications Plugin', icon: 'exclamation', page: 'notifications.html' }, { title: 'Geolocation Plugin', icon: 'location-arrow', page: 'geolocation.html' } //, //{ // title: 'Barcode Scanner', // icon: 'barcode', // page: 'barcodescanner.html' //} ]; return data; }); // //// Settings Data: Settings configuration //sensationApp.factory('SettingsData', function(){ // var data = {}; // // data.items = { // options: [ // { // name: 'First Setting', // value: true // }, // { // name: 'Second Setting', // value: false // }, // { // name: 'Third Setting', // value: false // }, // { // name: 'Fourth Setting', // value: false // }, // { // name: 'Fifth Setting', // value: false // }], // range:30 // }; // // return data; //}); // //// RSS Data: Feeds configuration //sensationApp.factory('FeedData', function(){ // // var data = { url: 'http://tabachines.staging.wpengine.com/api/get_recent_posts' }; // // return data; //}); // //// FEED Data Structure: JSON FEED Data Structure configuration //sensationApp.factory('FeedPluginData', function(){ // // // var data = { url: 'json/structure.json' }; // // return data; //});
import { combineReducers } from 'redux'; import avatar from './profileAvatarReducer'; import info from './profileInfoReducer'; import membership from './membershipReducer'; export default combineReducers({ avatar, info, membership });
var repeat = require('lodash').repeat module.exports.bar = arg => `bar::${repeat(arg, 3)}`
import React from 'react' class ToDoForm extends React.Component { constructor(props) { super(props) this.state = { 'text': '', 'project': 0, 'user': 0, 'is_active': true } } handleChange(event) { this.setState({ [event.target.name] : event.target.value }) } handleSubmit(event) { this.props.createToDo(this.state.text, this.state.project, this.state.user, this.state.is_active); event.preventDefault(); } render() { return ( <form onSubmit={(event)=> this.handleSubmit(event)}> <input type="text" name="text" placeholder="text" value={this.state.name} onChange={(event)=>this.handleChange(event)} /> <select name="project" onChange={(event) => this.handleChange(event)}> {this.props.projects.map((project) => <option value={project.id}>{project.name}</option>)} </select> <select name="user" onChange={(event) => this.handleChange(event)}> {this.props.users.map((user) => <option value={user.id}>{user.first_name} {user.last_name}</option>)} </select> <input type="submit" value="Create" /> </form> ) } } export default ToDoForm
/* Fake a Flog.* namespace */ if(typeof(Flog) == 'undefined') var Flog = {}; if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {}; Flog.RayTracer.Light = Class.create(); Flog.RayTracer.Light.prototype = { position: null, color: null, intensity: 10.0, initialize : function(pos, color, intensity) { this.position = pos; this.color = color; this.intensity = (intensity ? intensity : 10.0); }, getIntensity: function(distance){ if(distance >= intensity) return 0; return Math.pow((intensity - distance) / strength, 0.2); }, toString : function () { return 'Light [' + this.position.x + ',' + this.position.y + ',' + this.position.z + ']'; } }
var subtractProductAndSum = function(n) { let sumHolder = 0; let sum = n.toString().split(''); let prod = n.toString().split('').reduce((a, b) => a * b); for (let i = 0; i < sum.length; i++) { sumHolder += parseInt(sum[i]); } return prod - sumHolder; };
const Order = require('./model'); const uuidv1 = require('uuid/v1'); module.exports.getOrder = async uid => { return await Order.findOne({'policeInfo.uid': uid}).lean(); }; module.exports.getOrders = async () => { return await Order.find({}).lean(); }; module.exports.createOrder = async data => { data.policeInfo = { uid: uuidv1() }; return await Order.create(data); }; module.exports.updateOrder = async (uid, data) => { return await Order.findOneAndUpdate({'policeInfo.uid': uid}, {$set: data}).lean(); };
import React from 'react'; import { Link } from "react-router-dom"; import { BrowserRouter as Router, Switch, Route } from "react-router-dom"; import './App.css'; import StoreModel from './model_more/model'; import HomeView from './site_pages/home.js'; import LinkHandlerCategorys from './site_pages/linkhandlerCategory.js'; import LinkHandlerSubcategorys from './site_pages/linkhandlerSubcategory.js'; import LinkHandlerSubcategorysOrProducts from './site_pages/linkhandlerSubcategoryOrProduct.js'; import Header from './header_footer/header.js'; import Footer from './header_footer/footer.js'; import CheckOutView from './site_pages/checkOut'; import Success from './site_pages/success.js' import Pay from './ordering_components/api/payment_intents' import history from './history'; class App extends React.Component { constructor(props) { super(props); this.model = StoreModel; this.state = { value: "" }; } handleChange = (event) => { this.setState({ value: event.target.value, }); } render() { return (<Router history={history}> <Header model={this.model}/> <React.Fragment> <Switch> <Route path="/" exact component={() => <HomeView model={this.model} />}/> <Route path="/Checkout" exact component={() => <CheckOutView model={this.model} />}/> <Route path="/success" exact component={() => <Success model={this.model} />}/> <Route path="/api/payments_intents" exact component={() => <Pay/>}/> <Route path="/:category" exact component={() => <LinkHandlerCategorys model={this.model} />}/> <Route path="/:category/:subcatagory" exact component={() => <LinkHandlerSubcategorys model={this.model} />}/> <Route path="/:category/:subcatagory/:product" exact component={() => <LinkHandlerSubcategorysOrProducts model={this.model} />}/> <Route component={NoMatch} /> </Switch> </React.Fragment> <Footer model={this.model}/> </Router> ); } //<Route path="/specPlaylist" render={() => <playlistSettings model={heroifyModel}/>}/> } const NoMatch = () => ( <div className="pageWrapper"> <div className="pageTopDivider"></div> <div className="text-center"> <h className="headerPageText" >404 No match</h> <Link to="/"> <h1>Click here to go to homepage</h1> </Link> </div> </div> ); export default App;
const Calc = require('./calc'); function Indicator() { this.expression, this.name, this.args, this.parse = expression => { var splited = expression.split('_') this.expression = expression this.name = splited[0] this.args = splited.slice(1, splited.length) return this } this.applyTo = (candles) => { var results = Calc[this.name](candles, this.args) return candles.map( (candle, i)=> { var applied = candle applied[this.expression] = results[i] return applied } ) } } module.exports = new Indicator() /* var bbParams = { source: 'C', input: 20, stdDev: 2, output: 'base' //lower, base, upper } var emaParams = { source: 'C', input: 9 } */
const express = require('express') const parser = require('body-parser') const cors = require('cors') const mongoose = require('./db/schema.js') const Photo = mongoose.model('Photo') const app = express() app.set('port', process.env.PORT || 4200) app.use(parser.json()) app.use((cors())) app.get('/api/photos', (req, res) => { Photo.find() .then((photos) => { res.json(photos) }) .catch((err) => { console.log(err) }) }) app.post('/api/photos', (req, res) => { Photo.create(req.body) .then((photo) => { res.json(photo) }) .catch((err) => { console.log(err) }) }) app.get('/api/photos/:id', (req, res) => { Photo.findById(req.params.id) .then((photo) => { res.json(photo) }) .catch((err) => { console.log(err) }) }) app.listen(app.get('port'),() => { console.log('hello world from port' + app.get('port')); })
/* * TODO: tests to test the 'READ' operation of CRUD. * Not sure how to do it here, or why. * Maybe test the authorization. * This test should, too, start the server automatically, when this test * is run. */ /* eslint-disable no-console */ /* eslint-disable no-unused-expressions */ 'use strict'; const assert = require('assert'); const chai = require('chai'); const expect = require('chai').expect; const should = require('chai').should(); const chaiHttp = require('chai-http'); chai.use(chaiHttp); const request = require('supertest'); const cheerio = require('cheerio'); const fs = require('fs'); const User = require('../../models/user') const Questionnaire = require('../../models/questionnaire') const app = require('../../app.js'); const port = 3000; describe('Read Questionnaire', function () { /* * * TODO: * 1. make a test, that tries to access questionnaire editing, * while not being logged in * Implement this in the 'Questionnaire updating authorization' test area */ var id; // this is a global variable const fPath = 'test/assignment/testUpdateQs/'; function extractCsrfToken(res) { var $ = cheerio.load(res.text); return $('[name = _csrf]').val(); } /* * -- User logins -- */ /* * Log in as an admin */ // Create users with different roles const adminData = { name: 'admin', email: 'admin@email.fi', role: 'admin', password: '1234567890' } const teacherData = { name: 'teacher', email: 'teacher@email.fi', role: 'teacher', password: '1234567890' } const studentData = { name: 'student', email: 'student@email.fi', role: 'student', password: '1234567890' } // store said users to db before(async function () { try { await User.deleteMany({}); const admin = new User(adminData); await admin.save(); const teacher = new User(teacherData); await teacher.save(); const student = new User(studentData); await student.save(); } catch (err) { // eslint-disable-next-line no-console console.log(err); throw err; } }); const adminCredentials = { email: adminData.email, password: adminData.password }; let adminUser = request.agent(app); beforeEach(function (done) { adminUser .post('/users/login') .send(adminCredentials) .end(function (err, response) { if (err) return done(err); expect(response.statusCode).to.equal(302); expect('Location', '/users/me'); done(); }); }); /* * Log in as a teacher * NOTE: add a teacher to the database if doesn't exist */ const teacherCredentials = { email: teacherData.email, password: teacherData.password }; let teacherUser = request.agent(app); beforeEach(function (done) { teacherUser .post('/users/login') .send(teacherCredentials) .end(function (err, response) { if (err) return done(err); expect(response.statusCode).to.equal(302); expect('Location', '/users/me'); done(); }); }); /* * Log in as a student * NOTE: add a student to the database if doesn't exist */ const studentCredentials = { email: 'student@email.fi', password: '1234567890' }; let studentUser = request.agent(app); beforeEach(function (done) { studentUser .post('/users/login') .send(studentCredentials) .end(function (err, response) { if (err) return done(err); expect(response.statusCode).to.equal(302); expect('Location', '/users/me'); done(); }); }); let unauthorizedUser = request.agent(app); const questionnaireData = { title: "valid title", submissions: 1, questions: [ { title: "valid question title", maxPoints: "5", options: [ { option: "valid option", correctness: true }, { option: "another valid option", correctness: false } ] }, { title: "another valid question title", maxPoints: "5", options: [ { option: "valid option", correctness: true }, { option: "another valid option", correctness: false } ] }, ] }; beforeEach(async function() { await Questionnaire.deleteMany({}); let questionnaire = new Questionnaire(questionnaireData); id = questionnaire._id; await questionnaire.save(); }); /* * -- Functions -- */ function sendToServerList(getStatus, user, done) { user.get('/questionnaires') .end(function (err, res) { if (err) return done(err); expect(res.statusCode).to.equal(getStatus); // const csrfToken = '"' + extractCsrfToken(res) + '"'; // const data = rawData + csrfToken + ' }'; done(); }); } function sendToServerShow(id, getStatus, user, done) { user.get('/questionnaires/' + id) .end(function (err, res) { if (err) return done(err); expect(res.statusCode).to.equal(getStatus); // const csrfToken = '"' + extractCsrfToken(res) + '"'; // const data = rawData + csrfToken + ' }'; done(); }); } /* * -- Tests -- */ /** * Tests for authentication when sending the edited questionnaire */ describe('Listing questionnaires', function() { it('Admin should be able to list questionnaires.', function (done) { //const rawData = fs.readFileSync(fPath + '/adminQuestionnaire.json', 'utf8'); sendToServerList(200, adminUser, done); }); it('Teacher should be able to list questionnaires.', function (done) { //const rawData = fs.readFileSync(fPath + '/adminQuestionnaire.json', 'utf8'); sendToServerList(200, teacherUser, done); }); it('Student should NOT be able to list questionnaires.', function (done) { //const rawData = fs.readFileSync(fPath + '/adminQuestionnaire.json', 'utf8'); sendToServerList(302, studentUser, done); }); it('Non-logged-in user should NOT be able to list questionnaires.', function (done) { //const rawData = fs.readFileSync(fPath + '/adminQuestionnaire.json', 'utf8'); sendToServerList(302, unauthorizedUser, done); }); }); describe('Showing questions', function() { it('Admin should be able to show questions.', function (done) { //const rawData = fs.readFileSync(fPath + '/adminQuestionnaire.json', 'utf8'); sendToServerShow(id, 200, adminUser, done); }); it('Teacher should be able to show questions.', function (done) { //const rawData = fs.readFileSync(fPath + '/adminQuestionnaire.json', 'utf8'); sendToServerShow(id, 200, teacherUser, done); }); it('Student should NOT be able to show questions.', function (done) { //const rawData = fs.readFileSync(fPath + '/adminQuestionnaire.json', 'utf8'); sendToServerShow(id, 302, studentUser, done); }); it('Non-logged-in user should NOT be able to show questions.', function (done) { //const rawData = fs.readFileSync(fPath + '/adminQuestionnaire.json', 'utf8'); sendToServerShow(id, 302, unauthorizedUser, done); }); }); });
import React from 'react' import TabsClosable from '.' import { boolean } from "@storybook/addon-knobs"; export default { title: 'TabsClosable', component: TabsClosable } export const SimpleTabs = () => { const groupId = 'TABS-CLOSABLE-01' const tabs = [ { id: 'one', label: 'Tab one', content: <p style={{ backgroundColor: 'red', }}>Hello Tab One !</p>, }, { id: 'two', label: 'Tab two', content: <p>Hello Tab Two !</p>, }, { id: 'three', label: 'Tab Three', content: <p>Hello Tab Three !</p>, }, ] const newTab = { id: new Date().toISOString(), label: 'New tab', content: <p>Hello new Tab !</p>, } const [activeTabs, setActiveTabs] = React.useState(tabs) function onItemCloseHandler(id) { const newActiveTabs = activeTabs.filter((item, index) => index !== id) setActiveTabs(newActiveTabs) } function onItemAddHandler() { setActiveTabs([...activeTabs, newTab]) } return <TabsClosable tabs={activeTabs} disabled={boolean("Disabled", false, groupId)} onItemClose={onItemCloseHandler} selectedIndex={1} onAddItem={onItemAddHandler} /> }
import { Client } from 'pg' import { config } from '../../../config' import { chalk } from '../../services/chalk' const dbParams = { connectionString: config.databaseUrl, } if ((config.env && config.env !== 'development') || config.databaseSSL === 'true') { dbParams.ssl = true } export const db = new Client(dbParams) export const connect = () => new Promise((resolve, reject) => { db.connect((error) => { if (error) { chalk.error(`Error connecting to the database ${error}`, error) return reject(error) } chalk.success(`Connected to database at ${dbParams.connectionString}`) resolve() }) })
const app = require('express')(); const router = require('express').Router(); const { body } = require('express-validator'); const { sanitizeBody } = require('express-validator'); const bodyParser = require('body-parser'); const Firestore = require('@google-cloud/firestore'); const cors = require('cors'); const pick = require('lodash/pick'); const { roleCheck, globalFlags, ownerCheck, json } = require('./middleware'); const { mapCollection } = require('./utils'); const { getItemsByParams, getItemByPath, updateCogByPath } = require('./db'); const firestore = new Firestore({ projectId: 'starlit-channel-244200' }); app.use(cors()); app.use(globalFlags); app.use(json); app.use(bodyParser.json()); app.use('/reports', router); const REPORT_TYPES = ['api_abuse', 'malware', 'license']; const log = async (content, id) => await firestore.collection('logs').add({ content: content, created: Date.now(), module: 'reports', resourceId: id }); router.post( '/:username/:repo/:branch/:cog', [ body('comment') .trim() .escape() ], async (req, res) => { const ip = req.get('x-forwarded-for').split(',')[0]; const { username, repo, branch, cog } = req.params; const path = `${username}/${repo}/${branch}/${cog}`; const existing = await firestore .collection('reports') .where('path', '==', path) .where('ip', '==', ip) .get(); const canReport = !existing.size || existing.docs.reduce((can, item) => { if (!item.data().stale) { can = false; } return can; }, true); if (!canReport) { return res.status(400).send({ error: 'You already reported this cog' }); } const { type, comment } = req.body; if (!REPORT_TYPES.includes(type)) { return res.status(400).send({ error: 'Report type must be one of ' + REPORT_TYPES.join(', ') }); } const timestamp = Date.now(); const reportData = { path, authorName: username, repoName: repo, branchName: branch, cogName: cog, ip, type, comment, stale: false, seen: false, created: timestamp, updated: timestamp, seenBy: null, dismissedBy: null, qaNotified: false }; console.log(reportData); try { await firestore.collection('reports').add(reportData); return res.send({ path, type, comment, created: timestamp }); } catch (e) { console.error(e); res.status(503).send({ error: 'Could not create report' }); } } ); router.get('', roleCheck(['staff', 'qa']), async (req, res) => { const reports = await firestore .collection('reports') .orderBy('created', 'desc') .get(); const results = mapCollection(reports); const filtered = reportsStaffDataFilter(results); res.send({ count: results.length, results: filtered }); }); const reportsUserDataFilter = reports => reports.map(r => ({ ...pick(r, ['path', 'type', 'created', 'updated']) })); const reportsStaffDataFilter = reports => reports.map(r => ({ ...pick(r, [ 'id', 'path', 'comment', 'type', 'stale', 'seenBy', 'seen', 'dismissedBy', 'created', 'updated' ]) })); const isUserCheck = req => req.owner && !req.qa && !req.staff && !req.admin; router.get('/:username', ownerCheck, async (req, res) => { const { username } = req.params; let query = firestore .collection('reports') .where('authorName', '==', username); // filter out not seen and stale reports for non-qa+ owners const isUser = isUserCheck(req); if (isUser) { query = query.where('seen', '==', true).where('stale', '==', false); } const reports = await query.orderBy('created', 'desc').get(); let results = mapCollection(reports); if (isUser) { results = reportsUserDataFilter(results); } else { results = reportsStaffDataFilter(results); } res.send({ count: results.length, results }); }); router.post('/:id/stale', roleCheck(['staff', 'qa']), async (req, res) => { const { id } = req.params; const existing = await firestore .collection('reports') .doc(id) .get(); if (!existing.exists) { res.status(400).send({ error: 'Report does not exist' }); } const { stale } = req.body; const existingData = existing.data(); const updatedReport = { ...existingData, id: id, stale, updated: Date.now(), seen: true, seenBy: existingData.seenBy || req.user.data.nickname, dismissedBy: req.user.data.nickname }; let logContent = `${req.user.data.nickname} marked report as stale`; if (!stale) { logContent = `${req.user.data.nickname} dismissed stale report marking made by ${existingData.dismissedBy}`; } try { const saved = await firestore .collection('reports') .doc(id) .update(updatedReport); res.send({ ...pick(updatedReport, [ 'id', 'path', 'stale', 'seen', 'seenBy', 'updated', 'dismissedBy' ]) }); await log(logContent, id); } catch (e) { console.error(e); res.status(503).send({ error: 'Could not mark report as stale' }); } }); router.post('/:id/seen', roleCheck(['staff', 'qa']), async (req, res) => { const { id } = req.params; const existing = await firestore .collection('reports') .doc(id) .get(); if (!existing.exists) { res.status(400).send({ error: 'Report does not exist' }); } const existingData = existing.data(); const { seen } = req.body; const updatedReport = { ...existingData, id, seen, updated: Date.now(), seenBy: req.user.data.nickname }; let logContent = `${req.user.data.nickname} marked report as seen`; if (!seen) { updatedReport.seenBy = null; logContent = `${req.user.data.nickname} dismissed seen report marking made by ${existingData.seenBy}`; } try { const saved = await firestore .collection('reports') .doc(id) .update(updatedReport); res.send({ ...pick(updatedReport, ['id', 'path', 'seen', 'updated', 'seenBy']) }); await log(logContent, id); } catch (e) { console.error(e); res.status(503).send({ error: 'Could not mark report as stale' }); } }); module.exports = app;
Thorax.Router.create = function(module, props) { return module.exports.router = new (Thorax.Router.extend(_.defaults(props, module)))(); };
let amigo = { nome: 'José', sexo: 'M', peso: 85.4, engordar(p = 0) { console.log('Engordou') this.peso += p } } console.log(amigo.peso) amigo.engordar(2) console.log(amigo) console.log(amigo.nome) console.log(`${amigo.nome} pesa ${amigo.peso}Kg.`) const func1 = (param) => { } const func22 = (valor) => valor * 2 const func22 = valor => valor * 2 const func22 = (valor){ return valor * 2 }
"use strict" var FACILITY_TYPES = { COAL : 'coal', NUCLEAR : 'nuclear', GAS : 'gas', WIND : 'wind', SOLAR : 'solar', HYDRO : 'hydro' }; var GLOBAL_COST_TYPES = { LOBBY : 'lobby', RESEARCH : 'research', ADVERTISE : 'advertise' } function Resources(initialLevels, resourceCosts) { // Amount of that resource left in the world var levels = {}; for(var key in initialLevels) { levels[key] = initialLevels[key]; } // Request to use amount of resourceType. Returns amount you can use this.use = function(resourceType, amount) { var actualAmount = Math.min(amount, levels[resourceType]); levels[resourceType] -= actualAmount; return actualAmount; } // Gets the cost of one unit of resourceType this.getCost = function(resourceType) { if(resourceType == FACILITY_TYPES.WIND || resourceType == FACILITY_TYPES.SOLAR || resourceType == FACILITY_TYPES.HYDRO) { return 0; } else { return resourceCosts[resourceType]; } } this.getLevel = function(resourceType) { return levels[resourceType]; } this.getState = function() { return { [FACILITY_TYPES.COAL] : levels[FACILITY_TYPES.COAL] / initialLevels[FACILITY_TYPES.COAL], [FACILITY_TYPES.NUCLEAR] : levels[FACILITY_TYPES.NUCLEAR] / initialLevels[FACILITY_TYPES.NUCLEAR], [FACILITY_TYPES.GAS] : levels[FACILITY_TYPES.GAS] / initialLevels[FACILITY_TYPES.GAS], } } } function MyQueue() { var arr = []; this.isEmpty = function() { return arr.length == 0; } this.push = function(obj) { arr.push(obj); } this.pop = function() { var obj = arr[0]; arr.splice(0, 1); return obj; } } function Player(name, model, initialMoney, facilityFactory, globalCosts, regions, socket) { var self = this; // Amount of money this player has var money = initialMoney; // Reputations of this player per region var reputation = []; // Level of research per resourceType var researchLevels = {}; // Array of arrays listing facilities per region var facilities = []; var isPaused = false; var commandQueue = new MyQueue(); for(var i = 0; i < 6; i++) { reputation[i] = 0; facilities[i] = []; } for(var facilityType in FACILITY_TYPES) { researchLevels[FACILITY_TYPES[facilityType]] = 0; } this.pause = function() { isPaused = true; } this.start = function() { isPaused = false; doThings(); } this.getTotalReputation = function() { var total = 0; for(var i = 0; i < 6; i++) { total += reputation[i]; } return total; } this.notify = function(event, data) { socket.emit(event, data); } var doThings = function() { while(!commandQueue.isEmpty()) { var obj = commandQueue.pop(); socketFunctions[obj.event](obj.data); } } socket.on('build', function(data) { commandQueue.push({ 'event' : 'build', 'data' : data }); if(!isPaused) doThings(); }); socket.on('demolish', function(data) { commandQueue.push({ 'event' : 'demolish', 'data' : data }); if(!isPaused) doThings(); }); socket.on('lobby', function(data) { commandQueue.push({ 'event' : 'lobby', 'data' : data }); if(!isPaused) doThings(); }); socket.on('research', function(facility_type) { commandQueue.push({ 'event' : 'research', 'data' : facility_type }); if(!isPaused) doThings(); }); socket.on('advertise', function(region_id) { commandQueue.push({ 'event' : 'advertise', 'data' : region_id }); if(!isPaused) doThings(); }); var socketFunctions = { 'build' : function(data) { var facility = facilityFactory.build(data.facility_type, regions[data.region_id], self); if(money >= facility.getBuildCost()) { money -= facility.getBuildCost(); facilities[data.region_id].push(facility); model.notifyChange(); console.log(name + ' built a ' + data.facility_type + ' facility in region with id ' + data.region_id); } }, 'demolish' : function(data){ var found = false; for(var i = 0; i < facilities[data.region_id].length; i++) { var facility = facilities[data.region_id][i]; if(facility.getType() == data.facility_type) { facilities[data.region_id].splice(i, 1); found = true; break; } } if(found) { model.notifyChange(); console.log(name + ' demolished a ' + data.facility_type + ' facility in region with id ' + data.region_id); } }, 'lobby' : function(data) { if(money >= globalCosts[GLOBAL_COST_TYPES.LOBBY]) { regions[data.region_id].lobby(data.facility_type); money -= globalCosts[GLOBAL_COST_TYPES.LOBBY]; model.notifyChange(); console.log(name + ' lobbied in region with id ' + data.region_id + ' to reduce taxes on ' + data.facility_type + ' facilities.'); } }, 'research' : function(facility_type){ if(money >= globalCosts[GLOBAL_COST_TYPES.RESEARCH]) { researchLevels[facility_type]++; money -= globalCosts[GLOBAL_COST_TYPES.RESEARCH]; model.notifyChange(); console.log(name + ' researched ' + facility_type + ' facilities.'); } }, 'advertise' : function(region_id){ if(money >= globalCosts[GLOBAL_COST_TYPES.ADVERTISE]) { money -= globalCosts[GLOBAL_COST_TYPES.ADVERTISE]; reputation[region_id] += 1; model.notifyChange(); console.log(name + ' advertised in region with id ' + region_id + '.'); } } }; this.demolish = function(facility) { var regionId = facility.getRegion().getId(); for(var i = 0; i < facilities[regionId].length; i++) { if(facility == facilities[regionId][i]) { facilities[regionId].splice(i, 1); break; } } } // returns the name of this user this.getName = function() { return name; } // Returns the research level of this user for given facilityType this.getResearchLevel = function(facilityType) { return researchLevels[facilityType]; } // Returns array of facilities player has in region region this.getFacilities = function(region) { return facilities[region.getId()]; } // Gives player amount money this.pay = function(amount) { money += amount; } // Deducts amount money from player this.charge = function(amount) { money -= amount; } this.getScore = function(totalDemand) { var score = 0; for(var i = 0; i < 6; i++) { for(var j = 0; j < facilities[i].length; j++) { var facility = facilities[i][j]; if(facility.isRenewable()) { score += facility.getOutput(); } } } return score / totalDemand; } // Returns players reputation this.getReputation = function(region) { return reputation[region]; } this.getMoney = function() { return money; } this.getState = function(totalDemand) { return { 'name' : name, 'money' : money, 'score' : this.getScore(totalDemand), 'reputation' : reputation, 'research' : researchLevels } } // Returns a comparator that will order players based on reputation // (low to high) Player.getComparitor = function(region) { return function(a, b) { if(a.getReputation(region) < b.getReputation(region)) { return -1; } else if(a.getReputation(region) > b.getReputation(region)) { return 1; } else if(a.getTotalReputation() < b.getTotalReputation()) { return -1 } else if(a.getTotalReputation() > b.getTotalReputation()) { return 1 } else { return 0; } } } } function Facility(facilityType, buildCost, baseCost, baseOutput, owner, region, resources, researchStep) { var output = 0; // Returns true iff facility is renewable this.isRenewable = function() { return facilityType == FACILITY_TYPES.WIND || facilityType == FACILITY_TYPES.SOLAR || facilityType == FACILITY_TYPES.HYDRO } // Returns cost of building facility this.getBuildCost = function() { return buildCost; } // returns true iff facility is providing the grid this.isActive = function() { return (output > 0); } // Returns type of facility this.getType = function() { return facilityType; } // Returns base maintenance cost this.getBaseCost = function() { return baseCost; } // Returns base energy output this.getBaseOutput = function() { return baseOutput; } // Returns region this facility is in this.getRegion = function() { return region; } this.getOutput = function() { return output; } this.getMaxOutput = function() { var outputMultiplyer = 1 + researchStep * owner.getResearchLevel(facilityType); var toReturn = baseOutput * outputMultiplyer if(!this.isRenewable())toReturn = Math.min(toReturn, resources.getLevel(facilityType)); return toReturn; } // Causes facility to produce energy up to energyRequired. Returns amount of // energy produced this.produceEnergy = function(energyRequired) { var outputMultiplyer = 1 + 0.1 * owner.getResearchLevel(facilityType) output = Math.min(baseOutput * outputMultiplyer, energyRequired); if(!this.isRenewable()) { output = resources.use(facilityType, output); } var cost = output * resources.getCost(facilityType) * region.getTax(facilityType) + baseCost; var income = output * region.getPrice(); if(cost - income > owner.getMoney()) { owner.demolish(this); return 0; } else{ owner.charge(cost); owner.pay(income); return output; } } } function FacilitiesFactory(buildCosts, baseCosts, baseOutputs, resources, researchStep) { // Builds a facility of type facilityType in region region belonging // to owner this.build = function(facilityType, region, owner) { return new Facility(facilityType, buildCosts[facilityType], baseCosts[facilityType], baseOutputs[facilityType], owner, region, resources, researchStep); } this.getState = function() { var state = {}; for(var key in FACILITY_TYPES) { var facilityType = FACILITY_TYPES[key] state[facilityType] = { 'fuel_cost' : resources.getCost(facilityType), 'base_cost' : baseCosts[facilityType], 'base_output' : baseOutputs[facilityType], 'building_costs' : buildCosts[facilityType] } } return state; } } function Region(id, energyRequired, initialTaxes, taxStep, price) { // Dictionary of players keyed by name var players = {}; // Array of players var playersArray = []; // dictionary of initial taxes var taxes = initialTaxes; // returns id associated with region this.getId = function() { return id; } // Adds player to region this.addPlayer = function(player) { players[player.getName()] = player; playersArray.push(player); } // Returns price that grid will pay per unit of energy this.getPrice = function() { return price; } // Returns tax associated with facilityType in this region this.getTax = function(facilityType) { if(facilityType == FACILITY_TYPES.WIND || facilityType == FACILITY_TYPES.SOLAR || facilityType == FACILITY_TYPES.HYDRO) { return 0; } else { return taxes[facilityType]; } } // Lobbies region to decrement tax on facilityType this.lobby = function(facilityType) { if(taxes[facilityType] >= 1 + taxStep) { taxes[facilityType] -= taxStep; } } // Makes region consume energy from facilities on it this.consumeEnergy = function() { var enegryLeft = energyRequired; playersArray.sort(Player.getComparitor(this)); for(var i = playersArray.length - 1; i >= 0; i--) { var player = playersArray[i]; var facilities = player.getFacilities(this); for(var j = 0; j < facilities.length; j++) { var facility = facilities[j]; if(facility.isRenewable()) { enegryLeft -= facility.produceEnergy(enegryLeft); } } } for(var i = playersArray.length - 1; i >= 0; i--) { var player = playersArray[i]; var facilities = player.getFacilities(this); for(var j = 0; j < facilities.length; j++) { var facility = facilities[j]; if(!facility.isRenewable()) { enegryLeft -= facility.produceEnergy(enegryLeft); } } } } this.getState = function() { var supply = 0; var p = {}; for(var name in players) { p[name] = { 'active' : {}, 'total' : {}}; for(var key in FACILITY_TYPES) { var facilityType = FACILITY_TYPES[key]; p[name].active[facilityType] = 0; p[name].total[facilityType] = 0; } var facilities = players[name].getFacilities(this); for(var i = 0; i < facilities.length; i++) { var facility = facilities[i]; supply += facility.getMaxOutput(); p[name].total[facility.getType()]++; if(facility.isActive()) { p[name].active[facility.getType()]++; } } } return { 'players' : p, 'demand' : energyRequired, 'supply' : supply, 'taxes' : taxes, 'price' : this.getPrice() } } } function Model(initialMoney, facilitiesFactory, globalCosts, energyDemands, initialTaxes, taxStep, researchStep, prices) { // Array of all regions var regions = []; var hasStarted = false; // Dictionary of players keyed by name var players = {}; var numTicks = 0; var tickHandel; for(var i = 0; i < 6; i++) { regions[i] = new Region(i, energyDemands[i], initialTaxes, taxStep, prices[i]); } // Adds a client to the game this.addPlayer = function(name, socket) { var player = new Player(name, this, initialMoney, facilitiesFactory, globalCosts, regions, socket); players[player.getName()] = player; for(var i = 0; i < 6; i++) { regions[i].addPlayer(player); } } this.getPlayers = function() { return players; } // Starts game this.startGame = function() { if(!hasStarted) { hasStarted = true; var self = this; tickHandel = setInterval(function(){ self.tick(); }, 1000); this.notifyAllClients('game_start', generateState()); console.log('===================='); console.log('The game has started'); console.log('===================='); } } // Performs game tick this.tick = function() { for(var name in players) { players[name].pause(); } numTicks++; for(var i = 0; i < 6; i++) { regions[i].consumeEnergy(); } this.notifyChange(); if(this.isGameOver()) { } if(this.isGameOver()) { var totalDemand = 0; for(var i = 0; i < energyDemands.length; i++) { totalDemand += energyDemands[i]; } clearInterval(tickHandel); var scores = {}; for(var name in players) { scores[name] = players[name].getScore(totalDemand); } notifyAllClients('game_over', scores); console.log('==============='); console.log('The game is over'); console.log('==============='); console.log(scores); } for(var name in players) { players[name].start(); } } this.isGameOver = function() { var totalDemand = 0; for(var i = 0; i < energyDemands.length; i++) { totalDemand += energyDemands[i]; } var total = 0; for(var name in players) { total += players[name].getScore(totalDemand); } return total == totalDemand; } this.notifyAllClients = function(event, data) { for(var name in players) { players[name].notify(event, data); } } var generateState = function() { var totalDemand = 0; for(var i = 0; i < energyDemands.length; i++) { totalDemand += energyDemands[i]; } var state = { 'tax_step' : taxStep, 'research_step' : researchStep, 'players' : {}, 'regions' : [], 'facilities' : {}, 'facilities' : facilitiesFactory.getState(), 'global_costs' : globalCosts, 'num_ticks' : numTicks, 'resource_levels' : resources.getState() }; for(var name in players) { state.players[name] = players[name].getState(totalDemand); } for(var i = 0; i < regions.length; i++) { state.regions[i] = regions[i].getState(); } return state } // Sends message to all clients this.notifyChange = function() { this.notifyAllClients('notify_change', generateState()); } } /************************************* * Change these to parameterize game * *************************************/ var buildCosts = { [FACILITY_TYPES.COAL] : 800, [FACILITY_TYPES.NUCLEAR] : 9000, [FACILITY_TYPES.GAS] : 990, [FACILITY_TYPES.WIND] : 1010, [FACILITY_TYPES.SOLAR] : 1010, [FACILITY_TYPES.HYDRO] : 1000 }; var baseCosts = { [FACILITY_TYPES.COAL] : 100, [FACILITY_TYPES.NUCLEAR] : 200, [FACILITY_TYPES.GAS] : 100, [FACILITY_TYPES.WIND] : 100, [FACILITY_TYPES.SOLAR] : 100, [FACILITY_TYPES.HYDRO] : 100 }; var baseOutputs = { [FACILITY_TYPES.COAL] : 550, [FACILITY_TYPES.NUCLEAR] : 1100, [FACILITY_TYPES.GAS] : 550, [FACILITY_TYPES.WIND] : 130, [FACILITY_TYPES.SOLAR] : 125, [FACILITY_TYPES.HYDRO] : 110 }; var initialTaxes = { [FACILITY_TYPES.COAL] : 1.5, [FACILITY_TYPES.NUCLEAR] : 1.5, [FACILITY_TYPES.GAS] : 1.5, [FACILITY_TYPES.WIND] : 0, [FACILITY_TYPES.SOLAR] : 0, [FACILITY_TYPES.HYDRO] : 0 }; var resourceCosts = { [FACILITY_TYPES.COAL] : 0.51, [FACILITY_TYPES.NUCLEAR] : 0.45, [FACILITY_TYPES.GAS] : 0.5, [FACILITY_TYPES.WIND] : 0, [FACILITY_TYPES.SOLAR] : 0, [FACILITY_TYPES.HYDRO] : 0 }; var initialLevels = { [FACILITY_TYPES.COAL] : 2000000, [FACILITY_TYPES.NUCLEAR] : 2000000, [FACILITY_TYPES.GAS] : 2000000 }; var globalCosts = { [GLOBAL_COST_TYPES.LOBBY] : 201, [GLOBAL_COST_TYPES.RESEARCH] : 220, [GLOBAL_COST_TYPES.ADVERTISE] : 190 }; var energyDemands = [ 3000, 3000, 3000, 3000, 3000, 3000 ]; var prices = [ 1, 1, 1, 1, 1, 1 ]; var taxStep = 0.1; var researchStep = 0.1; var initialMoney = 2000; /****************** * End parameters * ******************/ var resources = new Resources(initialLevels, resourceCosts) var facilitiesFactory = new FacilitiesFactory(buildCosts, baseCosts, baseOutputs, resources, researchStep); var model = new Model(initialMoney, facilitiesFactory, globalCosts, energyDemands, initialTaxes, taxStep, researchStep, prices); var allSockets = []; var io = require('socket.io')(9001); io.on('connect', function(socket) { allSockets.push(socket); socket.on('go', function(data){ var players = model.getPlayers(); for(var playerName in players) { socket.emit('notify_player_joined', playerName); } socket.on('join_request', function(playerName){ if(model.getPlayers()[playerName]) { socket.emit('join_response', 0); } else { socket.emit('join_response', 1); //model.notifyAllClients('notify_player_joined', playerName) for(var i = 0; i < allSockets.length; i++) { var soc = allSockets[i]; if(soc != socket) { soc.emit('notify_player_joined', playerName); } } model.addPlayer(playerName, socket); console.log(playerName + ' joined the game.'); } }); socket.on('start', function(){ model.startGame(); }); }); });
import Vue from 'vue' import App from './App.vue' import store from './store' import * as filters from './utils/filters' import 'bootstrap' import 'bootstrap/dist/css/bootstrap.min.css' import { BootstrapVue, BootstrapVueIcons } from 'bootstrap-vue' import { ModalPlugin } from 'bootstrap-vue' import 'bootstrap/dist/css/bootstrap.css' import 'bootstrap-vue/dist/bootstrap-vue.css' Vue.config.productionTip = false new Vue({ store, render: h => h(App), }).$mount('#app') // register global utility filters. Object.keys(filters).forEach(key => { Vue.filter(key, filters[key]) }) Vue.use(BootstrapVue) Vue.use(BootstrapVueIcons) Vue.use(ModalPlugin)
import { zip, Inflater, Deflater } from '../node_modules/zip.js/WebContent/index.js'; zip.Inflater = Inflater; zip.Deflater = Deflater; export { zip }; export { default as Tree } from '@widgetjs/tree/src/index.js'; import { default as Vue } from 'vue'; import { default as VueMaterial } from 'vue-material'; Vue.use(VueMaterial); export { Vue }; export { default as vuedraggable } from 'vuedraggable'; // import * as d3 from 'd3/dist/d3.min.js'; export { d3 } from './d3-custom.js'; import * as messagepack from 'messagepack'; export { messagepack }; import PouchDB from 'pouchdb-browser'; export { PouchDB }; export { xyChart, heatChart, heatChartMultiMasked, colormap_names, get_colormap, dataflowEditor, extend, rectangleSelect, xSliceInteractor, ySliceInteractor, rectangleInteractor, ellipseInteractor, angleSliceInteractor, monotonicFunctionInteractor, scaleInteractor, rectangleSelectPoints } from 'd3-science'; //} from './node_modules/d3-science/src/index.js'; export { default as Split } from 'split.js'; export { default as sha1 } from 'sha1' export const template_editor_url = "template_editor_live.html";
var debug = require('debug')('mocha:mongoreporter'), Q = require('q'), mongo = require('mongodb'), dateFormat = require('dateFormat'), now; os = require('os'), snap = require('env-snapshot').EnvSnapshot(); module.exports = mocha_mongo_reporter; function mocha_mongo_reporter(runner, options) { var db = null; var passes = []; var failures = []; var meta = { user: snap.process_env["USER"], host: snap.os_hostname, type: snap.os_type, platform: snap.os_platform, arch: snap.os_arch, release: snap.os_release, totalmem: snap.os_totalmem, freemem: snap.os_freemem, cpus: snap.os_cpus }; var runnerEnd=Q.defer(), mongoConnect=Q.defer(); var mongoUrl=( options && options.reporterOption && options.reporterOption.url ) || process.env['MONGOURL']; debug("connecting to %s", mongoUrl); if(!(this instanceof mocha_mongo_reporter)) { return new mocha_mongo_reporter(runner); } mongo.MongoClient.connect(mongoUrl, function(err, _db) { if(err) { mongoConnect.reject(err); throw err; } debug("connected to mongo"); mongoConnect.resolve({}); db = _db; }); runner.on('pass', function(test){ now=new Date(); meta.timestamp=dateFormat(now, "isoDateTime", true); passes.push({ suite:test.fullTitle().match(new RegExp("(.*) "+test.title))[1], test:test.title, duration:test.duration, pass:true, meta:meta }); }); runner.on('fail', function(test, err){ now=new Date(); meta.timestamp=dateFormat(now, "isoDateTime", true); failures.push({ suite:test.fullTitle().match(new RegExp("(.*) "+test.title))[1], test:test.title, duration:test.duration, pass:false, err:err.message, meta:meta }); }); runner.on('end', function(){ debug("runner.end"); runnerEnd.resolve({}); }); Q.all([runnerEnd.promise, mongoConnect.promise]).then( updateDB, function onRejectedPromise() { debug("error connecting to mongo"); }); function updateDB() { var allDeferreds=[]; debug("updating db, %s %s", passes, failures); passes.concat(failures).forEach(function saveTestResults(test) { var deferred=Q.defer(); allDeferreds.push(deferred.promise); debug("testrun to insert: %s", JSON.stringify(test)); if(options.meta===false) test.meta=undefined; db.collection("testruns").insert(test, function mongoInsertCallback(err, results) { if(err) deferred.reject(err); deferred.resolve(results); }); }); Q.all(allDeferreds).then(function allDBUpdatesDone() { db.close(); process.exit(failures.length); }, function onDBErr(err) { debug("error saving to mongo: %j", err); db.close(); process.exit(failures.length); }); } }
// = // env variables for careful module.exports = { environment: 'dev', // this will match databases[option <- ] // main app port port: 3000, // mongodb port (expecte to run on localhost) mongoDbPort: 27017, databases: { dev: 'careship-id-dev', prod: 'careship-id' }, logs: { debug: './logs/jupiter_debug.log', error: './logs/app/jupiter_error.log' } }
var assert = require('chai').assert; var rules = require('../src/rules_functions.js'); describe('Alphanumeric rule on a number', () => { it('should return true for 0 and alphanumeric of false', () => { var result = rules.alphanumeric(0, {alphanumeric: false}); assert.equal(result, true); }); it('should return false for 0', () => { var result = rules.alphanumeric(0, {alphanumeric: true}); assert.equal(result, false); }); it('should return false for 1', () => { var result = rules.alphanumeric(1, {alphanumeric: true}); assert.equal(result, false); }); }); describe('Alphanumeric rule on a string', () => { it('should return true for "" and an alphanumeric of false', () => { var result = rules.alphanumeric('', {alphanumeric: false}); assert.equal(result, true); }); it('should return true for "abc123!@#" and an alphanumeric of false', () => { var result = rules.alphanumeric('abc123!@#', {alphanumeric: false}); assert.equal(result, true); }); it('should return true for ""', () => { var result = rules.alphanumeric('', {alphanumeric: true}); assert.equal(result, true); }); it('should return true for "aBc"', () => { var result = rules.alphanumeric('aBc', {alphanumeric: true}); assert.equal(result, true); }); it('should return true for "123"', () => { var result = rules.alphanumeric('123', {alphanumeric: true}); assert.equal(result, true); }); it('should return true for "abc123"', () => { var result = rules.alphanumeric('abc123', {alphanumeric: true}); assert.equal(result, true); }); it('should return true for "Düsseldorf"', () => { var result = rules.alphanumeric('Düsseldorf', {alphanumeric: true}); assert.equal(result, true); }); it('should return true for "321Düsseldorf"', () => { var result = rules.alphanumeric('321Düsseldorf', {alphanumeric: true}); assert.equal(result, true); }); it('should return false for "Düsseldorf!"', () => { var result = rules.alphanumeric('Düsseldorf!', {alphanumeric: true}); assert.equal(result, false); }); });
import { ce } from "../helpers/htmlFactory.js"; import auth from "../services/authService.js"; import likesService from "../services/likesService.js"; import movieService from "../services/movieService.js"; import viewFinder from "../viewFinder.js"; let section = undefined; let navLinkClass = undefined; function setupSection(sectionElement, linkClass) { section = sectionElement; navLinkClass = linkClass; } async function getView(id) { let movieDetail = await movieService.getMovie(id); console.log(movieDetail); let movieContainer = section.querySelector('#movie-details-container'); [...movieContainer.children].forEach(c => c.remove()); let userLikes = await likesService.getUserLikes(id); let movieLikes = await likesService.getMovieLikes(id); console.log(movieLikes); let movieDetails = createMovieDetails(movieDetail, userLikes.length > 0, movieLikes); movieContainer.appendChild(movieDetails); return section; } function createMovieDetails(movie, hasLiked, likes) { let movieHeading = ce('h1', undefined, `Movie title: ${movie.title}`); let movieImage = ce('img', { class: 'img-thumbnail', src: movie.img, alt: 'Movie' }); let imageDiv = ce('div', { class: 'col-md-8' }, movieImage); let descriptionHeading = ce('h3', { class: 'my-3' }, 'Movie Description'); let descriptionP = ce('p', undefined, movie.description); let deleteBtn = ce('a', { class: `btn btn-danger ${navLinkClass}`, 'data-route': 'delete', 'data-id': `${movie._id}`, href: `#/delete/${movie._id}` }, 'Delete'); deleteBtn.addEventListener('click', viewFinder.changeViewHandler); let editBtn = ce('a', { class: `btn btn-warning ${navLinkClass}`, 'data-route': 'edit-movie', 'data-id': `${movie._id}`, href: `#/edit/${movie._id}` }, 'Edit'); editBtn.addEventListener('click', viewFinder.changeViewHandler); let likeBtn = ce('a', { class: `btn btn-primary ${navLinkClass}`, 'data-route': 'like', 'data-id': `${movie._id}`, href: `#/like/${movie._id}` }, 'Like'); likeBtn.addEventListener('click', viewFinder.changeViewHandler); let likesSpan = ce('span', { class: 'enrolled-span likes' }, `Liked: ${likes}`); let descriptionDiv = ce('div', { class: 'col-md-4 text-center' }, descriptionHeading, descriptionP); let isOwner = auth.getUserId() === movie._ownerId; if (isOwner) { descriptionDiv.appendChild(deleteBtn); descriptionDiv.appendChild(editBtn); } if (!hasLiked && !isOwner) { descriptionDiv.appendChild(likeBtn); } descriptionDiv.appendChild(likesSpan); let movieDiv = ce('div', { class: 'row bg-light text-dark movie-details', 'data-id': `${movie._id}` }, movieHeading, imageDiv, descriptionDiv); return movieDiv; } async function like(movieId) { let body = { movieId }; await likesService.likeMovie(body); return moviePage.getView(movieId); } async function deleteMovie(movieId) { try { let deleteResult = await movieService.deleteMovie(movieId); return homePage.getView(); } catch (err) { console.error(err); alert(err); } } let moviePage = { setupSection, getView, like, deleteMovie } export default moviePage;
'use strict' Function.prototype.bind2 = function (context) { const _this = this const args = Array.prototype.slice.call(arguments, 1) const fNOP = function () {} const returnFun = function () { const bindedArgs = Array.prototype.slice.call(arguments) const ctx = this instanceof fNOP && context ? this : context return _this.apply(ctx, args.concat(bindedArgs)) } fNOP.prototype = this.prototype returnFun.prototype = new fNOP() return returnFun } Function.prototype.bind = function(oThis) { if (typeof this !== "function") { // 可能的与 ECMAScript 5 内部的 IsCallable 函数最接近的东西, throw new TypeError( "Function.prototype.bind - what " + "is trying to be bound is not callable" ); } var aArgs = Array.prototype.slice.call( arguments, 1 ), fToBind = this, fNOP = function(){}, fBound = function(){ return fToBind.apply( ( this instanceof fNOP && oThis ? this : oThis ), aArgs.concat( Array.prototype.slice.call( arguments ) ) ); } ; fNOP.prototype = this.prototype; fBound.prototype = new fNOP(); return fBound; }
;String.prototype.convertDigit=function(){var ret="";var _nums= ["0123456789","၀၁၂၃၄၅၆၇၈၉"];for(var i1=0;i1<this.length;i1++) {ret+=/[0-9]/.test(this.charAt(i1))?_nums[1].charAt(this.charAt (i1)):this.charAt(i1);}return ret;};var datelist={ en: ["sunday","monday","tuesday","wednesday","thursday","friday","s aturday","january","february","march","april","may","june","july"," august","september","october","november","december","\,","am", "pm"],bu:["တနဂၤေႏြေန႕","တနလၤာေန႕","အဂၤါေန႕","ဗုဒၶဟူးေန႕","ၾကာ သပေတးေန႕","ေသာၾကာေန႕","စေနေန႕", "ဇန္န၀ါရီလ","ေဖေဖာ္၀ါရီလ", "မတ္လ","ဧျပီလ","ေမလ","ဂၽြန္လ","ဂ်ဴလိုင္လ","ဩဂုတ္လ","စ က္တင္ဘာလ","ေအာက္တိုဘာလ","ႏို၀င္ဘာလ","ဒီဇင္ဘာလ","၊","မနက္ခင္း","မြန္းလြဲပိုင္း"] };String.prototype.convertDate=function() {var re;var ret=String(this);for(var i1=0;i1<datelist.en.length;i1+ +){var re=eval("/"+datelist.en[i1]+"/gi");if(re.test(ret)) {ret=ret.replace(re,datelist.bu[i1]);}}return ret.convertDigit();}
import React, {Component} from "react" import PropTypes from "prop-types" import {Tabs, TabPanel, Tab, TabList} from "react-tabs" import uuidV4 from 'uuid/v4' import isUrl from 'is-url' import Favicon from './Favicon' import WebViewWrapper from './WebViewWrapper' export default class TabsArea extends Component { PropTypes = { initalTabs: PropTypes.array.isRequired } state = { tabs: this.props.initalTabs, selectedTabIndex: 2 } constructor(props) { super(props) Tabs.setUseDefaultStyles(false) this.handleSelect = this.handleSelect.bind(this) } closeTab(index) { const newTabs = this.state.tabs.slice() newTabs.splice(index, 1) this.setState({ tabs: newTabs }) } handleSelect(index, last) { let lastTab = this.state.tabs.length - 1 if (index === lastTab) { let newTabs = this.state.tabs.slice() const newTabData = { title: 'New Tab', url: '', uuid: uuidV4() } newTabs.splice(newTabs.length - 1, 0, newTabData) this.setState({ tabs: newTabs, selectedTabIndex: newTabs.length-2 // Minus two because -1 for tab before new tab and then minus one again because react tabs starts at 1 }) } } render() { return ( <Tabs onSelect={this.handleSelect} forceRenderTabPanel={true} selectedIndex={this.state.selectedTabIndex}> <TabList> { this.state.tabs.map((site, index) => { const shouldHaveCloseTab = isUrl(site.url) return ( <Tab key={site.uuid}> <Favicon url={site.url}/> <p>{site.title}</p> { shouldHaveCloseTab ? <img className='close-button' src='./images/close.svg' onClick={() => this.closeTab(index)}/> : <span></span> } </Tab> ) }) } </TabList> { this.state.tabs.map(site => { return ( <TabPanel key={site.uuid}> <WebViewWrapper src={site.url} index={site.uuid}/> </TabPanel> ) }) } {/*Fake for new tab button*/} </Tabs> ) } }
define([ 'client/views/services', 'common/collections/services', 'backbone' ], function (ServicesView, ServicesCollection, Backbone) { describe('Services View', function () { beforeEach(function () { // clear window.location.search window.history.replaceState({}, '', window.location.href.split('?')[0]); window.GOVUK = { analytics: { trackEvent: function () {} } }; this.$el = $('<div><input id="filter" value="passport"/><select id="department"><option value="">All</option><option value="home-office">Home Office</option></select><select id="service-group"><option value="">All</option><option value="service1">Service 1</option></select></div>'); this.view = new ServicesView({ el: this.$el, model: new Backbone.Model(), collection: new ServicesCollection([]) }); }); it('uses the history API to update the URL after filtering', function () { this.view.filter('filter'); expect(window.location.search).toEqual('?filter=passport'); this.$el.find('#department').val('home-office'); this.view.filter('department'); expect(window.location.search).toEqual('?filter=passport&department=home-office'); this.$el.find('#filter').val(''); this.view.filter('filter'); expect(window.location.search).toEqual('?department=home-office'); this.$el.find('#service-group').val('service1'); this.view.filter('service-group'); expect(window.location.search).toEqual('?department=home-office&servicegroup=service1'); }); it('sends filter events to analytics', function() { spyOn(window.GOVUK.analytics, 'trackEvent'); this.$el.find('#filter').val('carer').trigger('search'); expect(window.GOVUK.analytics.trackEvent).toHaveBeenCalledWith('ppServices', 'filter', { label: 'carer', nonInteraction: true }); this.$el.find('#department').val('home-office').trigger('change'); expect(window.GOVUK.analytics.trackEvent).toHaveBeenCalledWith('ppServices', 'department', { label: 'home-office', nonInteraction: true }); }); }); });
//alert弹窗事件 /** * sendOption-{ "type":1, -1:confirm样式;2:alert样式 "msg":"确定吗?", -显示信息 "yes":"确定", -确定按钮的字样 "cancel":"取消" -取消按钮的字样 "yesParm":{} -yesFun执行时需要的参数 "cancelParm":{} -cancelFun执行时需要的参数 } yesFun:点击确定按钮后执行的函数名 cancelFun:点击取消按钮后执行的函数名 * */ function myAlert(sendOption,yesFun,cancelFun){ var defaults = { "type":1, "msg":"确定吗?", "yes":"确定", "cancel":"取消" }; var option = $.extend(defaults, sendOption); //console.log(option); var btns = ''; if(option.type===1){//confirm btns = '<div class="layui-btn layui-btn-normal yes">'+option.yes+'</div> ' + '<div class="layui-btn layui-btn-primary cancel">'+option.cancel+'</div> '; }else{//alert btns = '<div class="layui-btn layui-btn-normal yes" >'+option.yes+'</div> '; } $("body").append('<div class="myAlert"> ' + '<div class="alertBody"> ' + '<div class="text">'+option.msg+'</div> ' + '<div class="btnArea"> ' + btns + '</div> ' + '</div> ' + '</div>'); $(".myAlert").on("click",".cancel",function(){ cancel(); if(cancelFun){ cancelFun(option.cancelParm); } }); $(".myAlert").on("click",".yes",function(){ cancel(); if(yesFun){ yesFun(option.yesParm); } }); var cancel = function(){ $(".myAlert").remove(); } } //毫秒转化为yyyy-MM-dd HH:mm:ss(可指定转化形式) var format = function( time, format ) { var t = new Date( time ); var tf = function( i ) { return (i < 10 ? '0' : '') + i }; return format.replace( /yyyy|MM|dd|HH|mm|ss/g, function( a ) { switch( a ) { case 'yyyy': return tf( t.getFullYear() ); break; case 'MM': return tf( t.getMonth() + 1 ); break; case 'mm': return tf( t.getMinutes() ); break; case 'dd': return tf( t.getDate() ); break; case 'HH': return tf( t.getHours() ); break; case 'ss': return tf( t.getSeconds() ); break; } } ) }; //获取url传参 function getUrlParm( name ) { var reg = new RegExp( "(^|&)" + name + "=([^&]*)(&|$)" ); var r = window.location.search.substr( 1 ).match( reg ); if( r != null )return decodeURI( r[ 2 ] ); return null; } //单页面后退 function reverseSlide( parm1, parm2 ) { $( parm1 ).animate( { left: '30rem' }, 300 ).hide( 100 ); $( parm2 ).show(); } //单页面前进 function pageSlide( parm1, parm2 ) { $( parm1 ).hide(); $( parm2 ).show().animate( { left: '0' }, 300 ); } //H5-localStorage //存储 function setStorage( name, value ) { if( !window.localStorage ) { console.log( "浏览器不支持localStorage" ); } else { localStorage.setItem( name, value ); } } //删除 function deleteStorage(list){ for(var i=0;i<list.length;i++){ localStorage.removeItem(list[i]); } } //获取 function getStorage( name ) { //console.log( localStorage ); var val = localStorage.getItem( name ); return val; } //替换历史记录里的当前url;parmArr-需要添加的参数数组 function replaceState( parmArr ) { var hash = ""; if(location.href.split( "#" ).length!=1){ hash ="#"+location.href.split( "#" )[ 1 ]; }else{ } var beforeHash = location.href.split( "#" )[ 0 ]; var currentHref = beforeHash.split( "?" )[ 0 ]; var searchStr = ""; $.each( parmArr, function( j, parm ) {//遍历参数数组 for( var prop in parm ) {//取每个对象里面的键值对 if( j == 0 ) { searchStr += "?" + prop + "=" + parm[ prop ]; } else { searchStr += "&" + prop + "=" + parm[ prop ]; } } } ); history.replaceState( null, document.title, currentHref + searchStr +hash ); } //插入一条历史url function pushHistory() { var state = {title: "title",url: "#"}; window.history.pushState(state, "title", "#"); } //提示框-出现一段时间后消失/一直存在/有关闭按钮 /* * option:{text:'',time:1500,closeIcon:false} * time:0-一直存在,不消失 * */ function toggleDialog( option ) { var defaultOption = { text:'', time:1500, closeIcon:false }; option = $.extend(defaultOption,option); $(".dialogCon").remove(); var icon=''; if(option.closeIcon){ icon='<i class="closeIcon" onclick="$(this).parent(\'.dialogCon\').remove();">×</i>'; } var dialogCon = '<div class="text-center dialogCon">' + option.text + icon+'</div>'; $( "body" ).append( dialogCon ); var _this = $(".dialogCon"); var screenW = document.body.clientWidth; var dialogConW = _this.width(); _this.css({"left":(screenW-dialogConW)/2}); if(option.time===0){ _this.fadeIn( 500 ); }else{ var delayTime = option.time? option.time:1500; _this.fadeIn( 500 ).delay( delayTime ).fadeOut( 300 ); } } /*remove url of alert/confirm*/ var wAlert = window.alert; window.alert = function( message ) { try { var iframe = document.createElement( "IFRAME" ); iframe.style.display = "none"; iframe.setAttribute( "src", 'data:text/plain,' ); document.documentElement.appendChild( iframe ); var alertFrame = window.frames[ 0 ]; var iwindow = alertFrame.window; if( iwindow == undefined ) { iwindow = alertFrame.contentWindow; } iwindow.alert( message ); iframe.parentNode.removeChild( iframe ); } catch( exc ) { return wAlert( message ); } }; var wConfirm = window.confirm; window.confirm = function( message ) { try { var iframe = document.createElement( "IFRAME" ); iframe.style.display = "none"; iframe.setAttribute( "src", 'data:text/plain,' ); document.documentElement.appendChild( iframe ); var alertFrame = window.frames[ 0 ]; var iwindow = alertFrame.window; if( iwindow == undefined ) { iwindow = alertFrame.contentWindow; } var result = iwindow.confirm( message ); iframe.parentNode.removeChild( iframe ); return result; } catch( exc ) { return wConfirm( message ); } }; /*分页插件*/ (function(){ var defaults = { currentPage:1, totalPage:5, callBack:function( page ){} }; $.fn.mPage = function(sendOption) { //在这里面,this指的是用jQuery选中的元素 //example :$('a'),则this=$('a') var option = $.extend(defaults, sendOption); return this.each(function() { //对每个元素进行操作 var _this = $( this ); var currentPage = parseInt(option.currentPage); var totalPage = option.totalPage; var preHide='',nextHide=''; if(option.currentPage==1){//第一页时,隐藏上一页按钮 preHide = 'm-hide'; } if(option.currentPage==option.totalPage){//最后一页时,隐藏下一页按钮 nextHide = 'm-hide'; } _this.html('<button class="layui-btn layui-btn-primary prePageBtn '+preHide+'"></button> ' + '<div><span class="currentPage">'+currentPage+'</span>/<span class="totalPage">'+totalPage+'</span></div> ' + '<button class="layui-btn layui-btn-primary nextPageBtn '+nextHide+'"></button> ' + '<input type="text" class="layui-input pageInput"> ' + '<button class="layui-btn layui-btn-normal skipBtn">跳转</button>'); _this.off( "click" );//解绑事件,防止多次执行 _this.on( "click", ".prePageBtn", function(){ option.callBack( currentPage - 1 ); } ); _this.on( "click", ".nextPageBtn", function(){ option.callBack( currentPage + 1 ); } ); _this.on( "click", ".skipBtn", function(){ var p = parseInt( $( ".pageInput" ).val() ); console.log(p); if(p>totalPage || p <= 0 || !p ){//!p-没有输入值时,返回NaN,转为boolean-false toggleDialog({text:'请输入正确的页码'}); }else{ option.callBack( p ); } } ); }) } })(); /*load( 1 ); function load( i ) { console.log( 'i:' + i ); 分页插件用法 $( "#m-page" ).mPage( { currentPage: i, totalPage: 5, callBack: function( page ){ console.log( 'page:' + page ); load( page ); } } ) }*/ //获取地址前缀 var urlPrefix=getUrlPrefix(); function getUrlPrefix(){ var curWwwPath = window.document.location.href; var pathName = window.document.location.pathname; var pos = curWwwPath.indexOf(pathName); var localhostPaht = curWwwPath.substring(0, pos); var projectName = pathName.substring(0,pathName.substr(1).indexOf('/') + 1); return (localhostPaht + projectName); }
import React, { useState, useContext, useEffect } from "react"; import { Row, Col } from "react-bootstrap"; // import Sidebar_Teacher from "./Sidebar_Teacher"; import "../Score.css"; import { TextField } from "@material-ui/core"; import { Input } from "antd"; import Sidebar_Advisor from "./Sidebar_Advisor"; import { Select } from "antd"; import axios from "axios"; import Button from "@material-ui/core/Button"; import Icon from "@material-ui/core/Icon"; const { Option } = Select; const { TextArea } = Input; export const Score402_Advisor = () => { const [studentGroupNNG, setstudentGroupNNG] = useState([]); const [scoreList, setscoreList] = useState([]); const [newCheck, setnewCheck] = useState([]); const [newcheckname, setnewcheckname] = useState([]); const [new10score1_1, setnew10score1_1] = useState([]); const [new20score2_1, setnew20score2_1] = useState([]); const [new30score3_1, setnew30score3_1] = useState([]); const [new20score4_1, setnew20score4_1] = useState([]); const [new20score5_1, setnew20score5_1] = useState([]); const [new60score6_1, setnew60score6_1] = useState([]); const [newTotalscore7_1, setnewTotalscore7_1] = useState([]); const [newcomment, setnewcomment] = useState([]); const [new10score1_2, setnew10score1_2] = useState([]); const [new20score2_2, setnew20score2_2] = useState([]); const [new30score3_2, setnew30score3_2] = useState([]); const [new20score4_2, setnew20score4_2] = useState([]); const [new20score5_2, setnew20score5_2] = useState([]); const [new60score6_2, setnew60score6_2] = useState([]); const [newTotalscore7_2, setnewTotalscore7_2] = useState([]); const updateScorename = (id) => { axios .put("http://localhost:5001/score/update/", { score_1: new10score1_1, score_2: new20score2_1, score_3: new30score3_1, score_4: new20score4_1, score_5: new20score5_1, score_6: new60score6_1, score_total: newTotalscore7_1, score_comment: newcomment, score_11: new10score1_2, score_12: new20score2_2, score_13: new30score3_2, score_14: new20score4_2, score_15: new20score5_2, score_16: new60score6_2, score_total2: newTotalscore7_2, id: id }) .then((respond) => { setnewCheck( newCheck.map((val) => { return val.id == id ? { score_1: new10score1_1, score_2: new20score2_1, score_3: new30score3_1, score_4: new20score4_1, score_5: new20score5_1, score_6: new60score6_1, score_total: newTotalscore7_1, score_somment: newcomment, score_11: new10score1_2, score_12: new20score2_2, score_13: new30score3_2, score_14: new20score4_2, score_15: new20score5_2, score_16: new60score6_2, score_17: newTotalscore7_2, id:id } : val; }) ); }); }; // const getStudentscore = () => { // axios // .post("http://localhost:5001/p/add", { // name: newcheckname[0] , // stdname : newcheckname[1] // }) // .then(() => { // setscoreList([ // ...scoreList, // { // name: newcheckname[0] , // stdname : newcheckname[1] // }, // ]); // }); // }; const getAdvisorNNG = () => { axios.get("http://localhost:5001/score/nng").then((respond) => { setstudentGroupNNG(respond.data); }); }; const getScoreNNG = () => { axios.get("http://localhost:5001/score2/nng").then((respond) => { setstudentGroupNNG(respond.data); }); }; // const updateScoreStudent = (id) => { // axios.put("http://localhost:5001/group/update5/", { // advisorlaststname: newadvisorlastname, // id: id, // }).then((respond)=>{ // setgroupList( // groupList.map((val)=>{ // return val.id == id ? { // id: val.id, // groupname: val.ProjNameTH, // memberfirstname: val.Std_Name_1, // memberlastname: val.Std_Name_2, // advisorfirstname: val.AdvId, // advisorlastname: newadvisorlastname // } : val; // }) // ) // }) // }; // const getGropNNG = () => { // axios.post("http://localhost:5001/namegroup/nng").then((respond) => { // setnewCheck(respond.data); // setnewgroupNNG(respond.data); // }); // }; useEffect(() => { getAdvisorNNG(); }, []); return ( <Row className="content"> <Col> <Sidebar_Advisor /> </Col> <div className="rightblock_Score"> <div className="blockwhite_Score"> {/* <h1 className="Topname_Score">Score</h1> <hr className="hr-Score"></hr> */} <div className="blockscore"> <p className="หัวข้อใบประเมินคะแนน"> ใบรายงานผลคะแนน วิชา CS402 โครงงานพิเศษ 1 ภาคเรียนที่ 1/2563 </p> </div> <div className="blockscore1"> <Row className="block1row"> <span className="block1col1">อาจารย์ผู้ประเมิน:</span> <span className="block1col2">nng</span> <span className="block1col3">อาจารย์ นุชชากร งามเสาวรส</span> </Row> <Row className="block2row"> <span className="block2col1">กลุ่มโครงงาน:</span> <span className="block2col2"> <select showSearch style={{ width: 150, textAlign: "center" }} placeholder="Select ProjCode" optionFilterProp="children" onChange={(e) => { axios .post("http://localhost:5001/namegroup/nng", { newCheck: e.target.value, }) .then((respond) => { console.log(e.target.value); setnewCheck(respond.data); console.log(newCheck[0]); console.log( newCheck[0] ? newCheck[0].ProjNameTH : null ); }); }} > {studentGroupNNG.map((val, key) => { return ( <option key={key} value={val.ProjCode}> {val.ProjCode} </option> ); })} </select> </span> <span className="block2col3"> {newCheck[0] ? newCheck[0].ProjNameTH : null} </span> </Row> <row className="block3row"> <span className="block3col3"> {newCheck[0] ? newCheck[0].ProjNameEN : null} </span> </row> <Row className="block4row"> <span className="block4col1">อาจารย์ที่ปรึกษา:</span> <span className="block4col2"> {newCheck[0] ? newCheck[0].AdvId : null} </span> <span className="block4col3"> {newCheck[0] ? newCheck[0].ProjNameTH : null} </span> </Row> <Row className="block5row"> <span className="block5col1">กำหนดสอบวันที่:</span> <span className="block5col2">ศ.28, 13:30 - 15:00</span> </Row> </div> <div className="blockscore2"> <span class="std1"> <p className="id1"> {newCheck[0] ? newCheck[0].Username_id_1 : null} </p> <span>{newCheck[0] ? newCheck[0].Std_Name_1 : null}</span> </span> <span class="std2"> <p className="id1"> {newCheck[0] ? newCheck[0].Username_id_2 : null} </p> <p>{newCheck[0] ? newCheck[0].Std_Name_2 : null}</p> </span> </div> <div className="blockscore3"> <Row className="block4row1"> <span className="ส่วนที่1">ส่วนที่ 1</span> <span className="คะแนนความก้าวหน้า"> คะแนนความก้าวหน้าโครงงาน </span> <span className="คะแนน">(10 คะแนน)</span> <span className="ให้โดยที่ปรึกษา">(ให้โดยที่ปรึกษา)</span> <span className="คะแนนนศ1ช่อง1"> <Input className="inputscoreStd1_row1" placeholder="" onChange={(e) => { setnew10score1_1(e.target.value); }} /> </span> <span className="คะแนนนศ2ช่อง1"> <Input className="inputscoreStd2_row1" placeholder="" onChange={(e) => { setnew10score1_2(e.target.value); }} /> </span> </Row> </div> <div className="blockscore4"> <Row className="block4row2"> <span className="ส่วนที่2">ส่วนที่ 2</span> <span className="คุณภาพของรายงาน">คุณภาพของรายงาน</span> <span className="คะแนน30">(20 คะแนน)</span> <span className="คะแนนนศ1ช่อง2"> <Input className="inputscoreStd1_row2" placeholder="" onChange={(e) => { setnew20score2_1(e.target.value); }}/> </span> <span className="คะแนนนศ2ช่อง2"> <Input className="inputscoreStd2_row2" placeholder="" onChange={(e) => { setnew20score2_2(e.target.value); }}/> </span> </Row> </div> <div className="blockscore5"> <Row className="block5row1"> <span className="ส่วนที่2">ส่วนที่ 3</span> <span className="ส่วน3ย่อย"> คุณภาพของผลงานและความสมบูรณ์ของงาน <span className="คุณภาพของผลงานและความสมบูรณ์ของงาน_คะแนน30"> (30 คะแนน) </span> <span className="คะแนนนศ1ช่อง3"> <Input className="inputscoreStd1_row3" placeholder="" onChange={(e) => { setnew30score3_1(e.target.value); }}/> </span> <span className="คะแนนนศ2ช่อง3"> <Input className="inputscoreStd2_row3" placeholder="" onChange={(e) => { setnew30score3_2(e.target.value); }} /> </span> <p className="คุณภาพการนำเสนอและการตอบคำถาม"> คุณภาพการนำเสนอและการตอบคำถาม <span className="คุณภาพการนำเสนอและการตอบคำถาม_คะแนน20"> (20 คะแนน) </span> <span className="คะแนนนศ1ช่อง4"> <Input className="inputscoreStd1_row4" placeholder="" onChange={(e) => { setnew20score4_1(e.target.value); }} /> </span> <span className="คะแนนนศ2ช่อง4"> <Input className="inputscoreStd2_row4" placeholder="" onChange={(e) => { setnew20score4_2(e.target.value); }}/> </span> </p> <p className="การประยุกต์ใช้ความรู้ทางวิทยาการคอมพิวเตอร์อย่างเหมาะสม"> การประยุกต์ใช้ความรู้ทางวิทยาการคอมพิวเตอร์อย่างเหมาะสม <span className="การประยุกต์_คะแนน20">(20 คะแนน)</span> <span className="คะแนนนศ1ช่อง5"> <Input className="inputscoreStd1_row5" placeholder="" onChange={(e) => { setnew20score5_1(e.target.value); }}/> </span> <span className="คะแนนนศ2ช่อง5"> <Input className="inputscoreStd2_row5" placeholder="" onChange={(e) => { setnew20score5_2(e.target.value); }}/> </span> </p> </span> <span className="การนำเสนอโครงงาน">การนำเสนอโครงงาน</span> <span className="คะแนน60">(60 คะแนน)</span> <span className="คะแนนนศ1ช่อง6"> <Input className="inputscoreStd1_row6" placeholder="0" onChange={(e) => { setnew60score6_1(e.target.value); }}/> </span> <span className="คะแนนนศ2ช่อง6"> <Input className="inputscoreStd2_row6" placeholder="0" onChange={(e) => { setnew60score6_2(e.target.value); }} /> </span> </Row> </div> <div className="blockscore6"> <Row className="block6row"> <span className="รวม">รวม</span> <span className="คะแนนนศ1ช่อง7"> <Input className="inputscoreStd1_row7" placeholder="0" onChange={(e) => { setnewTotalscore7_1(e.target.value); }}/> </span> <span className="คะแนนนศ2ช่อง7"> <Input className="inputscoreStd2_row7" placeholder="0" onChange={(e) => { setnewTotalscore7_2(e.target.value); }} /> </span> </Row> <Row className="block7row"> <span className="ข้อเสนอแนะ"> ระบุข้อเสนอแนะ/สิ่งที่ต้องปรับปรุง </span> <span className="คอมเม้น"> <TextArea className="inputcomment" rows={4} onChange={(e) => { setnewcomment(e.target.value); }} /> </span> </Row> </div> <div className="blockscore7"> <span class="blockคำชี้แจง"> <p className="คำชี้แจง2">เกณฑ์การวัดผล วิชา CS402 เป็นดังนี้</p> <p className="คำชี้แจง2">ช่วงคะแนน 90 - 100 == เกรด A</p> <p className="คำชี้แจง2">ช่วงคะแนน 85 - 89 == เกรด B+</p> <p className="คำชี้แจง2">ช่วงคะแนน 80 - 84 == เกรด B</p> <p className="คำชี้แจง2">ช่วงคะแนน 70 - 79 == เกรด C+</p> <p className="คำชี้แจง2">ช่วงคะแนน 60 - 69 == เกรด C</p> <p className="คำชี้แจง2">ช่วงคะแนน 55 - 59 == เกรด D+</p> <p className="คำชี้แจง2">ช่วงคะแนน 50 - 54 == เกรด D</p> <p className="คำชี้แจง2">ช่วงคะแนน 0 - 49 == เกรด F</p> </span> <span class="blockคำชี้แจง"> <p className="คำชี้แจง">คำชี้แจง</p> <p className="คำชี้แจง">ช่วงเวลาสอบอาจแบ่งโดยคร่าว ดังนี้</p> <p className="คำชี้แจง">- นักศึกษาเตรียมตัวสอบ 10 นาที</p> <p className="คำชี้แจง">- นำเสนอผลงาน 30 - 40 นาที</p> <p className="คำชี้แจง">- ตอบคำถาม 30 นาที</p> <p className="คำชี้แจง">- กรรมการสรุปผลการสอบ 10 นาที</p> </span> </div> <Button id="btn-create" className="buttonttt" onClick={() => { updateScorename(newCheck[0] ?newCheck[0].id:null); }} variant="outlined" color="primary" type="submit" endIcon={<Icon>add</Icon>} > Submit </Button> </div> </div> </Row> ); };
const cp = process.cwd() + "/Controllers/"; const dashboard = require(cp + "DashboardController"); module.exports = function(fastify, opts, next) { fastify.get('/', { preValidation: [fastify.auth] }, dashboard.index) next(); };
import CONSTANTS from '@/utils/interfaces/constants'; const REDUCER_KEY = 'VisualAttention'; const API_PATH = 'visualAttention'; export default CONSTANTS(REDUCER_KEY, API_PATH); export const RESULT_KEY = { TIME: 'time', VIEWED_RINGS: 'viewed_rings', ERRORS: 'errors', CROSS_OUT_RINGS: 'cross_out_rings', ERRORS_SUM: 'errors_sum', CROSS_OUT_RINGS_SUM: 'cross_out_rings_sum' }; export const LABELS = { [RESULT_KEY.TIME]: 'Время выполнение теста', [RESULT_KEY.VIEWED_RINGS]: 'Количество просмотренных колец', [RESULT_KEY.ERRORS]: 'Количество ошибок', [RESULT_KEY.CROSS_OUT_RINGS]: 'Кол-во колец, кот. нужно зачеркнуть', [RESULT_KEY.ERRORS_SUM]: 'Количество ошибок за тест', [RESULT_KEY.CROSS_OUT_RINGS_SUM]: 'Кол-во колец, кот. нужно зачеркнуть в тесте' }; export const INTERPRETATION = { EFFICIENCY: { LEVEL_1: 'Уровень развития пространственного мышления очень высокий', LEVEL_2: 'Уровень развития пространственного мышления высокий', LEVEL_3: 'Уровень развития пространственного мышления выше среднего', LEVEL_4: 'Уровень развития пространственного мышления средний', LEVEL_5: 'Уровень развития пространственного мышления ниже среднего', LEVEL_6: 'Уровень развития пространственного мышления низкий', LEVEL_7: 'Уровень развития пространственного мышления очень низкий' }, ACCURACY: { LEVEL_1: 'Качество работы высокое', LEVEL_2: 'Качество работы выше среднего', LEVEL_3: 'Качество работы среднее', LEVEL_4: 'Качество работы ниже среднего', LEVEL_5: 'Качество работы низкое' } };
// uses Factory methods to create an object // create an oject without exposing the instantiation logic // usage: create object conditionally class Car { constructor(options) { this.doors = options.doors || 4; this.state = options.state || 'brand new'; this.color = options.color || 'white'; } } class Truck { constructor(options) { this.doors = options.doors || 4; this.color = options.color || 'white' } } class VehicleFactory { createVehicle(options) { if (options.vehicleType === 'car') return new Car(options); if (options.vehicleType === 'truck') return new Truck(options); } } // Test it: const factory = new VehicleFactory(); const car = factory.createVehicle({ vehicleType: 'car', color: 'silver' }); const truck = new VehicleFactory().createVehicle({ vehicleType: 'truck', color: 'red' }); console.log(car.color); console.log(truck.color);
import angular from 'angular' import geoMap from './geo-map' import geoInfoMap from './geo-info-map' import calendar from './calendar' import popupCalendar from './popup-calendar' import bindHtmlUnsafe from './bind-html-unsafe' import requestLoading from './request-loading' import ConfirmModal from './confirm-modal' import progressDateBoard from './progress-date-board' import uniqueUsername from './unique-username' import barChart from './bar-chart' import dateBox from './date-box' import timePicker from './time-picker' export default angular .module('HNA.GUANGMINGXING.components', []) .factory('ConfirmModal', ConfirmModal) .directive('bindHtmlUnsafe', bindHtmlUnsafe) .directive('requestLoading', requestLoading) .directive('hnaGeoMap', geoMap) .directive('hnaCalendar', calendar) .directive('hnaUniqueUsername', uniqueUsername) .directive('hnaProgressDateBoard', progressDateBoard) .directive('hnaPopupCalendar', popupCalendar) .directive('hnaTimePicker', timePicker) .component('hnaBarChart', barChart) .component('hnaDateBox', dateBox) .component('hnaGeoInfoMap', geoInfoMap)
// Importar los modelos const Product = require("../models/product"); const Category = require("../models/category"); const Order = require("../models/order"); const OrderDetail = require("../models/orderDetail"); const User = require("../models/user"); // Importar Moment.js const moment = require("moment"); moment.locale("es"); // Importar shortid const shortid = require("shortid"); // Operador para sequelize en sus búsquedas const { Op, fn } = require("sequelize"); // Renderizar el formulario de la tienda exports.formularioTiendaHome = (req, res, next) => { const { auth } = res.locals.usuario; let messages = []; let products = []; try { // Obtenemos los productos creados y lo mostramos las fecha modificadas con moment.js Product.findAll({ where: { available: 1, }, order: fn("RAND"), }).then(function (products) { products = products.map(function (product) { product.dataValues.createdAt = moment( product.dataValues.createdAt ).format("LLLL"); product.dataValues.updatedAt = moment( product.dataValues.updatedAt ).fromNow(); return product; }); res.render("store/store", { title: "Tienda | GloboFiestaCake's", auth, products, carrito: existeCarrito(req), }); }); } catch (error) { messages.push({ error, type: "alert-danger", }); res.render("store/store", { title: "Productos | GloboFiestaCake's", auth, messages, carrito: existeCarrito(req), products, }); } }; exports.buscarProducto = async (req, res, next) => { const { search } = req.body; const { auth } = res.locals.usuario; const messages = []; if (!search) { res.redirect("/tienda"); } else { try { Product.findAll({ where: { name: { [Op.like]: `%${search}%`, }, available: 1, }, order: fn("RAND"), }).then(function (products) { products = products.map(function (product) { product.dataValues.createdAt = moment( product.dataValues.createdAt ).format("LLLL"); product.dataValues.updatedAt = moment( product.dataValues.updatedAt ).fromNow(); return product; }); if (products.length) { res.render("store/store", { title: "Tienda | GloboFiestaCake's", auth, products, search, carrito: existeCarrito(req), }); } else { messages.push({ error: `No se encontraron resultados para: ${search}`, type: "alert-danger", }); Product.findAll({ where: { available: 1, }, order: fn("RAND"), }).then(function (products) { products = products.map(function (product) { product.dataValues.createdAt = moment( product.dataValues.createdAt ).format("LLLL"); product.dataValues.updatedAt = moment( product.dataValues.updatedAt ).fromNow(); return product; }); res.render("store/store", { title: "Tienda | GloboFiestaCake's", auth, products, search, carrito: existeCarrito(req), messages, }); }); } }); } catch (error) { messages.push({ error, type: "alert-danger", }); res.render("store/store", { title: "Tienda | GloboFiestaCake's", auth, products, search, carrito: existeCarrito(req), messages, }); } } }; // Busca un producto por su URL exports.obtenerProductoPorUrl = async (req, res, next) => { const { auth } = res.locals.usuario; let messages = []; // Si no esta registrado lo enviá a productos if (auth) { try { //Actualizamos el formulario // Obtener el producto mediante la URL const products = await Product.findOne({ where: { url: req.params.url, }, }); // Si el producto ya no esta disponible no lo deja continuar if (products["dataValues"].available === true) { const category = await Category.findByPk( products.dataValues.categoryId ); //Busca las categorías existentes const categories = await Category.findAll(); // Cambiar la visualización de la fecha con Moment.js const created = moment(products["dataValues"].createdAt).format("LLLL"); const updated = moment(products["dataValues"].updatedAt).fromNow(); res.render("store/order", { title: "Realizar pedido | GloboFiestaCake's", auth, created, updated, category: category.dataValues.name, categories, products: products, }); } else { messages.push({ error: `¡El producto ya no esta disponible!`, type: "alert-danger", }); Product.findAll({ where: { available: 1, }, order: fn("RAND"), }).then(function (products) { products = products.map(function (product) { product.dataValues.createdAt = moment( product.dataValues.createdAt ).format("LLLL"); product.dataValues.updatedAt = moment( product.dataValues.updatedAt ).fromNow(); return product; }); res.render("store/store", { title: "Tienda | GloboFiestaCake's", auth, products, carrito: existeCarrito(req), messages, }); }); } } catch (error) { res.redirect("/tienda"); } } else { res.redirect("/iniciar_sesion"); } }; exports.añadirAlCarrito = (req, res, next) => { const { amount } = req.body; const idProduct = req.params.id; // Verificamos si existe el carrito si no lo creamos if (!req.session.carrito) { req.session.carrito = []; } let carrito = req.session.carrito; carrito.push({ id: shortid.generate(), idProduct, amount }); req.session.carrito = carrito; res.redirect("/tienda"); }; exports.formularioCarrito = async (req, res, next) => { const { auth } = res.locals.usuario; try { let carritoPersonal = []; let carrito = req.session.carrito; let total = 0; numero = 1; for (let element of carrito) { const product = await Product.findByPk(element.idProduct); total = total + element.amount * product["dataValues"].unitPrice; carritoPersonal.push({ numero: numero++, id: element.id, name: product["dataValues"].name, amount: element.amount, unitPrice: product["dataValues"].unitPrice, subTotal: (element.amount * product["dataValues"].unitPrice).toFixed(2), }); } if (carritoPersonal.length) { res.render("store/cart", { title: "Carrito | GloboFiestaCake's", auth, carritoPersonal, total: total.toFixed(2), }); } else { res.redirect("/tienda"); } } catch (error) { console.log(error); res.redirect("/tienda"); } }; function existeCarrito(req) { try { // Verificamos si existe el carrito si no lo creamos if (!req.session.carrito) { req.session.carrito = []; } let carrito = req.session.carrito; if (carrito.length) { return true; } else { return false; } } catch (error) { console.log(error); } } exports.eliminarDelCarrito = (req, res, next) => { const { id } = req.params; let carrito = req.session.carrito; console.log(req.session.carrito); try { let index = 0; for (let element of carrito) { if (element.id === id) { carrito.splice(index, 1); break; } index++; } res.sendStatus(200); } catch (error) { res.sendStatus(401); } }; exports.terminarCompra = async (req, res, next) => { const { address, atHome } = req.body; const { id, email, phone, auth } = res.locals.usuario; try { let carrito = req.session.carrito; //Crear la orden await Order.create({ userId: id, address, atHome, phone, }); //Buscamos el id de la ultima orden const order = await Order.findOne({ limit: 1, order: [["createdAt", "DESC"]], }); for (let element of carrito) { //Crear el detalle orden await OrderDetail.create({ orderId: order["dataValues"].id, productId: element.idProduct, amount: element.amount, }); } //Elimina todos los perdidos con el email del usuario req.session.carrito = []; res.sendStatus(200); } catch (error) { console.log(error); res.sendStatus(401); } }; exports.eliminarCarrito = (req, res, next) => { //Elimina todos los perdidos con el email del usuario req.session.carrito = []; res.redirect("/tienda"); }; // Mostrar pedidos exports.formularioPedidosAdmin = async (req, res, next) => { const { auth } = res.locals.usuario; try { let pedidos = []; const orders = await Order.findAll(); let numero = 1; for (let element of orders) { const { firstName, lastName } = await User.findByPk(element.userId); pedidos.push({ numero, id: element.id, name: `${firstName} ${lastName}`, phone: element.phone, atHome: element.atHome, updatedAt: moment(element.updatedAt).format("LLLL"), status: element.status, }); numero++; } res.render("store/ordersAdmin", { title: "Pedidos | GloboFiestaCake's", pedidos, auth, }); } catch (error) { res.send(error); } }; exports.cambiarEstadoPedido = async (req, res, next) => { try { // Obtener el id del pedido // Patch como HTTP Verb obtiene solamente los valores a través de req.params const { id } = req.params; // Buscar la tarea a actualizar const pedido = await Order.findByPk(id); // Actualizar el estado del pedido // ternary operator const estado = pedido.status == 0 ? 1 : 0; await Order.update( { status: estado }, { where: { id, }, } ); res.sendStatus(200); } catch (error) { res.sendStatus(401); } }; exports.obtenerPedidoPorIdAdmin = async (req, res, next) => { const { auth } = res.locals.usuario; const { id } = req.params; try { const pedido = await Order.findByPk(id); let carritoPersonal = []; let carrito = await OrderDetail.findAll({ where: { OrderId: id, }, }); let total = 0; numero = 1; for (let element of carrito) { const product = await Product.findByPk(element.productId); total = total + element.amount * product["dataValues"].unitPrice; if (numero === carrito.length) { if (pedido["dataValues"].atHome === true) { total = total + 35; } } carritoPersonal.push({ numero: numero++, id: element.id, name: product["dataValues"].name, amount: element.amount, unitPrice: product["dataValues"].unitPrice, subTotal: (element.amount * product["dataValues"].unitPrice).toFixed(2), }); } const atHomeTotal = 35.0; res.render("store/orderDetailAdmin", { title: "Detalles del pedido | GloboFiestaCake's", auth, carritoPersonal, address: pedido["dataValues"].address, phone: pedido["dataValues"].phone, atHome: pedido["dataValues"].atHome, atHomeTotal: atHomeTotal.toFixed(2), atHomeNum: carritoPersonal.length + 1, total: total.toFixed(2), }); } catch (error) { console.log(error); res.redirect("/cuenta/pedidos"); } }; // Mostrar pedidos del cliente exports.formularioPedidos = async (req, res, next) => { const { id, firstName, lastName, auth } = res.locals.usuario; try { let pedidos = []; const orders = await Order.findAll({ where: { userId: id }, }); let numero = 1; for (let element of orders) { pedidos.push({ numero, id: element.id, name: `${firstName} ${lastName}`, phone: element.phone, atHome: element.atHome, updatedAt: moment(element.updatedAt).format("LLLL"), status: element.status, }); numero++; } res.render("store/orders", { title: "Mis pedidos | GloboFiestaCake's", pedidos, auth, }); } catch (error) { res.send(error); } }; exports.obtenerPedidoPorId = async (req, res, next) => { const { auth } = res.locals.usuario; const { id } = req.params; try { const pedido = await Order.findByPk(id); let carritoPersonal = []; let carrito = await OrderDetail.findAll({ where: { OrderId: id, }, }); let total = 0; numero = 1; for (let element of carrito) { const product = await Product.findByPk(element.productId); total = total + element.amount * product["dataValues"].unitPrice; if (numero === carrito.length) { if (pedido["dataValues"].atHome === true) { total = total + 35; } } carritoPersonal.push({ numero: numero++, id: element.id, name: product["dataValues"].name, amount: element.amount, unitPrice: product["dataValues"].unitPrice, subTotal: (element.amount * product["dataValues"].unitPrice).toFixed(2), }); } const atHomeTotal = 35.0; res.render("store/orderDetail", { title: "Detalles del pedido | GloboFiestaCake's", auth, carritoPersonal, address: pedido["dataValues"].address, phone: pedido["dataValues"].phone, atHome: pedido["dataValues"].atHome, atHomeTotal: atHomeTotal.toFixed(2), atHomeNum: carritoPersonal.length + 1, total: total.toFixed(2), }); } catch (error) { console.log(error); res.redirect("/cuenta/mis_pedidos"); } }; // Busca un categoría por su URL exports.obtenerCategoriaPorId = async (req, res, next) => { const { auth } = res.locals.usuario; try { // Obtener la categoría mediante la URL const categories = await Category.findOne({ where: { id: req.params.id, }, }); // Cambiar la visualización de las fechas con Moment.js const created = moment(categories["dataValues"].createdAt).format("LLLL"); const updated = moment(categories["dataValues"].updatedAt).fromNow(); res.render("store/category", { title: "Categoría | GloboFiestaCake's", auth, created, updated, categories: categories, }); } catch (error) { // En caso de haber errores volvemos a cargar las categorías. res.redirect("/tienda"); } };
import { grey, orange, lightOrange } from '../styles/colors' import { experience, mobile } from './breakpoints' import { css } from '@emotion/core' const globalStyles = css` * { box-sizing: border-box; margin: 0; padding: 0; text-rendering: optimizeLegibility; } body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol'; background-color: #eee; } h1 { font-size: 40pt; font-weight: 700; line-height: 1.1; color: ${grey}; } h2 { font-size: 26pt; font-weight: 700; line-height: 1.2; margin: 30pt 0; color: ${grey}; @media (max-width: ${experience}) { font-size: 20pt; } } h3 { font-size: 20pt; margin: 20pt 0; color: ${grey}; } ul { padding-left: 24px; } li, p { font-size: 14pt; font-weight: 300; line-height: 1.6; } p { color: ${grey}; margin: 12pt 0; } a { border-color: ${grey}; box-shadow: inset 0 -3px 0 ${orange}; padding-bottom: 2px; padding-top: 2px; transition: all 0.25s linear; text-decoration: none; &:link, &:visited { color: ${grey}; text-decoration: none; } &:hover { background: ${lightOrange}; text-decoration: none; } } /* Don't apply special link styles to anchors */ .anchor { box-shadow: none; &:hover { background: none; } } pre[class*='language-'] { background-color: ${grey}; } .language-text { font-size: 12pt; } pre[class*='language-'] { border-radius: 0; } /* Inline code snippets enclosed by single back ticks */ :not(pre) > code[class*='language-'] { background-color: #ddd !important; color: ${grey}; text-shadow: none; } .gatsby-highlight { background-color: #272822; border-radius: 0.3em; margin: 0.5em 0; padding: 1em; overflow: auto; @media (max-width: ${mobile}) { width: 100vw; position: relative; left: 50%; right: 50%; margin-left: -50vw; margin-right: -50vw; border-radius: 0; font-size: 12px; } } .gatsby-highlight pre[class*='language-'] { background-color: transparent; margin: 0; padding: 0; overflow: initial; float: left; min-width: 100%; } .gatsby-highlight-code-line { background-color: #444; display: block; margin-right: -1em; margin-left: -1em; padding-right: 1em; padding-left: 0.75em; border-left: 6px solid ${orange}; } ` export default globalStyles
const htmlmin = require("html-minifier") /** * Compresses HTML during production builds. * * @param {string} content HTML content * @param {string} outputPath Path to which the file will be written */ exports.compressHtml = (content, outputPath) => { // If not an HTML file or not a production build, return the content as it // was. if (!outputPath.endsWith(".html") || process.env.ELEVENTY_ENV !== "production") return content // Options for the minifying process. const minOpts = { useShortDoctype: true, removeComments: true, collapseWhitespace: true, minifyCSS: true, minifyJS: true } // Return compressed HTML. return htmlmin.minify(content, minOpts) } /** * Add the transform, written above. * * @param {object} eleventyConfig Eleventy's configuration object */ exports.default = (eleventyConfig) => { return eleventyConfig.addTransform("compress-html", exports.compressHtml) }
var otherPlayers={}; var playerID; var player; function loadGame(){ //cargar espacio loadEspacio(); //cargar jugador initMainPlayer(); listenToOtherPlayers(); window.onunload = function(){ }; window.onbeforeunload = function(){ }; } function listenToPlayer( playerData ) { if(playerID!=playerData.id){ otherPlayers[playerData.id].setOrientation( playerData.position, playerData.rotation ); } } var coso; function listenToOtherPlayers(){ //player ha entrado socket.on('newPositions', function(data){ coso = data; // console.log("Numero de players " + data.length); for(var i=0; i < data.length; i++){ if (data[i].id == playerID){ // console.log("tu id " + data[i].id); // console.log("tu z " + data[i].position.z); }else{ // console.log("otro id " + data[i].id); //si es otroplayer nuevo crearlo if(otherPlayers[data[i].id]==null){ otherPlayers[data[i].id] = new Player(data[i].id); otherPlayers[data[i].id].isMainPlayer=false; otherPlayers[data[i].id].init(); } // console.log("otro z " + data[i].position.z); //aqui pasar datos a listenToPlayer listenToPlayer(data[i]); } } }); //player ha salido socket.on('disconnected', function(data){ console.log("Dejconejtado " + data.id); scene.remove(otherPlayers[data.id].mesh); delete otherPlayers[data.id]; }); } function initMainPlayer(){ console.log("iniciando Main player"); socket.on('tuId', function(data){ console.log("Tu Id " + data.id); playerID=data.id; player = new Player(playerID); player.isMainPlayer=true; player.init(); }); } function loadEspacio(){ var size = 100; var divisions = 100; var gridHelper = new THREE.GridHelper( size, divisions ); scene.add( gridHelper ); // var light = new THREE.AmbientLight( 0x909090 ); // soft white light // scene.add( light ); var light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 ); scene.add( light ); var sphere_geometry = new THREE.SphereGeometry(1); var sphere_material = new THREE.MeshNormalMaterial(); var sphere = new THREE.Mesh(sphere_geometry,sphere_material); scene.add(sphere); var mdl_pos = new THREE.Vector3(0,0,-10); modelLoader('MilkTruck2.glb',mdl_pos); var mdl_pos = new THREE.Vector3(-50,0,-50); modelLoader('Sponza/Sponza.gltf',mdl_pos); var bulb = new THREE.PointLight( 0xff0000, 1, 100 ); bulb.position.set( -50, 5, -50 ); scene.add( bulb ); } function modelLoader(modelo,pos){ loader.load('/client/assets/'+modelo, function ( gltf ) { console.log("cargando " + modelo); model=gltf.scene; model.position.copy(pos); scene.add(model); gltf.animations; // Array<THREE.AnimationClip> gltf.scene; // THREE.Group gltf.scenes; // Array<THREE.Group> gltf.cameras; // Array<THREE.Camera> gltf.asset; // Object }, // called while loading is progressing function ( xhr ) { console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' ); }, // called when loading has errors function ( error ) { console.log( 'An error happened' ); } ); // }
const Alexa = require('alexa-sdk'); const audioEventHandlers = require('./audioEventHandlers'); const handlers = require('./handlers'); exports.handler = (event, context, callback) => { console.log('\n' + JSON.stringify(event, null, 2)); const alexa = Alexa.handler(event, context, callback); // Replace with your appId alexa.appId = 'amzn1.ask.skill.123'; alexa.registerHandlers(handlers, audioEventHandlers); alexa.execute(); };
var common = require('../app/common'); common.connect(); var Permission = require('mongoose').model('Permission'); exports.up = function(next){ var permission = new Permission(); permission.name = 'all'; permission.method = '*'; permission.path = '*'; permission.save(function (err, permission) { if (err) return next (err); next(); }); }; exports.down = function(next){ Permission.findOneAndRemove({ name:'all' }, next); };
/** * Created by zhoucaiguang on 2017/3/8. */ /** * Created by work on 2016/3/21. */ "use strict"; let mysql = require('mysql-promise')(); let util = require('util'); const role_1 = require('../configs/role'); const config = role_1.dbConfigs; mysql.configure({ host: config.server, user: config.user, password: config.password, database: config.database, }); class mysqlBase { constructor() { } query(sql, data) { if (util.isArray(data)) { return mysql.query(sql, data); } else { return mysql.query(sql); } } find(sql, data) { if (typeof sql === 'string') { sql = sql + " LIMIT 1"; } return this.query(sql, data).spread((response) => { return response; }); } select(sql, data) { return this.query(sql, data); } insert(tableName, fields) { let sql = "INSERT INTO "; if (typeof tableName === 'string') { sql += "`" + tableName + "` "; } if (typeof fields === 'object') { sql += "("; for (let i in fields) { sql += "`" + i + "`,"; } sql = sql.replace(/,$/g, ""); sql += ")value("; for (let i in fields) { sql += "'" + fields[i] + "',"; } sql = sql.replace(/,$/g, ""); sql += ") "; } return this.query(sql); } update(tableName, fields, where) { let sql = "UPDATE `" + tableName + "` SET "; if (typeof fields === "object") { for (let i in fields) { sql += "`" + i + "`" + "=" + "'" + fields[i] + "'" + ","; } } else if (typeof fields === "string") { sql += fields; } sql = sql.replace(/,$/g, ""); sql += ' WHERE '; sql += where; return this.query(sql); } } exports.mysqlBase = mysqlBase; /* export function query(sql: string, data?: any[]): Promise<Object> { if (util.isArray(data)) { return mysql.query(sql, data); } else { return mysql.query(sql); } } export function find(sql: string, data?: any[]): Promise<Object> { if (typeof sql === 'string') { sql = sql + " LIMIT 1"; } return this.query(sql, data).spread((response) => { return response; }); } export function select(sql: string, data?: any[]): Promise<Object> { return this.query(sql, data); } export function insert(tableName: string, fields: Object) { var sql = "INSERT INTO "; if (typeof tableName === 'string') { sql += "`" + tableName + "` "; } if (typeof fields === 'object') { sql += "("; for (var i in fields) { sql += "`" + i + "`,"; } sql = sql.replace(/,$/g, ""); sql += ")value("; for (var i in fields) { sql += "'" + fields[i] + "',"; } sql = sql.replace(/,$/g, ""); sql += ") "; } return this.query(sql); } export function update(tableName: string, fields: Object, where: string) { let sql = "UPDATE `" + tableName + "` SET "; if (typeof fields === "object") { for (var i in fields) { sql += "`" + i + "`" + "=" + "'" + fields[i] + "'" + ","; } } else if (typeof fields === "string") { sql += fields; } sql = sql.replace(/,$/g, ""); sql += ' WHERE '; sql += where; return this.query(sql); } */
import React from "react"; import { Link, prefixURL } from "next-prefixed"; import Head from "next/head"; import "../../static/styles/globals.css"; export default class Page extends React.Component { render() { const { children, activePath = "home", title = "Welkom", description = "Kevin Bal is een kinesitherapeut met een praktijk in Kontich (Reepkenslei). Zijn specialisaties zijn manuele kinesitherapie en orthopedische revalidatie.", } = this.props; return ( <div> <Head> <title>{title} | Kevin Bal Kinesitherapeut Kontich</title> <meta name="description" content={description} /> <meta charSet="utf-8" /> <meta name="robots" content="index, follow" /> <meta name="viewport" content="initial-scale=1.0, width=device-width" /> <link rel="shortcut icon" type="image/x-icon" href={prefixURL("/static/favicon.ico")} /> </Head> <header className="border-t-8 border-kevin-green"> <nav className="pt-8 flex flex-wrap justify-center"> <h1 className="hidden">Kevin Bal Kinesitherapie</h1> <div className="w-full flex justify-center"> <img src={prefixURL("/static/img/full_logo.svg")} className="h-32 md:h-48" alt="Kevin Bal Kinesitherapie" /> </div> <div className="w-5/6 flex justify-center pt-8 flex-wrap text-xl"> <Link href="/"> <a title="Home" className={ (activePath == "home" ? "underline " : "no-underline ") + "block sm:inline-block sm:mt-0 text-kevin-green hover:underline mr-8 mb-4 md:mr-12" } > Home </a> </Link> <Link href="/over-kevin/"> <a title="Over Kevin" className={ (activePath == "over-kevin" ? "underline " : "no-underline ") + "block sm:inline-block sm:mt-0 text-kevin-green hover:underline mr-8 mb-4 md:mr-12" } > Over Kevin </a> </Link> <Link href="/visie/"> <a title="visie" className={ (activePath == "visie" ? "underline " : "no-underline ") + "block sm:inline-block sm:mt-0 text-kevin-green hover:underline mr-8 mb-4 md:mr-12" } > Visie </a> </Link> <Link href="/ligging/"> <a title="ligging" className={ (activePath == "ligging" ? "underline " : "no-underline ") + "block sm:inline-block sm:mt-0 text-kevin-green hover:underline mr-8 mb-4 md:mr-12" } > Ligging </a> </Link> <Link href="/contact/"> <a title="contact" className={ (activePath == "contact" ? "underline " : "no-underline ") + "block sm:inline-block sm:mt-0 text-kevin-green hover:underline mr-8 mb-4" } > Contact </a> </Link> </div> </nav> </header> <div className="flex-1">{children}</div> <footer className="font-sans bg-grey-lighter text-white py-5 px-4 pin-b"> <div className="mx-auto max-w-xl overflow-hidden flex justify-between items-center"> <ul className="text-sm text-grey-dark list-reset flex items-center"> <li> <a href="/" className="block mr-4"> <img src={prefixURL("/static/img/logo.svg")} className="w-8" alt="logo" /> </a> </li> <li>Reepkenslei 45 - 2550 Kontich - 0468 47 31 90</li> </ul> <p className="inline-block py-2 px-3 text-grey-darker text-xs"> {" "} ©2019 Kevin Bal Kinesitherapie. </p> </div> </footer> </div> ); } }