text
stringlengths
7
3.69M
import React from 'react'; import netflix from '../Assets/Netflix.png'; import './Projects.css'; export const Projects = () => { return ( <section className="projects_container"> <h1>MY MISSION</h1> <div className="blog_color-box"></div> <section className="projects_into-container"> <h1 className="projects_title">Believe in the power of interaction</h1> <p>Beautifully designed responsive website with engaging user experience <br/> is the most powerful tool for brand and business build trust and strengthen the <br/> relationship with their audiences. </p> </section> </section> ) }
import React from 'react'; /** @jsx jsx */ import { jsx, css } from '@emotion/core'; const contanerStyle = css` display: inline-block; text-align: center; `; class HomePage extends React.Component { render() { return ( <section> <div css={contanerStyle}> Home Page </div> </section> ); } } export default HomePage;
import React from 'react'; import axios from 'axios' import './allData.css' import { Modal, Button,Table, Tag } from 'antd'; import { ExclamationCircleOutlined } from '@ant-design/icons'; const { Column, ColumnGroup } = Table; const { confirm } = Modal; export class AllData extends React.Component{ constructor(props){ super() this.state = { data:[], showData:[] } } componentDidMount(){ axios.get("http://120.77.99.3:1020/allData").then(res=>{ console.log(res) this.setState({data:res.data},()=>{ let bal = [] this.state.data.forEach((item,index)=>{ bal.push({key: index,index:item.id,Name: item.name,pwd: item.pwd,}) }) this.setState({ showData:bal }) }) }).catch(err=>{ console.log(err) }) } showConfirm = (e) => { //asdasdasdasd let that = this confirm({ title: '你确定要删除这个账号吗?', icon: <ExclamationCircleOutlined />, content: '删除此数据后将无法恢复,后果自负!', onOk(){ return new Promise((resolve, reject) => { setTimeout(()=>{ resolve(e) },800+Math.random()*1000) }).then((e)=>{ axios.get(`http://120.77.99.3:1020/deleteData`,{ params: { name: e.Name } }).then(res=>{ console.log(res) that.componentDidMount() }) }) }, onCancel() {console.log('已取消删除')}, }); } render(){ return( <div className="allData"> <Table dataSource={this.state.showData} pagination={false}> <Column title="编号" dataIndex="index" key="index" /> <Column title="姓名" dataIndex="Name" key="Name" /> <Column title="密码" dataIndex="pwd" key="pwd" /> <Column title="操作" key="action" render={(text, record) => ( <span> <a style={{ marginRight: 16 }}>编辑</a> <a onClick={()=>{this.showConfirm(record)}} >删除</a> </span> )} /> </Table> </div> ) } }
module.exports = function(grunt) { var exec = require("child_process").exec; var path = require("path"); var fs = require("fs"); var Zip = require("jszip"); grunt.loadNpmTasks("grunt-contrib-less"); grunt.loadNpmTasks("grunt-contrib-watch"); grunt.initConfig({ less: { light: { files: { "css/carrot.css": "css/seed.less", "css/carrot-twilight.css": "css/seed-twilight.less", "css/carrot-dark.css": "css/seed-dark.less" } } }, watch: { css: { files: ["css/*.less"], tasks: ["less"] }, options: { spawn: false } }, copy: [ "config/**", "_locales/**", "js/**", "css/*.css",//leave the LESS behind "**/*.html",//both main.html and the templates "templates/*", "require.js", "background.js", "installer.js", "./*.png", //in case we add images at some point "!node_modules/**" ] }); grunt.registerTask("default", ["less", "watch"]); grunt.registerTask("prep", ["less", "cleanup", "copyUnpacked"]); grunt.registerTask("package", ["prep", "chrome", "webstore", "compress:store"]); grunt.registerTask("store", ["prep", "webstore", "compress:store"]); grunt.registerTask("crx", ["prep", "chrome"]); grunt.registerTask("copyUnpacked", "Copies files to the build directory", function() { var srcPatterns = grunt.config.get("copy"); var files = grunt.file.expandMapping(srcPatterns, "./build/unpacked", { filter: "isFile" }); files.forEach(function(f) { grunt.file.copy(f.src[0], f.dest); }); }); grunt.registerTask("compress", "Generates the store .zip file", function() { var zipfile = new Zip(); var files = grunt.file.expand({ filter: "isFile", cwd: "./build/unpacked" }, "**/*"); files.forEach(function(file) { var buffer = fs.readFileSync(path.join("./build/unpacked", file)); zipfile.file(file, buffer); }); var zipped = zipfile.generate({ type: "nodebuffer", compression: "DEFLATE", compressionOptions: { level: 8 } }); fs.writeFileSync("./build/carrot.zip", zipped); }); grunt.registerTask("chrome", "Makes a new CRX package", function() { var manifest = JSON.parse(fs.readFileSync("./manifest.json")); manifest.icons["128"] = "icon-128-inverted.png"; fs.writeFileSync("./build/unpacked/manifest.json", JSON.stringify(manifest, null, 2)); //perform the Chrome packaging var c = this.async(); var here = fs.realpathSync(__dirname); var chrome = { win32: '"' + (process.env["ProgramFiles(x86)"] || process.env.ProgramFiles) + "\\Google\\Chrome\\Application\\chrome.exe" + '"', linux: "/opt/google/chrome/google-chrome", osx: "Beats me." }; var cmd = [ chrome[process.platform] ]; cmd.push("--pack-extension=" + path.join(here, "build/unpacked")); cmd.push("--pack-extension-key=" + path.join(here, "../Carrot.pem")); cmd = cmd.join(" "); exec(cmd,function(err, out, stderr) { if (err) { console.log("Unable to run Chrome for CRX packaging."); return c(); } fs.renameSync("./build/unpacked.crx", "./build/Carrot.crx"); c(); }); }); grunt.registerTask("webstore", "Prepares the manifest for the web store", function() { var manifest = JSON.parse(fs.readFileSync("./manifest.json")); delete manifest.update_url; delete manifest.key; manifest = JSON.stringify(manifest, null, 2); fs.writeFileSync("./build/unpacked/manifest.json", manifest); }); grunt.registerTask("cleanup", "Removes the build/unpacked directory", function() { var c = this.async(); exec("rm -rf ./build/*", c); }); grunt.registerTask("checkLocale", "Finds unregistered strings for a given locale; checkLocale:XX for a language code XX", function(language) { var english = require("./_locales/en/messages.json"); var other = require(`./_locales/${language}/messages.json`); console.log(`Checking ${language} against English string file`); for (var k in english) { if (!(k in other)) { console.log(`- Missing string: ${k}`); } } }) };
export { default as Banner } from './components/Banner'; export { default as Services } from './components/Services';
import clock from 'clock'; import document from 'document'; import { preferences } from 'user-settings'; import { me as appbit } from 'appbit'; import { display } from 'display'; import { today } from 'user-activity'; import { BodyPresenceSensor } from 'body-presence'; import { HeartRateSensor } from 'heart-rate'; import * as util from '../common/utils'; // TODO: add day and night mode variations and transition, add settings to set the transition time // UI elements const timeLabel = document.getElementById('time-text-tag'); const timeLabelShadow = document.getElementById('time-shadow-text-tag'); const bpmLabel = document.getElementById('bpm-text-tag'); const stepsLabel = document.getElementById('steps-text-tag'); bpmLabel.text = '--'; stepsLabel.text = '--'; const permissions = { heartRate: appbit && appbit.permissions.granted('access_heart_rate'), activity: appbit && appbit.permissions.granted('access_activity') }; // App state const state = { permissions, onWrist: false, displayIsOn: (display && display.on) ?? true, stepsToday: undefined, bpmSensor: {} }; const updateState = updatedProperty => { console.log( `UpdateState called with updatedProperty param: ${JSON.stringify( updatedProperty )}` ); const keys = Object.keys(updatedProperty); const key = keys && keys[0]; const value = keys && keys.map(key => updatedProperty[key])[0]; // if value unchanged, no need to update if (value === state[key]) { console.log('State unchanged'); return state; } state[key] = value; console.log(`Updated state: ${JSON.stringify(state)}`); return state; }; const updateSensor = (sensor, label = null) => { if (state.onWrist && state.displayIsOn) { sensor.start(); } else { sensor.stop(); if (label) { label.text = '--'; } } }; const updateStepsValue = () => { if (permissions.activity && state.displayIsOn) { let steps = undefined; // Get adjusted steps from the online service if available, otherwise use local value if (today && today.adjusted && today.adjusted.steps) { steps = today.adjusted.steps; } else if (today && today.local && today.local.steps) { steps = today.local.steps; } updateState({ stepsToday: steps }); // Display today's steps value if (stepsLabel) { stepsLabel.text = `${util.formatNumericStrings(state.stepsToday ?? 0)}`; } } }; if (display) { updateStepsValue(); // set steps on app load display.addEventListener('change', () => { updateState({ displayIsOn: display.on }); if (state.bpmSensor) { // Sense heart rate when screen is switched on updateSensor(state.bpmSensor, bpmLabel); } // Update steps when screen is switched on updateStepsValue(); }); } if (permissions.heartRate && HeartRateSensor) { const bpmSensor = new HeartRateSensor(); updateState({ bpmSensor }); if (bpmSensor) { // Listen for heart rate readings and update UI label bpmSensor.addEventListener('reading', () => { if (bpmLabel) { bpmLabel.text = `${bpmSensor.heartRate}`; } }); } } if (permissions.activity) { const bpmSensor = state.bpmSensor; // Sense heart rate when watch is being worn if (bpmSensor && BodyPresenceSensor) { const bodySensor = new BodyPresenceSensor(); if (bodySensor) { updateState({ onWrist: bodySensor.present }); bodySensor.addEventListener('reading', () => { updateState({ onWrist: bodySensor.present }); updateSensor(bpmSensor, bpmLabel); }); bodySensor.start(); } } } if (clock) { // Update the clock every minute clock.granularity = 'minutes'; // Update the <text> element every tick with the current time clock.ontick = evt => { let today = evt.date; let hours = today.getHours(); if (preferences.clockDisplay === '12h') { hours = hours % 12 || 12; // 12h format } else { hours = util.zeroPad(hours); // 24h format } let mins = util.zeroPad(today.getMinutes()); if (timeLabel) { timeLabel.text = `${hours}:${mins}`; } if (timeLabelShadow) { timeLabelShadow.text = timeLabel.text; } }; }
const Koa = require('koa'); const Router = require('koa-router'); const koaBody = require('koa-body'); const products = require('./products'); const app = new Koa(); const router = new Router(); app.use(koaBody()); app.use(async (ctx, next) => { try { await next(); console.log(ctx.url, '>', ctx.response.status) } catch (err) { console.error(ctx.url, '> Fail:', err); } }) router.get('/', (ctx) => { ctx.body = 'Health check: on'; }); router.use(products.routes()); app.use(router.routes()); module.exports = { app, };
const Episode = require("../models/Episode"); const errorWrapper = require("../helpers/error/errorWrapper"); const Lesson = require("../models/Lesson"); const getAllEpisodes = errorWrapper(async (req, res, next) => { const { lesson_id } = req.params; const lesson = await Lesson.findById(lesson_id).populate("episodes"); const episodes = await lesson.episodes.sort(function (a, b) { return a.ranking - b.ranking; }); res.status(200).json({ success: true, // episodeCount: episodes.length, data: episodes, }); }); const addNewEpisodeToLesson = errorWrapper(async (req, res, next) => { const user_id = req.user.id; const lesson_id = req.param.id || req.params.lesson_id; const information = req.body; const episode = await Episode.create({ ...information, lesson: lesson_id, user: user_id, }); res.status(200).json({ success: true, data: episode, }); }); const getSingleEpisode = errorWrapper(async (req, res, next) => { const episode = req.myEpisode; res.status(200).json({ success: true, data: episode, }); }); const editEpisode = errorWrapper(async (req, res, next) => { const { id } = req.params; const { ranking, title, url } = req.body; let episode = await Episode.findById(id); episode.ranking = ranking; episode.title = title; episode.url = url; episode = await episode.save(); res.status(200).json({ success: true, data: episode, }); }); const deleteEpisode = errorWrapper(async (req, res, next) => { const { id } = req.params; await Episode.findByIdAndRemove(id); res.status(200).json({ success: true, data: {}, }); }); module.exports = { addNewEpisodeToLesson, getAllEpisodes, getSingleEpisode, editEpisode, deleteEpisode, };
import { combineReducers } from "redux"; import LoginAdmin from "./LoginAdmin"; import GetAllMovies from "./GetAllMovies"; import AddMovie from "./AddMovie"; import EditMovie from "./EditMovie"; export default combineReducers({ LoginAdmin, GetAllMovies, AddMovie, EditMovie, });
import { bisect } from 'd3-array' class DiscreteScale { constructor() { this.x0 = 0 this.x1 = 1 this.domain = [0.5] this.range = [0, 1] this.n = 1 } getValue = x => { const { range, domain, n } = this return range[bisect(domain, x, 0, n)] } rescale() { const { x0, x1, n } = this let i = -1 this.domain = new Array(n) while (++i < n) { this.domain[i] = ((i + 1) * x1 - (i - n) * x0) / (n + 1) } } setDomain = val => { this.x0 = +val[0] this.x1 = +val[1] this.rescale() return this } setRange = val => { this.range = val.slice() this.n = this.range.length - 1 return this } } export default DiscreteScale
/* 🤖 this file was generated by svg-to-ts*/ export const EOSIconsStackedLineChart = { name: 'stacked_line_chart', data: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M2 19.99l7.5-7.51 4 4 7.09-7.97L22 9.92l-8.5 9.56-4-4-6 6.01-1.5-1.5zm1.5-4.5l6-6.01 4 4L22 3.92l-1.41-1.41-7.09 7.97-4-4L2 13.99l1.5 1.5z"/></svg>` };
var mongoose = require('mongoose'), schema = mongoose.Schema, todo = new schema({ user_id : String, content : String, update_date : Date }); mongoose.model('Todo', todo); mongoose.connect('mongodb://localhost/my-express1-todo');
const readline = require('readline'); const r1 = readline.createInterface({ input: process.stdin, output: process.stdout }); r1.question('Enter a number? ', (answer) => { var sum = 0; for(var i = 1; i <= answer;i++) { if(i % 3 ==0 ) { //console.log('Sum is1',i); sum = sum+ i; } } cosnsole.log('Sum is ', sum); r1.close; });
// @flow import React from 'react' import styled, { createGlobalStyle } from 'styled-components' import { useDispatch } from 'react-redux' import Filters from './views/filters/' import List from './views/list' import { filterPrograms } from './store/actions/' const GlobalStyle = createGlobalStyle` body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; background-color: #f2f2f2; margin: 20px; overflow: hidden; } * { box-sizing: border-box; } @media screen and (min-width: 1440px) { body{ max-width: 1440px; margin: auto; } } ` const Container = styled.div` height: calc(100vh - 140px); overflow: auto; display: flex; flex-direction: column; align-items: center; @media screen and (min-width: 700px) { flex-direction: row; align-items: flex-start; overflow: hidden; } @media screen and (max-width: 423px) { height: calc(100vh - 170px); } ` const Footer = styled.div` display: flex; align-items: center; justify-content: center; span { font-size: 18px; } h3 { margin: 10px; } ` export default function App() { const dispatch = useDispatch() const handleHashChange = React.useCallback(() => { window.location.hash.length && dispatch(filterPrograms(window.location.hash)) }, [dispatch]) React.useEffect(() => { handleHashChange() window.addEventListener('hashchange', handleHashChange) return () => { window.removeEventListener('hashchange', handleHashChange) } }, [handleHashChange]) return ( <> <GlobalStyle /> <h1>SpaceX Launch Programs</h1> <Container> <Filters /> <List /> </Container> <Footer> <h3>{'Developed By:'}</h3> <span>{' Croiden Lobo'}</span> </Footer> </> ) }
import { CLICK_FAQ, CLOSE_FAQ } from "../constants/actionTypes"; export default (state={jsonData:[]},action)=>{ switch(action.type){ case CLICK_FAQ: return{ ...state, jsonData:action.payload } case CLOSE_FAQ: return{ ...state, jsonData:action.payload } default : return state; } }
//app.js App({ onLaunch: function() { wx.getSystemInfo({ success: e => { this.globalData.addArr = new Array(); this.globalData.StatusBar = e.statusBarHeight; let custom = wx.getMenuButtonBoundingClientRect(); this.globalData.Custom = custom; let CustomBar = custom.bottom + custom.top - e.statusBarHeight; this.globalData.CustomBar = CustomBar; //适配全面屏底部距离 if (CustomBar > 75) { this.globalData.tabbar_bottom = "y" } } }) if (!wx.cloud) { console.error('请使用 2.2.3 或以上的基础库以使用云能力') } else { wx.cloud.init({ // env 参数说明: // env 参数决定接下来小程序发起的云开发调用(wx.cloud.xxx)会默认请求到哪个云环境的资源 // 此处请填入环境 ID, 环境 ID 可打开云控制台查看 // 如不填则使用默认环境(第一个创建的环境) env: '', traceUser: true, }) } }, //设置全局对象 globalData: { userInfo: null, // addArr : [], userInfo:{}, bgPoster:'' }, getURL: function(fileID) { wx.cloud.downloadFile({ fileID: fileID, success: res => { // get temp file path console.log(res.tempFilePath) return res.tempFilePath }, fail: err => { // handle error console.log('getURL失败', err) } }) }, })
const dxfparsing = require('dxf-parsing'); const dxf = dxfparsing.Parser; const mongoose = require('mongoose'); const Schema = mongoose.Schema; require('mongoose-currency').loadType(mongoose); const Currency = mongoose.Types.Currency; var geoProperties = new Schema({ EXCESS_SQM: { type: String, required: false }, LINC_ID: { type: String, required: false }, STREET_NAM: { type: String, required: false }, ESTATE: { type: String, required: false }, DELIV_STAT: { type: String, required: false }, REMARK: { type: String, required: false }, BLOCK_ID: { type: String, required: false }, EX_PLOT_NO: { type: String, required: false }, PLOT_NO: { type: String, required: false }, ORG_SIZE: { type: String, required: false }, ADDRESS: { type: String, required: false }, EX_SIZE: { type: String, required: false }, RATE_PSqM: { type: Currency, required: false }, AMT_PAYABL: { type: Currency, required: false }, NOR_PREMIU: { type: Currency, required: false }, CAP_CONB: { type: Currency, required: false }, SCAP_CONB: { type: String, required: false }, SURVEY_FEE: { type: Currency, required: false }, SSURVEY_FE: { type: String, required: false }, ADM_CHARGE: { type: Currency, required: false }, RegConvFee: { type: Currency, required: false }, SRegConvFe: { type: String, required: false }, STAMP_DUTY: { type: Currency, required: false }, ANN_GRent: { type: Currency, required: false }, LandCharge: { type: Currency, required: false }, SLandCharg: { type: String, required: false }, DeliverySt: { type: Number, required: false }, SurPlFilen: { type: String, required: false }, DNFilename: { type: String, required: false } }) var geoObjectSchema = new Schema({ type: { type: String, default: 'Polygon' }, coordinates: [] }); var featureSchema = new Schema({ type: { type: String, default: 'Feature' }, properties: geoProperties, geometry: geoObjectSchema }, { timestamps: true }); var geoFeatureCollection = new Schema({ type: { type: String, default: 'FeatureCollection' }, name: { type: String, unique: true }, features: [featureSchema] }, { timestamps: true }); let GeoFeatures = mongoose.model('GeoFeature', geoFeatureCollection); module.exports = GeoFeatures;
import React, { useState } from 'react' import {useDispatch, useSelector } from 'react-redux' import {closeModal} from "../../features/modal/Clickevent" import {signupUser} from "../../features/serverReducer/authreducer" import './modal.css' function Modal() { const [email, setEmail] = useState('') const [password, setPassword] = useState('') const value = useSelector((state)=>state.ClickeventReducer.value) const loading = useSelector((state)=>state.authReducer.loading) const invalid = useSelector((state)=>state.authReducer.invalid) const type = useSelector((state)=>state.ClickeventReducer.type) const dispatch = useDispatch() const userdata = {type,email,password} if(!value) { return null; } return ( <div className="modalContainer"> <div className="modalContent"> <div className="modalHeader"> <h1>{type}</h1> <h2 onClick={()=>dispatch(closeModal())}>x</h2> </div> <div className="modalForm"> {invalid && <div className="invalid">Email or Password May be wrong</div> } {loading && <div className="loader"></div> } <label htmlFor="email">Email</label> <input type="text" value={email} onChange={(e)=>setEmail(e.target.value)}/> <label htmlFor="password">Password</label> <input type="text" value={password} onChange={(e)=>setPassword(e.target.value)} /> </div> <div className="modalFooter"> <button onClick={()=>dispatch(signupUser(userdata))}>{type}</button> </div> </div> </div> ) } export default Modal
class Car { constructor(){ this.x = width / 2; this.y = height / 2; this.r = 50; this.gravity = 0.25; this.velocity = 0; } show() { fill(255, 255, 0); stroke(0) strokeWeight(4); // ellipse(this.x, this.y, this.r * 2); rect(this.x, this.y, this.r, 100); } update(){ // this.velocity += this.gravity; // this.x = this.velocity; this.velocity += this.gravity; this.x += this.velocity; // console.log(this.velocity) if(this.x > width - this.r ){ this.x = width - this.r; this.velocity = 0; } if (this.x < this.r) { this.x = this.r; this.velocity = 0; } } up() { this.velocity -= 5; } cright(){ this.velocity -= 10; } cright() { this.velocity += 10; } }
const prompt = require("prompt") prompt.message = " " prompt.delimiter = " " exports.run = (args) => { console.log("Do you want free succ?") ask() } function ask() { prompt.start() prompt.get("Answer", (err, res) => { const answer = res.Answer.toLowerCase() if(answer === "yes") { for (let i = 0; i < 8000; i++) { console.log("WELL TOO BAD GET A FUCKING GIRLFRIEND OR BOYFRIEND") } } else if(answer === "no") { console.log("then why the fuck did you run this command lmao") process.exit() } else { console.log("can u say \"yes\" or \"no\"") ask() } }) }
'use strict'; mainApp.controller('FilterController', ['$rootScope', '$scope','$http','PostService', 'UserService','$location', function ($rootScope, $scope,$http,PostService, AuthService,$location) { $scope.postType = ''; $scope.toFilter = ''; $scope.fromFilter = ''; $scope.toDateFilter = ''; $scope.fromDateFilter = ''; $scope.transportationTypeFilter = ''; $scope.quickFilter = '-createdDate'; PostService.getCity().then(function (data) { $scope.cities = data; }); $scope.changeValue = function () { filterOptions.postType = $scope.postType; filterOptions.toLocation = $scope.toFilter; filterOptions.fromLocation = $scope.fromFilter; filterOptions.quickFilter = $scope.quickFilter; var toDate=''; var fromDate=''; if($scope.toDateFilter!==''){ toDate = new Date($scope.toDateFilter).toJSON().slice( 0, 10 ); } if($scope.fromDateFilter!=='') { fromDate = new Date($scope.fromDateFilter).toJSON().slice(0, 10); } filterOptions.toDate = toDate; filterOptions.fromDate =fromDate; filterOptions.transportationType = fromDate; function filterOptions() { var options = ''; for (var propName in filterOptions) { if (filterOptions[propName] !== undefined) { options += " " + filterOptions[propName]; } } return options; } }; $scope.clearFilterOptions = function () { filterOptions.postType = ''; filterOptions.toLocation = ''; filterOptions.fromLocation = ''; filterOptions.toDate = ''; filterOptions.fromDate = ''; filterOptions.transportationType = ''; filterOptions.quickFilter = ''; $scope.postType = ''; $scope.toFilter = ''; $scope.fromFilter = ''; $scope.toDateFilter = ''; $scope.fromDateFilter = ''; $scope.transportationTypeFilter = ''; $scope.quickFilter = ''; $mdToast.showSimple('Шүүлтийн сонголтууд цэвэрлэгдлээ...'); }; } ]);
"use strict"; let Seconds = function(minuteString) { let splits = minuteString.split(":"); let err = "minutes need to be formatted mm::ss. received " + minuteString; if (splits.length !== 2) { throw new Error(err); } if (Number(splits[0]) === null || Number(splits[1]) === null) { throw new Error(err); } this.seconds = Number(splits[0]) * 60 + Number(splits[1]); } Seconds.prototype = { constructor: Seconds, addSeconds: function(other) { let self = this; if (typeof(other) === 'string') { self.seconds += new Seconds(other).seconds; } else if (typeof(other) === 'number') { self.seconds += other; } else if (other.seconds && typeof(other.seconds) === 'number') { self.seconds += other.seconds; } else { throw new Error("trying to add seconds that wont work"); } }, toMinutes: function() { return this.seconds / 60; } }; let playerForGraph = function(player) { this.firstName = player.firstName; this.lastName = player.lastName; this.playerId = player.playerId; this.seasonStats = { min: new Seconds("00:00"), fgm: 0, fga: 0, fG3M: 0, fG3A: 0, ftm: 0, fta: 0, oreb: 0, dreb: 0, ast: 0, stl: 0, blk: 0, pts: 0 }; this.games = []; }; playerForGraph.prototype = { constructor: playerForGraph, addGame: function(game) { let self = this; self.games.push(game); self.seasonStats.min.addSeconds(game.min); self.seasonStats.fgm += game.fgm; self.seasonStats.fga += game.fga; self.seasonStats.fG3M += game.fG3M; self.seasonStats.fG3A += game.fG3A; self.seasonStats.ftm += game.ftm; self.seasonStats.fta += game.fta; self.seasonStats.oreb += game.oreb; self.seasonStats.dreb += game.dreb; self.seasonStats.ast += game.ast; self.seasonStats.stl += game.stl; self.seasonStats.blk += game.blk; self.seasonStats.pts += game.pts; } }; let gameForGraph = function(game) { this.team = game.team; this.date = game.date; this.vs = game.vs; this.min = game.statline.min; this.fgm = game.statline.fgm; this.fga = game.statline.fga; this.fG3M = game.statline.fG3M; this.fG3A = game.statline.fG3A; this.ftm = game.statline.ftm; this.fta = game.statline.fta; this.oreb = game.statline.oreb; this.dreb = game.statline.dreb; this.ast = game.statline.ast; this.stl = game.statline.stl; this.blk = game.statline.blk; this.pts = game.statline.pts; }; gameForGraph.prototype = { constructor: gameForGraph, per: function() { let self = this; let multiple = self.f3GM; multiple -= PF * lgFt / lgPF; multiple += FT / 2 * (2 - tmAst / 3 / tmFG); multiple += FG * (2 - factor * tmAST / tmFG); multiple += 2 * AST / 3; let vopMultipe = DRBP; vopMultiple // return (1 / self.min) * [ self.f3GM + (2 / 3) * self.ast } }; module.exports = { playerForGraph, gameForGraph }
/* This is the data we will be using to create our article components */ /* Look over this data, then proceed to line 91*/ const data = [ { title: 'Lambda School Students: "We\'re the best!"', date: 'Nov 5th, 2018', firstParagraph: `Lucas ipsum dolor sit amet ben twi'lek padmé darth darth darth moff hutt organa twi'lek. Ben amidala secura skywalker lando moff wicket tatooine luke.Solo wampa wampa calrissian yoda moff.Darth grievous darth gonk darth hutt.Darth baba skywalker watto fett jango maul han.Mon ewok sidious sidious lando kenobi grievous gamorrean solo.Yoda wedge utapau darth calamari. Hutt calamari darth jabba.Darth dooku amidala organa moff.Boba darth binks solo hutt skywalker dantooine skywalker.Qui - gonn jar twi'lek jinn leia jango skywalker mon.`, secondParagraph: `Grievous fett calamari anakin skywalker hutt.Alderaan darth kenobi darth r2- d2 windu mothma.Sidious darth calamari moff.Wampa mothma sith wedge solo mara.Darth gonk maul sith moff chewbacca palpatine mace amidala.C - 3po solo skywalker anakin yoda leia.Maul wampa bespin watto jade ewok darth jabba.Lando dantooine moff k - 3po dantooine luke.Fisto mandalore darth wedge c - 3p0 ahsoka.Secura moff palpatine fett.Anakin sith darth darth.Moff solo leia ben ponda jade.Binks jango aayla skywalker skywalker cade.Mustafar darth ventress anakin watto.Yavin jawa sebulba owen jinn tatooine sith organa.`, thirdParagraph: `Dagobah hutt jawa leia calamari ventress skywalker yoda. Binks wicket hutt coruscant sidious naboo ackbar tatooine. Hutt lars padmé darth. Maul solo darth darth jabba qui-gon chewbacca darth maul. Moff baba wicket han. C-3po antilles moff qui-gon ahsoka aayla dooku amidala. Palpatine droid amidala droid k-3po twi'lek padmé wookiee. Leia moff calamari mon obi-wan. Solo grievous lando coruscant. Jinn darth palpatine obi-wan mon.` }, { title: 'Javascript and You, ES6', date: 'May 7th, 2019', firstParagraph: `Alohamora wand elf parchment, Wingardium Leviosa hippogriff, house dementors betrayal. Holly, Snape centaur portkey ghost Hermione spell bezoar Scabbers. Peruvian-Night-Powder werewolf, Dobby pear-tickle half-moon-glasses, Knight-Bus. Padfoot snargaluff seeker: Hagrid broomstick mischief managed. Snitch Fluffy rock-cake, 9 ¾ dress robes I must not tell lies. Mudbloods yew pumpkin juice phials Ravenclaw’s Diadem 10 galleons Thieves Downfall. Ministry-of-Magic mimubulus mimbletonia Pigwidgeon knut phoenix feather other minister Azkaban. Hedwig Daily Prophet treacle tart full-moon Ollivanders You-Know-Who cursed. Fawkes maze raw-steak Voldemort Goblin Wars snitch Forbidden forest grindylows wool socks`, secondParagraph: `Boggarts lavender robes, Hermione Granger Fantastic Beasts and Where to Find Them. Bee in your bonnet Hand of Glory elder wand, spectacles House Cup Bertie Bott’s Every Flavor Beans Impedimenta. Stunning spells tap-dancing spider Slytherin’s Heir mewing kittens Remus Lupin. Palominos scarlet train black robes, Metamorphimagus Niffler dead easy second bedroom. Padma and Parvati Sorting Hat Minister of Magic blue turban remember my last.`, thirdParagraph: `Toad-like smile Flourish and Blotts he knew I’d come back Quidditch World Cup. Fat Lady baubles banana fritters fairy lights Petrificus Totalus. So thirsty, deluminator firs’ years follow me 12 inches of parchment. Head Boy start-of-term banquet Cleansweep Seven roaring lion hat. Unicorn blood crossbow mars is bright tonight, feast Norwegian Ridgeback. Come seek us where our voices sound, we cannot sing above the ground, Ginny Weasley bright red. Fanged frisbees, phoenix tears good clean match.` }, { title: 'React vs Angular vs Vue', date: 'June 7th, 2019', firstParagraph: `Bulbasaur Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ivysaur Lorem ipsum dolor sit amet, consectetur adipiscing elit. Venusaur Lorem ipsum dolor sit amet, consectetur adipiscing elit. Charmander Lorem ipsum dolor sit amet, consectetur adipiscing elit. Charmeleon Lorem ipsum dolor sit amet, consectetur adipiscing elit. Charizard Lorem ipsum dolor sit amet, consectetur adipiscing elit. Squirtle Lorem ipsum dolor sit amet, consectetur adipiscing elit. Wartortle Lorem ipsum dolor sit amet, consectetur adipiscing elit. Blastoise Lorem ipsum dolor sit amet, consectetur adipiscing elit. Caterpie Lorem ipsum dolor sit amet, consectetur adipiscing elit. Metapod Lorem ipsum dolor sit amet, consectetur adipiscing elit. Butterfree Lorem ipsum dolor sit amet, consectetur adipiscing elit. Weedle Lorem ipsum dolor sit amet, consectetur adipiscing elit. Kakuna Lorem ipsum dolor sit amet, consectetur adipiscing elit. Beedrill Lorem ipsum dolor sit amet, consectetur adipiscing elit.`, secondParagraph: `Pidgey Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pidgeotto Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pidgeot Lorem ipsum dolor sit amet, consectetur adipiscing elit. Rattata Lorem ipsum dolor sit amet, consectetur adipiscing elit. Raticate Lorem ipsum dolor sit amet, consectetur adipiscing elit. Spearow Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fearow Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ekans Lorem ipsum dolor sit amet, consectetur adipiscing elit. Arbok Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pikachu Lorem ipsum dolor sit amet, consectetur adipiscing elit. Raichu Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sandshrew Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sandslash Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nidoran Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nidorina Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nidoqueen Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nidoran Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nidorino Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nidoking Lorem ipsum`, thirdParagraph: `Gotta catch 'em all Horsea gym Ninjask Absol Sinnoh Poliwag. Gotta catch 'em all Youngster wants to fight Soda Pop Floatzel Leech Life Seismitoad Ariados. Earthquake Pokemon Glitch City Tail Whip Skitty Ekans Dialga. Ut aliquip ex ea commodo consequat James Castform Lotad the power that's inside Burnt Berry Makuhita. Ghost Ariados Corphish Dusclops Golbat Gligar Zweilous.` }, { title: 'Professional Software Development in 2019', date: 'Jan 1st, 2019', firstParagraph: `Hodor hodor HODOR! Hodor hodor - hodor, hodor. Hodor hodor... Hodor hodor hodor; hodor hodor. Hodor hodor hodor, hodor, hodor hodor. Hodor, hodor. Hodor. Hodor, hodor - hodor... Hodor hodor hodor; hodor HODOR hodor, hodor hodor?! Hodor hodor, hodor. Hodor hodor hodor hodor hodor! Hodor hodor - HODOR hodor, hodor hodor hodor hodor hodor; hodor hodor? `, secondParagraph: `Hodor, hodor. Hodor. Hodor, hodor, hodor. Hodor hodor, hodor. Hodor hodor, hodor, hodor hodor. Hodor! Hodor hodor, hodor; hodor hodor hodor? Hodor, hodor. Hodor. Hodor, hodor - HODOR hodor, hodor hodor hodor! Hodor, hodor. Hodor. Hodor, HODOR hodor, hodor hodor, hodor, hodor hodor. Hodor hodor - hodor - hodor... Hodor hodor hodor hodor hodor hodor hodor?! Hodor hodor - hodor hodor hodor. Hodor. Hodor hodor... Hodor hodor hodor hodor hodor? `, thirdParagraph: `Hodor hodor - hodor... Hodor hodor hodor hodor. Hodor. Hodor! Hodor hodor, hodor hodor hodor hodor hodor; hodor hodor? Hodor! Hodor hodor, HODOR hodor, hodor hodor?! Hodor! Hodor hodor, HODOR hodor, hodor hodor, hodor, hodor hodor. Hodor, hodor. Hodor. Hodor, hodor, hodor. Hodor hodor... Hodor hodor hodor?! Hodor, hodor... Hodor hodor HODOR hodor, hodor hodor. Hodor.` }, { title: "Star Wars, nothing but Star Wars", date: "Time Unknown, but in a Galaxy far far away", firstParagraph: "It looks like Sandpeople did this, all right. Look, here are Gaffi sticks, Bantha tracks. It's just...I never heard of them hitting anything this big before. They didn't. But we are meant to think they did. These tracks are side by side. Sandpeople always ride single file to hide there numbers. These are the same Jawas that sold us Artoo and Threepio. And these blast points, too accurate for Sandpeople. Only Imperial stormtroopers are so precise. Why would Imperial troops want to slaughter Jawas? If they traced the robots here, they may have learned who they sold them to. And that would lead them home! Wait, Luke! It's too dangerous. Uncle Owen! Aunt Beru! Uncle Owen!", secondParagraph: "Well, the Force is what gives a Jedi his power. It's an energy field created by all living things. It surrounds us and penetrates us. It binds the galaxy together. Now, let's see if we can't figure out what you are, my little friend. And where you come from. I saw part of the message he was... I seem to have found it.", thirdParagraph: "Hey...hey, open the pressure maintenance hatch on unit number... where are we? Three-two-six-eight-two-seven. If we can just avoid any more female advice, we ought to be able to get out of here. Well, let's get moving! Where are you going? No, wait. They'll hear! Come here, you big coward! Chewie! Come here! Listen. I don't know who you are, or where you came from, but from now on, you do as I tell you. Okay? Look, Your Worshipfulness, let's get one thing straight! I take orders from one person! Me! It's a wonder you're still alive. Will somebody get this big walking carpet out of my way? No reward is worth this." }, { title: "These are the voyages of the starship Enterprise", date: "In the Future", firstParagraph: "Run a manual sweep of anomalous airborne or electromagnetic readings. Radiation levels in our atmosphere have increased by 3,000 percent. Electromagnetic and subspace wave fronts approaching synchronization. What is the strength of the ship's deflector shields at maximum output? The wormhole's size and short period would make this a local phenomenon. Do you have sufficient data to compile a holographic simulation?", secondParagraph: "Shields up. I recommend we transfer power to phasers and arm the photon torpedoes. Something strange on the detector circuit. The weapons must have disrupted our communicators. You saw something as tasty as meat, but inorganically materialized out of patterns used by our transporters. Captain, the most elementary and valuable statement in science, the beginning of wisdom, is 'I do not know.' All transporters off.", thirdParagraph: "Sensors indicate human life forms 30 meters below the planet's surface. Stellar flares are increasing in magnitude and frequency. Set course for Rhomboid Dronegar 006, warp seven. There's no evidence of an advanced communication network. Total guidance system failure, with less than 24 hours' reserve power. Shield effectiveness has been reduced 12 percent. We have covered the area in a spherical pattern which a ship without warp drive could cross in the given time." } ]; /* Step 1: Create a function that creates a component. You will want your component to look like the template below: <div class="article"> <h2>{title of the article}</h2> <p class="date">{date of the article}</p> {three separate paragraph elements} <span class='expandButton'></span> </div> Hint: You will need to use createElement more than once here! Your function should take either an object as it's one argument, or 5 separate arguments mapping to each piece of the data object above. Step 2: Add an event listener to the expandButton span. This event listener should toggle the class 'article-open' on the 'article' div. Step 3: return the entire component. Step 4: Map over the data, creating a component for each oject and add each component to the DOM as children of the 'articles' div. Step 5: Add a new article to the array. Make sure it is in the same format as the others. Refresh the page to see the new article. */ const container = document.querySelector(".articles"); data.forEach(function(array){ container.appendChild(createComponent(array.title, array.date, array.firstParagraph, array.secondParagraph, array.thirdParagraph)) }) function createComponent(title, date, first, second, third){ const div = document.createElement("div"); const titleh2 = document.createElement("h2"); const dateCont = document.createElement("p") const par1 = document.createElement("p"); const par2 = document.createElement("p"); const par3 = document.createElement("p"); const span = document.createElement("span"); // set structure of elements div.appendChild(titleh2) div.appendChild(dateCont) div.appendChild(par1) div.appendChild(par2) div.appendChild(par3) div.appendChild(span) // set classes div.classList.add("article"); dateCont.classList.add("date"); span.classList.add("expandButton"); // set text content titleh2.textContent = title; dateCont.textContent = date; par1.textContent = first; par2.textContent = second; par3.textContent = third; span.textContent = "Expand"; //button events span.addEventListener("click", function(){ div.classList.toggle("article-open") }) return div; }
/** * @overview GTA:Multiplayer Default Package: Utility File * @author Jan "Waffle" C. * @copyright (c) GTA:Multiplayer [gta-mp.net] * @license https://master.gta-mp.net/LICENSE */ "use strict"; let Utility = module.exports; Utility.hashes = require('./hashes/hashes'); /** * Broadcasts a Message to all Players. * * @param {string} message the message to broadcast. * @param {RGB=} [opt_color] color of the message */ Utility.broadcastMessage = (message, opt_color) => { for (let player of g_players) { player.SendChatMessage(message, opt_color); } }; /** * Returns the player from his id or (part of his) Name * * @param {string/number} idOrName Networkid or name of the player (or some digits of the name) * @param {boolean=} [allowDuplicates=false] False: If multiple players have the same Name only the first one found is returned. * True: Returns an array with all duplicate players with the name * @param {boolean=} [caseSensitive=false] True if case sensitive, false if not * @return {Player} An array with the players found with the id or the name, * only contains the first one found if allowDuplicates was false, empty array if no player was found */ Utility.getPlayer = (idOrName, opt_allowDuplicates, opt_caseSensitive) => { let allowDuplicates = opt_allowDuplicates || false; let caseSensitive = opt_caseSensitive || false; let id = parseInt(idOrName); let fnCheck; if (isNaN(id)) { if(caseSensitive === false) { idOrName = idOrName.toLowerCase(); } // define fnCheck to check the players name fnCheck = target => { let targetName; if(caseSensitive === false) { //ignore capital letters targetName = target.name.toLowerCase(); } else { // do not ignore capital letters targetName = target.name; } if (targetName.indexOf(idOrName) === 0) { return true; } return false; }; } else { fnCheck = target => target.client.networkId === id; } let playerArray = []; for (let tempPlayer of g_players) { if (fnCheck(tempPlayer)) { playerArray.push(tempPlayer); if(allowDuplicates === false) { // exit the loop, because we just return the first player found break; } } } return playerArray; };
import axios from "axios"; export default { // User sign up userSignup: function(userData) { return ( axios.post("/api/signup", userData) ) }, // User log in userLogin: function(userData) { return axios.post("/api/login", userData); }, userLogout: function() { return axios.get("/logout") }, // Create default shelves createDefaultShelves: function(userId) { return axios.post("/api/createdefaultshelves", userId); }, // Find one by email findEmail: function(userData){ return axios.get("/api/findemail", userData); }, // Check if user is logged in userLoggedIn: function() { return axios.get("/api/logged-in"); }, userShelves: function(userId) { return axios.post("/api/user/shelves", userId); }, saveBook: function(data) { return axios.post("/api/shelf/addbook", data); }, saveShelfToBook: function(data) { return axios.post("/api/book/addshelf", data); }, createShelf: function(data) { return axios.post("/api/addshelf", data); }, getShelfInfo: function(id) { return axios.post("/api/shelf/getbooks", id); }, removeBook: function(data) { return axios.post("/api/shelf/removebook", data); } };
import React from "react"; import Head from "next/head"; const url = "https://casprine-blog.now.sh/"; const SEO = ({ title, description, issue }) => { return ( <Head> <title>{title}</title> <link rel="shortcut icon" href="../../../static/images/circle-dark.png" type="image/png" /> <meta name="title" content={title} /> <meta name="description" content={description} /> <meta property="og:type" content="website" /> <meta property="og:url" content={url + issue} /> <meta property="og:title" content={title} /> <meta property="og:description" content={description} /> <meta property="og:image" content="../../../static/images/circle-dark.png" /> <meta name="twitter:card" content="summary" /> <meta name="twitter:site" content="@casprine_ix" /> <meta name="twitter:title" content={title} /> <meta name="twitter:description" content={description} /> <meta name="twitter:image" content="../../../static/images/circle-dark.png" /> </Head> ); }; export default SEO;
var routerUrl = [ "/page/orderList", "/page/dataListDetail/:id", "/page/productList", "/page/billingList", "/page/shippingList", "/page/userList", "/page/fileList", "/page/recordList", "/page/roleClass", "/page/productList", "/page/productClass", "/page/colorClass", "/page/optionClass", "/page/accessoriesClass", "/page/modelClass", "/page/braceClass", "/page/rolePermissionList", "/page/userListSet", "/page/orderPlaceList", "/page/orderReceivedList", "/page/orderCancelledList", "/page/orderOnHoldList", "/page/orderProcessedList", "/page/orderShippedList", "/page/braceDataList", "/page/optionsValueClass", "/page/productListDetail/:id", "/page/optionValueRelationship/:id", "/page/accessoriesValueRelationship/:id" ]
/* Ridiculous strawberry picking game https://evgenii.com/blog/ridiculous-strawberry-picking/ License: Public Domain Image credits ============= 1. "The Blue Marble" By NASA/Apollo 17 crew; taken by either Harrison Schmitt or Ron Evans. Sources: http://www.nasa.gov/images/content/115334main_image_feature_329_ys_full.jpg, https://commons.wikimedia.org/wiki/File:The_Earth_seen_from_Apollo_17.jpg 2. "The Sun photographed at 304 angstroms" by NASA/SDO (AIA). Sources: http://sdo.gsfc.nasa.gov/assets/img/browse/2010/08/19/20100819_003221_4096_0304.jpg, https://commons.wikimedia.org/wiki/File:The_Sun_by_the_Atmospheric_Imaging_Assembly_of_NASA%27s_Solar_Dynamics_Observatory_-_20100819.jpg */ (function(){ // A Slider UI element function SickSlider(sliderElementSelector) { var that = { // A function that will be called when user changes the slider position. // The function will be passed the slider position: a number between 0 and 1. onSliderChange: null, // Store the previous slider value in order to prevent calling onSliderChange function with the same argument previousSliderValue: -42, // Does not react to user input when false enabled: true, didRequestUpdateOnNextFrame: false }; // Initializes the slider element // // Arguments: // sliderElementSelector: A CSS selector of the SickSlider element. that.init = function(sliderElementSelector) { that.slider = document.querySelector(sliderElementSelector); that.sliderHead = that.slider.querySelector(".SickSlider-head"); var sliding = false; // Start dragging slider // ----------------- that.slider.addEventListener("mousedown", function(e) { sliding = true; that.updateHeadPositionOnTouch(e); }); that.slider.addEventListener("touchstart", function(e) { sliding = true; that.updateHeadPositionOnTouch(e); }); that.slider.onselectstart = function () { return false; }; // End dragging slider // ----------------- document.addEventListener("mouseup", function(){ sliding = false; }); document.addEventListener("dragend", function(){ sliding = false; }); document.addEventListener("touchend", function(e) { sliding = false; }); // Drag slider // ----------------- document.addEventListener("mousemove", function(e) { if (!sliding) { return; } that.updateHeadPositionOnTouch(e); }); document.addEventListener("touchmove", function(e) { if (!sliding) { return; } that.updateHeadPositionOnTouch(e); }); that.slider.addEventListener("touchmove", function(e) { if (typeof e.preventDefault !== 'undefined' && e.preventDefault !== null) { e.preventDefault(); // Prevent screen from sliding on touch devices when the element is dragged. } }); }; // Returns the slider value (a number form 0 to 1) from the cursor position // // Arguments: // // e: a touch event. // that.sliderValueFromCursor = function(e) { var pointerX = e.pageX; if (e.touches && e.touches.length > 0) { pointerX = e.touches[0].pageX; } pointerX = pointerX - that.slider.offsetLeft; var headLeft = (pointerX - 16); if (headLeft < 0) { headLeft = 0; } if ((headLeft + that.sliderHead.offsetWidth) > that.slider.offsetWidth) { headLeft = that.slider.offsetWidth - that.sliderHead.offsetWidth; } // Calculate slider value from head position var sliderWidthWithoutHead = that.slider.offsetWidth - that.sliderHead.offsetWidth; var sliderValue = 1; if (sliderWidthWithoutHead !== 0) { sliderValue = headLeft / sliderWidthWithoutHead; } return sliderValue; }; // Changes the position of the slider // // Arguments: // // sliderValue: a value between 0 and 1. // that.changePosition = function(sliderValue) { var headLeft = (that.slider.offsetWidth - that.sliderHead.offsetWidth) * sliderValue; that.sliderHead.style.left = headLeft + "px"; }; // Update the slider position and call the callback function // // Arguments: // // e: a touch event. // that.updateHeadPositionOnTouch = function(e) { if (!that.enabled) { return; } var sliderValue = that.sliderValueFromCursor(e); // Handle the head change only if it changed significantly (more than 0.1%) if (Math.round(that.previousSliderValue * 1000) === Math.round(sliderValue * 1000)) { return; } that.previousSliderValue = sliderValue; if (!that.didRequestUpdateOnNextFrame) { // Update the slider on next redraw, to improve performance that.didRequestUpdateOnNextFrame = true; window.requestAnimationFrame(that.updateOnFrame); } }; that.updateOnFrame = function() { that.changePosition(that.previousSliderValue); if (that.onSliderChange) { that.onSliderChange(that.previousSliderValue); } that.didRequestUpdateOnNextFrame = false; }; that.init(sliderElementSelector); return that; } // Show debug messages on screen var debug = (function(){ var debugOutput = document.querySelector(".EarthOrbitSimulation-debugOutput"); function print(text) { var date = new Date(); debugOutput.innerHTML = text + " " + date.getMilliseconds(); } return { print: print }; })(); // Shows the current date on screen var simulationTime = (function(){ var startYear = 1997, monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], secondsSinceStartYear = (31 /*jan*/ + 28 /*feb*/ + 31 /*mar*/ + 30 /*apr*/ + 31 /*may*/ + 30 /*jun*/ + 31 /*jul*/ + 31 /*aug*/ + 30 /*sep*/ + 23 /*oct*/) * 24 * 3600 + 12 * 3600 /*noon*/, numberOfSimulatedSecondsSinceStart = secondsSinceStartYear, // Seconds since the start of the simulations, updateCycle = -1, // Used to limit the number of climate calculations, in order to improve performance secondsInSiderealYear = 365.242189 * 24 * 3600, // The length of the sidereal year for the Earth, in seconds timeElement = document.querySelector(".EarthOrbitSimulation-time"), previousTime = ""; // The function is called on each frame, which is 60 time per second function update() { if (physics.state.paused) { return; } numberOfSimulatedSecondsSinceStart += physics.constants.timeIncrementPerFrameInSeconds; updateCycle += 1; if (updateCycle > 5) { updateCycle = 0; } if (updateCycle !== 0) { return; } // Update climate only once in 10 cycles, to improve performance var yearsSinceStart = Math.floor(numberOfSimulatedSecondsSinceStart / secondsInSiderealYear); var year = startYear + yearsSinceStart; var secondsSinceYearStart = (numberOfSimulatedSecondsSinceStart % secondsInSiderealYear); var monthId = Math.floor(secondsSinceYearStart / secondsInSiderealYear * 12); var monthName = monthNames[monthId]; showTime(year, monthName); } function showTime(year, month) { var text = month + " " + year; if (text === previousTime) { return; } timeElement.innerHTML = text; previousTime = text; } function reset() { numberOfSimulatedSecondsSinceStart = secondsSinceStartYear; } return { reset: reset, update: update }; })(); // Calculates the average global temperature on Earth var climate = (function() { var initialTemperatureCelsius = 16, currentTemperatureCelsius = initialTemperatureCelsius, updateCycle = -1, // Used to limit the number of climate calculations, in order to improve performance previouslyDisplayedTemperature = 0, // Stores the previously display temperature temperatureElement = document.querySelector(".EarthOrbitSimulation-temperatureValue"), temperatureDescriptionElement = document.querySelector(".EarthOrbitSimulation-temperatureDescription"), // The number of cycles for Earth to survive in extreme cold or hot conditions. maxNumberOfExtremeCyclesToSurvive = 5, // The number of cycles that Earth has been under extreme cold or hot conditions. cyclesUnderExtremeConditions = 0; function update(earthSunDistanceMeters, habitableZoneInnerDistanceMeters, habitableZoneOuterDistanceMeters) { if (physics.state.paused) { return; } if (isEarthDead()) { physics.state.paused = true; var message = "High global temperature caused some of the water to evaporate and create a runaway greenhouse effect. The temperature rose even higher, and all animal species living on the surface of the planet have become extinct."; if (currentTemperatureCelsius < 10) { if (physics.currentSunMassRatio() === 0) { // Sun has been removed message = "The absence of the Sun caused the shutdown of photosynthesis in plants and other organisms. All animal species living on the surface of the planet have become extinct."; } else { message = "Low global temperature caused the shutdown of photosynthesis in plants and other organisms. All animal species living on the surface of the planet have become extinct."; } } gameoverMessage.show(message); return; } updateCycle += 1; if (updateCycle > 30) { updateCycle = 0; } if (updateCycle !== 0) { return; } // Update climate only once in 100 cycles, to improve performance var tempChange = 0; // Change in temperature degrees if (earthSunDistanceMeters < habitableZoneInnerDistanceMeters) { // Earth is heating tempChange = Math.ceil(habitableZoneInnerDistanceMeters / earthSunDistanceMeters) ; if (tempChange > 3) { tempChange = 3; } if (tempChange === 0) { tempChange = 1; } } else if (earthSunDistanceMeters > habitableZoneOuterDistanceMeters) { // Earth is cooling var distanceToOuterEdge = habitableZoneOuterDistanceMeters - earthSunDistanceMeters; tempChange = Math.floor(5 * distanceToOuterEdge / habitableZoneOuterDistanceMeters); if (tempChange < -5) { tempChange = -5; } if (tempChange === 0) { tempChange = -1; } } else { // Earth is in the habitable zone if (currentTemperatureCelsius != initialTemperatureCelsius) { // Restore the temperature tempChange = Math.ceil((initialTemperatureCelsius - currentTemperatureCelsius) / 5); if (tempChange === 0) { if (currentTemperatureCelsius > initialTemperatureCelsius) { tempChange = -1; } if (currentTemperatureCelsius < initialTemperatureCelsius) { tempChange = 1; } } } } currentTemperatureCelsius += tempChange; displayCurrentTemperature(currentTemperatureCelsius); displayTemperatureDescription(); } function displayCurrentTemperature(currentTemperatureCelsius) { if (previouslyDisplayedTemperature === currentTemperatureCelsius) { return; } previouslyDisplayedTemperature = currentTemperatureCelsius; temperatureElement.innerHTML = currentTemperatureCelsius; } function displayTemperatureDescription(changeDegrees) { var description = "nice", showTooHotWarning = false, showTooColdWarning = false; if (currentTemperatureCelsius > initialTemperatureCelsius) { if (currentTemperatureCelsius >= 40) { // Extremely hot showTooHotWarning = true; description = "too hot"; cyclesUnderExtremeConditions += 1; } else { cyclesUnderExtremeConditions = 0; if (currentTemperatureCelsius >= 30) { description = "hot"; } else if (currentTemperatureCelsius >= 20) { description = "warm"; } } } else { if (currentTemperatureCelsius <= 0) { // Extremely cold description = "freezing"; showTooColdWarning = true; cyclesUnderExtremeConditions += 1; } else { cyclesUnderExtremeConditions = 0; if (currentTemperatureCelsius <= 7) { description = "cold"; } else if (currentTemperatureCelsius <= 12) { description = "cool"; } } } temperatureDescriptionElement.innerHTML = description; // Style the description warning with blinking and color if needed // ----------- var descriptionElementClass = ""; if (showTooHotWarning) { descriptionElementClass = "EarthOrbitSimulation-isBlinking EarthOrbitSimulation-hasTooHotWarning"; } else if (showTooColdWarning) { descriptionElementClass = "EarthOrbitSimulation-isBlinking EarthOrbitSimulation-hasTooColdWarning"; } temperatureDescriptionElement.className = descriptionElementClass; } function isEarthDead() { return cyclesUnderExtremeConditions > maxNumberOfExtremeCyclesToSurvive; } function reset() { currentTemperatureCelsius = initialTemperatureCelsius; updateCycle = -1; cyclesUnderExtremeConditions = 0; } return { reset: reset, update: update }; })(); // Calculates the location of the habitable zone var habitableZone = (function() { var innerEdgeMultiplier = 0.84, // The distance in AUs of the inner edge of the habitable zone outerEdgeMultiplier = 1.7, // The distance in AUs of the outer edge of the habitable zone values = { innerDistanceMeters: 1, // The distance from the Sun to the inner edge of the habitable zone, in meters outerDistanceMeters: 1 // The distance from the Sun to the outer edge of the habitable zone, in meters }; // Update habitable zone based on the mass of the Sun. // `massOfTheSunRatio` is a proportion of normal mass of the Sun (default is 1). function update(massOfTheSunRatio) { var sunLuminocity = Math.pow(massOfTheSunRatio, 3); values.innerDistanceMeters = innerDistanceMeters(sunLuminocity); values.outerDistanceMeters = outerDistanceMeters(sunLuminocity); } // Returns the distance of the inner edge of the habitable zone form the Sun in meters. // `sunLuminocityRatio` is a proportion of Sun luminocity (default is 1). function innerDistanceMeters(sunLuminocityRatio) { return Math.sqrt(sunLuminocityRatio) * innerEdgeMultiplier * physics.constants.earthSunDistanceMeters; } // Returns the distance of the outer edge of the habitable zone form the Sun in pixels. function innerDistancePixels() { return values.innerDistanceMeters / physics.constants.scaleFactor; } // Returns the distance of the outer edge of the habitable zone form the Sun in meters. // `sunLuminocityRatio` is a proportion of Sun luminocity (default is 1). function outerDistanceMeters(sunLuminocityRatio) { return Math.sqrt(sunLuminocityRatio) * outerEdgeMultiplier * physics.constants.earthSunDistanceMeters; } // Returns the distance of the outer edge of the habitable zone form the Sun in pixels. function outerDistancePixels() { return values.outerDistanceMeters / physics.constants.scaleFactor; } return { innerDistancePixels: innerDistancePixels, outerDistancePixels: outerDistancePixels, update: update, values: values }; })(); var helper = (function(){ function showBlockElement(elemenent) { elemenent.style.display = 'block'; } function hideBlockElement(elemenent) { elemenent.style.display = 'none'; } function showInlineElement(elemenent) { elemenent.style.display = 'inline'; } function hideInlineElement(elemenent) { elemenent.style.display = 'none'; } function rotateElement(element, deg) { element.style.webkitTransform = 'rotate(' + deg + 'deg)'; element.style.mozTransform = 'rotate(' + deg + 'deg)'; element.style.msTransform = 'rotate(' + deg + 'deg)'; element.style.oTransform = 'rotate(' + deg + 'deg)'; element.style.transform = 'rotate(' + deg + 'deg)'; } function createImage(src, alt) { var image = document.createElement('img'); image.setAttribute('src', src); image.setAttribute('alt', alt); return image; } /** * Remove item from array * * Modifies the array “in place”, i.e. the array passed as an argument * is modified as opposed to creating a new array. Also returns the modified * array for your convenience. * * Source: http://stackoverflow.com/a/36540678/297131 */ function removeFromArray(array, item) { var itemIndex; // Look for the item (the item can have multiple indices) itemIndex = array.indexOf(item); while (itemIndex !== -1) { // Remove the item, then return the modified array array.splice(itemIndex, 1); itemIndex = array.indexOf(item); } // Return the modified array return array; } // http://stackoverflow.com/a/5169076/297131 function addClass(element, clazz) { if (!hasClass(element, clazz)) { element.className += " " + clazz; } } function removeClass(element, clazz) { if (hasClass(element, clazz)) { var reg = new RegExp('(\\s|^)' + clazz + '(\\s|$)'); element.className = element.className.replace(reg,' '); element.className = element.className.trim(); } } function hasClass(elemement, clazz) { return elemement.className.match(new RegExp('(\\s|^)' + clazz + '(\\s|$)')); } return { addClass: addClass, removeClass: removeClass, removeFromArray: removeFromArray, createImage: createImage, rotateElement: rotateElement, showInlineElement: showInlineElement, hideInlineElement: hideInlineElement, showBlockElement: showBlockElement, hideBlockElement: hideBlockElement }; })(); // Checks if two objects are collided var collision = (function(){ // Return true if two object are collided function areCollided(objectOnePosition, objectTwoPosition, objectTwoSize) { var correctedObjectTwoSize = objectTwoSize * 0.8; var objectTwoHalf = correctedObjectTwoSize / 2; var objectTwoLeft = objectTwoPosition.x - objectTwoHalf; var objectTwoRight = objectTwoPosition.x + objectTwoHalf; var objectTwoRightTop = objectTwoPosition.y - objectTwoHalf; var objectTwoBottom = objectTwoPosition.y + objectTwoHalf; return (objectOnePosition.x >= objectTwoLeft && objectOnePosition.x <= objectTwoRight && objectOnePosition.y >= objectTwoRightTop && objectOnePosition.y <= objectTwoBottom); } return { areCollided: areCollided }; })(); // Calculates the position of the Earth var physics = (function() { var constants = { gravitationalConstant: 6.67408 * Math.pow(10, -11), earthSunDistanceMeters: 1.496 * Math.pow(10, 11), earthAngularVelocityMetersPerSecond: 1.990986 * Math.pow(10, -7), massOfTheSunKg: 1.98855 * Math.pow(10, 30), pixelsInOneEarthSunDistance: 100, // The length of one AU (Earth-Sun distance) in pixels. // The number of calculations of orbital path done in one 16 millisecond frame. // The higher the number, the more precise are the calculations and the slower the simulation. numberOfCalculationsPerFrame: 100 }; // A factor by which we scale the distance between the Sun and the Earth // in order to show it on screen constants.scaleFactor = constants.earthSunDistanceMeters / constants.pixelsInOneEarthSunDistance; // The number of seconds advanced by the animation in each frame. // The frames are fired 60 times per second. constants.timeIncrementPerFrameInSeconds = 3600 * 24 * 2; // The length of the time increment, in seconds. constants.deltaT = constants.timeIncrementPerFrameInSeconds / constants.numberOfCalculationsPerFrame; // Initial condition of the model var initialConditions = { distance: { value: constants.earthSunDistanceMeters, speed: 0.00 }, angle: { value: Math.PI / 6, speed: constants.earthAngularVelocityMetersPerSecond } }; // Current state of the system var state = { distance: { value: 0, speed: 0 }, angle: { value: 0, speed: 0 }, massOfTheSunKg: constants.massOfTheSunKg, paused: false }; function calculateDistanceAcceleration(state) { // [acceleration of distance] = [distance][angular velocity]^2 - G * M / [distance]^2 return state.distance.value * Math.pow(state.angle.speed, 2) - (constants.gravitationalConstant * state.massOfTheSunKg) / Math.pow(state.distance.value, 2); } function calculateAngleAcceleration(state) { // [acceleration of angle] = - 2[speed][angular velocity] / [distance] return -2.0 * state.distance.speed * state.angle.speed / state.distance.value; } // Calculates a new value based on the time change and its derivative // For example, it calculates the new distance based on the distance derivative (velocity) // and the elapsed time interval. function newValue(currentValue, deltaT, derivative) { return currentValue + deltaT * derivative; } function resetStateToInitialConditions() { state.distance.value = initialConditions.distance.value; state.distance.speed = initialConditions.distance.speed; state.angle.value = initialConditions.angle.value; state.angle.speed = initialConditions.angle.speed; } // The distance that is used for drawing on screen function earthSunDistancePixels() { return state.distance.value / constants.scaleFactor; } // The main function that is called on every animation frame. // It calculates and updates the current positions of the bodies function updatePosition() { if (physics.state.paused) { return; } for (var i = 0; i < constants.numberOfCalculationsPerFrame; i++) { calculateNewPosition(); } } // Calculates position of the Earth function calculateNewPosition() { // Calculate new distance var distanceAcceleration = calculateDistanceAcceleration(state); state.distance.speed = newValue(state.distance.speed, constants.deltaT, distanceAcceleration); state.distance.value = newValue(state.distance.value, constants.deltaT, state.distance.speed); // Calculate new angle var angleAcceleration = calculateAngleAcceleration(state); state.angle.speed = newValue(state.angle.speed, constants.deltaT, angleAcceleration); state.angle.value = newValue(state.angle.value, constants.deltaT, state.angle.speed); if (state.angle.value > 2 * Math.PI) { state.angle.value = state.angle.value % (2 * Math.PI); } } // Updates the mass of the Sun function updateFromUserInput(solarMassMultiplier) { state.massOfTheSunKg = constants.massOfTheSunKg * solarMassMultiplier; } // Returns the current mass of the Sun as a fraction of the normal mass. function currentSunMassRatio() { return state.massOfTheSunKg / constants.massOfTheSunKg; } return { earthSunDistancePixels: earthSunDistancePixels, resetStateToInitialConditions: resetStateToInitialConditions, currentSunMassRatio: currentSunMassRatio, updatePosition: updatePosition, initialConditions: initialConditions, updateFromUserInput: updateFromUserInput, constants: constants, state: state }; })(); // Show a full screen message when the game is lost var gameoverMessage = (function(){ var containerElement = document.querySelector(".EarthOrbitSimulation"), gameoverMessageContentElement = document.querySelector(".EarthOrbitSimulation-gameoverMessageContent"), restartButton = document.querySelector(".EarthOrbitSimulation-gameoverButton"), continueButton = document.querySelector(".EarthOrbitSimulation-continueButton"), gameoverCssClass = 'EarthOrbitSimulation-hasGameoverMessage', gameoverWithRestartButtonCssClass = 'EarthOrbitSimulation-hasGameoverMessage-hasRestartButton'; function show(message) { showMessage(true); gameoverMessageContentElement.innerHTML = message; } function showWithContinueButton(message, didClickContinue) { gameoverMessageContentElement.innerHTML = message; showMessage(false); continueButton.onclick = function() { didClickContinue(); return false; // Prevent default click }; } function showMessage(hasRestartButton) { helper.addClass(containerElement, gameoverCssClass); if (hasRestartButton) { helper.addClass(containerElement, gameoverWithRestartButtonCssClass); } else { helper.removeClass(containerElement, gameoverWithRestartButtonCssClass); } } function hide() { helper.removeClass(containerElement, gameoverCssClass); } function init() { restartButton.onclick = userInput.didClickRestart; } return { show: show, showWithContinueButton: showWithContinueButton, gameoverMessage: gameoverMessage, hide: hide, init: init }; })(); // Returns a random number, same numbers each time. var seedableRandom = (function(){ var currentIndex = 1; // Resets the generator, the nextValue function will start returning same numbers function reset() { currentIndex = 1; } // Returns a random number between 0 and 1, inclusive function nextValue() { var value = Math.E * 7321 * (Math.sin(Math.E * currentIndex * 121) + 1); value = (value > 1) ? (value % 1) : value; // always between 1 and zero currentIndex++; return value; } // Returns random boolean function getBoolean() { return nextValue() > 0.5; } return { nextValue: nextValue, getBoolean: getBoolean, reset: reset }; })(); // Displays the number of collected strawberries var strawberryCounter = (function(){ var values = { collectedNumber: 0 // number of strawberries picked }, strawberryCounterNumberElement = document.querySelector(".EarthOrbitSimulation-strawberryCounterNumber"), strawberryCounterElement = document.querySelector(".EarthOrbitSimulation-strawberryCounter"); function reset() { values.collectedNumber = 0; strawberryCounterNumberElement.innerHTML = "0"; } function increment() { values.collectedNumber += 1; strawberryCounterNumberElement.innerHTML = "" + values.collectedNumber; // Blink the counter strawberryCounterElement.className = 'EarthOrbitSimulation-strawberryCounter'; void strawberryCounterElement.offsetWidth; strawberryCounterElement.className = 'EarthOrbitSimulation-strawberryCounter EarthOrbitSimulation-strawberryCounter-isBlinking'; } return { values: values, reset: reset, increment: increment }; })(); // The pool of strawberry DOM elements. // Adding and removing DOM elements is relatively slow operation and can be noticeable on mobile devices. // We use this object for improving performance by keeping strawberry elements in the DOM // instead of removing and adding them each time the number of strawberries is changed on screen. var strawberryPool = (function() { var container = document.querySelector(".EarthOrbitSimulation-container"), cachedElements = []; // Contains existing but currently hidden strawberry elements. /* Hides the element and caches it for later use with 'getOne' function */ function hideAndCache(element) { helper.addClass(element, 'EarthOrbitSimulation-isHidden'); cachedElements.push(element); } /* Returns a strawberry element */ function getOne() { var element = getOneFromCache(); if (element !== null) { return element; } // The cache is empty - create a new element instead and add to the DOM element = helper.createImage('https://evgenii.com/image/blog/2016-09-17-ridiculous-strawberry-picking/strawberry.png', 'Cosmic strawberry'); element.className = 'EarthOrbitSimulation-strawberry'; container.appendChild(element); return element; } // Returns a strawberry element from cache or null if the cache is empty. function getOneFromCache() { if (cachedElements.lenght === 0) { return null; } var element = cachedElements.shift(); if (typeof element === 'undefined' || element === null) { return null; } element.style.left = '100px'; element.style.top = '-1000px'; helper.removeClass(element, 'EarthOrbitSimulation-isHidden'); return element; } return { getOne: getOne, hideAndCache: hideAndCache }; })(); /* Represents a single juicy strawberry */ function OneStrawberry() { var that = { container: document.querySelector(".EarthOrbitSimulation-container"), element: null, // Contains the DOM element for the strawberry, initialDistanceFromTheSunMeters: 5.0 * physics.constants.earthSunDistanceMeters, distanceFromTheSunMeters: 1, speedMetersPerSecond: 3000.0, // How fast the strawberry is moving // The distance from the Sun at which the strawberry slows down form light speed to ordinary speed distanceFromTheSunLightSpeedOffMeters: 2.0 * physics.constants.earthSunDistanceMeters, lightSpeedMetersPerSecond: 200000.0, // How fast the strawberry is travelling at 'light speed' initialAngle: -0.2, angle: 1, strawberrySizePixels: 35.0, rotationClockwise: true, // When true, the strawberry is rotating clockwise approachCurvature: 3, position: {x: 1, y: 1} // Current position }; /* Updates the strawberry position and detects collision with the Sun or the Earth. This function is called on every frame, 60 times per second. */ that.update = function() { if (physics.state.paused) { return; } // Update strawberry position // ------------------ that.updatePosition(); var distanceFromTheSunPixels = that.distanceFromTheSunMeters / physics.constants.scaleFactor; that.position = that.calculatePosition(distanceFromTheSunPixels, that.angle); that.drawstrawberry(that.position); }; that.updatePosition = function() { var currentSpeed = 0; if (that.distanceFromTheSunMeters > that.distanceFromTheSunLightSpeedOffMeters) { // Use light speed, too far fro the Sun currentSpeed = that.lightSpeedMetersPerSecond; } else { // Use normal speeed, close to the Sun currentSpeed = that.speedMetersPerSecond; } var distanceTravelledInOneFrame = currentSpeed * physics.constants.timeIncrementPerFrameInSeconds; that.distanceFromTheSunMeters -= distanceTravelledInOneFrame; }; // Return true if the strawberry has collided with the Sun that.isCollidedWithTheSun = function() { var sizeOfTheSun = 1.4 * graphics.values.currentSunsSizePixels; if (sizeOfTheSun < 50) { sizeOfTheSun = 50; } return collision.areCollided(that.position, graphics.values.center, sizeOfTheSun); }; // Return true if the strawberry has collided with the Earth that.isCollidedWithTheEarth = function() { return collision.areCollided(that.position, graphics.values.earthPosition, 2.0 * graphics.values.earthSize); }; that.drawstrawberry = function(position) { var left = (position.x - that.strawberrySizePixels / 2) + "px"; var top = (position.y - that.strawberrySizePixels / 2) + "px"; that.element.style.left = left; that.element.style.top = top; }; that.calculatePosition = function(distance, angle) { var rotationSign = that.rotationClockwise ? 1 : -1; // Add some curvature to the motion var curvature = rotationSign * Math.sin(distance / 300) * that.approachCurvature; var udatedAngle = curvature + angle; var centerX = Math.cos(udatedAngle) * distance + graphics.values.center.x; var centerY = Math.sin(-udatedAngle) * distance + graphics.values.center.y; return { x: centerX, y: centerY }; }; // Shows the strawberry element on screen that.showElement = function() { if (that.element !== null) { return; } that.element = strawberryPool.getOne(); }; // Show strawberry on screen that.show = function() { that.distanceFromTheSunMeters = that.initialDistanceFromTheSunMeters; that.angle = that.calculateNewAngle(); that.approachCurvature = that.calculateNewCurvature(); that.speedMetersPerSecond = that.calculateNewSpeed(); that.rotationClockwise = seedableRandom.getBoolean(); var rotationAngle = that.calculateNewRotationAngle(); helper.rotateElement(that.element, rotationAngle); }; /* Calculates the rotation angle for the strawberry image in degrees. Angle of 0 means the strawberry image is not rotatied. */ that.calculateNewRotationAngle = function() { var correctionDegrees = -13; // correct for the image rotation. var rotationAngle = that.angle / Math.PI * 180.0; // Convert to degrees rotationAngle = 90 - rotationAngle + correctionDegrees; return rotationAngle; }; /* Calculates a curvature multiplier for the strawberry path, a value between 0 and 5. 0 means the path is linear, and 5 means the path is highly curved. */ that.calculateNewCurvature = function() { return 5 * seedableRandom.nextValue(); }; /* Calculates an angle at which the strawberry approaches the sun, in radians. Angle of 0 means, the strawberry approaches the Sun from the right. */ that.calculateNewAngle = function() { return 2 * Math.PI * seedableRandom.nextValue(); }; /* Calculates the speed for the strawberry. The speed increases with the number of picked strawberries making the game harder. There is also a slight random variation in speed. */ that.calculateNewSpeed = function() { var speedDifficultyIncrease = 25 * strawberryCounter.values.collectedNumber; // Make every third strawberry come faster in the beginning // to prevent players from using an easy strategy of using the inner habitable zone orbit. if (strawberryCounter.values.collectedNumber < 10 && strawberryCounter.values.collectedNumber !== 0 && strawberryCounter.values.collectedNumber % 3 === 0) { speedDifficultyIncrease = 1000; } return 2500 + (1000 * seedableRandom.nextValue()) + speedDifficultyIncrease; }; that.remove = function() { if (that.element === null) { return; } strawberryPool.hideAndCache(that.element); that.element = null; }; that.init = function() { that.showElement(); that.show(); }; that.init(); return that; } // Shows the strawberries var strawberries = (function(){ var allStrawberries = [], // Currently shown strawberries // Show the "Strawberry has landed" only once shownstrawberryHasLandedOnEarthMessage = false, // Show the "Sun has been removed" message only once shownSunWasRemovedMessage = false; /* Updates the strawberry position and detects collision with the Sun or the Earth. This function is called on every frame, 60 times per second. */ function update() { if (physics.state.paused) { return; } for (var i = 0; i < allStrawberries.length; i++) { var strawberry = allStrawberries[i]; strawberry.update(); isCollidedWithSun(strawberry); isCollidedWithEarth(strawberry); } } // Check if strawberry has collided with the Sun function isCollidedWithSun(strawberry) { if (!strawberry.isCollidedWithTheSun()) { return; } userInput.removeSun(); if (!shownSunWasRemovedMessage) { physics.state.paused = true; shownSunWasRemovedMessage = true; gameoverMessage.showWithContinueButton("Greetings Earthlings! We detected an unauthorized dark energy transfer that slowed down the inflation of the Universe and triggered a cosmic real estate crisis. To restore our profits we have removed your star. We apologize for any inconvenience and wish you a good night. ~The Intergalactic Realty Association of Neighbourly Temporal Spacelords.", didTapContinueButtonAfterSunHasBeenRemoved); } } // Check if strawberry has collided with the Earth function isCollidedWithEarth(strawberry) { if (!strawberry.isCollidedWithTheEarth()) { return; } strawberryCounter.increment(); removeOneStrawberry(strawberry); if (shownstrawberryHasLandedOnEarthMessage) { addStrawberries(); } else { physics.state.paused = true; shownstrawberryHasLandedOnEarthMessage = true; gameoverMessage.showWithContinueButton("A giant strawberry-shaped object safely landed on the Earth. Its landing site became a thriving tourist attraction, where one can sip on a strawberry smoothie from a strawberry-shaped disposable cup, while perusing a vast selection of strawberry-shaped key chains, baseball caps and spaceship fresheners.", didTapContinueButtonAfterCollisionWithEarth); } } function didTapContinueButtonAfterSunHasBeenRemoved() { gameoverMessage.hide(); physics.state.paused = false; } function didTapContinueButtonAfterCollisionWithEarth() { gameoverMessage.hide(); addStrawberries(); physics.state.paused = false; } /* Start showing the first strawberry. */ function reset() { seedableRandom.reset(); currentStrawberriesToShow = 0; removeAllStrawberries(); addStrawberries(); } var currentStrawberriesToShow = 0; /* Contains the amount of strawberries to add to the screen when the given amount of picked strawberries is reached. For example ("0": 1) means that we start by showing one strawberry. When four strawberries are picked ("4": 1) we add another strawberry, now showing two in total. When five strawberries are picked ("5": -1) we remove one strawberry, showing one in total. When seven strawberries are picked ("7": 1) we add another strawberry again, showing two in total on screen. */ var dataStrawberriesToAdd = { "0": 1, // total 1 "4": 1, // total 2 "5": -1, // total 1 "7": 1, // total 2 "8": -1, // total 1 "10": 1, // total 2 "12": 1, // total 3 "13": -1, // total 2 "14": -1, // total 1 "15": 1, // total 2 "17": -1, // total 1 "20": 1, // total 2 "25": 1, // total 3 "26": -1, // total 2 "30": 1, // total 3 "34": -1, // total 2 "37": 1, // total 3 "38": -1, // total 2 "40": 1, // total 3 "42": 1, // total 4 "43": -1, // total 3 "44": -1, // total 2 "45": 1, // total 3 "47": -1, // total 2 "50": 1, // total 3 "55": 1, // total 4 "56": -1, // total 3 "60": 1, // total 4 "64": -1, // total 3 "67": 1, // total 4 "68": -1, // total 3 "70": 1, // total 4 "72": 1, // total 5 "73": -1, // total 4 "74": -1, // total 3 "75": 1, // total 4 "77": -1, // total 3 "80": 1, // total 4 "85": 1, // total 5 "86": -1 // total 4 }; // Returns the increase in the number of strawberries on screen. // 0 - same number // 1 - one more strawberry is added // -1 - the number of strawberries is reduced by one function strawberriesIncrease() { for (var numberProperty in dataStrawberriesToAdd) { if (dataStrawberriesToAdd.hasOwnProperty(numberProperty)) { var collectedNumber = parseInt(numberProperty, 10); if (strawberryCounter.values.collectedNumber === collectedNumber) { return dataStrawberriesToAdd[numberProperty]; } } } return 0; } function addStrawberries() { currentStrawberriesToShow += strawberriesIncrease(); var strawberriesToAdd = currentStrawberriesToShow - allStrawberries.length; if (strawberriesToAdd === 0 && allStrawberries.length === 0) { strawberriesToAdd = 1; } for (var i = 0; i < strawberriesToAdd; i++) { addOneStrawberry(); } } function addOneStrawberry() { var strawberry = OneStrawberry(); allStrawberries.push(strawberry); } function removeAllStrawberries() { for (var i = 0; i < allStrawberries.length; i++) { allStrawberries[i].remove(); } allStrawberries = []; } function removeOneStrawberry(strawberry) { strawberry.remove(); helper.removeFromArray(allStrawberries, strawberry); } return { reset: reset, update: update }; })(); // Draw the scene var graphics = (function() { var canvas = null, // Canvas DOM element. context = null, // Canvas context for drawing. canvasHabitableZone = null, // Habitable zone canvas DOM element contextHabitableZone = null, // Habitable zone canvas context canvasHeight = 400, colors = { orbitalPath: "#777777", habitableZoneFillColor: "#00FF00" }, previousEarthPosition = null, earthElement, sunElement, values = { center: { x: 1, y: 1 }, earthPosition: { x: 1, y: 1 }, earthSize: 25, sunsSize: 60 }; values.currentSunsSizePixels = values.sunsSize; function drawTheEarth(earthPosition) { var left = (earthPosition.x - values.earthSize/2) + "px"; var top = (earthPosition.y - values.earthSize/2) + "px"; earthElement.style.left = left; earthElement.style.top = top; } function calculateEarthPosition(distance, angle) { var centerX = Math.cos(angle) * distance + values.center.x; var centerY = Math.sin(-angle) * distance + values.center.y; return { x: centerX, y: centerY }; } // Updates the size of the Sun based on its mass. The sunMass argument is a fraction of the real Sun's mass. function updateSunSizeAndBrightness(sunMass) { // Change brightness sunElement.setAttribute("style","filter:brightness(" + sunMass + "); " + "-webkit-filter:brightness(" + sunMass + "); "); var sunsDefaultWidth = values.sunsSize; values.currentSunsSizePixels = sunsDefaultWidth * Math.pow(sunMass, 1/3); sunElement.style.width = values.currentSunsSizePixels + "px"; sunElement.style.marginLeft = -(values.currentSunsSizePixels / 2.0) + "px"; sunElement.style.marginTop = -(values.currentSunsSizePixels / 2.0) + "px"; } // Draw the habitable zone // `sunMassRatio` is a proportion of normal mass of the Sun (default is 1). function redrawHabitableZone(sunMassRatio) { habitableZone.update(sunMassRatio); contextHabitableZone.clearRect(0, 0, canvas.width, canvas.height); contextHabitableZone.fillStyle = colors.habitableZoneFillColor; contextHabitableZone.globalAlpha = 0.15; contextHabitableZone.beginPath(); contextHabitableZone.arc(values.center.x, values.center.y, habitableZone.innerDistancePixels(), 0, 2*Math.PI, true); contextHabitableZone.arc(values.center.x, values.center.y, habitableZone.outerDistancePixels(), 0, 2*Math.PI, false); contextHabitableZone.fill(); } function drawOrbitalLine(newEarthPosition) { if (previousEarthPosition === null) { previousEarthPosition = newEarthPosition; return; } context.beginPath(); context.strokeStyle = colors.orbitalPath; context.moveTo(previousEarthPosition.x, previousEarthPosition.y); context.lineTo(newEarthPosition.x, newEarthPosition.y); context.stroke(); previousEarthPosition = newEarthPosition; } // Return true if Earth has collided with the Sun function isEarthCollidedWithTheSun(earthPosition) { return collision.areCollided(earthPosition, values.center, values.currentSunsSizePixels); } // Draws the scene function drawScene(distance, angle) { values.earthPosition = calculateEarthPosition(distance, angle); drawTheEarth(values.earthPosition); drawOrbitalLine(values.earthPosition); if (isEarthCollidedWithTheSun(values.earthPosition)) { physics.state.paused = true; gameoverMessage.show("The Earth has collided with the Sun and evaporated at temperature over 5,700 degrees. It was quick and almost painless death for all life."); } } function showCanvasNotSupportedMessage() { document.getElementById("EarthOrbitSimulation-notSupportedMessage").style.display ='block'; } function calculateScreenCenter() { values.center.x = Math.floor(canvas.width / 2); values.center.y = Math.floor(canvas.height / 2); } // Resize canvas to will the width of container function fitToContainer(){ layoutCanvas(canvas, canvasHeight); layoutCanvas(canvasHabitableZone, canvasHeight); calculateScreenCenter(); } function layoutCanvas(canvasElement, height) { canvasElement.style.width = '100%'; canvasElement.style.height = height + 'px'; canvasElement.width = canvasElement.offsetWidth; canvasElement.height = canvasElement.offsetHeight; } // Returns true on error and false on success function initCanvas() { // Find the canvas HTML element canvas = document.querySelector(".EarthOrbitSimulation-canvas"); // Check if the browser supports canvas drawing if (!(window.requestAnimationFrame && canvas && canvas.getContext)) { return true; } // Get canvas context for drawing context = canvas.getContext("2d"); if (!context) { return true; } // Error, browser does not support canvas return false; } // Returns true on error and false on success function initHabitableZoneCanvas() { canvasHabitableZone = document.querySelector(".EarthOrbitSimulation-canvasHabitableZone"); // Get canvas context for drawing contextHabitableZone = canvasHabitableZone.getContext("2d"); if (!contextHabitableZone) { return true; } // Error, browser does not support canvas return false; } // Create canvas for drawing and call success argument function init(success) { if (initCanvas()) { // The browser can not use canvas. Show a warning message. showCanvasNotSupportedMessage(); return; } if (initHabitableZoneCanvas()) { // The browser can not use canvas. Show a warning message. showCanvasNotSupportedMessage(); return; } // Update the size of the canvas fitToContainer(); earthElement = document.querySelector(".EarthOrbitSimulation-earth"); sunElement = document.querySelector(".EarthOrbitSimulation-sun"); redrawHabitableZone(1); // Execute success callback function success(); } function clearScene() { context.clearRect(0, 0, canvas.width, canvas.height); previousEarthPosition = null; } return { fitToContainer: fitToContainer, drawScene: drawScene, updateSunSizeAndBrightness: updateSunSizeAndBrightness, redrawHabitableZone: redrawHabitableZone, clearScene: clearScene, values: values, init: init }; })(); // Start the simulation var simulation = (function() { // The method is called 60 times per second function animate() { physics.updatePosition(); simulationTime.update(); graphics.drawScene(physics.earthSunDistancePixels(), physics.state.angle.value); strawberries.update(); climate.update(physics.state.distance.value, habitableZone.values.innerDistanceMeters, habitableZone.values.outerDistanceMeters); window.requestAnimationFrame(animate); } function start() { graphics.init(function() { // Use the initial conditions for the simulation physics.resetStateToInitialConditions(); strawberries.reset(); gameoverMessage.init(); // Redraw the scene if page is resized window.addEventListener('resize', function(event){ graphics.fitToContainer(); graphics.clearScene(); graphics.redrawHabitableZone(physics.currentSunMassRatio()); graphics.drawScene(physics.earthSunDistancePixels(), physics.state.angle.value); }); animate(); }); } return { start: start }; })(); // React to user input var userInput = (function(){ var sunsMassElement = document.querySelector(".EarthOrbitSimulation-sunsMass"); var restartButton = document.querySelector(".EarthOrbitSimulation-reload"); var massSlider; function updateSunsMass(sliderValue) { var sunsMassValue = sliderValue * 2; if (sunsMassValue > 1) { sunsMassValue = Math.pow(5, sunsMassValue - 1); } var formattedMass = parseFloat(Math.round(sunsMassValue * 100) / 100).toFixed(2); sunsMassElement.innerHTML = formattedMass; physics.updateFromUserInput(sunsMassValue); graphics.updateSunSizeAndBrightness(sunsMassValue); graphics.redrawHabitableZone(sunsMassValue); } function didClickRestart() { gameoverMessage.hide(); strawberryCounter.reset(); physics.resetStateToInitialConditions(); graphics.clearScene(); updateSunsMass(0.5); massSlider.changePosition(0.5); climate.reset(); physics.state.paused = false; simulationTime.reset(); strawberries.reset(); massSlider.enabled = true; return false; // Prevent default click } function init() { massSlider = SickSlider(".EarthOrbitSimulation-massSlider"); massSlider.onSliderChange = updateSunsMass; massSlider.changePosition(0.5); restartButton.onclick = didClickRestart; } function removeSun() { massSlider.changePosition(0); massSlider.enabled = false; updateSunsMass(0); } return { didClickRestart: didClickRestart, removeSun: removeSun, init: init }; })(); simulation.start(); userInput.init(); })();
import React from 'react' import { Text, Animated, Easing } from 'react-native' import { StackNavigator, DrawerNavigator } from 'react-navigation' import MapComponent from '../../components/MapComponent/MapComponent' import ProfileComponent from '../../components/ProfileComponent/ProfileComponent' import LoginComponent from '../../components/LoginComponent/LoginComponent' import DrawerContainer from '../../containers/DrawerContainer' // https://github.com/react-community/react-navigation/issues/1254 const noTransitionConfig = () => ({ transitionSpec: { duration: 0, timing: Animated.timing, easing: Easing.step0 } }) // drawer stack const DrawerStack = DrawerNavigator({ screen1: { screen: MapComponent }, screen2: { screen: LoginComponent }, screen3: { screen: ProfileComponent }, }, { gesturesEnabled: false, contentComponent: DrawerContainer, drawerOpenRoute: 'DrawerOpen', drawerCloseRoute: 'DrawerClose', drawerToggleRoute: 'DrawerToggle' }) const drawerButton = (navigation) => <Text style={{padding: 5, color: 'white'}} onPress={() => { // Coming soon: navigation.navigate('DrawerToggle') // https://github.com/react-community/react-navigation/pull/2492 if (navigation.state.index === 0) { navigation.navigate('DrawerOpen') } else { navigation.navigate('DrawerClose') } } }>Menu</Text> const DrawerNavigation = StackNavigator({ DrawerStack: { screen: DrawerStack } }, { headerMode: 'float', navigationOptions: ({navigation}) => ({ headerStyle: {backgroundColor: '#4C3E54'}, title: 'Welcome!', headerTintColor: 'white', gesturesEnabled: false, headerLeft: drawerButton(navigation) }) }) // Manifest of possible screens const PrimaryNav = StackNavigator({ loginStack: { screen: DrawerNavigation }, drawerStack: { screen: DrawerNavigation } }, { // Default config for all screens headerMode: 'none', title: 'Main', initialRouteName: 'loginStack', transitionConfig: noTransitionConfig }) export default PrimaryNav
sap.ui.define([], function () { "use strict"; var oFormatter = { isNonEmpty: function (param) { if (!param) { return false; } if (typeof param === "string") { return (param.trim()) ? true : false; } }, toDateString: function (param) { if (!param instanceof Date) { return ""; } param = param.toDateString(); param = param.substr(4, 14); param = param.splice(6,0,","); return param; }, convertToPositiveNum: function (param1, param2) { if (param1) { param1 = Math.abs(param1); } else { param1 = 0; } return (param1 + param2); }, getNumericValue: function (sValue, iDecimalPlaces) { if (!sValue) { sValue = 0; } var nValue = Number(sValue); if (isNaN(nValue)) { nValue = 0; } if (iDecimalPlaces && Number.isInteger(iDecimalPlaces)) { nValue = Number(nValue.toFixed(iDecimalPlaces)); } return nValue; }, isBothTrue: function (bParam1, bParam2) { if (bParam1 === true && bParam2 === true) { return true; } else { return false; } }, getDifference: function (vNum1, vNum2) { return (Math.abs(vNum1 - vNum2)); }, setActiveLink: function (oModel) { var appointmentData = this.getView().getModel("oDateModel").getData(); var oFormatDate = oFormatter.getDateFormat(oModel); var b = new Date(oFormatDate).getTime(); var oArrSelectedAppointment = jQuery.grep(appointmentData, function (element, index) { var a = new Date(element.appointmentDate).getTime(); return (a === b); }); if (oModel.active === 'crntMonthDate') { return true; } else { return false; } }, setVisible: function (oModel) { var appointmentData = this.getView().getModel("oDateModel").getData(); var oFormatDate = oFormatter.getDateFormat(oModel); var b = new Date(oFormatDate).getTime(); var oArrSelectedAppointment = jQuery.grep(appointmentData, function (element, index) { var a = new Date(element.appointmentDate).getTime(); return (a === b); }); if (oModel.active === 'crntMonthDate' && oArrSelectedAppointment.length > 0) { return true; } else { return false; } }, getDateFormat: function (oModel) { var oReferenceDate = new Date(oModel.fullDate); var month, date, validation = true; if (validation) { if (oReferenceDate.getMonth().toString().length <= 1) { month = "0" + (oReferenceDate.getMonth() + 1); } else { month = oReferenceDate.getMonth() + 1; } if (oReferenceDate.getDate().toString().length <= 1) { date = "0" + oReferenceDate.getDate(); } else { date = oReferenceDate.getDate(); } } var oReferenceFormatDate = oReferenceDate.getFullYear() + "-" + month + "-" + date; return oReferenceFormatDate; }, setFirstText: function (oModel) { var appointmentData = this.getView().getModel("oDateModel").getData(); var oFormatDate = oFormatter.getDateFormat(oModel); var b = new Date(oFormatDate).getTime(); var oArrSelectedAppointment = jQuery.grep(appointmentData, function (element, index) { var a = new Date(element.appointmentDate).getTime(); return (a === b); }); if (oArrSelectedAppointment.length > 0) { return oArrSelectedAppointment[0].customers[0]; } else { return null; } }, setSecondText: function (oModel) { var appointmentData = this.getView().getModel("oDateModel").getData(); var oFormatDate = oFormatter.getDateFormat(oModel); var b = new Date(oFormatDate).getTime(); var oArrSelectedAppointment = jQuery.grep(appointmentData, function (element, index) { var a = new Date(element.appointmentDate).getTime(); return (a === b); }); if (oArrSelectedAppointment.length > 0 && (oArrSelectedAppointment[0].customers).length >= 1) { return oArrSelectedAppointment[0].customers[1]; } else { return null; } }, setThirdText: function (oModel) { var appointmentData = this.getView().getModel("oDateModel").getData(); var oFormatDate = oFormatter.getDateFormat(oModel); var b = new Date(oFormatDate).getTime(); var oArrSelectedAppointment = jQuery.grep(appointmentData, function (element, index) { var a = new Date(element.appointmentDate).getTime(); return (a === b); }); if (oArrSelectedAppointment.length > 0 && (oArrSelectedAppointment[0].customers).length >= 2) { return oArrSelectedAppointment[0].customers[2]; } else { return null; } }, setFourthText: function (oModel) { var appointmentData = this.getView().getModel("oDateModel").getData(); var oFormatDate = oFormatter.getDateFormat(oModel); var b = new Date(oFormatDate).getTime(); var oArrSelectedAppointment = jQuery.grep(appointmentData, function (element, index) { var a = new Date(element.appointmentDate).getTime(); return (a === b); }); if (oArrSelectedAppointment.length > 0 && (oArrSelectedAppointment[0].customers).length >= 3) { return oArrSelectedAppointment[0].customers[3]; } else { return null; } }, setFirstVisible: function (oModel) { var appointmentData = this.getView().getModel("oDateModel").getData(); var oFormatDate = oFormatter.getDateFormat(oModel); var b = new Date(oFormatDate).getTime(); var oArrSelectedAppointment = jQuery.grep(appointmentData, function (element, index) { var a = new Date(element.appointmentDate).getTime(); return (a === b); }); if (oArrSelectedAppointment.length > 0 && (oArrSelectedAppointment[0].customers).length > 1) { return true; } else { return false; } }, setButtonVisible: function (oModel) { var appointmentData = this.getView().getModel("oDateModel").getData(); var oFormatDate = oFormatter.getDateFormat(oModel); var b = new Date(oFormatDate).getTime(); var oArrSelectedAppointment = jQuery.grep(appointmentData, function (element, index) { var a = new Date(element.appointmentDate).getTime(); return (a === b); }); if (oArrSelectedAppointment.length > 0 && (oArrSelectedAppointment[0].customers).length > 4) { return true; } else { return false; } }, setSecondVisible: function (oModel) { var appointmentData = this.getView().getModel("oDateModel").getData(); var oFormatDate = oFormatter.getDateFormat(oModel); var b = new Date(oFormatDate).getTime(); var oArrSelectedAppointment = jQuery.grep(appointmentData, function (element, index) { var a = new Date(element.appointmentDate).getTime(); return (a === b); }); if (oArrSelectedAppointment.length > 0 && (oArrSelectedAppointment[0].customers).length > 3) { return true; } else { return false; } } }; return oFormatter; });
import RecognizerMixin from 'ember-gestures/mixins/recognizers'; import layout from './template'; import Component from '@ember/component'; import { computed } from '@ember/object'; import { htmlSafe } from '@ember/string'; const HorizontalSwipeView = Component.extend(RecognizerMixin, { layout: layout, classNames: ['horizontal-swipe-view', 'ember-appointment-slots-pickers'], recognizers: 'swipe', // Attributes width: 0, index: 0, onswipe: null, init() { this._super(...arguments); this.items = this.items || []; }, swipeLeft() { const onswipe = this.onswipe; return onswipe && onswipe(1); }, swipeRight() { const onswipe = this.onswipe; return onswipe && onswipe(-1); }, totalWidth: computed('items.length', 'width', function () { return this.get('items.length') * this.width; }), offset: computed('width', 'index', function () { return -1 * this.width * this.index; }), style: computed('offset', 'totalWidth', function () { const {offset, totalWidth} = this; return htmlSafe(` -ms-transform: translate3d(${offset}px,0,0); -o-transform: translate3d(${offset}px,0,0); -moz-transform: translate3d(${offset}px,0,0); -webkit-transform: translate3d(${offset}px,0,0); transform: translate3d(${offset}px,0,0); width:${totalWidth}px; `); }), styleItem: computed('width', function () { const width = this.width; return htmlSafe(`width:${width}px`); }) }); HorizontalSwipeView.reopenClass({ positionalParams: ['items'] }); export default HorizontalSwipeView;
//= require jquery //= require jquery_ujs //= require bootstrap-sprockets //= require refugee_manager //= require ../for_admin //= require_tree . /*global $, ForAdmin */ // コントローラー名からオブジェクトを取得してフックを実行する // @see http://qiita.com/naoty_k/items/d490b456e0f385942be8 $(function () { var $body = $('body'), controller = $body.data('controller').replace(/\//g, '_'), action = $body.data('action'), activeController = ForAdmin[controller]; if (activeController !== undefined) { if ($.isFunction(activeController[action])) { activeController[action](); } } });
module.exports = { purge: ['./index.html', './src/**/*.{vue,js,ts,jsx,tsx}'], darkMode: false, // or 'media' or 'class' theme: { colors: { primary: "var(--primary-colour)", primarylight: "var(--primary-colour-light)", primarydark: "var(--primary-colour-dark)", secondary: "var(--secondary-colour)", secondarylight: "var(--secondary-colour-light)", secondarydark: "var(--secondary-colour-dark)", bgdark: "var(--background-dark)", bglight: "var(--background-light)", white: "#FFF", disabled: "#a4a7ab", }, extend: {}, }, variants: { extend: {}, }, plugins: [], }
import React,{useState} from 'react' import NavBar from '../Menu/NavBar' import Footer from '../Footer/Footer' import axios from 'axios' export default props=>{ const [imagem,setImagem] = useState(); const [nomeAtivo ,setNomeAtivo] = useState(); const [descricao, setDescricao] = useState(); const [modelo, setModelo] = useState(); const [idResponsavel, setIdResponsavel] = useState(); const [nivelSaude, setNivelSaude] = useState(); const [error, setError] = useState('') const CadastrarAtivo = ()=>{ axios.post("https://empresaapi.herokuapp.com/app/ativo", { imagem: imagem, nome: nomeAtivo, descricao: descricao, modelo: modelo, usuario: idResponsavel, saudenv: nivelSaude}).then((item)=>{ console.log(item) }).catch((err)=>{ console.log(err) }) } async function HandlePost(e){ e.preventDefault() try{ setError('Cadastrado com Sucesso!') await CadastrarAtivo() }catch{ setError('Erro ao Cadastrar !') } } const HandleImagem = (e)=>{ setImagem(e.target.value) } const HandleNomeAtivo = (e)=>{ setNomeAtivo(e.target.value) } const HandleDescricao = (e)=>{ setDescricao(e.target.value) } const HandleModelo = (e)=>{ setModelo(e.target.value) } const HandleIdResponsavel = (e)=>{ setIdResponsavel(e.target.value) } const HandleNivelSaude = (e)=>{ setNivelSaude(e.target.value) } return( <div> <NavBar></NavBar> <div> <h1>CADASTRAR ATIVO</h1> <form onSubmit={HandlePost}> <div class="form-group"> <label for="exampleInputEmail1">Imagem</label> <input type="text" class="form-control" onChange={HandleImagem} placeholder="insira a imagem"></input> </div> <div class="form-group"> <label for="exampleInputPassword1">Nome do Ativo</label> <input type="text" class="form-control" onChange={HandleNomeAtivo} placeholder="Digite o nome do Ativo"></input> </div> <div class="form-group"> <label for="exampleInputPassword1">Descrição do Ativo</label> <input type="text" class="form-control" onChange={HandleDescricao} placeholder="Digite a descrição do Ativo"></input> </div> <div class="form-group"> <label for="exampleInputEmail1">Modelo</label> <input type="text" class="form-control" onChange={HandleModelo} placeholder="Digite o nome do modelo"></input> </div> <div class="form-group"> <label for="exampleInputPassword1">Responsável pelo Ativo (Insira o ID do Funcionario)</label> <input type="text" class="form-control" onChange={HandleIdResponsavel} placeholder="Digite o nome completo do resposavel"></input> </div> <div class="form-group"> <label for="exampleInputPassword1">Nivel de Saude (Não precisa usar o simbolo %, use numeros inteiros)</label> <input type="number" class="form-control" onChange={HandleNivelSaude} placeholder="Digite o Nivel de saude da unidade em porcentagem"></input> </div> <div className="alert alert-warning" role="alert"> <h1>{error}</h1> </div> <button type="submit" class="btn btn-primary">Cadastrar</button> </form> </div> <Footer></Footer> </div> ) }
import { TOGGLE_CART_HIDDEN, ADD_ITEM, REMOVE_ITEM, DECREASE_ITEM_QUANTITY } from '../types'; import { addItemToCart, removeItemFromCart } from './cartUtils'; const initialState = { hidden: true, cartItems: [] }; function cartReducer(state = initialState, action) { const { type, payload } = action; switch (type) { case TOGGLE_CART_HIDDEN: return { ...state, hidden: payload || !state.hidden }; case ADD_ITEM: return { ...state, cartItems: addItemToCart(state.cartItems, payload) }; case DECREASE_ITEM_QUANTITY: return { ...state, cartItems: removeItemFromCart(state.cartItems, payload) }; case REMOVE_ITEM: return { ...state, cartItems: state.cartItems.filter(item => item.id !== payload.id) }; default: return state; } } export default cartReducer;
const Sequelize = require('sequelize'); module.exports = function(sequelize, DataTypes) { return sequelize.define('SalesOrderPayment', { entity_id: { autoIncrement: true, type: DataTypes.INTEGER.UNSIGNED, allowNull: false, primaryKey: true, comment: "Entity ID" }, parent_id: { type: DataTypes.INTEGER.UNSIGNED, allowNull: false, comment: "Parent ID", references: { model: 'sales_order', key: 'entity_id' } }, base_shipping_captured: { type: DataTypes.DECIMAL(20,4), allowNull: true, comment: "Base Shipping Captured" }, shipping_captured: { type: DataTypes.DECIMAL(20,4), allowNull: true, comment: "Shipping Captured" }, amount_refunded: { type: DataTypes.DECIMAL(20,4), allowNull: true, comment: "Amount Refunded" }, base_amount_paid: { type: DataTypes.DECIMAL(20,4), allowNull: true, comment: "Base Amount Paid" }, amount_canceled: { type: DataTypes.DECIMAL(20,4), allowNull: true, comment: "Amount Canceled" }, base_amount_authorized: { type: DataTypes.DECIMAL(20,4), allowNull: true, comment: "Base Amount Authorized" }, base_amount_paid_online: { type: DataTypes.DECIMAL(20,4), allowNull: true, comment: "Base Amount Paid Online" }, base_amount_refunded_online: { type: DataTypes.DECIMAL(20,4), allowNull: true, comment: "Base Amount Refunded Online" }, base_shipping_amount: { type: DataTypes.DECIMAL(20,4), allowNull: true, comment: "Base Shipping Amount" }, shipping_amount: { type: DataTypes.DECIMAL(20,4), allowNull: true, comment: "Shipping Amount" }, amount_paid: { type: DataTypes.DECIMAL(20,4), allowNull: true, comment: "Amount Paid" }, amount_authorized: { type: DataTypes.DECIMAL(20,4), allowNull: true, comment: "Amount Authorized" }, base_amount_ordered: { type: DataTypes.DECIMAL(20,4), allowNull: true, comment: "Base Amount Ordered" }, base_shipping_refunded: { type: DataTypes.DECIMAL(20,4), allowNull: true, comment: "Base Shipping Refunded" }, shipping_refunded: { type: DataTypes.DECIMAL(20,4), allowNull: true, comment: "Shipping Refunded" }, base_amount_refunded: { type: DataTypes.DECIMAL(20,4), allowNull: true, comment: "Base Amount Refunded" }, amount_ordered: { type: DataTypes.DECIMAL(20,4), allowNull: true, comment: "Amount Ordered" }, base_amount_canceled: { type: DataTypes.DECIMAL(20,4), allowNull: true, comment: "Base Amount Canceled" }, quote_payment_id: { type: DataTypes.INTEGER, allowNull: true, comment: "Quote Payment ID" }, additional_data: { type: DataTypes.TEXT, allowNull: true, comment: "Additional Data" }, cc_exp_month: { type: DataTypes.STRING(12), allowNull: true, comment: "Cc Exp Month" }, cc_ss_start_year: { type: DataTypes.STRING(12), allowNull: true, comment: "Cc Ss Start Year" }, echeck_bank_name: { type: DataTypes.STRING(128), allowNull: true, comment: "Echeck Bank Name" }, method: { type: DataTypes.STRING(128), allowNull: true, comment: "Method" }, cc_debug_request_body: { type: DataTypes.STRING(32), allowNull: true, comment: "Cc Debug Request Body" }, cc_secure_verify: { type: DataTypes.STRING(32), allowNull: true, comment: "Cc Secure Verify" }, protection_eligibility: { type: DataTypes.STRING(32), allowNull: true, comment: "Protection Eligibility" }, cc_approval: { type: DataTypes.STRING(32), allowNull: true, comment: "Cc Approval" }, cc_last_4: { type: DataTypes.STRING(100), allowNull: true, comment: "Cc Last 4" }, cc_status_description: { type: DataTypes.STRING(32), allowNull: true, comment: "Cc Status Description" }, echeck_type: { type: DataTypes.STRING(32), allowNull: true, comment: "Echeck Type" }, cc_debug_response_serialized: { type: DataTypes.STRING(32), allowNull: true, comment: "Cc Debug Response Serialized" }, cc_ss_start_month: { type: DataTypes.STRING(128), allowNull: true, comment: "Cc Ss Start Month" }, echeck_account_type: { type: DataTypes.STRING(255), allowNull: true, comment: "Echeck Account Type" }, last_trans_id: { type: DataTypes.STRING(255), allowNull: true, comment: "Last Trans ID" }, cc_cid_status: { type: DataTypes.STRING(32), allowNull: true, comment: "Cc Cid Status" }, cc_owner: { type: DataTypes.STRING(128), allowNull: true, comment: "Cc Owner" }, cc_type: { type: DataTypes.STRING(32), allowNull: true, comment: "Cc Type" }, po_number: { type: DataTypes.STRING(32), allowNull: true, comment: "Po Number" }, cc_exp_year: { type: DataTypes.STRING(4), allowNull: true, comment: "Cc Exp Year" }, cc_status: { type: DataTypes.STRING(4), allowNull: true, comment: "Cc Status" }, echeck_routing_number: { type: DataTypes.STRING(32), allowNull: true, comment: "Echeck Routing Number" }, account_status: { type: DataTypes.STRING(32), allowNull: true, comment: "Account Status" }, anet_trans_method: { type: DataTypes.STRING(32), allowNull: true, comment: "Anet Trans Method" }, cc_debug_response_body: { type: DataTypes.STRING(32), allowNull: true, comment: "Cc Debug Response Body" }, cc_ss_issue: { type: DataTypes.STRING(32), allowNull: true, comment: "Cc Ss Issue" }, echeck_account_name: { type: DataTypes.STRING(32), allowNull: true, comment: "Echeck Account Name" }, cc_avs_status: { type: DataTypes.STRING(32), allowNull: true, comment: "Cc Avs Status" }, cc_number_enc: { type: DataTypes.STRING(128), allowNull: true }, cc_trans_id: { type: DataTypes.STRING(32), allowNull: true, comment: "Cc Trans ID" }, address_status: { type: DataTypes.STRING(32), allowNull: true, comment: "Address Status" }, additional_information: { type: DataTypes.TEXT, allowNull: true, comment: "Additional Information" } }, { sequelize, tableName: 'sales_order_payment', timestamps: false, indexes: [ { name: "PRIMARY", unique: true, using: "BTREE", fields: [ { name: "entity_id" }, ] }, { name: "SALES_ORDER_PAYMENT_PARENT_ID", using: "BTREE", fields: [ { name: "parent_id" }, ] }, ] }); };
import "./styles.css"; import { Button } from "../../components"; import { useParams } from "react-router-dom"; import { data } from "../../data"; // context import { useContextValue } from "../../useContext"; import { addToCart } from "../../useContext/actions"; const Product = () => { const { dispatch } = useContextValue(); const { id } = useParams(); const product = data.find(product => product.id === +id); const { img, company, name, info, price } = product; return ( <div className='product'> <div className='container'> <div className='product__product-Wrapper'> <img src={"/" + img} alt='img-products' className='product__img' /> <div className='product__details'> <p className='product__compony'>{company}</p> <p className='product__info'> Name product: <span>{name}</span> </p> <p className='product__info'>Description:</p> <p>{info}</p> <p className='product__info'> price<span> ${price}</span> </p> <Button className='button--bg-dark' onClick={() => dispatch(addToCart(product))} > Add </Button> </div> </div> </div> </div> ); }; export default Product;
import React, { Component } from 'react'; import { Text, View, Image, StyleSheet, } from 'react-native'; export default class Icon extends Component { render() { const { size = 26, title, subtitle, style, iconStyle, titleStyle, subtitleStyle, source, onLayout, } = this.props; return ( <View style={[styles.container, style]} onLayout={evt => onLayout && onLayout(evt)}> <Image source={source} style={[{ width: size, height: size }, iconStyle]} /> { title ? typeof title === 'string' ? <Text style={[styles.title, titleStyle]}>{title}</Text> : title : null } { subtitle ? typeof title === 'string' ? <Text style={[styles.subtitle, subtitleStyle]}>{subtitle}</Text> : subtitle : null } </View> ); } } const styles = StyleSheet.create({ container: { justifyContent: 'center', alignItems: 'center', }, title: { color: '#222', fontSize: 14, }, subtitle: { color: '#999', fontSize: 12, }, });
function checkAllBoxes() { if ( $('#checkAll').prop('checked') == true ) { $('.itemBox').prop('checked',true); } else { $('.itemBox').prop('checked',false); } }
import React, {Component} from 'react' import {Form, Input, Icon, Button, message} from 'antd' class Login extends Component { render() { return ( <div> Login </div> ) } } // const newLogin = Form.create()(Login); // export default newLogin; export default Login;
var map; function initMap() { var userLocation = new google.maps.LatLng(userLat, userLng); var map = new google.maps.Map(document.getElementById('map'), { center: userLocation, zoom: 14 }); // The followings: One pop-up window about the name and location of the stop // for each of them. var mainStWindow = new google.maps.InfoWindow({ content: mainStString }); var gilmanStWindow = new google.maps.InfoWindow({ content: gilmanStString }); var diamondWindow = new google.maps.InfoWindow({ content: diamondString }); var davisWindow = new google.maps.InfoWindow({ content: davisString }); // Sets he icon as the shuttle stop markers var markerImageAnchorPt = new google.maps.Point(10, 10); var markerIcon = { url: 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png', labelOrigin: markerImageAnchorPt }; var mainStMarker = new google.maps.Marker({ position: mainStLatLng, map: map, icon: markerIcon, label: { text: 'M', color: '#0000FF', fontWeight: 'bold' } }); var gilmanStMarker = new google.maps.Marker({ position: gilmanStLatLng, map: map, icon: markerIcon, label: { text: 'G', color: '#0000FF', fontWeight: 'bold' } }); var diamondStMarker = new google.maps.Marker({ position: diamondLatLng, map: map, icon: markerIcon, label: { text: 'D', color: '#0000FF', fontWeight: 'bold' } }); var davisStMarker = new google.maps.Marker({ position: davisLatLng, map: map, icon: markerIcon, label: { text: 'D', color: '#0000FF', fontWeight: 'bold' } }); // The following: Adds event listeners to each marker, so that they can // respond to user clicking. mainStMarker.addListener('click', function() { mainStWindow.open(map, mainStMarker); }); gilmanStMarker.addListener('click', function() { gilmanStWindow.open(map, gilmanStMarker); }); diamondStMarker.addListener('click', function() { diamondWindow.open(map, diamondStMarker); }); davisStMarker.addListener('click', function() { davisWindow.open(map, davisStMarker); }); // Draw an arrow symbol to indicate the shuttle location var shuttleSymbol = { path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW, scale: 4, fillColor: '#5555FF', fillOpacity: 0.7, strokeWeight: 2, strokeColor: '#000000', strokeOpacity: 1 }; // Draw the route of the shuttle from the list of locations in GoogleMapsVariables.js var shuttlePath = new google.maps.Polyline({ path: shuttleCoords, icons: [{ icon: shuttleSymbol, offset: '100%' }], geodesic: true, strokeColor: '#00FF00', strokeOpacity: 0.5, strokeWeight: 5 }); shuttlePath.setMap(map); /* * Animates the shuttle marker along the path, but only runs if it's a * weekday, and it's during operation time (7:45 am -- 6:00 pm). * Test code: Substitute line with "var d = new Date()" with the following: var d = new Date(2017, 10, 22, 7, 44, 59, 0); * Notice: The following functions have to be defined within the initialization * method of the map, otherwise bugs would occur. We blame Google for this. */ function animateShuttlePath() { // var d = new Date(); // Obtain the current date and time // if (isOperationHour(d)) { // // If it's not the operation time right now, double-check after 10 seconds. // setTimeout(animateShuttlePath, 10000); // } else { // animateCircle(shuttlePath); // } if (isRunning) { animateCircle(shuttlePath); } else { // If it's not the operation time right now, double-check after 10 seconds. setTimeout(animateShuttlePath, 10000); } } // This method checks if the user has allowed the location query, // and if so, displays the user location on the map. function addUserLocationMarker() { if (geoLocationFunctionOn === 1) { // If the user allows access to location, update the userLocation, // and add a marker for the location on the map. userLocation = new google.maps.LatLng(userLat, userLng); var userLocationMarker = new google.maps.Marker({ position: userLocation, map: map }); userLocationMarker.setMap(map); } else if (geoLocationFunctionOn === 0) { // Keep calling this method until the user allows or blocks the // the access to the current location setTimeout(addUserLocationMarker, 500); } } animateShuttlePath(); addUserLocationMarker(); } // Animates the marker for the shuttle along the predefined route. // To change speed: adjust speedOfMarker and markerUpdateIntervalMS // Source: https://developers.google.com/maps/documentation/javascript/examples/overlay-symbol-animate function animateCircle(line) { var updateTimeCount = 0; var speedOfMarker = 30; var markerUpdateIntervalMS = 200; window.setInterval(function() { updateTimeCount = (updateTimeCount+1)%(speedOfMarker*100); var icons = line.get('icons'); icons[0].offset = (updateTimeCount/speedOfMarker) + '%'; line.set('icons', icons); }, markerUpdateIntervalMS); }
import React from 'react' import "../App.css" import homeImage from '../images/home_img.svg' import { NavLink } from 'react-router-dom' export default function Home() { return ( <div className="home-container"> <div className="home-container-left"> <img className="home-image" src={homeImage} /> </div> <div className="home-container-right"> <div className="d-grid gap-2 col-6 mx-auto"> <NavLink to="/server" className="btn btn-primary text-light" type="button">je suis un coiffeur</NavLink> <NavLink to="/client" className="btn btn-outline-primary" type="button">je veux me coiffer</NavLink> </div> </div> </div> ) }
/* jshint browser: true */ /* jshint unused: false */ /* global $, Joi, frontendConfig, arangoHelper, _, Backbone, templateEngine, window */ (function () { 'use strict'; window.ViewsView = Backbone.View.extend({ el: '#content', readOnly: false, template: templateEngine.createTemplate('viewsView.ejs'), initialize: function () { }, refreshRate: 10000, sortOptions: { desc: false }, searchString: '', remove: function () { this.$el.empty().off(); /* off to unbind the events */ this.stopListening(); this.unbind(); delete this.el; return this; }, events: { 'click #createView': 'createView', 'click #viewsToggle': 'toggleSettingsDropdown', 'click .tile-view': 'gotoView', 'keyup #viewsSearchInput': 'search', 'click #viewsSearchSubmit': 'search', 'click #viewsSortDesc': 'sorting' }, checkVisibility: function () { if ($('#viewsDropdown').is(':visible')) { this.dropdownVisible = true; } else { this.dropdownVisible = false; } arangoHelper.setCheckboxStatus('#viewsDropdown'); }, checkIfInProgress: function () { if (window.location.hash.search('views') > -1) { var self = this; var callback = function (error, lockedViews) { if (error) { console.log('Could not check locked views'); } else { if (lockedViews.length > 0) { _.each(lockedViews, function (foundView) { if ($('#' + foundView.collection)) { // found view html container $('#' + foundView.collection + ' .collection-type-icon').removeClass('fa-clone'); $('#' + foundView.collection + ' .collection-type-icon').addClass('fa-spinner').addClass('fa-spin'); } else { $('#' + foundView.collection + ' .collection-type-icon').addClass('fa-clone'); $('#' + foundView.collection + ' .collection-type-icon').removeClass('fa-spinner').removeClass('fa-spin'); } }); } else { // if no view found at all, just reset all to default $('.tile .collection-type-icon').addClass('fa-clone').removeClass('fa-spinner').removeClass('fa-spin'); } window.setTimeout(function () { self.checkIfInProgress(); }, self.refreshRate); } }; if (!frontendConfig.ldapEnabled) { window.arangoHelper.syncAndReturnUnfinishedAardvarkJobs('view', callback); } } }, sorting: function () { if ($('#viewsSortDesc').is(':checked')) { this.setSortingDesc(true); } else { this.setSortingDesc(false); } this.checkVisibility(); this.render(); }, setSortingDesc: function (yesno) { this.sortOptions.desc = yesno; }, search: function () { this.setSearchString(arangoHelper.escapeHtml($('#viewsSearchInput').val())); this.render(); }, toggleSettingsDropdown: function () { var self = this; // apply sorting to checkboxes $('#viewsSortDesc').attr('checked', this.sortOptions.desc); $('#viewsToggle').toggleClass('activated'); $('#viewsDropdown2').slideToggle(200, function () { self.checkVisibility(); }); }, render: function (data) { var self = this; if (data) { self.$el.html(self.template.render({ views: self.applySorting(data.result), searchString: self.getSearchString() })); } else { this.getViews(); this.$el.html(this.template.render({ views: [], searchString: self.getSearchString() })); } if (self.dropdownVisible === true) { $('#viewsSortDesc').attr('checked', self.sortOptions.desc); $('#viewsToggle').addClass('activated'); $('#viewsDropdown2').show(); } $('#viewsSortDesc').attr('checked', self.sortOptions.desc); arangoHelper.setCheckboxStatus('#viewsDropdown'); var searchInput = $('#viewsSearchInput'); var strLength = searchInput.val().length; searchInput.focus(); searchInput[0].setSelectionRange(strLength, strLength); arangoHelper.checkDatabasePermissions(this.setReadOnly.bind(this)); }, setReadOnly: function () { this.readOnly = true; $('#createView').parent().parent().addClass('disabled'); }, setSearchString: function (string) { this.searchString = string; }, getSearchString: function () { return this.searchString.toLowerCase(); }, applySorting: function (data) { var self = this; // default sorting order data = _.sortBy(data, 'name'); // desc sorting order if (this.sortOptions.desc) { data = data.reverse(); } var toReturn = []; if (this.getSearchString() !== '') { _.each(data, function (view, key) { if (view && view.name) { if (view.name.toLowerCase().indexOf(self.getSearchString()) !== -1) { toReturn.push(view); } } }); } else { return data; } return toReturn; }, gotoView: function (e) { var name = $(e.currentTarget).attr('id'); if (name) { var url = 'view/' + encodeURIComponent(name); window.App.navigate(url, {trigger: true}); } }, getViews: function () { var self = this; this.collection.fetch({ success: function (data) { var res = { result: [] }; self.collection.each(function (view) { res.result.push(view.toJSON()); }); self.render(res); self.checkIfInProgress(); }, error: function (error) { console.log(error); } }); }, createView: function (e) { if (!this.readOnly) { e.preventDefault(); this.createViewModal(); } }, createViewModal: function () { var buttons = []; var tableContent = []; tableContent.push( window.modalView.createTextEntry( 'newName', 'Name', '', false, 'Name', true, [ { rule: Joi.string().regex(/^[a-zA-Z0-9\-_]*$/), msg: 'Only symbols, "_" and "-" are allowed.' }, { rule: Joi.string().required(), msg: 'No view name given.' } ] ) ); tableContent.push( window.modalView.createReadOnlyEntry( undefined, 'Type', 'arangosearch', undefined, undefined, false, undefined ) ); buttons.push( window.modalView.createSuccessButton('Create', this.submitCreateView.bind(this)) ); window.modalView.show('modalTable.ejs', 'Create New View', buttons, tableContent); }, submitCreateView: function () { var self = this; var name = $('#newName').val(); var options = JSON.stringify({ name: name, type: 'arangosearch', properties: {} }); $.ajax({ type: 'POST', cache: false, url: arangoHelper.databaseUrl('/_api/view'), contentType: 'application/json', processData: false, data: options, success: function (data) { window.modalView.hide(); arangoHelper.arangoNotification('View', 'Creation in progress. This may take a while.'); self.getViews(); }, error: function (error) { if (error.responseJSON && error.responseJSON.errorMessage) { arangoHelper.arangoError('Views', error.responseJSON.errorMessage); } } }); } }); }());
function Career() { return ( <section className='relative border-t border-gray-200 dark:border-gray-800'> {/* Background gradient */} <div className='absolute inset-0 opacity-25 pointer-events-none bg-gradient-to-b from-gray-100 to-white dark:from-gray-800 dark:to-gray-900' aria-hidden='true'></div> {/* End background gradient */} <div className='relative max-w-6xl px-4 mx-auto sm:px-6'> <div className='py-12 md:py-20'> {/* Section header */} <div className='max-w-3xl pb-12 mx-auto text-center md:pb-20'> <h2 className='mb-4 h2 font-red-hat-display'> Explore roles at Appy’s offices around the world </h2> <p className='text-xl text-gray-600 dark:text-gray-400'> Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est. </p> </div> {/* Section content */} <div className='lg:flex lg:items-start lg:justify-between'> {/* Job categories */} <div className='flex-grow max-w-xs mx-auto sm:max-w-lg md:max-w-3xl lg:mx-0 lg:order-1'> <div className='grid gap-4 sm:grid-cols-2 md:grid-cols-3 sm:gap-6'> {/* 1st job item */} <a className='block group' href='#0'> <div className='relative h-0 pb-9/16 sm:pb-1/1'> <img className='absolute inset-0 object-cover w-full h-full' src={require('../images/career-01.jpg').default} width='240' height='240' alt='Career 01' /> <div className='absolute inset-0 opacity-75 bg-gradient-to-t from-gray-900' aria-hidden='true'></div> <div className='absolute bottom-0 left-0 right-0 m-4 text-center text-white'> <h4 className='text-lg font-bold tracking-tight break-words font-red-hat-display'> Development </h4> <div className='text-sm italic opacity-70'>4 Positions</div> </div> </div> </a> {/* 2nd job item */} <a className='block group' href='#0'> <div className='relative h-0 pb-9/16 sm:pb-1/1'> <img className='absolute inset-0 object-cover w-full h-full' src={require('../images/career-02.jpg').default} width='240' height='240' alt='Career 02' /> <div className='absolute inset-0 opacity-75 bg-gradient-to-t from-gray-900' aria-hidden='true'></div> <div className='absolute bottom-0 left-0 right-0 m-4 text-center text-white'> <h4 className='text-lg font-bold tracking-tight break-words font-red-hat-display'> Product & Design </h4> <div className='text-sm italic opacity-70'>10 Positions</div> </div> </div> </a> {/* 3rd job item */} <a className='block group' href='#0'> <div className='relative h-0 pb-9/16 sm:pb-1/1'> <img className='absolute inset-0 object-cover w-full h-full' src={require('../images/career-03.jpg').default} width='240' height='240' alt='Career 03' /> <div className='absolute inset-0 opacity-75 bg-gradient-to-t from-gray-900' aria-hidden='true'></div> <div className='absolute bottom-0 left-0 right-0 m-4 text-center text-white'> <h4 className='text-lg font-bold tracking-tight break-words font-red-hat-display'> Marketing </h4> <div className='text-sm italic opacity-70'>2 Positions</div> </div> </div> </a> {/* 4th job item */} <a className='block group' href='#0'> <div className='relative h-0 pb-9/16 sm:pb-1/1'> <img className='absolute inset-0 object-cover w-full h-full' src={require('../images/career-04.jpg').default} width='240' height='240' alt='Career 04' /> <div className='absolute inset-0 opacity-75 bg-gradient-to-t from-gray-900' aria-hidden='true'></div> <div className='absolute bottom-0 left-0 right-0 m-4 text-center text-white'> <h4 className='text-lg font-bold tracking-tight break-words font-red-hat-display'> Data Science </h4> <div className='text-sm italic opacity-70'>4 Positions</div> </div> </div> </a> {/* 5th job item */} <a className='block group' href='#0'> <div className='relative h-0 pb-9/16 sm:pb-1/1'> <img className='absolute inset-0 object-cover w-full h-full' src={require('../images/career-05.jpg').default} width='240' height='240' alt='Career 05' /> <div className='absolute inset-0 opacity-75 bg-gradient-to-t from-gray-900' aria-hidden='true'></div> <div className='absolute bottom-0 left-0 right-0 m-4 text-center text-white'> <h4 className='text-lg font-bold tracking-tight break-words font-red-hat-display'> Internal Systems </h4> <div className='text-sm italic opacity-70'>0 Positions</div> </div> </div> </a> {/* 6th job item */} <a className='block group' href='#0'> <div className='relative h-0 pb-9/16 sm:pb-1/1'> <img className='absolute inset-0 object-cover w-full h-full' src={require('../images/career-06.jpg').default} width='240' height='240' alt='Career 06' /> <div className='absolute inset-0 opacity-75 bg-gradient-to-t from-gray-900' aria-hidden='true'></div> <div className='absolute bottom-0 left-0 right-0 m-4 text-center text-white'> <h4 className='text-lg font-bold tracking-tight break-words font-red-hat-display'> Administrative </h4> <div className='text-sm italic opacity-70'>0 Positions</div> </div> </div> </a> </div> </div> {/* Locations links */} <div className='max-w-lg mx-auto mt-8 lg:w-64 lg:mt-0 lg:ml-0 lg:mr-6'> <h3 className='mb-4 text-lg font-bold tracking-tight text-center lg:text-left'> Locations </h3> <ul className='flex flex-wrap justify-center -mx-3 -my-1 font-medium lg:flex-col lg:justify-start lg:mx-0'> <li className='px-3 py-1 lg:px-0'> <a className='flex items-center text-teal-500' href='#0'> <svg className='flex-shrink-0 w-4 h-4 mr-3 text-gray-400 fill-current dark:text-gray-500' viewBox='0 0 16 16' xmlns='http://www.w3.org/2000/svg'> <path d='M7.3 8.7c-.4-.4-.4-1 0-1.4l7-7c.4-.4 1-.4 1.4 0 .4.4.4 1 0 1.4l-7 7c-.4.4-1 .4-1.4 0zM7.3 14.7c-.4-.4-.4-1 0-1.4l7-7c.4-.4 1-.4 1.4 0 .4.4.4 1 0 1.4l-7 7c-.4.4-1 .4-1.4 0zM.3 9.7c-.4-.4-.4-1 0-1.4l7-7c.4-.4 1-.4 1.4 0 .4.4.4 1 0 1.4l-7 7c-.4.4-1 .4-1.4 0z' /> </svg> <span>All locations (44)</span> </a> </li> <li className='px-3 py-1 lg:px-0'> <a className='flex items-center text-gray-600 dark:text-gray-400 hover:text-teal-500' href='#0'> <svg className='flex-shrink-0 w-4 h-4 mr-3 text-gray-400 fill-current dark:text-gray-500' viewBox='0 0 16 16' xmlns='http://www.w3.org/2000/svg'> <path d='M7.3 8.7c-.4-.4-.4-1 0-1.4l7-7c.4-.4 1-.4 1.4 0 .4.4.4 1 0 1.4l-7 7c-.4.4-1 .4-1.4 0zM7.3 14.7c-.4-.4-.4-1 0-1.4l7-7c.4-.4 1-.4 1.4 0 .4.4.4 1 0 1.4l-7 7c-.4.4-1 .4-1.4 0zM.3 9.7c-.4-.4-.4-1 0-1.4l7-7c.4-.4 1-.4 1.4 0 .4.4.4 1 0 1.4l-7 7c-.4.4-1 .4-1.4 0z' /> </svg> <span>London, UK (14)</span> </a> </li> <li className='px-3 py-1 lg:px-0'> <a className='flex items-center text-gray-600 dark:text-gray-400 hover:text-teal-500' href='#0'> <svg className='flex-shrink-0 w-4 h-4 mr-3 text-gray-400 fill-current dark:text-gray-500' viewBox='0 0 16 16' xmlns='http://www.w3.org/2000/svg'> <path d='M7.3 8.7c-.4-.4-.4-1 0-1.4l7-7c.4-.4 1-.4 1.4 0 .4.4.4 1 0 1.4l-7 7c-.4.4-1 .4-1.4 0zM7.3 14.7c-.4-.4-.4-1 0-1.4l7-7c.4-.4 1-.4 1.4 0 .4.4.4 1 0 1.4l-7 7c-.4.4-1 .4-1.4 0zM.3 9.7c-.4-.4-.4-1 0-1.4l7-7c.4-.4 1-.4 1.4 0 .4.4.4 1 0 1.4l-7 7c-.4.4-1 .4-1.4 0z' /> </svg> <span>Milan, Italy (22)</span> </a> </li> <li className='px-3 py-1 lg:px-0'> <a className='flex items-center text-gray-600 dark:text-gray-400 hover:text-teal-500' href='#0'> <svg className='flex-shrink-0 w-4 h-4 mr-3 text-gray-400 fill-current dark:text-gray-500' viewBox='0 0 16 16' xmlns='http://www.w3.org/2000/svg'> <path d='M7.3 8.7c-.4-.4-.4-1 0-1.4l7-7c.4-.4 1-.4 1.4 0 .4.4.4 1 0 1.4l-7 7c-.4.4-1 .4-1.4 0zM7.3 14.7c-.4-.4-.4-1 0-1.4l7-7c.4-.4 1-.4 1.4 0 .4.4.4 1 0 1.4l-7 7c-.4.4-1 .4-1.4 0zM.3 9.7c-.4-.4-.4-1 0-1.4l7-7c.4-.4 1-.4 1.4 0 .4.4.4 1 0 1.4l-7 7c-.4.4-1 .4-1.4 0z' /> </svg> <span>New York, NYC (4)</span> </a> </li> <li className='px-3 py-1 lg:px-0'> <a className='flex items-center text-gray-600 dark:text-gray-400 hover:text-teal-500' href='#0'> <svg className='flex-shrink-0 w-4 h-4 mr-3 text-gray-400 fill-current dark:text-gray-500' viewBox='0 0 16 16' xmlns='http://www.w3.org/2000/svg'> <path d='M7.3 8.7c-.4-.4-.4-1 0-1.4l7-7c.4-.4 1-.4 1.4 0 .4.4.4 1 0 1.4l-7 7c-.4.4-1 .4-1.4 0zM7.3 14.7c-.4-.4-.4-1 0-1.4l7-7c.4-.4 1-.4 1.4 0 .4.4.4 1 0 1.4l-7 7c-.4.4-1 .4-1.4 0zM.3 9.7c-.4-.4-.4-1 0-1.4l7-7c.4-.4 1-.4 1.4 0 .4.4.4 1 0 1.4l-7 7c-.4.4-1 .4-1.4 0z' /> </svg> <span>Berlin, DE (12)</span> </a> </li> </ul> </div> </div> </div> </div> </section> ); } export default Career;
'use strict'; const response = require('../res'); const connection = require('../conn'); const bcrypt = require('bcrypt'); const jwt = require('jsonwebtoken'); const config = require('../config'); exports.me = function(req, res) { const token = req.headers['x-access-token'] if (!token) return res.status(400).json({type: 'error', message: 'x-access-token header tidak ditemukan.'}) jwt.verify(token, config.jwtToken, (error, result) => { if (error) return res.status(403).json({type: 'error', message: 'Token yang diberikan salah.', error}) return res.json({ type: 'success', message: 'token yang diberikan benar.', result }) }) }; exports.login = function(req, res) { const email = req.body.email const password = req.body.password connection.query('SELECT * FROM v_users where email=?', email, function (error, rows, fields){ if(error){ console.log(error) } else{ if (rows.length == 0) return res.status(403).json({type: 'error', message: 'User tidak ditemukan'}) const user = rows[0] bcrypt.compare(password, user.password, (error, result) => { if (error) return res.status(500).json({type: 'error', message: 'enkripsi error', error}) if (result) { res.json({ type: 'success', message: 'User berhasil login', user: {id: user.id, email: user.email, nama:user.nama, roleuser:user.role, bkdid:user.bkdid}, token: jwt.sign({id: user.id, email: user.email}, config.jwtToken, {expiresIn: '7d'}) }) } else return res.status(403).json({type: 'error', message: 'Password salah.'}) }) } }); };
let linkedList = require('./LinkedList'); let list = new linkedList(1); function deleteMiddleNode(list, nodeToDelete){ let runner = list.head; while(runner.data !== nodeToDelete){ runner=runner.next; } if (runner.next){ runner.data = runner.next.data; runner.next = runner.next.next; } } list.appendFromArray([1, 2, 2, 3, 4, 9,100, 10, 3, 3, 3, 3, 1]); deleteMiddleNode(list,100) console.log(list.printList())
/**************************constructeur***********************/ var Player= function(x, y, vx, vy, width, height, color) { this.x= x; this.y= y; this.vx= vx; this.vy=vy; this.width= width; this.height= height; this.color= color; this.draw= function() //dessiner l'Payer { ctx.fillStyle=this.color; ctx.fillRect(this.x, this.y, this.width, this.height); }; };
let days = ['mon', 'tue', 'wed', 'thu', 'sat']; let res = days.splice(1,3, 'sun', 'fri') // n에서 m 까지 요소 대체 console.log(days) console.log(res) // n에서 m까지 반환 // slice(n,m) n부터 m까지 반환 // concat(arr) 합쳐 새배열 반환 let dd = ['cat', 'louis', 'lulu', 'dog'] // arr는 보통 안 씀 dd.forEach((item, idx, arr) => { console.log(`${idx+1}. ${item}`) }) console.log(dd.indexOf('louis')) console.log(dd.includes('teemo')) let arr = [1,2,3,4,5] let result = arr.find((item) => { return item % 2 === 0; }) console.log(result) // 첫번째 요소만 반환 result = arr.filter((item) => { return item % 2 === 0; }) console.log(result) // 모든 요소 반환 let newDD = dd.map((element, index) => { return Object.assign({}, element, { bool : element.length > 3 }) }) console.log(newDD) // join, split arr = [13,8,5,27] arr.sort((a,b)=>{ return a - b; }) console.log(arr) // lodash찾아볼것 // for, forof, foreach result = 0; arr.forEach((num) => { result += num; }) console.log(result) resut = arr.reduce((prev, cur)=>{ console.log(prev) return prev + cur; },100) console.log(result) let stockList = [ {ticker: 'QCOM', MC:176}, {ticker: 'TSM', MC:553}, {ticker: 'TSLA', MC:773}, {ticker: 'NIKE', MC:228}, {ticker: 'LVMH', MC:260}, {ticker: 'NVDA', MC:330} ] result = stockList.reduce((prev, cur)=>{ if(cur.MC > 280) { prev.push(cur.ticker); } return prev; },[]); console.log(result)
// ================================================================================ // // Copyright: M.Nelson - technische Informatik // Die Software darf unter den Bedingungen // der APGL ( Affero Gnu Public Licence ) genutzt werden // // weblet: allg/filesystem/folder/show // ================================================================================ { var i; var str = ""; var ivalues = { stylePath : null, styleName : 'filesystem.css', action : '/file/ls.xml', diraddaction : '/file/mkdir.xml', dirdelaction : '/file/rmdir.xml', fileaddaction : '/file/mkfile.html', filedelaction : '/file/rmfile.xml', filelinkaction : '/file/mklink.xml', filedownloadaction : '/file/download.html', mvaction : '/file/mv.xml', popupadd : 'fileadd', popuprename : 'filerename', popupselect : 'dirselect', sorttyp : { FD_NAME : 0, FD_CREATE : 1, FD_MOD : 2, FD_ACCESS : 3 }, withdir : false, showpath : true, needmove : false, delbutton : '', startdir : '', }; var svalues = { }; weblet.loadClass("MneAjaxTable", "table/mne_atable.js"); weblet.initDefaults(ivalues, svalues); weblet.loadview(); var attr = { hinput : weblet.initpar.hinput == true, dirselectButton : { checktype : { reg : '#', help : "#mne_lang#Verzeichnis auswählen"} }, dirlistButton : { checktype : { reg : '#', help : "#mne_lang#Listenansicht"} }, dirsymbolButton : { checktype : { reg : '#', help : "#mne_lang#Symbolansicht"} } } if ( weblet.obj.title != null && weblet.initpar.showpath ) { weblet.obj.title.innerHTML = '<div id="dirselectButton" class="button dirselect"></div> <div style="display:inline-block"></div>'; weblet.obj.title = weblet.obj.title.lastChild; } if ( weblet.obj.titleright != null ) weblet.obj.titleright.innerHTML = '<div id="dirlistButton" class="button dirlist"></div><div id="dirsymbolButton" class="button dirsymbol"></div>' + weblet.obj.titleright.innerHTML; weblet.findIO(attr); weblet.findIO(attr, weblet.obj.titlecontainer); weblet.obj.viewtype = ( typeof weblet.win.mne_config.dirtype == 'undefined' ) ? 'list': weblet.win.mne_config.dirtype; weblet.obj.rframe = {}; weblet.obj.noselect = true; weblet.obj.dragit = false; weblet.obj.filesystempath = weblet.path; weblet.act_values = { dir : weblet.initpar.startdir, path : weblet.initpar.startdir.replace(/\//g, "->"), filename : null }; MneAjax.prototype.load.call(weblet, weblet.obj.filesystempath + "/object_list.js"); try { eval(weblet.req.responseText); } catch(e) { weblet.exception("load list:",e); } MneAjax.prototype.load.call(weblet, weblet.obj.filesystempath + "/object_rsymbol.js"); try { eval(weblet.req.responseText); } catch(e) { weblet.exception("load rsymbol:",e); } MneAjax.prototype.load.call(weblet, weblet.obj.filesystempath + "/object_edit.js"); try { eval(weblet.req.responseText); } catch(e) { weblet.exception("load edit:",e); } weblet.showValue = function(weblet, param) { if ( weblet == null || this.eleIsNotdefined(weblet.act_values)) { this.act_values = {}; this.act_values.dir = this.initpar.startdir; this.act_values.path = this.initpar.startdir.replace(/\//g, "->"); this.act_values.filename = null; weblet = this; } if ( this.obj.title.className.indexOf("modifyok") >= 0) { if ( this.confirm('#mne_lang#Reihenfolge wurde verändern - neu anzeigen ?') != true ) return; } if ( weblet != this ) { if ( typeof param != 'undefined' && param.setdependid == "del" ) { if ( this.act_values.dir == weblet.act_values.dir && weblet.act_values.filename == null ) { this.act_values.dir = weblet.act_values.parentdir; this.act_values.path = weblet.act_values.parentpath; this.act_values.filename = null; } } else { this.act_values = {}; this.act_values.dir = weblet.act_values.dir; this.act_values.path = ( weblet.act_values.filename == null ) ? weblet.act_values.path : weblet.act_values.parentpath; this.act_values.filename = null; } } this.eleMkClass(this.obj.title, "modifyok", false); this.obj.noselect = false; this.closepopups(); this.init(this, param); this["init" + this.obj.viewtype](this, param); if ( this.obj.title != null && this.initpar.showpath ) this.obj.title.innerHTML = this.act_values.path + '&nbsp;<div id="dirselectButton" class="button search"></div>'; this.findIO(attr, this.obj.titlecontainer); MneAjaxWeblet.prototype.readData.call(this, this); this["show" + this.obj.viewtype](); if ( this.initpar.delbutton != '' ) { var b = this.initpar.delbutton.split(','); for ( var i=0; i < b.length; i++) { if ( typeof this.obj.buttons[b[i]] != 'undefined') { this.obj.buttons[b[i]].parentNode.removeChild(this.obj.buttons[b[i]]); delete this.obj.buttons[b[i]]; } } } } weblet.readDataParam = function(weblet, param) { var p = ( typeof param == 'undefined' ) ? {} : param; p['rootInput.old'] = this.initpar.root; p['dirInput.old'] = weblet.act_values.dir; p['idname'] = "fullname"; p['singledir'] = 1; p['sorttyp'] = this.obj.sorttyp; return p; } weblet.init = function(weblet, param) { var attr = {}; MneAjax.prototype.load.call(this, this.obj.filesystempath + "/view_" + this.obj.viewtype + ".html"); this.obj.contentframe.innerHTML = this.req.responseText; this.eleMkClass(this.scrollframe, "fileshow fileshow_" + this.obj.viewtype, true, 'fileshow'); this.findIO(attr); } weblet.dirselect = function() { this.openpopup(this.initpar.popupselect); return false; }; weblet.ispicture = function(name) { str = name.toLowerCase().split('.'); if ( str.length > 1 ) switch(str[str.length - 1] ) { case "jpg" : case "jpeg" : case "png" : case "tiff" : case "gif" : return true; default: return false; } return false; } weblet.dirlist = function() { this.win.mne_config.dirtype = this.obj.viewtype = 'list'; this.showValue(this); this.obj.buttons.dirlist.blur(); } weblet.dirsymbol = function() { this.win.mne_config.dirtype = this.obj.viewtype = 'rsymbol'; this.showValue(this); this.obj.buttons.dirsymbol.blur(); } weblet.onbtnclick = function(id, button) { if ( button.weblet.oid == this.initpar.popupselect ) { this.act_values.dir = button.weblet.act_values.menuid; this.act_values.path = button.weblet.act_values.path; this.act_values.filename = null; this.showValue(this); this.setDepends('dirselect') } }; }
import React, { Component, PropTypes } from 'react'; import { View, AsyncStorage } from 'react-native'; import { Actions } from 'react-native-router-flux'; import SideMenuButton from './sideMenuBtn'; export default class Menu extends Component { logout = () => { this.props.closeDrawer(); AsyncStorage.removeItem('User', () => { Actions.login(); }); } goToProfile = () => { this.props.closeDrawer(); AsyncStorage.getItem('User', (err, user) => { user = JSON.parse(user); Actions.profile({uid: user.uid}); }); } goToSettings = () => { this.props.closeDrawer(); Actions.settings(); } render() { return ( <View style={{marginTop: 130}}> <View> <SideMenuButton source={require('../img/profile.png')} onPress={this.goToProfile} menuText="Profile" /> <SideMenuButton source={require('../img/notifications.png')} onPress={ () => console.log('pressed') } menuText="Notifications" /> <SideMenuButton source={require('../img/clock.png')} onPress={ () => console.log('pressed') } menuText="History" /> <SideMenuButton source={require('../img/about.png')} onPress={ () => console.log('pressed') } menuText="About" /> </View> <View style={{bottom: -70}}> <SideMenuButton source={require('../img/settings.png')} onPress={this.goToSettings} menuText="Settings" /> <SideMenuButton source={require('../img/logout.png')} onPress={this.logout} menuText="Log out" /> </View> </View> ); } }
import React from "react"; import { Link } from "react-router-dom"; import LogoImg from 'assets/img/bayty_icon.png'; import UserAvater from 'assets/img/Profile-icon.png'; import styled from 'styled-components' import './style.css' const CompanyNameDiv = styled.div` @media only screen and (max-width: 1024px) { display: none; `; const Header = (props) => { return ( <div className="admin-header col-md-12 col-sm-12"> {/* <div className="company-name col-md-3"> <Link to="/admin/profile"> <p>Baity Admin</p> </Link> </div> */} <CompanyNameDiv className="company-name col-md-3 col-sm-12" > <Link to="/"> <p>Baity Admin</p> </Link> </CompanyNameDiv> <div className="company-logo col-md-6 col-sm-6 col-xs-6"> <Link to="/"> <img className="logo-img" src={LogoImg} alt="Smiley face" height="50px" width="80px" /> </Link> </div> <div className="company-admin col-md-3 col-sm-6 col-xs-6"> <Link to="/admin/profile"> <span>Amdin</span> <img className="user-avater" src={UserAvater} alt="Smiley face" height="32px" width="30px" /> </Link> </div> </div> ); } export default Header;
import React from "react"; import './ProcessLine.scss'; class ProcessLine extends React.Component { size = 'M 0,2 L ' + this.props.value + ',2'; render() { return ( <div className="ProcessLine"> <p className="skill-title">{this.props.title}</p> <div className="process-bar"> <svg viewBox="0 0 100 5" preserveAspectRatio="none"> <path d="M 0,2 L 100,2" stroke="rgba(0,0,0,0.07)" strokeWidth="5"/> <path d={this.size} stroke="#C0E3E7" strokeWidth="5"/> </svg> <p className="value">{this.props.value}%</p> </div> </div> ) } } export default ProcessLine;
(function(){ 'use strict'; var home = angular.module('home', ['home_services']); home.controller('home_ctrl', ['$scope', '$routeParams', 'home_services', function($scope, $routeParams, home_services){ var self = this; this.data = { cid: $routeParams.CID }; this.homeData = undefined; home_services.get_data(self.data) .then(function success(res){ console.log(res); self.homeData = res.data; }, function error(err){ console.log(err); }); this.getRandomHour = function(){ return Math.floor((Math.random()*7)+1); }; }]); })();
/** * @file /models/RoleSchema.js * @description 角色表——模型层 */ const mongoose = require('mongoose') // 表结构 const RoleSchema = mongoose.Schema({ roleName: String, rolePermission: { type: Object, default: JSON.parse('{ "checkedPages": [], "checkedBtns": [] }') }, "createTime": { type: Date, default: Date.now() }, //创建时间 "updateTime": { type: Date, default: Date.now() }, //更新时间 remark: String }) // 导出表结构创建的模型(导出模型名,表结构,数据库表名称 collection) module.exports = mongoose.model('Role', RoleSchema, 'role')
import { ProxyState } from "../AppState.js" export default class Question { constructor(data) { this.value = data.value this.question = data.question this.answer = data.answer this.category = data.category.title } get Cover() { return /*html*/` <div class="col-4 card p-4 text-center" onclick="app.questionController.flipOver()"> <h2>${this.category}</h2> <h3>${this.value}</h3> </div > ` } get Template() { return /*html*/` <div class="col-4 card p-4 text-center" onclick="app.questionController.flipAnswer()"> <h4>${this.question}</h4> </div > ` } get Answer() { return /*html*/` <div class="col-4 card p-4 text-center"> <h4>Answer Submission</h4> <div class="form-group"> <input type="text" class="form-control" name="answer" id="answer" placeholder="Your answer here..."> </div> <button class="btn btn-info" onclick="app.questionController.reveal()">Answer</button> </div > ` } get Reveal() { return /*html*/` <div class="col-4 card p-4 text-center" onclick="app.questionController.next()"> <h4>${this.answer}</h4> </div > ` } }
import React, { Component, PropTypes } from 'react'; class CancelButton extends Component { render() { return ( <button onClick={this.props.onCancel} className='btn space'>Cancel</button> ); } } CancelButton.propTypes = { onCancel: PropTypes.func.isRequired, }; export default CancelButton;
const getInputParams = event => { const { queryStringParameters: queryParams, body: requestBody, pathParameters: pathParams, resource, httpMethod, requestContext: context } = event; if (context) console.log("Authorizer Values", context); return { queryParams, body: requestBody ? JSON.parse(requestBody) : null, pathParams, resource, httpMethod, context }; }; module.exports = { getInputParams };
import ColorModeProvider from './ColorModeProvider' export default ColorModeProvider export * from './ColorModeProvider'
// Книги по умолчанию var books = [{ image: 'http://www.booksiti.net.ru/books/58932900.jpg', info: { title: 'Страна багровых туч', author: 'Аркадий и Борис Стругацкие', year: '1957' } }, { image: 'http://rusbuk.ru/uploads/book/1515510/bd575f039aafbea20ed97370adc0fe867c71eb54.jpeg', info: { title: 'Гиперболоид инженера Гарина', author: 'Алексей Толстой', year: '1927' } }, { image: 'http://www.wwww4.com/w6022/3991278.jpg', info: { title: 'Вы, конечно, шутите, мистер Фейнман!', author: 'Ричард Фейнман', year: '1985' } }]; var DEFAULT_IMAGE = "http://artod.net/wp-content/uploads/2016/11/no-image.png"; var firstAddFlag = false; // флаг для отделения инициализация от добавления новых книг var yearFlag = true; // флаг для проверки корректности введенного значения года издания var noneEmptyFlag = false; // флаг для проверки заполнености формы // заполнение таблицы значениями по умолчанию и обработка нажатия табличных кнопок function init() { // заполнение таблицы исходными значениями for (var i = 0; i < books.length; i++) { addBook(books[i], i); } firstAddFlag = true; var table = document.getElementById("bookTable"); //обработка нажатия кнопок в таблице table.onclick = function (event) { event = event || window.event; var target = event.target || event.srcElement; var row = target.parentNode.parentNode; var classList = target.className.split(/\s+/); for (var i = 0; i < classList.length; i++) { switch (classList[i]) { case 'del-btn' : deleteBook(row.rowIndex); break; case "edit-btn" : showEditForm(row.rowIndex); break; } } } } // функция добавления новой книги function addBook(book, index) { // добавление в массив if (firstAddFlag) { // books.splice(index, 0, book); books.push(book); } // добавление в таблицу var row = document.getElementById('bookTable').insertRow(index); row.insertCell(0).innerHTML = '<img class="table_image" src = "' + books[index].image + '">'; row.insertCell(1).innerHTML = '<p class = "table_text title"><span class="table_text_title">' + books[index].info.title + '</span></p>' + '<p class = "table_text author">' + books[index].info.author + '</p>' + '<p class = "table_text year">' + books[index].info.year + ' г.</p>'; row.insertCell(2).innerHTML = "<button class='button table_button edit-btn'>Редактировать</button>\n<button class='button table_button del-btn'>Удалить</button>"; } // функция редактирования существующей книги function editBook(book, index) { // вставка новых значений в массив books.splice(index, 1, book); // вставка новых значений в таблицу // текущие данные заменяются данными из формы var row = document.getElementById("bookTable").childNodes[index]; row.cells[0].firstChild.src = book.image; row.cells[1].getElementsByClassName("title")[0].innerHTML = '<span class="table_text_title">' + book.info.title + '</span>'; row.cells[1].getElementsByClassName("author")[0].innerHTML = book.info.author; row.cells[1].getElementsByClassName("year")[0].innerHTML = book.info.year + ' г.'; return false; } // функция удаления книги function deleteBook(index) { document.getElementById('bookTable').deleteRow(index); books.splice(index, 1); } // работа с формой редактирования книги function showEditForm(rowNumber) { showForm(rowNumber); // данные книги из массива вносятся в форму document.getElementById("new-title").value = books[rowNumber].info.title; document.getElementById("new-author").value = books[rowNumber].info.author; document.getElementById("new-year").value = books[rowNumber].info.year; document.getElementById("new-image").value = books[rowNumber].image; var book; var saveButton = document.getElementById("save-btn"); // обработка при клике на кнопку Сохранить saveButton.addEventListener("click", function () { noneEmptyFlag = isEmpty(); if (yearFlag) { // проверка на корректность года if (noneEmptyFlag) { // проверка на заполнение book = getChangeBook(); editBook(book, rowNumber); closeForm(); } else { alert("Заполните все обязательные строки"); } } else { alert("Введите корректный год!"); } }) } // работа с формой добавления книги function showAddForm() { showForm(-1); var book; var saveButton = document.getElementById("save-btn"); saveButton.addEventListener("click", function () { noneEmptyFlag = isEmpty(); if (yearFlag) { // проверка на корректность года if (noneEmptyFlag) { // проверка на заполнение firstAddFlag = true; book = getChangeBook(); addBook(book, books.length); closeForm(); } else { alert("Заполните все строки"); } } else { alert("Введите корректный год!"); } }) } // функция вывода формы function showForm(rowNumber) { document.getElementById("bookTable").style.display = "none"; document.getElementById("add-btn").style.display = "none"; var editType = rowNumber >= 0 ? 'Редактирование' : 'Добавление'; form = document.createElement('div'); // создание формы form.id = 'popupWin'; form.className = 'form'; form.innerHTML = '<h2 class="form_name">' + editType + ' книги</h2>' + '<p class="form_text">Наименование*</p>' + '<input id = "new-title" class = "form_field">' + '<p class="form_text">Автор*</p>' + '<input id = "new-author" class = "form_field">' + '<p class="form_text">Год выпуска*</p>' + '<input type="number" id = "new-year" class = "form_field form_field_year" onchange="checkYear(this.value)">' + '<p class="form_text">Изображение</p>' + '<input id = "new-image" class = "form_field" >' + '<br><input type = "button" class="button form_button" value = "Сохранить" id = "save-btn">' + ' <button id = "cancel-btn" class = "button form_button" onclick="closeForm()">Отменить</button>' ; document.body.appendChild(form); // добавление формы на страницу return false; } // Функция проверки на заполнение формы function isEmpty() { if (!(document.getElementById("new-title").value) || !(document.getElementById("new-author").value) || !(document.getElementById("new-year").value)) { return false; } else { return true; } } // функция проверки корректности года function checkYear(year) { if (year < 2018) { yearFlag = true; } else { yearFlag = false; alert("Год издания не может превышать 2017"); } } // получение книги из формы function getChangeBook() { var book = { "image": document.getElementById("new-image").value, "info": { title: document.getElementById("new-title").value, author: document.getElementById("new-author").value, year: document.getElementById("new-year").value } } if (!document.getElementById("new-image").value) { book.image = DEFAULT_IMAGE; } return book; } // функция закрытия формы function closeForm() { document.getElementById("bookTable").style.display = "block"; document.getElementById("add-btn").style.display = "block"; form.parentNode.removeChild(form); // удаление окна return false; }
import Ajax from './ajax.js'; export const reqserver = () => { return Ajax("/home/server", {}, "GET"); } export const reqmain = () => { return Ajax("/home/main", {}, 'GET'); } export const reqdetail = (data) => { return Ajax("/detail", { data }, 'GET'); } export const reqgetmainListoffset = (count) => { return Ajax('/home/main', { count }, 'GET'); }; export const reqsearchkeywords = (keywords) => { return Ajax("/search", { keywords }, 'GET'); }; export const reqsearchhot = () => { return Ajax("/hot", {}, 'GET'); };
var fs = require("fs"); var path = require("path"); var request = require("request"); describe("cleanupOnExceptions", function(){ var Plasma = require("organic").Plasma; var plasma = new Plasma(); var Tissue = require("../../index"); var tissue = new Tissue(plasma, {}); var daemonCell; var spawnOptions = { target: path.normalize(__dirname+"/../data/daemonCell.js") } it("creates cell instance as daemon", function(next){ tissue.start(spawnOptions, function(c){ setTimeout(next, 500) }) }); it("triggers error", function(next){ request.get("http://localhost:1337/throwException", function(err, res, body){ next() }) }); it("should gracefully handle exception and exit by deleting its marker", function(next){ tissue.list({target: "daemons"}, function(c){ expect(c.data.length).toBe(0); next(); }); }); });
// Packages const redis = require('async-redis'); module.exports = { redisClient: redis.createClient() }
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Capture from '../../Capture'; import './index.css'; import rightArrow from './../../../images/right-arrow.png'; import FormProgress from '../../FormProgress'; /** * @Params * nextStep => function passed down to handle changing to * the next step in the create story process * * @summary * Displays page capturing images using the camera component * which uses WebRTC. It also allows the user to take multiple * photos and remove multiple photos * * @returns * Returns JSX for capturing photos from the users camera */ class CreateStoryCamera extends Component { saveAndContinue = (e) => { e.preventDefault(); const { nextStep } = this.props; nextStep(); } render() { const { handlePhotoChange, step, onAddPicture, removePicture, values } = this.props; return ( <form onSubmit={this.saveAndContinue} className="create-story-form"> <div className="form-navigation"> <FormProgress size={4} step={step} /> <button type="submit" className="navigation-btn-next">Next <img className="navigation-arrow" src={rightArrow} alt="Next" /> </button> </div> <Capture handlePhotoChange={handlePhotoChange} onAddPicture={onAddPicture} removePicture={removePicture} values={values} /> </form> ); } } CreateStoryCamera.propTypes = { nextStep: PropTypes.func.isRequired, }; export default CreateStoryCamera;
// DATA // ===================================================================== let friends = [ { name: "Ronnie Ringles", photo: "https://img.rawpixel.com/s3fs-private/rawpixel_images/website_content/k-208-pai-08.jpg?auto=format&bg=transparent&con=3&cs=srgb&dpr=1&fm=jpg&ixlib=php-3.1.0&mark=rawpixel-watermark.png&markalpha=90&markpad=13&markscale=10&markx=25&q=75&usm=15&vib=3&w=800&s=11f75f3e1393c05ddb94ce66c70fc4c5", scores: [ "5", "1", "4", "4", "5", "1", "2", "5", "4", "1" ] }, { name: "Paul Chen", photo: "https://img.rawpixel.com/s3fs-private/rawpixel_images/website_content/335-mckinsey-185.jpg?auto=format&bg=transparent&con=3&cs=srgb&dpr=1&fm=jpg&ixlib=php-3.1.0&mark=rawpixel-watermark.png&markalpha=90&markpad=13&markscale=10&markx=25&q=75&usm=15&vib=3&w=800&s=048dcc167a9ad4c9b131c90e0155a2a4", scores: [ "4", "2", "5", "1", "3", "2", "2", "1", "3", "2" ] }, { name: "Reid Bubbles", photo: "https://img.rawpixel.com/s3fs-private/rawpixel_images/website_content/366-mj-7703-fon-jj.jpg?auto=format&bg=transparent&con=3&cs=srgb&dpr=1&fm=jpg&ixlib=php-3.1.0&mark=rawpixel-watermark.png&markalpha=90&markpad=13&markscale=10&markx=25&q=75&usm=15&vib=3&w=600&s=96fafd35f8092f592971053d44db7832", scores: [ "5", "2", "2", "2", "4", "1", "3", "2", "5", "5" ] }, { name: "Chris Beetpads", photo: "https://img.rawpixel.com/s3fs-private/rawpixel_images/website_content/387-felix-mg-3047.jpg?auto=format&bg=transparent&con=3&cs=srgb&dpr=1&fm=jpg&ixlib=php-3.1.0&mark=rawpixel-watermark.png&markalpha=90&markpad=13&markscale=10&markx=25&q=75&usm=15&vib=3&w=800&s=f305084533cdf2f8e07dc7be0d32901a", scores: [ "3", "3", "4", "2", "2", "1", "3", "2", "2", "3" ] }, { name: "Xavier Casino", photo: "https://img.rawpixel.com/s3fs-private/rawpixel_images/website_content/360-mckinsey-57.jpg?auto=format&bg=transparent&con=3&cs=srgb&dpr=1&fm=jpg&ixlib=php-3.1.0&mark=rawpixel-watermark.png&markalpha=90&markpad=13&markscale=10&markx=25&q=75&usm=15&vib=3&w=800&s=3a2b1365b94658857bd117dc405e7b31", scores: [ "4", "3", "4", "1", "5", "2", "5", "3", "1", "4" ] }, { name: "Art Temis", photo: "https://img.rawpixel.com/s3fs-private/rawpixel_images/website_content/k-232-mckinsey-0419_1.jpg?auto=format&bg=transparent&con=3&cs=srgb&dpr=1&fm=jpg&ixlib=php-3.1.0&mark=rawpixel-watermark.png&markalpha=90&markpad=13&markscale=10&markx=25&q=75&usm=15&vib=3&w=600&s=594e0d75064e82afb7bf38563f79cf82", scores: [ "4", "4", "2", "3", "2", "2", "3", "2", "4", "5" ] } ]; // Here we export the array. This makes it accessible to other files using require. module.exports = friends;
angular.module('restApi', ['ngResource']) .factory('Threads', function($resource) { var url = 'rest/threads/:threadid'; return $resource(url, {}, {getItems: {method: 'GET', url: url + '/items', isArray: true}}); }) .factory('Participants', function($resource) { var url = 'rest/participants/:participantid'; var ratingsUrl = url + '/ratings'; return $resource('rest/participants/:participantid'); }) .factory('Ratings', function($resource) { return $resource('rest/participants/:participantid/ratings/:ratingid', {ratingid: '@id'}, { count: {method: 'GET', url: 'rest/participants/:participantid/ratings/count'} }); }) .factory('Questions', function($resource) { return $resource('rest/questions/:questionid'); });
import React, {useState, useEffect} from 'react'; import {View, Text, TextInput, TouchableWithoutFeedback} from 'react-native'; import {Actions} from 'react-native-router-flux'; import { MainCard, CardItem, Header, Autocomplete, } from '@aaua/components/common'; import styles from './styles'; const AutocompleteScreen = ({ defaultList, data, onSelect, textInputPlaceholder, }) => { // const {t} = useTranslation(); // const defaultSearchedCars = [ // {id: '7', title: 'Audi'}, // {id: '10', title: 'BMW'}, // {id: '19', title: 'Chevrolet'}, // {id: '25', title: 'Daewoo'}, // {id: '37', title: 'Ford'}, // ]; const [filteredItems, setFilteredItems] = useState(defaultList); const [text, setText] = useState(''); // const { // citiesBrands: {brands}, // } = useSelector(state => state); const {itemContainer, itemText, textInputContainer, textInputStyle} = styles; const searchingItems = searchedText => { var searchedItems = data.filter(item => { return item.title.toLowerCase().indexOf(searchedText.toLowerCase()) == 0; }); if (searchedText.length <= 0) { searchedItems = []; } if (searchedItems.length == 1) { setFilteredItems([]); } // data.some(e => { // if (e.title.toLowerCase() === searchedText.toLowerCase().trim()) { // setFilteredItems([]); // } // }); setFilteredItems(searchedItems.slice(0, 5)); }; const onChangeCar = title => { if (title.length >= 1) { searchingItems(title); } setText(title); }; const onSelectItem = obj => { setFilteredItems([]); onSelect(obj); Actions.pop(); }; const renderList = () => { return filteredItems.map(item => { return ( <TouchableWithoutFeedback key={item.title} onPress={() => onSelectItem(item)}> <View style={itemContainer}> <Text style={itemText}>{item.title}</Text> </View> </TouchableWithoutFeedback> ); }); }; return ( <CardItem style={{ flexDirection: 'column', }}> <View style={textInputContainer}> <TextInput style={textInputStyle} autoCorrect={false} placeholderTextColor={'#414244'} placeholder={textInputPlaceholder} onChangeText={onChangeCar} value={text} /> </View> {renderList()} </CardItem> ); }; export default AutocompleteScreen;
const findJob = (urn, context) => { return context.collection('jobs').find({'urn': urn}).toArray() .then(result => { console.log(result[0]) return result[0] }) } const findCompany = (urn, context) => { return context.collection('companies').find({'urn': urn}).toArray() .then(result => { console.log(result[0]) return result[0] }) } // Resolvers const resolvers = { Query: { jobByUrn: (_, { urn }, context) => findJob(urn, context) }, Job: { company: (parent, _, context) => findCompany(parent.companyId, context) } }; module.exports = resolvers;
const navigationToggle = document.querySelector('.navigation-toggle'); const navigationLinks = document.querySelectorAll('.navigation__link'); navigationToggle.addEventListener('click', ()=>{ document.body.classList.toggle('navigation-open'); }); navigationLinks.forEach(link =>{ link.addEventListener('click', () =>{ document.body.classList.remove('navigation-open'); }) })
let onclickImage; let isOpen = false; function init() { onclickImage = document.querySelector("section.query-content img"); onclickImage.onclick = openModal; } function openModal() { if (isOpen === false) { onclickImage.classList.add("modal-open"); //onclickImage.classList.add("overlay"); //modal overlay box som er display hidden og kommentert ut i CSSn nå. //onclickImage.className += "imageModal"; //class som er lagt til som skulle align`e bilde boxn. //onclickImage.style.display = "block"; //onclickImage.style.width = "80%"; //onclickImage.style.height = "80%"; } else { //onclickImage.classList.remove("overlay"); //modal overlay box onclickImage.classList.remove("modal-open"); } isOpen = !isOpen; } setTimeout(init, 2000);
import * as mechanics from "./mechanics"; export default class Apple { static pieceName = "Apple"; static sprite = "Apple.png"; static description = "An apple that can be pushed around. Open tulips will eat it and stay full for a while."; sprite = "Apple.png"; constructor(){ //Just putting it here } update(board, ownPos, dt){ //Does nothing return []; } collide(board, playerPos, ownPos, dir){ //Calls the helper function from mechanics return mechanics.pushBlock(board, playerPos, ownPos, dir); } }
$(document).ready(function () { var $noticia = $('div.noticia'); $noticia.parents(".seccion").children(".noticia-secundaria"); });
// EXPORT DEFAULT: MAIN export { default } from "./Main";
const { parse } = require('path') const cheerio = require('cheerio') const minimatch = require('minimatch') function replacePlaceholders (text, placeholders) { return text.replace(/\{([^}]+)\}/g, (match, pattern) => { if (placeholders.hasOwnProperty(pattern)) { return placeholders[pattern] } return match }) } // Parses attached images in metadata and transforms the array in a proper map export default function AdaptiveImages (options) { const defaultOptions = { imagesKey: 'images', mapKey: 'imagesMap', imageWidths: [1440, 960, 480], imageSizes: ['(min-width: 960px) 960px', '100vw'], defaultSize: 960, namingPattern: '{dir}{name}-{size}{ext}', srcsetPattern: '{url} {size}w', htmlFileGlob: '**/*.html', htmlImageSelector: 'img' } function parseSrc (src) { const parsedSrc = parse(src) if (parsedSrc.dir.length) { parsedSrc.dir = `${parsedSrc.dir}/` } return parsedSrc } function formatName (src, size) { return replacePlaceholders(options.namingPattern, { ...parseSrc(src), size }) } function formatSrcset (src) { return options.imageWidths .map((size) => { const url = formatName(src, size) return replacePlaceholders(options.srcsetPattern, { url, size }) }) } function generateImageObject (path) { const srcset = formatSrcset(path) const defaultIndex = options.imageWidths.indexOf(options.defaultSize) const src = srcset[defaultIndex].split(' ')[0] const sizes = options.imageSizes.join(', ') const { base } = parseSrc(path) return { src, srcset: srcset.join(', '), sizes, name: base } } function addImageToMap (imageMap, path) { const image = generateImageObject(path) return { ...imageMap, [path]: image } } // Plugin to transform array of images into a map of image objects function processImages (files, metalsmith, done) { setImmediate(done) Object.keys(files).map((filename) => { const file = files[filename] if (file.hasOwnProperty(options.imagesKey)) { file[options.mapKey] = file[options.imagesKey] .reduce(addImageToMap, {}) } }) } // Plugin to replace images function replaceImages (files, metalsmith, done) { setImmediate(done) Object.keys(files).map((filename) => { const file = files[filename] if (minimatch(filename, options.htmlFileGlob)) { replaceMatchingImages(file) } }) } function replaceMatchingImages (file) { const $ = cheerio.load(file.contents, { xmlMode: true, lowerCaseTags: true, lowerCaseAttributeNames: true }) $(options.htmlImageSelector).map((index, img) => { const { src, ...attrs } = img.attribs const replacement = renderImage(src, attrs) $(img).replaceWith(replacement) }) file.contents = Buffer.from($.html()) } // Renderer for a responsive image. Additional attributes can be passed. function renderImage (src, attrs) { const image = generateImageObject(src) attrs = { src: image.src, srcset: image.srcset, sizes: image.sizes, ...attrs } attrs = Object.keys(attrs) .reduce((attrList, attribute) => { return [ ...attrList, `${attribute}="${attrs[attribute]}"` ] }, []) return `<img ${attrs.join(' ')}/>` } options = { ...defaultOptions, ...options } return { processImages, replaceImages, renderImage } }
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {number[][]} descriptions * @return {TreeNode} */ var createBinaryTree = function (descriptions) { let nodes = new Map(); let inMap = new Map(); // 记入每个节点的入度 for (let i = 0; i < descriptions.length; i++) { let parent = descriptions[i][0], child = descriptions[i][1], flag = descriptions[i][2]; if (!(nodes.has(parent))) { let node = new TreeNode(parent); nodes.set(parent, node) } if (!(nodes.has(child))) { let node = new TreeNode(child); nodes.set(child, node) } if (flag == 1) { nodes.get(parent).left = nodes.get(child) } else { nodes.get(parent).right = nodes.get(child) } inMap.set(child, true); } for (let [key, node] of nodes.entries()) { if (!(inMap.get(key))) { return node } } return null };
function autoPartial(fn) { const collect = (boundArgs, ...args) => { const collectedArgs = boundArgs.concat(args); return collectedArgs.length >= fn.length ? fn.apply(null, collectedArgs) : collect.bind(null, collectedArgs); }; return collect.bind(null, []); } const deliveryNotification = autoPartial( (name, job, quantity, item) => `Hi, I’m ${name} the ${job}. ` + `I’ve brought you ${quantity} ${item}`); const mail = deliveryNotification("Frank", "postal worker", 5, "letters"); console.log(mail); const susansDelivery = deliveryNotification("Susan", "postal worker"); const moreMail = susansDelivery(2, "packages"); console.log(moreMail); const threeThingsFromSusan = susansDelivery(3); const bills = threeThingsFromSusan("bills"); console.log(bills); function partialFactory() { const hole = {}; function mergeArgs(unmerged, merged, args) { return ( !unmerged.length && !args.length ? merged : !args.length ? mergeArgs(unmerged.slice(1), merged.concat([unmerged[0]]), args) : !unmerged.length ? mergeArgs(unmerged, merged.concat([args[0]]), args.slice(1)) : unmerged[0] === hole ? mergeArgs(unmerged.slice(1), merged.concat([args[0]]), args.slice(1)) : /* unmerged is not a hole */ mergeArgs(unmerged.slice(1), merged.concat([unmerged[0]]), args)); } return { _: hole, holePartial: (fn, ...args) => { const initialArgs = args; return (...args) => { const mergedArgs = mergeArgs(initialArgs, [], args); return fn.apply(null, mergedArgs); }; } }; } const {_, holePartial} = partialFactory(); const mailDelivery = holePartial(deliveryNotification, _, "postal worker", _, "letters"); const mondaysMail = mailDelivery("Frank", 3), tuesdaysMail = mailDelivery("Susan", 7); console.log(mondaysMail); console.log(tuesdaysMail); function power(exponent: number, base: number) : number { let result = 1; for (let i = 0; i < exponent; i++) { result = result * base; } return result; } const square = holePartial(power, _, 2), cube = holePartial(power, _, 3); console.log([1, 2, 3].map(square)); console.log([1, 2, 3].map(cube));
require("../common/vendor.js"), (global.webpackJsonp = global.webpackJsonp || []).push([ [ "pages/chat_list/chat/_tools" ], { "04f7": function(t, e, n) { n.d(e, "b", function() { return r; }), n.d(e, "c", function() { return o; }), n.d(e, "a", function() {}); var r = function() { var t = this; t.$createElement; t._self._c; }, o = []; }, "587b": function(t, e, n) {}, bff9: function(t, e, n) { n.r(e); var r = n("04f7"), o = n("fe91"); for (var a in o) [ "default" ].indexOf(a) < 0 && function(t) { n.d(e, t, function() { return o[t]; }); }(a); n("dc29"); var u = n("f0c5"), c = Object(u.a)(o.default, r.b, r.c, !1, null, "4414a57e", null, !1, r.a, void 0); e.default = c.exports; }, dc29: function(t, e, n) { var r = n("587b"); n.n(r).a; }, f6416: function(t, e, n) { function r(t) { return t && t.__esModule ? t : { default: t }; } function o(t, e) { return f(t) || i(t, e) || u(t, e) || a(); } function a() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function u(t, e) { if (t) { if ("string" == typeof t) return c(t, e); var n = Object.prototype.toString.call(t).slice(8, -1); return "Object" === n && t.constructor && (n = t.constructor.name), "Map" === n || "Set" === n ? Array.from(t) : "Arguments" === n || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n) ? c(t, e) : void 0; } } function c(t, e) { (null == e || e > t.length) && (e = t.length); for (var n = 0, r = new Array(e); n < e; n++) r[n] = t[n]; return r; } function i(t, e) { if ("undefined" != typeof Symbol && Symbol.iterator in Object(t)) { var n = [], r = !0, o = !1, a = void 0; try { for (var u, c = t[Symbol.iterator](); !(r = (u = c.next()).done) && (n.push(u.value), !e || n.length !== e); r = !0) ; } catch (t) { o = !0, a = t; } finally { try { r || null == c.return || c.return(); } finally { if (o) throw a; } } return n; } } function f(t) { if (Array.isArray(t)) return t; } function l(t, e, n, r, o, a, u) { try { var c = t[a](u), i = c.value; } catch (t) { return void n(t); } c.done ? e(i) : Promise.resolve(i).then(r, o); } function s(t) { return function() { var e = this, n = arguments; return new Promise(function(r, o) { function a(t) { l(c, r, o, a, u, "next", t); } function u(t) { l(c, r, o, a, u, "throw", t); } var c = t.apply(e, n); a(void 0); }); }; } Object.defineProperty(e, "__esModule", { value: !0 }), e.default = void 0; var d = r(n("a34a")), p = r(n("80d6")), h = { props: { show: Boolean }, methods: { chooseImg: function(t) { var e = this; return s(d.default.mark(function n() { var r, a, u, c; return d.default.wrap(function(n) { for (;;) switch (n.prev = n.next) { case 0: return n.next = 2, p.default.chooseImage({ sourceType: [ t ], count: 1, is_upload: !0 }); case 2: if (r = n.sent, a = o(r, 1), u = a[0], !e.is_peer_blocked) { n.next = 8; break; } return e.showBlockToast(), n.abrupt("return"); case 8: return n.next = 10, p.default.uploadImg({ filePath: u }); case 10: c = n.sent, e.$emit("chooseImg", c); case 12: case "end": return n.stop(); } }, n); }))(); } } }; e.default = h; }, fe91: function(t, e, n) { n.r(e); var r = n("f6416"), o = n.n(r); for (var a in r) [ "default" ].indexOf(a) < 0 && function(t) { n.d(e, t, function() { return r[t]; }); }(a); e.default = o.a; } } ]), (global.webpackJsonp = global.webpackJsonp || []).push([ "pages/chat_list/chat/_tools-create-component", { "pages/chat_list/chat/_tools-create-component": function(t, e, n) { n("543d").createComponent(n("bff9")); } }, [ [ "pages/chat_list/chat/_tools-create-component" ] ] ]);
"use strict"; // App Module: the name invxApp matches the ng-app attribute in the main <html> tag // the parameters in the array are the modules that the application depends on (in this case, only "invx"). var app = angular.module("invxApp", ["invx"]);
import {combineReducers} from 'redux' import todoReducer from './todoReducer' import filterReducer from './filterReducer' export default combineReducers({ todoReducer,filterReducer })
/** * NPM import */ import React from 'react'; import PropTypes from 'prop-types'; /** * Local import */ /** * Code */ const ProfileBloc = ({ firstname, lastname, birthday, adress, mail, phone, urlPicture, }) => ( <div className="cv-bloc-profile"> <div className="cv-picture-bloc"> <img src={urlPicture} alt="Profile" className="profile-pic" /> </div> <div className="cv-profile-bloc"> <div className="info-wrapper"> <div>Firstname | </div> <div>Lastname | </div> <div>Birthday | </div> <div>Adress | </div> <div>Mail | </div> <div>Phone | </div> </div> <div className="data-wrapper"> <div className="profile-info">{firstname}</div> <div className="profile-info">{lastname}</div> <div className="profile-info">{birthday}</div> <div className="profile-info">{adress}</div> <div className="profile-info">{mail}</div> <div className="profile-info">{phone}</div> </div> </div> </div> ); ProfileBloc.propTypes = { firstname: PropTypes.string.isRequired, lastname: PropTypes.string.isRequired, birthday: PropTypes.string.isRequired, adress: PropTypes.string.isRequired, mail: PropTypes.string.isRequired, phone: PropTypes.string.isRequired, urlPicture: PropTypes.string.isRequired, }; /** * Export */ export default ProfileBloc;
import jwt from "jsonwebtoken"; const auth = async (req, res, next) => { try { // extract the jwt token from the request header Authorization: Bearer <Token> if (!req.headers.authorization) { return res .status(404) .json({ error: "No authorization header provided" }); } const token = req.headers.authorization.split(" ")[1]; if (token) { try { const decodedData = await jwt.verify(token, process.env.JWT_SECRET); req.userId = decodedData.id; } catch (error) { return res.status(404).json({ error: "Unauthenticated" }); } } else { return res.status(404).json({ error: "Token not found" }); } // now have access to userId as part of the request next(); } catch (error) { res.status(500).json({ error: "Internal Server Error." }); } }; export default auth;
import React, {Component} from 'react'; import '../App.css'; import ShoppingCartItem from './ShoppingCartItem' import {connect} from 'react-redux' import { fetchShopItemCreator } from '../reducer' class ShoppingCart extends Component { renderShoppingCartItems = () => { console.log('shoppingCart props********. shoppingCartItems in render', this.props.shoppingCartItems) return this.props.shoppingCartItems .filter(item => item.shopping_cart_id === this.props.currentUser.id) .map(item => <ShoppingCartItem key={item.id} {...item} /> ) } items = () => { return this.props.shoppingCartItems .filter(item => item.shopping_cart_id === this.props.currentUser.id) .length } subTotal = () => { console.log('_________shoppingCartItem props--------------- ', this.props.shoppingCartItems) return this.props.shoppingCartItems .filter(item => item.shopping_cart_id === this.props.currentUser.id) .reduce((totalPrice,itemInShoppingCart) => totalPrice + itemInShoppingCart.item.price, 0) } estimatedtaxxxx = () => { let summmm = this.props.shoppingCartItems return Math.max(summmm .filter(item => item.shopping_cart_id === this.props.currentUser.id) .reduce((totalPrice,item) => totalPrice + item.item.price, 0) *(0.07)).toFixed(2) } totalToPay = () => { let summmm = this.props.shoppingCartItems return ( ( summmm .filter(item => item.shopping_cart_id === this.props.currentUser.id) .reduce((totalPrice,item) => totalPrice + item.item.price, 0) ) + ( summmm .filter(item => item.shopping_cart_id === this.props.currentUser.id) .reduce((totalPrice,item) => totalPrice + item.item.price, 0) *(0.07) ) ) } handleCheckout = () => { console.log('procede checkout') let emptyArr = this.props.shoppingCartItems .filter(item => item.shopping_cart_id === this.props.currentUser.id) for (let i = 0; i < emptyArr.length; i++) { fetch(`https://ironladyback.herokuapp.com/api/v1/shopping_cart_items/${emptyArr[i].id}`, { // fetch(`http://localhost:3000/api/v1/shopping_cart_items/${emptyArr[i].id}`, { method: "DELETE" }) .then(resp => resp.json()) .then(data => {console.log(data) }) } this.props.checkout(); } render(){ console.log('shoppingCart props********. shoppingCartItems', this.props.shoppingCartItems) return ( <div className="App "> <h1>Items in shoppingCart</h1> <div className="shopppingCardCardDiv"> {this.renderShoppingCartItems()} </div> <div className="shopppingCardCardDiv1"> <div className="card text-white bg-primary mb-3 sticky-top" > <div className="card-header bg-transparent border-success">Go to checkout</div> <div className="card-body text-success checkoutDivBody "> <p className="checkoutDivBodyP">Items : {this.items()}</p> <p className="checkoutDivBodyP">Subtotal : ${this.subTotal()}</p> <p className="checkoutDivBodyP">Shipping address: {this.props.currentUser.email}</p> <p className="checkoutDivBodyP">Estimated tax : ${this.estimatedtaxxxx()}</p> </div> <div className="card-footer bg-transparent border-success">Total : {this.totalToPay()}</div> </div> <br></br> <br></br> <button type="button" class="btn btn-info" onClick={this.handleCheckout}>Checkout</button> </div> </div> ); }} function msp(state){ return { shoppingCartItems: state.shoppingCartItems, } } const mdp = dispatch => { return { checkout:() => dispatch({type: 'CHECKOUT'}) } } export default connect(msp,mdp)(ShoppingCart);
var rjsOptimizer = require('requirejs/bin/r.js'); var amdConfig = { baseUrl: 'src', exclude:['a.js','b.js'], path:{ 'lib': '../lib' } }; var requireConfig = { baseUrl: DIR.build }; var options = { umd: false }; gulp.task('package', ['clean:dist'], function() { $.util.log($.util.colors.blue(['package: add ng injector annotations for minification safety then concatenate all js files,', 'minify, obfuscate and save to distribution folder '].join())); return gulp.src([ DIR.build + '/assets/js/**/*.js', '!' + DIR.build + '/assets/js/vendor/**/*' ]) .pipe($.debug({verbose: true})) .pipe(rjsOptimizer(requireConfig, options)) //.pipe($.concat('modules.js')) //.pipe($.uglify()) //.pipe($.merge(gulp.src(DIR.build + '/assets/vendor/**/*.js'))) // TODO: Add minified libraries AFTER uglify .pipe($.debug({verbose: true})) //.pipe($.concat('app.js')) .pipe(gulp.dest(DIR.dist)); });
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer') .BundleAnalyzerPlugin; module.exports = class GridsomePluginBundleAnalyzer { constructor(api, options = {}) { const production = process.env.NODE_ENV === 'production'; api.chainWebpack((webpackConfig) => { if (production || !options.onlyProduction) { webpackConfig .plugin('plugin-bundle-analyzer') .use(BundleAnalyzerPlugin) .init((Plugin) => new Plugin(options.analyzerOptions)); } }); } static defaultOptions() { return { onlyProduction: true, analyzerOptions: { analyzerPort: 'auto', analyzerMode: 'static' } }; } };
import React from 'react'; import './App.css'; import Sale from './Components/Sale'; import Searche from './Components/searche'; import { BrowserRouter as Router, Switch, Route, Redirect, } from 'react-router-dom' class App extends React.Component{ render(){ return( <React.Fragment> <Router> <Switch> <Route path='/sale'><Sale/></Route> <Route path='/search'><Searche/></Route> </Switch> {/* <Sitefoother/> */} <Redirect from={'/'} to={'/sale'} /> </Router> </React.Fragment> ); } }export default App;
var express = require('express') , morgan = require('morgan') , compression = require('compression') , app = express() , port = process.env.PORT || 3000; app.use(morgan('short')); app.use(compression()); app.use(express.static('client')); app.use('/data', express.static('server/data')); app.listen(port, function() { console.log('kanban-chart server listening on port ' + port); });
const About = () => { return ( <section className="about"> <div className="page-top"> <div className="container"> <div className="row"> <div className="col-lg-12"> <h1 className="page-title">About</h1> <h2 className="page-description">About</h2> </div> </div> </div> </div> <div className="page-content"> <div className="container"> <div className="row"> <div className="col-lg-6"> <img src="/img/product1.jpeg" alt="product" className="w-100" /> </div> <div className="col-lg-6"> <div className="about-item"> <div className="title"> Lorem ipsum dolor sit amet </div> <div className="about-text"> Lorem ipsum is simply free text dolor sit am adipi we help you ensure everyone is in the right jobs sicing elit, sed do consulting firms Et leggings across the nation tempor. </div> <div className="about-features"> <p className="about-feature"><i className="fas fa-long-arrow-alt-right"></i> Lorem ipsum is simply</p> <p className="about-feature" ><i className="fas fa-long-arrow-alt-right"></i> Lorem ipsum is simply</p> <p className="about-feature"><i className="fas fa-long-arrow-alt-right"></i> Lorem ipsum is simply</p> </div> </div> </div> </div> </div> </div> </section> ) } export default About
import React, { Fragment } from 'react'; import styled from 'styled-components'; import './Header.css'; /** * { * div() {} * p() {} * button() {} * h1() {} * } */ const StyledH1 = styled.h1` color: purple; color: ${(props) => (props.color ? props.color : 'purple')}; `; // template export const StyledButton = styled.button` color: orange; border-radius: ${(props) => { console.log('styled button props', props.rounded, props.myProp); return props.rounded ? '12px' : '0px'; }}; `; function Header(props) { const { color } = props; return ( <Fragment> <StyledH1 color={color}>Hello World</StyledH1> <StyledButton rounded={true} myProp={'myValue'}>hello</StyledButton> <StyledButton>hello</StyledButton> </Fragment> ); } export default Header;
// http://bl.ocks.org/michellechandra/0b2ce4923dc9b5809922 $(document).ready(function() { var drag = d3.behavior.drag() .origin(function(d) { return d; }) .on("dragstart", dragstarted) .on("drag", dragged) .on("dragend", dragended); function dragstarted(d) { d3.event.sourceEvent.stopPropagation(); d3.select(this).classed("dragging", true); } function dragged(d) { d3.select(this).attr("left", d.left = d3.event.left).attr("top", d.top = d3.event.top); } function dragended(d) { d3.select(this).classed("dragging", false); } // Define constants var color = d3.scale.category10(); var domain = [0, 1, 2, 3, 4, 5, 6]; var range = ["#FFE87C", "#e31a1c", "#1f78b4", "#b15928", "#33a02c", "#6a3d9a", "#ff7f00"]; color.domain(domain); color.range(range); var category_to_number = {"All": 0, "Mexican": 1, "Chinese": 2, "Italian": 3, "American": 4, "Multiple": 5, "Other": 6}; var category_to_name = {0: "All", 1: "Mexican", 2: "Chinese", 3: "Italian", 4: "American", 5: "Multiple", 6: "Other"}; var active = d3.select(null); //Width and height of map var width = $(document).width() - 50; var window_height = $(document).height(); // space from bottom for notes 1 and 2 var note_margin1 = 5; // y-value for second line of note var note_margin2 = 20; // amount to shift map up var translate_up = 50; var map_height = window_height - translate_up - (2 * note_margin2); // amount to shift map left var translate_left = width / 25; // how much to magnify map of US var map_scale = Math.max(1000, width); // amount to shift cuisine type buttons to left var legend_margin = 10; // amount to shift data source buttons to the left var button_margin = 150; // amount to shift categories boxes down var categories_top = 20; // y at which to start drawing data source buttons var legend_top = 200; // colors for boxes on right var both_color_rgb = "#bcbddc"; var academic_color_rgb = "#9e9ac8"; var scraped_color_rgb = "#807dba"; var current_color_rgb = "#54278f"; var source_title = 'Academic and Scraped'; var title = "Academic and Scraped Data"; function make_business_text(name, city, state) { var text = '<span style="font-size: 120%; font-weight: bold">' + name + '</span>' + '<br/><span style="font-size: 110%; font-style: italic">' + city + ', ' + state + '</span>'; return text; } function review_text(reviews_data, business_text, review_number) { if (reviews_data.length == 0) { box_text = business_text + '<br/><br/>' + 'No reviews!'; } else { box_text = business_text + '<br/><br/>' + reviews_data[review_number]['text'] + '<br/><br/> - ' + reviews_data[review_number]['uname']; } return box_text; } function draw_business(business_data, circle_data, temporary_box) { // don't let box be drawn outside of window var x = Math.max(circle_data['pageX'] - 50, 100); var y = Math.max(circle_data['pageY'] - 50, 100); var business_text = make_business_text(business_data.name, business_data.city, business_data.state) var business_color = color(category_to_number[business_data.cat]); temporary_box .transition() .duration(200) .style("opacity", .9) .style("background-color", business_color) temporary_box.html(business_text) .style("left", x + "px") .style("top", y + "px"); } function draw_reviews(reviews_data, business_data, circle_data, drag) { // review number to look for var review_number = 0; // absolute number, which could be negative var review_number_absolute = 0; // don't let box be drawn outside of window var x = Math.max(circle_data['pageX'] - 30, 100); var y = Math.max(circle_data['pageY'] - 50, 100); var business_text = make_business_text(business_data.name, business_data.city, business_data.state) var box_text = review_text(reviews_data, business_text, review_number); var business_color = color(category_to_number[business_data.cat]); var permanent_box = d3.select("body") .append("div") .attr("class", "tooltip") .style("min-width", "300px") .style("max-width", "380px") .style("opacity", 0) .attr("id", "permanent-box"); // box to click on right arrow and see next review var right_box = d3.select("body") .append("div") .attr("class", "tooltip") .style("opacity", 0) .attr("id", "right-box") .text('→') .style("cursor", "pointer"); var left_box = d3.select("body") .append("div") .attr("class", "tooltip") .style("opacity", 0) .attr("id", "left-box") .text('←') .style("cursor", "pointer"); permanent_box .transition() .duration(50) .style("opacity", .9) .style("background-color", business_color) permanent_box.html(box_text) .style("left", x - 80 + "px") .style("top", y - 50 + "px") .on("dblclick", function() { this.remove(); right_box.remove(); left_box.remove(); }); // Merge this with lines above? Will transitions still work? right_box .transition() .duration(50) .style("opacity", 1) .style("background-color", business_color) right_box.style("left", x + permanent_box.node().getBoundingClientRect()['width'] - 108 + "px") .style("top", y - 47 + "px") .style("width", "20px") .on("click", function() { review_number_absolute += 1; review_number = Math.abs(review_number_absolute % reviews_data.length); box_text = review_text(reviews_data, business_text, review_number); permanent_box.html(box_text); right_box .style("left", x + permanent_box.node().getBoundingClientRect()['width'] - 108 + "px"); }); left_box .transition() .duration(50) .style("opacity", 1) .style("background-color", business_color) left_box.style("left", x - 75 + "px") .style("top", y - 47 + "px") .style("width", "20px") .on("click", function() { review_number_absolute -= 1; review_number = Math.abs(review_number_absolute % reviews_data.length); box_text = review_text(reviews_data, business_text, review_number); permanent_box.html(box_text); right_box .style("left", x + permanent_box.node().getBoundingClientRect()['width'] - 108 + "px"); }); d3.select('body').call(d3.keybinding() .on('→', function() { review_number_absolute += 1; review_number = Math.abs(review_number_absolute % reviews_data.length); box_text = review_text(reviews_data, business_text, review_number); permanent_box.html(box_text); right_box.style("left", x + permanent_box.node().getBoundingClientRect()['width'] - 108 + "px"); }) .on('←', function() { review_number_absolute -= 1; review_number = Math.abs(review_number_absolute % reviews_data.length); box_text = review_text(reviews_data, business_text, review_number); permanent_box.html(box_text); right_box.style("left", x + permanent_box.node().getBoundingClientRect()['width'] - 108 + "px"); }) .on('escape', function() { permanent_box.remove(); right_box.remove(); left_box.remove(); })); } // Shuffle an array: https://github.com/coolaj86/knuth-shuffle function shuffle(data) { var currentIndex = data.length, temporaryValue, randomIndex; // While there remain elements to shuffle... while (0 !== currentIndex) { // Pick a remaining element... randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; // And swap it with the current element. temporaryValue = data[currentIndex]; data[currentIndex] = data[randomIndex]; data[randomIndex] = temporaryValue; } return data; } function add_data(map_data, business_data, projection) { // path generator that will convert GeoJSON to SVG paths and tell path generator to use albersUsa projection var path = d3.geo.path().projection(projection); var source = 'both' var category = "All"; function reset() { active.classed("active", false); active = d3.select(null); svg.transition() .duration(750) .call(zoom.translate([0, 0]).scale(1).event); g.selectAll("circle").attr("r", 2.75); } function clicked(d) { if (active.node() === this) return reset(); active.classed("active", false); active = d3.select(this).classed("active", true); var bounds = path.bounds(d), dx = bounds[1][0] - bounds[0][0], dy = bounds[1][1] - bounds[0][1], x = (bounds[0][0] + bounds[1][0]) / 2, y = (bounds[0][1] + bounds[1][1]) / 2, scale = Math.max(1, Math.min(8, 0.9 / Math.max(dx / width, dy / window_height))), translate = [width / 2 - scale * x, window_height / 2 - scale * y]; svg.transition() .duration(750) .call(zoom.translate(translate).scale(scale).event); g.selectAll("circle").attr("r", 1.5); } function zoomed() { g.style("stroke-width", 1.5 / d3.event.scale + "px"); g.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")"); } d3.select("body").append("div") .attr("id", "title") .attr("align", "center") .style("font-size", "28px") .text(title); // Create SVG element and append map to the SVG var svg = d3.select("body") .append("svg") .attr("width", width) .attr("height", window_height) .on("click", stopped, true); svg.append("rect") .attr("class", "background") .style("fill", "white") .attr("width", width) .attr("height", window_height) .on("click", reset); // d3.select("#title").on("click", reset); var g = svg.append("g"); g.selectAll("path") .data(map_data.features) .enter() .append("path") .attr("d", path) .style("stroke", "#fff") .style("stroke-width", "1") .attr("class", "zip") .on("click", clicked); var temporary_box = d3.select("body") .append("div") .attr("class", "tooltip") .attr("id", "temporary-box") .style("max-width", "250px") .style("min-width", "100px") .style("opacity", 0) .style("cursor", "pointer"); var zoom = d3.behavior.zoom() .translate([0, 0]) .scale(1) .scaleExtent([1, 8]) .on("zoom", zoomed); // shuffle the data with each update business_data = shuffle(business_data); g.selectAll("circle") .data(business_data) .enter() .append("circle") .style("cursor", "pointer") .attr("visible_tag", function(d) { d.category_correct = 1; d.source_correct = 1; }) .attr("cx", function(d) { var location = projection([d.lon, d.lat]); return location[0]; }) .attr("cy", function(d) { var location = projection([d.lon, d.lat]); return location[1]; }) .attr("r", 2.75) .style("fill", function(d) { return color(category_to_number[d.cat]) }) .style("opacity", 0.4) .attr("color", function(d) { return color(category_to_number[d.cat]); }) .each(function (business_data, i) { $(this).hoverIntent( function(circle_data) {draw_business(business_data, circle_data, temporary_box);}, function() { temporary_box.transition() .duration(200) .style("opacity", 0); }) }) .each(function (business_data, i) { $(this).click( function(circle_data) {get_reviews(business_data, circle_data);}) }); // To do: make function for drawing buttons // Buttons for type of restaurant - academic, scraped, or both g.append("rect") .attr("id", "both_rect") .attr("x", width - button_margin) .attr("y", legend_top) .attr("rx", 2) .attr("ry", 2) .attr("width", 123) .attr("height", 18) .style("fill", current_color_rgb) .style("cursor", "pointer") .on("click", function() { var source = 'both'; update_source(source); d3.select('#both_text').style("fill", "white"); d3.select('#academic_text').style("fill", "black"); d3.select('#scraped_text').style("fill", "black"); d3.select('#both_text').style("font-weight", "bold"); d3.select('#academic_text').style("font-weight", "normal"); d3.select('#scraped_text').style("font-weight", "normal"); d3.select('#both_rect').style("fill", current_color_rgb); d3.select('#academic_rect').style("fill", academic_color_rgb); d3.select('#scraped_rect').style("fill", scraped_color_rgb); }); g.append("text") .attr("id", "both_text") .attr("x", width - button_margin + 3) .attr("y", legend_top + 13) .style("fill", "white") .style("font-size", "13px") .style("font-weight", "bold") .text("Academic + Scraped") .style("cursor", "pointer") .on("click", function() { var source = 'both'; update_source(source); d3.select('#both_text').style("fill", "white"); d3.select('#academic_text').style("fill", "black"); d3.select('#scraped_text').style("fill", "black"); d3.select('#both_text').style("font-weight", "bold"); d3.select('#academic_text').style("font-weight", "normal"); d3.select('#scraped_text').style("font-weight", "normal"); d3.select('#both_rect').style("fill", current_color_rgb); d3.select('#academic_rect').style("fill", academic_color_rgb); d3.select('#scraped_rect').style("fill", scraped_color_rgb); }); // Buttons for type of restaurant - academic, scraped, or both g.append("rect") .attr("id", "academic_rect") .attr("x", width - button_margin) .attr("y", legend_top + 24) .attr("rx", 2) .attr("ry", 2) .attr("width", 62) .attr("height", 18) .style("fill", academic_color_rgb) .style("cursor", "pointer") .on("click", function() { var source = 'Academic'; update_source(source); d3.select('#both_text').style("fill", "black"); d3.select('#academic_text').style("fill", "white"); d3.select('#scraped_text').style("fill", "black"); d3.select('#both_text').style("font-weight", "normal"); d3.select('#academic_text').style("font-weight", "bold"); d3.select('#scraped_text').style("font-weight", "normal"); d3.select('#both_rect').style("fill", both_color_rgb); d3.select('#academic_rect').style("fill", current_color_rgb); d3.select('#scraped_rect').style("fill", scraped_color_rgb); }); g.append("text") .attr("id", "academic_text") .attr("x", width - button_margin + 3) .attr("y", legend_top + 37) .style("fill", "black") .style("font-size", "13px") .text("Academic") .style("cursor", "pointer") .on("click", function() { var source = 'Academic'; update_source(source); d3.select('#both_text').style("fill", "black"); d3.select('#academic_text').style("fill", "white"); d3.select('#scraped_text').style("fill", "black"); d3.select('#both_text').style("font-weight", "normal"); d3.select('#academic_text').style("font-weight", "bold"); d3.select('#scraped_text').style("font-weight", "normal"); d3.select('#both_rect').style("fill", both_color_rgb); d3.select('#academic_rect').style("fill", current_color_rgb); d3.select('#scraped_rect').style("fill", scraped_color_rgb); }); // Buttons for type of restaurant - academic, scraped, or both g.append("rect") .attr("id", "scraped_rect") .attr("x", width - button_margin) .attr("y", legend_top + 48) .attr("rx", 2) .attr("ry", 2) .attr("width", 50) .attr("height", 18) .style("fill", scraped_color_rgb) .style("cursor", "pointer") .on("click", function() { var source = 'Scraped'; update_source(source); d3.select('#both_text').style("fill", "black"); d3.select('#academic_text').style("fill", "black"); d3.select('#scraped_text').style("fill", "white"); d3.select('#both_text').style("font-weight", "normal"); d3.select('#academic_text').style("font-weight", "normal"); d3.select('#scraped_text').style("font-weight", "bold"); d3.select('#both_rect').style("fill", both_color_rgb); d3.select('#academic_rect').style("fill", academic_color_rgb); d3.select('#scraped_rect').style("fill", current_color_rgb); }); g.append("text") .attr("id", "scraped_text") .attr("x", width - button_margin + 3) .attr("y", legend_top + 60) .style("fill", "black") .style("font-size", "13px") .text("Scraped") .style("cursor", "pointer") .on("click", function() { var source = 'Scraped'; update_source(source); d3.select('#both_text').style("fill", "black"); d3.select('#academic_text').style("fill", "black"); d3.select('#scraped_text').style("fill", "white"); d3.select('#both_text').style("font-weight", "normal"); d3.select('#academic_text').style("font-weight", "normal"); d3.select('#scraped_text').style("font-weight", "bold"); d3.select('#both_rect').style("fill", both_color_rgb); d3.select('#academic_rect').style("fill", academic_color_rgb); d3.select('#scraped_rect').style("fill", current_color_rgb); }); var legend_data = new Set(color.domain()); legend_data = Array.from(legend_data); legend_data = legend_data.sort(); var legend = g.selectAll(".legend") .data(legend_data) .enter().append("g") .attr("class", "legend") .attr("transform", function(d, i) { return "translate(-50," + i * 20 + ")"; }); legend.append("rect") .attr("x", width - legend_margin) .attr("y", categories_top) .attr("width", 18) .attr("height", 18) .style("fill", color) .on("click", function(d) { var category = category_to_name[d]; update_category(category); }); legend.append("text") .attr("id", "category-text") .attr("x", width - legend_margin - 6) .attr("y", categories_top + 9) .attr("dy", ".35em") .style("text-anchor", "end") .text(function(d) { return category_to_name[d]; }) .style("font-size", "13px") .style("font-weight", function(d) { if (category_to_name[d] == "All") { return "bold"; } else { return "normal"; } }) .on("click", function(d) { var category = category_to_name[d]; update_category(category); }); g.append("text") .attr('id', 'note') .attr("x", width / 8) .attr("y", map_height + note_margin1) .attr("text-anchor", "left") .style("font-size", "12px") .html("Hover over dots to see a business's information, and click to see its reviews. Navigate reviews with the arrow keys, and hit \"escape\" or double click to remove a box."); g.append("text") .attr('id', 'note') .attr("x", width / 8) .attr("y", map_height + note_margin2) .attr("text-anchor", "left") .style("font-size", "12px") .html('Data are from Yelp.com\'s <a style="fill: #1f77b4;" href="https://www.yelp.com/dataset_challenge" target="_blank">Academic Dataset</a> and Yelp.com. Code is adapted from <a style="fill: #1f77b4;" href="http://bl.ocks.org/michellechandra/0b2ce4923dc9b5809922" target="_blank">Michelle Chandra\'s code</a> and several D3 tutorials.'); // title = source_title + " Data (" + business_data.length.toLocaleString('en') + ")"; title = source_title + " Data"; d3.select("#title").text(title); svg.call(zoom).call(zoom.event); d3.select("#loading").remove(); }; function update_source(source) { d3.selectAll("circle") .style("opacity", function(d) { if (d.type != source & source != "both") { d.source_correct = 0; return 0; } else { d.source_correct = 1; } if (d.category_correct == 0) { return 0; } if (d.category_correct == 1) { return 0.9; } }) .style("pointer-events", function(d) { if (d.type != source & source != "both") { d.source_correct = 0; return "none"; } else { d.source_correct = 1; } if (d.category_correct == 0) { return "none"; } if (d.category_correct == 1) { return "all"; } }); if (source == 'both') { source_title = 'Academic and Scraped'; } else { source_title = source; } title = source_title + " Data"; d3.select("#title").text(title); } function update_category(category) { d3.selectAll("circle") .style("opacity", function(d) { if ((d.cat != category) & (category != "All")) { d.category_correct = 0; return 0; } else { d.category_correct = 1; } if (d.source_correct == 0) { return 0; } if (d.source_correct == 1) { return 0.9; } }) .style("pointer-events", function(d) { if ((d.cat != category) & (category != "All")) { d.category_correct = 0; return "none"; } else { d.category_correct = 1; } if (d.source_correct == 0) { return "none"; } if (d.source_correct == 1) { return "all"; } }); d3.selectAll("#category-text") .style("font-weight", function(d) { if (category_to_name[d] == category) { return "bold"; } else { return "normal"; } }); } // If the drag behavior prevents the default click, // also stop propagation so we don’t click-to-zoom. function stopped() { if (d3.event.defaultPrevented) d3.event.stopPropagation(); } function get_reviews(business_data, circle_data) { $.getJSON($SCRIPT_ROOT + "/data", {dtype: 'reviews', business_id: business_data.business_id, business_type: business_data.type}, function(data) { draw_reviews(data, business_data, circle_data); } ); } function main() { var projection = d3.geo.albersUsa() // translate to center of screen, slightly to the left .translate([(width / 2) - translate_left, window_height / 2 - translate_up]) // scale things down so see entire US .scale([map_scale]); // Get the map data and draw the map $.getJSON($SCRIPT_ROOT + "/data", {dtype: 'map'}, function(map_data) { // Get the businesses data and add dots to map $.getJSON($SCRIPT_ROOT + "/data", {dtype: 'business'}, function(business_data) { // document.getElementById("loading").style.width = "0%"; add_data(map_data, business_data, projection); } ); } ); } main(); });
import moment from 'moment'; export const hoje = moment().format('YYYY-MM-DD'); export const amanha = moment() .add(1, 'days') .format('YYYY-MM-DD');
import AppOne from "./AppOne"; export default AppOne;
import { RECEIVE_DATA } from '../actions'; export const sitesReducer = (state = [], action) => { switch (action.type) { case RECEIVE_DATA: return [ ] default: return state } } export const sitesByIdReducer = (state = [], action) => { switch (action.type) { case RECEIVE_DATA: // return action.payload.reduce((items, item) => { // items[item.id] = item // return items // }, {}) [] default: return state } }
import shared from "../author-profile"; describe("AuthorProfile tests on web", () => { shared(); });
angular.module("console").controller("AddLotteryRuleCtrl", ["$scope", function ($scope) { }]);
var express = require('express') var app = express() // Definição de request e response da root app.get('/', function (request, response) { response.send('Vocês estão prontas crianças?') }) // Disparando porta que o app ficara "listening" huehue app.listen(8085, function () { console.log('Estamos na porta 8085, capitão!') })
import { Row, Col, Container, Modal, Form, Button } from 'react-bootstrap'; import '../styles/modal.css'; import '../styles/modal-form.css'; import React, { useState } from 'react'; import axios from 'axios'; import ModalConfirm from '../../modal-list/modal-confirm.js'; import { auth, fs } from "../../../../../config/firebase"; import { useHistory } from 'react-router-dom'; import { useForm } from "react-hook-form"; const ModalFormIlustra = ({ onHide, show, item }) => { //Rotas para a página const history = useHistory(); /*Funções para abrir e fechar o Modal de Confirmação */ const [showConfirm, setShow] = useState(false); const handleClose = () => setShow(false); const handleShow = () => setShow(true); const [campos, setCampos] = useState({ tipo: '', nome: '', contato: '', email: '', desc: '', adicao_personagem: '', fundo: '' }); function getRandomInt(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min)) + min; } function handleInputChange(event) { campos[event.target.name] = event.target.value; setCampos(campos); } function handleFormSubmit() { campos["tipo"] = item; setCampos(JSON.stringify(campos)); auth.onAuthStateChanged(user => { if (user) { let num_pedido = getRandomInt(1000000, 9999999); let uid = user.uid; let status = "Pedido recebido"; let data = new Date(); fs.collection('Encomendas-list').add({ uid, campos, status, data, num_pedido }).then(() => { axios.post('/encomendas/send-ilustra', campos, { headers: { 'Content-Type': 'application/json' } }).then((response) => { setCampos({ tipo: '', nome: '', contato: '', email: '', desc: '', adicao_personagem: '', fundo: '' }); onHide(); handleShow(); setTimeout(() => { handleClose(); history.push('/perfil'); }, 4000) }); }); } }) } //Validação do form const { register, formState: { errors }, handleSubmit } = useForm(); const onSubmit = () => handleFormSubmit(); const [telefone, setTelefone] = useState(""); function handleTelefone(e) { campos[e.target.name] = e.target.value; setCampos(campos); const modelo = /^([0-9]{2})([0-9]{4,5})([0-9]{4})$/; var str = e.target.value.replace(/[^0-9]/g, "").slice(0, 11); const result = str.replace(modelo, "($1)$2-$3"); setTelefone(result); } return (<> <Modal backdrop="static" onHide={onHide} show={show} dialogClassName="modal-mobile-enc modal-mobile-enc-form" > <Modal.Header closeButton id="modal-enc-header"> <div /> </Modal.Header> <Modal.Body> <Container className="modal-container-form"> <Row className="modal-enc-linhaForm"> <h1>{"ILUSTRAÇÃO DIGITAL - " + item}</h1> </Row> <Row className="modal-line-form"> <Form onSubmit={handleSubmit(onSubmit)}> <Row> <Col xs={12} md={8}> <Form.Group className="mb-3" controlId="exampleForm.ControlInput1"> <Form.Label>Nome Completo</Form.Label> <Form.Control type="text" placeholder="Nome" name="nome" {...register('nome', { required: true })} onChange={handleInputChange} /> {errors.nome ? ( <> {errors.nome.type === "required" && ( <p style={{ color: "red", fontSize: 10, margin: 1 }}> Campo obrigatório </p> )} </> ) : null} </Form.Group> </Col> <Col xs={12} md={4}> <Form.Group className="mb-3" controlId="exampleForm.ControlInput1"> <Form.Label>Contato (whatsapp)</Form.Label> <Form.Control type="text" placeholder="(xx) xxxxx-xxxx" name="contato" value={telefone} {...register('contato', { required: true })} onChange={handleTelefone.bind(this)} /> {errors.contato ? ( <> {errors.contato.type === "required" && ( <p style={{ color: "red", fontSize: 10, margin: 1 }}> Campo obrigatório </p> )} </> ) : null} </Form.Group> </Col> </Row> <Row> <Col xs={12} md={8}> <Form.Group className="mb-3" controlId="exampleForm.ControlInput1"> <Form.Label>E-mail</Form.Label> <Form.Control type="email" placeholder="name@example.com" name="email" {...register('email', { required: true })} onChange={handleInputChange} /> {errors.email ? ( <> {errors.email.type === "required" && ( <p style={{ color: "red", fontSize: 10, margin: 1 }}> Campo obrigatório </p> )} </> ) : null} </Form.Group> <Form.Group className="mb-2.5" controlId="exampleForm.ControlTextarea1"> <Form.Label>Descrição do pedido</Form.Label> <Form.Control as="textarea" rows={5} name="desc" {...register('desc', { required: true })} onChange={handleInputChange} /> {errors.desc ? ( <> {errors.desc.type === "required" && ( <p style={{ color: "red", fontSize: 10, margin: 1 }}> Campo obrigatório </p> )} </> ) : null} </Form.Group> </Col> <Col xs={12} md={4}> <Col> <Form.Group className="mb-3" controlId="exampleForm.ControlInput1"> <Form.Label>Adição de personagem? (+20R$)</Form.Label> <Row> <Col xs={6}> <Form.Check type="radio" className="default-radio default-radio-add"> <Form.Check.Input className="radioBtn" name="adicao_personagem" type="radio" value="Sim" onChange={handleInputChange} required /> <Form.Check.Label>Sim</Form.Check.Label> </Form.Check> </Col> <Col xs={6}> <Form.Check type="radio" className="default-radio default-radio-add" > <Form.Check.Input className="radioBtn" name="adicao_personagem" type="radio" value="Não" onChange={handleInputChange} /> <Form.Check.Label>Não</Form.Check.Label> </Form.Check> </Col> </Row> </Form.Group> </Col> <Col> <Form.Group className="mb-3 radio-back" controlId="exampleForm.ControlInput1" > <Form.Label>Qual tipo de fundo você deseja?</Form.Label> <Form.Check type="radio" className="default-radio default-radio-back default-radio-backs" > <Form.Check.Input className="radioBtn" name="fundo" type="radio" value="Sem fundo" onChange={handleInputChange} required /> <Form.Check.Label>Sem fundo</Form.Check.Label> </Form.Check> <Form.Check type="radio" className="default-radio default-radio-back" required > <Form.Check.Input className="radioBtn" name="fundo" type="radio" value="Pattern simples" onChange={handleInputChange} /> <Form.Check.Label>Pattern simples</Form.Check.Label> </Form.Check> <Form.Check type="radio" className="default-radio default-radio-back" > <Form.Check.Input className="radioBtn" name="fundo" type="radio" value="Cor sólida" onChange={handleInputChange} /> <Form.Check.Label>Cor sólida</Form.Check.Label> </Form.Check> <Form.Check type="radio" className="default-radio" > <Form.Check.Input className="radioBtn" name="fundo" type="radio" value="Outro (informar na descrição)" onChange={handleInputChange} /> <Form.Check.Label>Outro (informar na descrição)</Form.Check.Label> </Form.Check> </Form.Group> </Col> </Col> </Row> <Row> <div className="botao-encomende d-flex justify-content-end"> <Button className="btn btn-primary button-save" variant="primary" type="submit" block> FAZER ORÇAMENTO </Button> </div> </Row> </Form> </Row> </Container> </Modal.Body> </Modal> <ModalConfirm show={showConfirm} onHide={handleClose} /> </>) } export default ModalFormIlustra;
import React from 'react'; import Copyright from './Copyright/Copyright'; import PreFooter from './PreFooter/PreFooter'; class Footer extends React.Component { render() { return ( <footer className = "footer"> <PreFooter /> <Copyright /> </footer> ); } } export default Footer;
import { combineReducers } from "redux"; const initialState = []; const rootReducer = (state = initialState, action) => { switch (action.type) { case "ADD_TRACKER": return [action.payload, ...state]; case "PAUSE_TRACKER": return state.map((tracker) => { if (tracker.id === action.payload.id) { tracker.startTime ? (tracker.startTime = 0) : (tracker.startTime = Date.now()); tracker.totalTime = action.payload.totalTime; } return tracker; }); case "REMOVE_TRACKER": return state.filter((tracker) => tracker.id !== action.payload.id); default: return state; } }; export default combineReducers({ trackers: rootReducer });
$(document).ready(function(){ var add="<button class='btn btn-success' id='add2'>添加</button>"; var xiaohui="<button class='btn btn-danger' id='del'>销毁</button>"; var apply ="<button class='btn btn-danger' id='apply'>申请销毁</button>"; $.ajax({ url:"bookBad/showAllBadBooks", dataType:"json", success:function(data){ $.each(data, function(index, item){ if(item.btype==0){ var state="未审核"; var btn=add+" "+apply; } else if (item.btype==1){ var state="正在审核"; var btn="请等待处理"; } else{ var state="审核通过"; var btn=" "+xiaohui; } $("#tb").append("<tr>" + "<td>"+item.badId+"</td>" + "<td>"+item.isbn+"</td>" + "<td>"+item.badtime+"</td>" + "<td>"+item.badnum+"</td>" + "<td>"+state+"</td>" + "<td>"+btn+"</td>" + "</tr>") }); } }); $("#add").on("click",function() { var isbn =$("#isbn").val(); if (isbn=="请输入isbn号") { alert("请输入isbn号"); }else{ $.ajax({ url:"bookBad/replaceBadBook", dataType:"json", data:{ 'Id':"", 'isbn':isbn, 'badnum':1, }, success:function(data){ alert(data[0]); window.location.reload(); }, error:function (jqXHR, textStatus, errorThrown) { /*弹出jqXHR对象的信息*/ alert(jqXHR.responseText);//???? alert(jqXHR.status);//200 alert(jqXHR.readyState);//4 alert(jqXHR.statusText);//parsererror /*弹出其他两个参数的信息*/ alert(textStatus);//parsererror alert(errorThrown);//SyntaxError: Unexpected token ? in JSON at position 0 } }); } }) $("#tables").on("click","#add2",function () { var isbn= $(this).parents("tr").find("td").eq(1).text(); $.ajax({ url:"bookBad/replaceBadBook", dataType:"json", data:{ 'Id':"", 'isbn':isbn, }, success:function(data){ alert(data[0]); window.location.reload(); }, error:function (jqXHR, textStatus, errorThrown) { /*弹出jqXHR对象的信息*/ alert(jqXHR.responseText);//???? alert(jqXHR.status);//200 alert(jqXHR.readyState);//4 alert(jqXHR.statusText);//parsererror /*弹出其他两个参数的信息*/ alert(textStatus);//parsererror alert(errorThrown);//SyntaxError: Unexpected token ? in JSON at position 0 } }); }) $("#tables").on("click","#del",function () { var isbn= $(this).parents("tr").find("td").eq(1).text(); $.ajax({ url:"bookBad/deleteBadBooks", dataType:"json", data:{ 'isbn':isbn, }, success:function(){ alert("成功"); window.location.reload(); },error:function (jqXHR, textStatus, errorThrown) { /*弹出jqXHR对象的信息*/ alert(jqXHR.responseText);//???? alert(jqXHR.status);//200 alert(jqXHR.readyState);//4 alert(jqXHR.statusText);//parsererror /*弹出其他两个参数的信息*/ alert(textStatus);//parsererror alert(errorThrown);//SyntaxError: Unexpected token ? in JSON at position 0 } }); }) $("#tables").on("click","#apply",function () { var isbn= $(this).parents("tr").find("td").eq(1).text(); $.ajax({ url:"bookBad/applyBadBook", dataType:"json", data:{ 'isbn':isbn, 'btype':1, }, success:function(){ alert("成功"); window.location.reload(); },error:function (jqXHR, textStatus, errorThrown) { /*弹出jqXHR对象的信息*/ alert(jqXHR.responseText);//???? alert(jqXHR.status);//200 alert(jqXHR.readyState);//4 alert(jqXHR.statusText);//parsererror /*弹出其他两个参数的信息*/ alert(textStatus);//parsererror alert(errorThrown);//SyntaxError: Unexpected token ? in JSON at position 0 } }); }) })
/* * Copyright (c) 2017 Inspireso and/or its affiliates. * Licensed under the MIT License. * */ module.exports = { MessageBox: require('./MessageBox'), Nabbar: require('./Nabbar'), SearchBar: require('./SearchBar'), Tabbar: require('./Tabbar'), Toast: require('./Toast') };
export { default as Header } from './Header' export { default as PageWrapper } from './PageWrapper'