text
stringlengths
7
3.69M
import express from 'express'; import setupMiddleware from './middleware'; import prisma from './db'; const app = express(); setupMiddleware(app); app.use('/testing', (req, res) => { res.status(333).json({ fuck: 'yes!' }); }); app.get('/seasons', async (req, res) => { try { const response = await prisma.seasons(); res.status(200).json(response); } catch (e) { res.status(500).json(e); } }); app.post('/seasons', async (req, res) => { try { const response = await prisma.createSeason(req.body); res.status(201).json(response); } catch (e) { res.status(500).json(e); } }); // catch-all app.all('*', (req, res) => { res.status(200).json({ ok: true }); }); export default app;
import React from "react"; function Show({ selected, hide }) { return ( <div className="show"> <div> <h1> {selected.Title} </h1> <img src={selected.Poster} alt="tasveer.." /> </div> <div> <h3> {selected.Plot} </h3> <h2>{selected.Actors} </h2> </div> <div> <h2>{selected.Awards}</h2> <h2> {selected.Ratings.map((rating) => ( <ul key={rating.Value}> {rating.Source}-{rating.Value} </ul> ))} </h2> </div> <div style={{ paddingLeft: "150px" }}> <button onClick={hide}>Close</button> </div> </div> ); } export default Show;
var a = getApp(); Page({ data: { showSearch: !1 }, onLoad: function(t) { var e = this; t.from && (e.data.from = t.from), a.util.getLocation(function(a) { var t = a.data.message.message; e.setData({ location: t.address, location_x: t.location_x, location_y: t.location_y, pois: t.pois.slice(0, 10) }); }), a.util.request({ url: "wmall/home/location/index", success: function(a) { var a = a.data.message.message; e.setData({ addresses: a }); } }); }, onInput: function(t) { var e = this, o = t.detail.value; if (!o) return e.setData({ showSearch: !1 }), !1; a.util.request({ url: "system/common/map/suggestion", data: { key: o }, success: function(a) { var t = a.data.message.message; console.log("o", o) console.log("t",t) t.length > 0 && e.setData({ searchAddress: t, showSearch: !0 }); } }); }, onChooseAddress: function(t) { var e = this, o = t.currentTarget.dataset; if (!o.x || !o.y) return a.util.toast("该地址无效"), !1; o.onshow = 1, a.util.setStorageSync("location", o, 300); var s = "./mapStore"; // "paotui" == e.data.from ? s = "../paotui/guide" : "gohome" == e.data.from ? s = "/gohome/pages/home/index" : "tongcheng" == e.data.from && (s = "/gohome/pages/tongcheng/index"), "paotui" == e.data.from ? s = "../paotui/guide" : "gohome" == e.data.from ? s = "/gohome/pages/home/index" : "tongcheng" == e.data.from && (s = "/gohome/pages/tongcheng/index"), wx.switchTab({ url: s, fail: function(a) { "switchTab:fail can not switch to no-tabBar page" != a.errMsg && "switchTab:fail:can not switch to non-TabBar page" != a.errMsg || wx.redirectTo({ url: s }); } }); }, onPullDownRefresh: function() { this.onLoad(), wx.stopPullDownRefresh(); } });
import React from 'react' import { Subtitle } from '../../Titles/Subtitle/Subtitle' export const KillerDetails = (props) => { const { death } = props return ( <> <div style={{ width: '100%', margin: '5%' }}> <Subtitle title="Cause" isMargin={true}> <h3>{death.cause}</h3> </Subtitle> <Subtitle title="Last Words" isMargin={true}> <h3>{`${death.last_words}`}</h3> </Subtitle> </div> </> ) }
import React from 'react'; import { Component } from 'react'; import { Form,Button } from 'react-bootstrap'; class BMI extends Component { constructor(props){ super(props); this.state={ height:null, weight:null } } handlesubmit=(event)=>{ event.preventDefault() } handleInputChange=(event)=>{ event.preventDefault() console.log(event) console.log(event.target.height) console.log(event.target.value) this.setState({ [event.target.name]:event.target.value }) } calculate=()=>{ var c=document.getElementById("resBMR") var {height}=this.state; var {weight}=this.state; console.log("h=",height,"w=",weight) var bmi=(weight/(height*height))*10000; if (bmi>25){ c.innerHTML="<br><h6>BMI : "+bmi+"</h4><p>OverWeight</p>" } else if(bmi<15){ c.innerHTML="<br><h6>BMI : "+bmi+"</h4><p>UnderWeight</p>" } else{ c.innerHTML="<br><h6>BMI : "+bmi+"</h4><p>Normal</p>" } console.log('bmi:',bmi) } render(){ //const {height}=this.state; //const {weight}=this.state; return( <div> <div className="container my-3"> <Form onSubmit={this.handlesubmit}> <Form.Group> <Form.Label>Enter height in cm</Form.Label> <Form.Control type="number" name="height" placeholder="Enter height in cm" onChange={this.handleInputChange}/> </Form.Group> <Form.Group> <Form.Label>Enter weight in kg</Form.Label> <Form.Control type="number" name="weight" placeholder="Enter weight in kg" onChange={this.handleInputChange}/> </Form.Group> <Form.Group> <Button className="btn-sucess" onClick={this.calculate}>Calculate</Button> </Form.Group> </Form> <div id="resBMR" className="text-center"></div> </div> </div> ) } } export default BMI
export let requestInterval = function(fn, delay) { var requestAnimFrame = (function() { return ( window.requestAnimationFrame || function(callback, element) { window.setTimeout(callback, 1000 / 60); } ); })(), start = new Date().getTime(), handle = {}; function loop() { handle.value = requestAnimFrame(loop); var current = new Date().getTime(), delta = current - start; if (delta >= delay) { fn.call(); start = new Date().getTime(); } } handle.value = requestAnimFrame(loop); return handle; };
var express = require('express'); var router = express.Router(); var reviewCtrl = require(REVIEW_CONTROLLER); router.get('/', reviewCtrl.Query); router.post('/', reviewCtrl.Add); module.exports = router;
const { Provider } = require('./libs/wechat-weapp-redux.js'); const configureStore = require('./store/configureStore.js'); import locales from './utils/locales.js' import T from './libs/wxapp-i18n.js' T.registerLocale(locales) T.setLocale('zh') wx.T = T App(Provider(configureStore())({ onLaunch() { }, globalData: { userInfo: null, color: '#FF7920', point: { latitude: 0, longitude: 0 } } }))
var address = null; var saveState = ""; window.onload = function () { if (address == null) address = document.getElementById("search-field"); } $('#form').submit(function (e) { alert("test"); e.preventDefault(); invalidInput(); }); // When a key is pressed into the input field // When the user pressed enter, they have entered their address into the system function keyPressed(val) { if (event.key == 'Enter' && correctFormat(address.value)) { saveState = address.value; return submitAddress(); } else { var key = event.keyCode || event.charcode; if (key == 8) // Backspace correctFormat(address.value.substring(0, address.value.length - 1)); else correctFormat(address.value + event.key) } /* API TESTINg, for an actual address Can be removed if not used // Obtained from https://docs.microsoft.com/en-us/bingmaps/rest-services/locations/find-a-location-by-address#examples // Using the api to verify for a real address if (address.value.length >= 3) { getAddress().then( data => ( console.log(data) ) ); } */ } function correctFormat(str) { var hasNumber = false; var hasWord = false; str = str.trim(); if (str == "") { validInput(); return false; } for (var i = 0; i < str.length; i++) { if (!hasNumber && str.charAt(i) >= '0' && str.charAt(i) <= '9') { hasNumber = true; } else if (!hasNumber && (str.charAt(i) < '0' || str.charAt(i) > '9')) { invalidInput(); return false; } if (hasNumber && (str.charAt(i) >= 'a' && str.charAt(i) <= 'z') || (str.charAt(i) >= 'A' && str.charAt(i) <= 'Z') && !hasWord) { hasWord = true; } // Can't have a number after the word if (hasWord && str.charAt(i) >= '0' && str.charAt(i) <= '9') { invalidInput(); return false; } } // Show the user the problem after 4 numbers if (hasNumber && !hasWord && str.length > 4) invalidInput(); if (hasWord && hasNumber) { validInput(); return true; } return false; } /* API TESTING, for an actual address Getting the actual response from the APi as a JSON object * // Code snippet from https://levelup.gitconnected.com/all-possible-ways-of-making-an-api-call-in-plain-javascript-c0dee3c11b8b async function getAddress() { let response = await fetch('http://dev.virtualearth.net/REST/v1/Locations/CA/Manitoba/?locality=' + address.value.trim() + '&maxResults=1&key=ArwDx4-VpPz6dyWwnHZg8Pp00fFMs6qqCmk1uf3Q9HhM9xaaiLXG9RwqK3O0lEBO'); let data = await response.json(); return data; } */ function invalidInput() { document.getElementById("changeFeedback").style.display = "block"; } function validInput() { document.getElementById("changeFeedback").style.display = "none"; } function submitCheck() { if (correctFormat(address.value)) { submitAddress(); } else invalidInput(); } function submitAddress() { if (address == null) { invalidInput(); return; } // Remove prior memory [if any] window.localStorage.clear(); var userAddress = address.value.trim(); setUserAddress(userAddress); return redirect(); } // Redirect the user to the main page function redirect() { window.location.href = "Main_Page.html", true; return false; }
/**坐标系转换:80西安转2000,西安1980即EPSG:4610,China Geodetic Coordinate System 2000即EPSG:4490 */ proj4.defs("EPSG:4490","+proj=longlat +ellps=GRS80 +no_defs");
'use strict'; var express = require('express'); var mongoose = require('mongoose'); var conf = require('./config'); // Connect to mongodb mongoose.connect('mongodb://localhost/test') // conf.MONGOHQ_URL console.log('DB connection established'); // Express var app = express(); // Env. settings app.use(express.static(__dirname + '/public')); // Routes var routes = require('./routes'); // Start server app.listen(3000, function() { console.log('Server listening on port 3000...'); });
(function() { 'use strict'; var hotelModule = angular.module('Hotel', [ 'ngRoute', 'Hotel.Common', 'Hotel.User', 'Hotel.Login', 'Hotel.Room', 'angular-storage', 'angular.filter', 'ui.select', 'ngSanitize', 'ui.bootstrap', 'AngularPrint' ]); hotelModule.config(function($routeProvider) { $routeProvider //route for the home page .when('/roomboard', { templateUrl: 'client/src/hotel/room/tmpl/roomsboard.html', controller: 'RoomboardCtrl', controllerAs: 'roomboard', activeTab: 'roomboard' }) .when('/login', { templateUrl: 'loginModalContainer', controller: 'LoginCtrl', // controllerAs: 'login', }) .when('/roommanage', { templateUrl: 'client/src/hotel/room/tmpl/roommanage.html', controller: 'RoomManageCtrl', controllerAs: 'roommanage', activeTab: 'roommanage' }) /* .when('/exchangeroom', { templateUrl: 'client/src/hotel/room/tmpl/exchangeroom.html', controller: 'ExchangeCtrl', controllerAs: 'exchangeroom', activeTab: 'exchangeroom' })*/ .when('/checkout', { templateUrl: 'client/src/hotel/room/tmpl/checkoutroom.html', controller: 'CheckoutCtrl', controllerAs: 'checkout', activeTab: 'checkout' }) .when('/checkin', { templateUrl: 'client/src/hotel/room/tmpl/checkinroom.html', controller: 'CheckinCtrl', controllerAs: 'checkin', activeTab: 'checkin' }) .when('/addRoom', { templateUrl: 'client/src/hotel/room/tmpl/addroom.html', controller: 'AddRoomCtrl', controllerAs: 'addroom', activeTab: 'roommanage' }) .when('/transfer', { templateUrl: 'transferModalContainer', controller: 'TransferCtrl', // controllerAs: 'login', }) .otherwise({ redirectTo: '/roomboard' // redirectTo: '/login' }); }); hotelModule.run( function($rootScope, $location, $http, store) { $rootScope.globals = store.get('globals') || {}; if ($rootScope.globals && $rootScope.globals.currentUser) { $http.defaults.headers.common['Authorization'] = 'Basic ' + $rootScope.globals.currentUser.token; } $rootScope.$on('$locationChangeStart', function(event, next, current) { // redirect to login page if not logged in and trying to access a restricted page var restrictedPage = $.inArray($location.path(), ['/login']) === -1; var loggedIn = $rootScope.globals && $rootScope.globals.currentUser; if (restrictedPage && !loggedIn) { $location.path('/login'); } }); }); hotelModule.value('FLOORS', [{ name: '所有楼层', value: '' }, { name: '一楼', value: '1' }, { name: '二楼', value: '2' }, { name: '三楼', value: '3' }]); hotelModule.value('ROOM_TYPES', [{ name: '所有房间类', value: '' }, { name: '单人间', value: '1' }, { name: '双人间', value: '2' }, { name: '三人间', value: '3' }, { name: '四人间', value: '4' }]); hotelModule.value('ROOM_STATUS', [{ name: '所有状态房间', value: '' }, { name: '可租用', value: '1' }, { name: '已入住', value: '2' }, { name: '待收拾', value: '3' }, { name: '待维修', value: '4' }]); hotelModule.value('ROOM_PRICES', [{ name: 'Big room', id: '1', value: '100' }, { name: 'Small room', id: '2', value: '50' }, { name: '3 level Room', id: '3', value: '150' }]); })();
import React, { Fragment, useState } from 'react'; import NavBar from '../../components/narbars/navbar'; import SideBar from '../../components/narbars/sideBarComentarios'; const Principal = () => { const [ sideBar, setSideBar ] = useState(false) return ( <Fragment> <NavBar setSideBar={setSideBar} /> <SideBar setSideBar={setSideBar} sideBar={sideBar} /> </Fragment> ); } export default Principal;
import dynamic from "next/dynamic"; import "tailwindcss/tailwind.css"; function MyApp({ Component, pageProps }) { return ( <div className="flex flex-col items-center min-h-screen"> <Component {...pageProps} /> </div> ); } export default dynamic(() => Promise.resolve(MyApp), { ssr: false, });
module.exports = function requireFromCWD( mod ) { const resolvedPath = require.resolve( mod, { paths: [ process.cwd() ] } ); return require( resolvedPath ); };
//Name: //points break down: //implement a simultaneous two-player mode (50) //Redesign the game's artwork, UI, and sound to change its theme/aesthetic (to something other than sci-fi) (50) // game configuration object let config = { type: Phaser.CANVAS, width: 640, height: 480, scene: [ Menu, Menu2, Menu3, Play, Player2], } // main game object let game = new Phaser.Game(config); //reserve keyboard vars let keyUP, keyLEFT, keyRIGHT,keyF; //Multiplayer keyboard vars let keyD, keyA, keyW; // define game settings game.settings = { spaceshipSpeed: 3, gameTimer: 60000 }
import isInteger from './is-integer' export default function isNaturalNumber(thing) { return isInteger(thing) && parseInt(thing) >= 0 }
/* Translate the provided string to pig latin. Pig Latin takes the first consonant (or consonant cluster) of an English word, moves it to the end of the word and suffixes an "ay". If a word begins with a vowel you just add "way" to the end. Input strings are guaranteed to be English words in all lowercase. */ function translatePigLatin(str) { var consonant = str.match(/^[a-z]/) && str.match(/[^aeiou]*/).join(''); if (consonant !== '') { var newStr = str.replace(consonant, '') + consonant + "ay"; } else { newStr = str + "way"; } return newStr; } translatePigLatin("consonant");
var HVector = (function () { function HVector (x, y, z) { this.x = x || 0; this.y = y || 0; this.z = z || 0; } HVector.prototype = { scale : function (sc) { var s = this; s.x *= sc; s.y *= sc; s.z *= sc; }, getLength : function () { var s = this; return Math.sqrt (s.x*s.x + s.y*s.y + s.z*s.z); }, setLength : function (len) { var s = this; var r = s.getLength(); r ? s.scale(len/r) : x = len; }, dot : function (v) { var s = this; return s.x*v.x+s.y*v.y+s.z*v.z; }, cross : function (v) { var s = this; var cx = s.y * v.z - s.z * v.y; var cy = s.z * v.x - s.x * v.z; var cz = s.x * v.y - s.y * v.x; return new HVector(cx, cy, cz); }, angleBetween : function (v) { var s = this; var dp = s.dot (v); var cosAngle = dp / (s.getLength() * v.s.getLength()); return HDegree.acosD (cosAngle); }, getPerspective : function (radio) { var s = this; radio = radio ? radio : 300; return radio / (s.z + radio); }, persProject : function (radio) { var s = this; radio = radio ? radio : s.getPerspective(); s.x *= radio; s.y *= radio; s.z = 0; }, persProjectNew : function (radio) { var s = this; radio = radio ? radio : s.getPerspective(); var vector = {x:radio*s.x,y:radio*s.y}; return vector; //return new HVector (radio*s.x, radio*s.y, 0); }, rotateX : function (ang) { var s = this; var ca = HDegree.cosD (ang); var sa = HDegree.sinD (ang); s.rotateXTrig(ca, sa); }, rotateXTrig : function (ca,sa) { var s = this; var ry = s.y * ca - s.z * sa; var rz = s.y * sa + s.z * ca; s.y = ry; s.z = rz; }, getAngleX : function () { var s = this; return HDegree.atan2D(s.z, s.y); }, setAngleX : function (ang) { var s = this; var r = Math.sqrt (s.y*s.y + s.z*s.z); s.y = r * HDegree.cosD (ang); s.z = r * HDegree.sinD (ang); }, rotateY : function (ang) { var s = this; var ca = HDegree.cosD (ang); var sa = HDegree.sinD (ang); s.rotateYTrig(ca, sa); }, rotateYTrig : function (ca,sa) { var s = this; var rx = s.x * ca + s.z * sa; var rz = s.x * -sa + s.z * ca; s.x = rx; s.z = rz; }, getAngleY : function () { var s = this; return HDegree.atan2D (s.z, s.x); }, setAngleY : function (ang) { var s = this; var r = Math.sqrt (s.x*s.x + s.z*s.z); s.x = r * HDegree.cosD (ang); s.z = r * HDegree.sinD (ang); }, rotateZ : function (ang) { var s = this; var ca = HDegree.cosD (ang); var sa = HDegree.sinD (ang); s.rotateZTrig(ca, sa); }, rotateZTrig : function (ca,sa) { var s = this; var rx = s.x * ca - s.y * sa; var ry = s.x * sa + s.y * ca; s.x = rx; s.y = ry; }, getAngleZ : function () { var s = this; return HDegree.atan2D (s.y, s.x); }, setAngleZ : function (ang) { var s = this; var r = Math.sqrt (s.y*s.y + s.x*s.x); s.y = r * HDegree.cosD (ang); s.x = r * HDegree.sinD (ang); }, rotateXY : function (a,b) { var s = this; var ca = HDegree.cosD (a); var sa = HDegree.sinD (a); var cb = HDegree.cosD (b); var sb = HDegree.sinD (b); s.rotateXYTrig(ca, sa, cb, sb); }, rotateZTrig : function (ca,sa) { var s = this; // x-axis rotation var rz = s.y * sa + s.z * ca; s.y = s.y * ca - s.z * sa; // y-axis rotation s.z = s.x * -sb + rz * cb; s.x = s.x * cb + rz * sb; }, rotateXY : function (a,b) { var s = this; var ca = HDegree.cosD (a); var sa = HDegree.sinD (a); var cb = HDegree.cosD (b); var sb = HDegree.sinD (b); s.rotateXYTrig(ca, sa, cb, sb); }, rotateXYTrig : function (ca, sa, cb, sb) { var s = this; // x-axis rotation var rz = s.y * sa + s.z * ca; s.y = s.y * ca - s.z * sa; // y-axis rotation s.z = s.x * -sb + rz * cb; s.x = s.x * cb + rz * sb; }, rotateXYZ : function (a,b,c) { var s = this; var ca = HDegree.cosD (a); var sa = HDegree.sinD (a); var cb = HDegree.cosD (b); var sb = HDegree.sinD (b); var cc = HDegree.cosD (c); var sc = HDegree.sinD (c); s.rotateXYZTrig(ca, sa, cb, sb, cc, sc); }, rotateXYZTrig : function (ca, sa, cb, sb,cc,sc) { var s = this; // x-axis rotation var ry = s.y * ca - s.z * sa; var rz = s.y * sa + s.z * ca; // y-axis rotation var rx = s.x * cb + rz * sb; s.z = s.x * -sb + rz * cb; // z-axis rotation s.x = rx * cc - ry * sc; s.y = rx * sc + ry * cc; } }; return HVector; })(); var HDegree = (function () { function HDegree () { } HDegree.sinD = function (angle) { return Math.sin (angle * (Math.PI / 180)); }; HDegree.cosD = function (angle) { return Math.cos (angle * (Math.PI / 180)); }; HDegree.tanD = function (angle) { return Math.tan (angle * (Math.PI / 180)); }; HDegree.asinD = function (ratio) { return Math.asin (ratio) * (180 / Math.PI); }; HDegree.acosD = function (ratio) { return Math.acos (ratio) * (180 / Math.PI); }; HDegree.atanD = function (ratio) { return Math.atan (ratio) * (180 / Math.PI); }; HDegree.atan2D = function (y,x) { return Math.atan2 (y, x) * (180 / Math.PI); }; HDegree.distance = function (x1, y1, x2, y2) { var dx = x2 - x1; var dy = y2 - y1; return Math.sqrt (dx*dx+dy*dy); }; return HDegree; })();
'use strict'; let mongoose = require ("mongoose"); let Schema = mongoose.Schema; let BasePlugins = require ("./plugins/BasePlugins"); // create a schema let schema = new Schema({ // _id: { type: Number, inc: true}, // _id: Schema.Types.ObjectId, user_id: Number, // fullname: String, event_id: Number, // class_id: Number, score: Number, time: Number, // exam_no: {type:Number, default:1}, }); let col_name = 'user_score_events'; schema.set('autoIndex', false); schema.plugin(BasePlugins, {col_name: col_name}); module.exports = mongoose.model(col_name, schema);
import React, { Component } from "react"; import styled, { ThemeProvider } from "styled-components"; import { theme1, theme2 } from '../theme/Themes' import ThemeSelect from '../theme/ThemeSelect' const AppWrapper = styled.div` text-align: center; ` const AppHeader = styled.div` height: 12rem; padding: 1rem; color: ${props => props.theme.dark}; background-color: ${props => props.theme.primary}; ` const AppTitle = styled.h1` font-weight: 900; ` const AppIntro = styled.p` font-size: large; code { font-size: 1.3rem; } ` const EmojiWrapper = styled.span.attrs({ role: 'img' })`` class App extends Component { state = { theme: theme1 } handleThemeChange = e => { let theme = e.target.value theme === 'theme1' ? (theme = theme1) : (theme = theme2) this.setState({ theme }) } render() { return ( <ThemeProvider> <AppWrapper> <AppHeader> <AppTitle>Welcome to React</AppTitle> </AppHeader> <AppIntro> Bootstrapped with <code>create-react-app</code>. </AppIntro> <AppIntro> Components styled with <code>styled-components</code>{' '} <EmojiWrapper aria-label="nail polish"></EmojiWrapper> </AppIntro> <ThemeSelect handleThemeChange={this.handleThemeChange} /> </AppWrapper> </ThemeProvider> ) } } export default App
angular.module('EDRLightbox', ['ngResource']) .factory('stateCtrlService', function ($resource) { return $resource('JSON/states.json'); });
import React, {Component} from 'react' //import config from './config.json'; class Test extends Component{ render() { return ( <div> Hello World! </div> ); } } export default Test;
import React, {useContext} from 'react'; import {View, Text, Button} from 'react-native'; import {AuthContext} from '../../contexts/auth'; export default function Profile() { const {signOut} = useContext(AuthContext); return ( <View> <Text>Profile</Text> <Button onPress={() => signOut()} title="Sair" /> </View> ); }
const fs = require("fs"); const chalk = require("chalk"); const addNote = (title, body) => { const notes = getNotes(); const index = notes.findIndex(item => item.title === title); if (index === -1) { notes.push({ title, body }); saveNotes(notes); console.log(chalk.bgGreen("New note added..!!")); } else { console.log(chalk.bgRed("Note already Exists..!!")); console.log(notes[index]); } }; const saveNotes = notes => { fs.writeFileSync("notes.json", JSON.stringify(notes)); }; const getNotes = () => { try { const notesBuffer = fs.readFileSync("notes.json"); const notesJSON = notesBuffer.toString(); return JSON.parse(notesJSON); } catch (e) { return []; } }; const removeNote = title => { let notes = getNotes(); const prevlength = notes.length; notes = notes.filter(item => item.title !== title); if (prevlength === notes.length) { console.log(chalk.bgRed("Note doesn't Existed")); } else { saveNotes(notes); console.log(chalk.bgGreen("Note removed successfully..!!")); } }; const listNotes = () => { let notes = getNotes(); console.log(chalk.blue.inverse.bold("Your Notes: ")); notes.forEach((item, index) => console.log( chalk.bold.green(`Your title${index + 1}: `) + chalk.green(item.title) ) ); }; const readNote = title => { let notes = getNotes(); const note = notes.find(item => item.title === title); if (note) { console.log(chalk.bgGreen(`Title: ${chalk.bold(note.title)}`)); console.log(`Body: ${note.body}`); } else { console.log(chalk.bgRed("No Record Found")); } }; module.exports = { addNote, removeNote, listNotes, readNote };
let defaultState = { agileData: [], devopsData: [], engineeringData: [] } export default (state = defaultState, action) => { switch (action.type) { case "REQUEST_PENDING": return {...state,isPending:action.isPending }; case "REQUEST_FAILED": return {error:action.error }; case "ADD_AGILE_FOR_ANALYTICS": return { ...state, agileData: action.updates ,isPending:false}; case "ADD_DEVOPS_FOR_ANALYTICS": return { ...state, devopsData: action.updates,isPending:false }; case "ADD_ENGINEERING_FOR_ANALYTICS": return { ...state, engineeringData: action.updates,isPending:false }; default: return state; } }
// function problem1(arr){ // let firstLineArgs = arr.shift().split(/\|+/g).filter(x => x).map(x => x.trim()); // // let dataArr = []; // // for (let i = 0; i < arr.length; i++) { // let currentLineArgs = arr[i].split(/\|+/g).filter(x => x).map(x => x.trim()); // // let object = {}; // // object[firstLineArgs[0]] = currentLineArgs[0]; // object[firstLineArgs[1]] = Number(currentLineArgs[1]); // object[firstLineArgs[2]] = Number(currentLineArgs[2]); // // dataArr.push(object); // } // // let outputStr = JSON.stringify(dataArr); // // console.log(outputStr); // } // problem1(['| Town | Latitude | Longitude |', // '| Sofia | 42.696552 | 23.32601 |', // '| Beijing | 39.913818 | 116.363625 |'] // ); // // function problem2(jsonStr){ // let objects = JSON.parse(jsonStr); // // let output = '<table>\n'; // // output += ' <tr><th>name</th><th>score</th></tr>\n'; // // for (let i = 0; i < objects.length; i++) { // let currentObject = objects[i]; // // let escapedName = escapeHtml(currentObject['name']); // //let escapedScore = escapeHtml(currentObject['score']); // // let currentLine = ` <tr><td>${escapedName}</td><td>${currentObject['score']}</td></tr>\n`; // // output += currentLine; // } // // // output+= '</table>'; // // console.log(output); // // function escapeHtml(unsafe) { // return unsafe // .replace(/&/g, "&amp;") // .replace(/</g, "&lt;") // .replace(/>/g, "&gt;") // .replace(/"/g, "&quot;") // .replace(/'/g, "&#39;"); // } // } // problem2('[{"name":"Pesho","score":479},{"name":"Gosho","score":205}]'); // function problem3(jsonStr){ // let objects = JSON.parse(jsonStr); // // let output = '<table>\n'; // // let properties = []; // // output+= ' <tr>'; // for (let key in objects[0]) { // output += `<th>${key}</th>`; // properties.push(key); // } // // output+= '</tr>\n'; // // for (let obj of objects) { // output+= ' <tr>'; // // for (let property of properties) { // let escaped = escapeHtml(obj[property].toString()); // // output += `<td>${escaped}</td>`; // } // // output += '</tr>\n'; // } // // output += '</table>'; // // console.log(output); // // function escapeHtml(unsafe) { // return unsafe // .replace(/&/g, "&amp;") // .replace(/</g, "&lt;") // .replace(/>/g, "&gt;") // .replace(/"/g, "&quot;") // .replace(/'/g, "&#39;"); // } // } //problem3('[{"Name":"Tomatoes & Chips","Price":2.35},{"Name":"J&B Chocolate","Price":0.96}]'); // function problem4(arr){ // let townsAndIncome = {}; // // let lastTown = ''; // for (let i = 0; i < arr.length; i++) { // if(i%2 ===0){ //town // lastTown = arr[i]; // }else{ // if(townsAndIncome[lastTown] === undefined){ // townsAndIncome[lastTown] = 0; // } // // let income = Number(arr[i]); // // townsAndIncome[lastTown] += income; // } // } // // console.log(JSON.stringify(townsAndIncome)); // } //problem4(['Sofia', '20', 'Varna', '3', 'Sofia', '5', 'Varna', '4']); // function problem5(arr){ // let entriesAndCount = {}; // // for (let i = 0; i < arr.length; i++) { // let currentLineArgs = arr[i].split(/\W+/g).filter(x => x); // // for (let j = 0; j < currentLineArgs.length; j++) { // let currentWord = currentLineArgs[j]; // // if(entriesAndCount[currentWord] === undefined){ // entriesAndCount[currentWord] = 0; // } // // entriesAndCount[currentWord] += 1; // } // } // // console.log(JSON.stringify(entriesAndCount)); // } // // function problem6(arr){ // let entriesAndCount = new Map(); // // for (let i = 0; i < arr.length; i++) { // let currentLineArgs = arr[i].split(/\W+/g).filter(x => x).map(x => x.toLowerCase()); // // for (let j = 0; j < currentLineArgs.length; j++) { // let currentWord = currentLineArgs[j]; // // if(entriesAndCount.get(currentWord) === undefined){ // entriesAndCount.set(currentWord, 0); // } // // entriesAndCount.set(currentWord, entriesAndCount.get(currentWord) + 1); // } // } // // let allWords = Array.from(entriesAndCount.keys()).sort(); // // allWords.forEach(w => console.log(`'${w}' -> ${entriesAndCount.get(w)} times`)); // // } // problem6(['Far too slow, you\'re far too slow.']); // problem6(['The man was walking the dog down the road when it suddenly started barking against the other dog. Surprised he pulled him away from it.']); // function problem7(arr){ // let pattern = RegExp('(.*?)\\s<->\\s(.*)', 'g'); // // let townsAndPopulation = new Map(); // // for (let i = 0; i < arr.length; i++) { // let currentLine = arr[i]; // // let match = pattern.exec(currentLine); // // if(match !== null) // { // let townName = match[1]; // let population = Number(match[2]); // // if(!townsAndPopulation.has(townName)) { // townsAndPopulation.set(townName, 0); // } // // townsAndPopulation.set(townName, townsAndPopulation.get(townName) + population); // } // // pattern.exec(currentLine); // } // // for (let [town, population] of townsAndPopulation) { // console.log(`${town} : ${population}`); // // } // } // problem7(['Sofia <-> 1200000', // 'Montana <-> 20000', // 'New York <-> 10000000', // 'Washington <-> 2345000', // 'Las Vegas <-> 1000000']); // function problem8(arr){ // let pattern = RegExp('(.*?)\\s*->\\s*(.*?)\\s*->\\s*(\\d+\\.?[\\d]*)\\s*:\\s*(\\d+\\.?[\\d]*)', 'g'); // // let townProductMoney = new Map(); // // for (let line of arr) { // let match = pattern.exec(line); // // if(match !== null){ // let town = match[1]; // let product = match[2]; // let sales = Number(match[3]); // let price = Number(match[4]); // // let money = sales*price; // // if(!townProductMoney.has(town)){ // townProductMoney.set(town, new Map()); // } // // if(!townProductMoney.get(town).has(product)){ // townProductMoney.get(town).set(product, 0); // } // // townProductMoney.get(town).set(product, townProductMoney.get(town).get(product) + money); // } // // pattern.exec(line); // } // // for (let [town, map] of townProductMoney) { // console.log(`Town - ${town}`); // // for (let [product, revenue] of map) { // console.log(`$$$${product} : ${revenue}`); // } // // } // } // problem8([ // 'Sofia -> Laptops HP -> 200 : 2000', // 'Sofia -> Raspberry -> 200000 : 1500', // 'Sofia -> Audi Q7 -> 200 : 100000', // 'Montana -> Portokals -> 200000 : 1', // 'Montana -> Qgodas -> 20000 : 0.2', // 'Montana -> Chereshas -> 1000 : 0.3' // ]); // function problem9(arr){ // let pattern = RegExp('(.*?)\\s*\\|\\s*(.*?)\\s*\\|\\s*(\\d+\\.?[\\d]*)', 'g'); // // let inputProductTownPrice = new Map(); // let productTownPrice = new Map(); // // for (let line of arr) { // let match = pattern.exec(line); // // if(match !== null){ // let town = match[1]; // let product = match[2]; // let price = Number(match[3]); // // if(!inputProductTownPrice.has(product)){ // inputProductTownPrice.set(product, new Map()); // } // // inputProductTownPrice.get(product).set(town, price); // } // // pattern.exec(line); // } // // for (let [product, townPriceMap] of inputProductTownPrice) { // let cheapestTown = ''; // let cheapestPrice = Number.POSITIVE_INFINITY; // // for (let [town, price] of townPriceMap) { // if (cheapestPrice > price){ // cheapestTown = town; // cheapestPrice = price; // } // } // // productTownPrice.set(product, {'town': cheapestTown, 'price': cheapestPrice}); // } // // for (let [product, obj] of productTownPrice) { // // console.log(`${product} -> ${obj.price} (${obj.town})`); // } // } // problem9([ // 'Sofia City | Audi | 100000', // 'Sofia City | BMW | 100000', // 'Sofia City | Mitsubishi | 10000', // 'Sofia City | Mercedes | 10000', // 'Sofia City | NoOffenseToCarLovers | 0', // 'Mexico City | Audi | 1000', // 'Mexico City | BMW | 99999', // 'New York City | Mitsubishi | 10000', // 'New York City | Mitsubishi | 1000', // 'Mexico City | Audi | 100000', // 'Washington City | Mercedes | 1000' // ]); // function problem10(arr){ // let pattern = RegExp('[a-zA-Z]+', 'g'); // // let allMatches = []; // // for (let i = 0; i < arr.length; i++) { // let line = arr[i]; // // let matches = pattern.exec(line); // // while(matches !== null){ // let currentMatch = matches[0].toLowerCase(); // allMatches.push(currentMatch); // // matches = pattern.exec(line); // } // } // // let filtered = allMatches.filter(onlyUnique); // // console.log(filtered.join(', ')); // // function onlyUnique(value, index, self) { // return self.indexOf(value) === index; // } // } // problem10([ // 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque quis hendrerit dui.', // 'Quisque fringilla est urna, vitae efficitur urna vestibulum fringilla.', // 'Vestibulum dolor diam, dignissim quis varius non, fermentum non felis.', // 'Vestibulum ultrices ex massa, sit amet faucibus nunc aliquam ut.', // 'Morbi in ipsum varius, pharetra diam vel, mattis arcu.', // 'Integer ac turpis commodo, varius nulla sed, elementum lectus.', // 'Vivamus turpis dui, malesuada ac turpis dapibus, congue egestas metus.' // ]);
import React, { PropTypes } from 'react'; import {Link} from 'react-router'; class Nav extends React.Component { render () { let styles={ root:{ width:"100%", height:"40px", backgroundColor:'#8BC34A' }, link:{ display:'block', textDecoration:'none', width:'33.33%', height:'40px', float:'left', color:'#fff', textAlign:'center', fontWeight:'600', lineHeight:'40px' } } return( <div style={styles.root}> <Link style={styles.link} to="/" activeStyle={{color:'#7C4DFF'}} onlyActiveOnIndex={true}>List</Link> <Link style={styles.link} to="/complete" activeStyle={{color:'#7C4DFF'}}>Complete</Link> <Link style={styles.link} to="/active" activeStyle={{color:'#7C4DFF'}}>Active</Link> </div> ) } } export default Nav;
import {createAppContainer} from 'react-navigation'; import {createBottomTabNavigator} from 'react-navigation-tabs'; import {HomeScreen} from './controller/home'; import {RecycleTestComponent} from './controller/recyclerView'; import {SettingsScreen} from './controller/test'; import {LoginView} from './controller/login'; import {SignUp} from './controller/signup'; import {Swipe} from './controller/swipe'; import {CommentLoad} from './controller/commentLoad'; import {SliderImp} from './controller/slider'; import {StackNav} from './controller/stackNavigation'; import {postSignup} from './controller/postSignup'; import {UploadPicture} from './controller/uploadPicture'; import {CameraDemo} from './controller/cameraDemo'; import {AmazonDemo} from './controller/amazonDemo'; const TabNavigator = createBottomTabNavigator( { Home: HomeScreen, CreatePost: postSignup, ListShow: RecycleTestComponent, PostUser: SettingsScreen, Login: LoginView, SignUp: SignUp, Swiper: Swipe, Comment: CommentLoad, Slider: SliderImp, Pict: UploadPicture, StackNavigation: StackNav, C: CameraDemo, A: AmazonDemo, }, { initialRouteName: 'CreatePost', }, ); export default createAppContainer(TabNavigator);
const { Datatypes } = require('sequelize'); module.exports = (sequelize) => sequelize.define('projects',{ id:{type: Datatypes.INTEGER, primaryKey: true, autoIncrement: true}, usertId: { type: Sequelize.INTEGER, references:{ model:'users', key: 'id', user: 'name', phone: 'cell_phone_number', e_mail: 'email' }, onDelete: 'CASCADE' }, nameProject: {type: DataTypes.STRING, required: true}, projectDescription: {type: DataTypes.TEXT, required: true}, budget: {type: DataTypes.FLOAT, required: true}, createdAt: Datatypes.DATE, updatedAt: Datatypes.DATE });
<script type="text/javascript"> Ext.ns('np.mod'); np.mod.purchase = { init: function() { } } np.mod.purchase.init(); </script>
App.controller('SemestreController', [ '$scope', 'SemestreService', 'NiveauService', '$http', '$q', function($scope, SemestreService, NiveauService, $http, $q) { var self = this; self.semestre = { idSemestre : null, dateDebut : '', dateFin : '', description : '' }; self.semestreshow = { idSemestre : null, dateDebut : '', dateFin : '', description : '' }; self.semestres = []; self.niveaux = []; self.idSelectedNiveau = null; $scope.showMe = false; self.fetchAllSemestre = function() { SemestreService.fetchAllSemestre().then(function(d) { self.formations = d; // console.error('semestres a inserer:' + self.semestres); }, function(errResponse) { console.error('Error while fetching Currencies'); }); }; self.fetchAllNiveaux = function() { NiveauService.fetchAllNiveaux().then(function(d) { self.niveaux = d; }, function(errResponse) { console.error('Error while fetching Currencies'); }); }; self.getOneSemestre = function(id) { SemestreService.getOneSemestre(id).then(function(d) { self.semestreshow = d; console.log(self.semestreshow); }, function(errResponse) { console.error('Error while fetching Currencies'); }); }; self.fetchAllSemestre = function() { SemestreService.fetchAllSemestre().then(function(d) { self.semestres = d; }, function(errResponse) { console.error('Error while fetching Currencies'); }); }; self.createSemestre = function() { SemestreService.createSemestre(self.semestre).then( function(d) { self.semestre = d; console.log(' id de semestre a ajouter:' + self.semestre.idSemestre + ' au niveau ' + self.idSelectedNiveau); self.addSemestreToNiveau(self.semestre.idSemestre, self.idSelectedNiveau); self.fetchAllSemestre; }, function(errResponse) { console.error('Error while creating semestre.'); }); }; self.updateSemestre = function(semestre, id) { SemestreService.updateSemestre(semestre, id).then( self.fetchAllSemestre, function(errResponse) { console.error('Error while updating semestre.'); }); }; self.deleteSemestre = function(id) { SemestreService.deleteSemestre(id).then(self.fetchAllSemestre, function(errResponse) { console.error('Error while deleting semestre.'); }); }; self.addSemestreToNiveau = function(idS, idN) { SemestreService.addSemestreToNiveau(idS, idN).then(function(d) { self.niveaux = d; self.fetchAllSemestre(); self.reset(); }, function(errResponse) { console.error('Error while adding semestre to niveau.'); }); }; self.update = function() { console.log('updating d\'un Semestre' + self.semestre.idSemestre); self.updateSemestre(self.semestre, self.semestre.idSemestre); // self.addFornationToNiveau(self.idformation,self.niveau.idNiveau); self.fetchAllSemestre(); // self.fetchAllFormations(); self.reset(); }; self.add = function() { if (self.semestre.idSemestre === null) { // convertion de date de string a date var st2 = self.semestre.dateFin; var st1 = self.semestre.dateDebut; console.log('date old ' + self.semestre.dateFin); var dateF = new Date(st2); var dateD = new Date(st1); dateF = new Date(dateF.getTime() + 86400000); dateD = new Date(dateD.getTime() + 86400000); console.log(' semestre newwwwwww ' + dateF); self.semestre.dateFin = dateF; self.semestre.dateDebut = dateD; self.createSemestre(self.semestre); } else { self .updateSemestre(self.semestre, self.semestre.idSemestre); console.log('formation updated with id ', self.semestre.idSemestre); } self.reset(); $scope.showMe = false; }; self.edit = function(id) { for (var i = 0; i < self.semestres.length; i++) { if (self.semestres[i].idSemestre == id) { self.semestre = angular.copy(self.semestres[i]); break; } } $scope.showMe = false; }; self.remove = function(id) { console.log('id to be deleted', id); self.deleteSemestre(id); $scope.showMe = false; }; self.show = function(id) { self.getOneSemestre(id); // $scope.showMe = !$scope.showMe; if ($scope.showMe === true) { $scope.showMe = $scope.showMe; } else { $scope.showMe = !$scope.sowMe; } }; self.reset = function() { self.semestre = { idSemestre : null, dateDebut : '', dateFin : '', description : '' }; $scope.myForm.$setPristine(); // reset Form }; self.fetchAllSemestre(); self.fetchAllNiveaux(); } ]);
import React, { Component } from 'react'; const Rating=({count,onchange=()=>{}}) =>{ let stararray=[] for ( let i=0;i<5;i++){ if(i<count){ stararray.push(<span onClick={()=>onchange(i+1)} key={i}>★</span>)} else stararray.push(<span onClick={()=>onchange(i+1)} key={i}>☆</span>) } return (<div>{stararray}</div>) } export default Rating;
/** * DomoGeeek v0.1 * https://github.com/ltoinel/domogeeek * * Copyright 2014 DomoGeeek * Released under the Apache License 2.0 (Apache-2.0) * * @desc: Member schema for MongoDB. * @author: ltoinel@free.fr */ var mongoose = require('mongoose') ,Schema = mongoose.Schema ,ObjectId = Schema.ObjectId; var memberSchema = new Schema({ list: ObjectId, date: {type: Date, default: Date.now}, phone: String, name: String, status:{type: Number, default: 0} }); module.exports = mongoose.model('Member', memberSchema);
const navbar = document.querySelector('.navbar'); const headerContent = document.querySelector('.header__content'); const title = document.querySelectorAll('.title'); const underline = document.querySelectorAll('.underline'); const aboutImg = document.querySelector('.about__image'); const aboutPara = document.querySelector('.about__paragraph'); const service = document.querySelectorAll('.service'); window.sr = ScrollReveal(); sr.reveal(aboutImg, { duration: 2000, origin: 'bottom', distance: '10rem', }); sr.reveal(aboutPara, { duration: 2000, origin: 'bottom', }); for (let i = 0; i < title.length; i++) { sr.reveal(title[i], { duration: 2000, opacity: 0, }); sr.reveal(underline[i], { duration: 2000, opacity: 0, }); } for (let i = 0; i < service.length; i++) { sr.reveal(service[i], { // duration: 4000, origin: 'bottom', distance: '30rem', }); }
/* * @lc app=leetcode.cn id=450 lang=javascript * * [450] 删除二叉搜索树中的节点 */ // @lc code=start /** * 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 {TreeNode} root * @param {number} key * @return {TreeNode} */ var deleteNode = function(root, key) { if (root === null) return null; if (root.val === key) { // 考虑三种情况 // 1. 没有左右子树 直接删除 if (root.left == null && root.right == null) return null; // 2. 有左右子树中一个 if (root.left == null) return root.right; if (root.right == null) return root.left; // 3. 左右子树皆有 let node = getMin(root.right); root.val = node.val; root.right = deleteNode(root.right, node.val); } else if (root.val > key) {// 直接遍历root左边的子树 root.left = deleteNode(root.left, key) } else if (root.val < key) { root.right = deleteNode(root.right, key) } return root; }; let getMin = (node) => { while (node.left) node = node.left; return node; } // 如果删除的节点左右子树都有,那么需要获得右子树最小的节点替换这个删除的节点,才能保证二叉搜索树的特性。 // @lc code=end
import React from "react"; import styles from "./loading.module.scss"; const Loading = () => { return ( <div className={styles.loader}> <div className={styles.loader_text}>loading</div> </div> ); }; export default Loading;
import React, { useState } from 'react' import { Button, Modal } from 'react-bootstrap' import { firebaseApp } from '../firebaseConfig'; export default function DeleteStudent ({nendo,student}){ const [show,setShow] = useState(false); const handleClose = () => setShow(false); const handleShow = () => setShow(true); const deletedata = ()=>{ firebaseApp.database().ref("studentdata").child('year'+nendo).child(student.keyId).remove(); setShow(false) } return( <> <span className="mx-2"> <Button variant="outline-danger" size="sm" onClick={handleShow}>削除</Button> </span> <Modal show={show} onHide = {handleClose}> <Modal.Header> <h4>{nendo}年度 - {student.studentId}</h4> </Modal.Header> <Modal.Body> <div className="container"> <div> <h4>{student.studentId}学生のデータを削除しますか?</h4> </div> <div className="form-group row justify-content-center"> <button className="btn btn-danger" onClick={deletedata}>削除</button> <button className="btn btn-outline-dark mx-3" onClick={handleClose}>キャンセル</button> </div> </div> </Modal.Body> </Modal> </> ); }
var studentId = [23,52,23,67,26,25,2,56,2,67] var uniqId= []; for (var i = 0; i< studentId.length; i++){ var element = studentId[i]; var index = uniqId.indexOf(element); if (index == -1){ uniqId.push(element) } } console.log(uniqId)
var request = require('request'); const uuid = require('uuid'); array =[] //array to store used Guid //MS API to add role assignment for a particular user(principal id) function getAddRoleAssignment(reqData,authToken,roleassignmentid){ return new Promise((resolve,reject)=>{ var options = { 'method': 'PUT', 'url': `https://management.azure.com/${reqData.scope}/providers/Microsoft.Authorization/roleAssignments/${roleassignmentid}?api-version=2015-07-01`, 'headers': { 'Authorization': authToken, 'Content-Type': 'application/json' }, body: JSON.stringify({"properties":{"roleDefinitionId":reqData.roleDefination,"principalId":reqData.principalId}}) }; try{ request(options, function (error, response) { if (!error && (response.statusCode == 200 || response.statusCode == 201 ||response.statusCode == 202)){ resolve(JSON.parse(response.body)) }else if(!error && response.statusCode >= 400){ reject(JSON.parse(response.body)) }else{ reject(error) } }); }catch(err){ console.log(err) reject(err) } }) } //Function to generate a unique guuid function getuuid(){ return new Promise((resolve,reject)=>{ role = uuid.v4() if(array.includes(role)){ getuuid() }else{ array.push(role) resolve(role) } }) } //Add role for a user by Global Admin exports.addRoleAssignment = async(req,res)=>{ try{ reqData = req.body authToken = req.header('Authorization')//User AuthToken //Generate a unique ID await getuuid().then(async(roleID)=>{ //Add Role Assignment having a unique Guuid await getAddRoleAssignment(reqData,authToken,roleID).then((addResponse)=>{ res.send(addResponse) }).catch(err=>{ //Error in Adding roles res.status(400).send(err) }) }).catch(err=>{ //error in fetching guid console.log(err) res.status(400).send({"Error":"Error in fetching guid.TryAgain!!"}) }) }catch(err){ res.status(404).send({"Error":"Error in fetching Details.TryAgain!!"}) } }
import React from 'react'; import { StyleSheet, View, Text, Image, TouchableOpacity } from 'react-native'; function CalcDisplay({displayText, displayTxtColor}){ return( <View style={styles.container}> <Text style={[styles.text, {color: displayTxtColor}]}>{displayText}</Text> </View> ); } export default CalcDisplay; const styles = StyleSheet.create({ container: { height: "35%", width: "100%", justifyContent: "flex-end" }, text: { textAlign: "right", fontSize: 60, marginBottom: "5%", marginRight: "5%" }, iconContainer: { marginLeft: "2%", backgroundColor: "#eeeeee", width: 50, height: 50, borderRadius: 25, borderColor: "#000", borderWidth: 3, justifyContent: "center", alignItems: "center" }, icon: { height: "90%", width: "90%", resizeMode: "contain", borderRadius: 25, padding: 5 } });
var searchData= [ ['oleds_3a_20initialization_20and_20service_20functions',['OLEDs: initialization and service functions',['../group___l_c_d___i_n_t_e_r_f_a_c_e___a_p_i.html',1,'']]] ];
import React from "react"; const ProjectItems = ({ href, link, par }) => { return ( <div className="project-item"> <li> <h4> <a href={href} target="_blank" rel="noopener noreferrer"> {link} </a> </h4> <p className="ml-3" dangerouslySetInnerHTML={{ __html: par }} /> </li> </div> ); }; export default ProjectItems;
var KthLargest = function(k, nums) { this.sorted = nums.sort((a, b) => a - b); this.k = k; }; KthLargest.prototype.add = function(val) { let left = 0; let right = this.sorted.length - 1; let insertIndex = left; while (left <= right) { let mid = left + Math.floor((right - left) / 2); if (val > this.sorted[mid]) { left = mid + 1; insertIndex = mid + 1; } else if (val < this.sorted[mid]) { right = mid - 1; insertIndex = mid; } else { // we found target insertIndex = mid; break; } } this.sorted.splice(insertIndex, 0, val); return this.sorted[this.sorted.length - this.k]; }; let item1 = new KthLargest(3, [4, 5, 8, 2]); console.log(item1.add(3)); console.log(item1.add(5)); console.log(item1.add(10)); console.log(item1.add(9)); console.log(item1.add(4));
import ejs from 'ejs'; import React from 'react'; import { RouterContext } from 'react-router'; import { renderToString } from 'react-dom/server'; function renderComponents (props) { return renderToString( <RouterContext {...props} /> ); } export default (renderProps, html) => { return new Promise((resolve, reject) => { resolve( ejs.render(html, { delimiter: '?', reactOutput: renderComponents(renderProps) }) ); }); };
var openFile = function(url, callback){ var req = new XMLHttpRequest(); req.onload = callback; req.open("GET", url); req.send(); }
import JiraClient from "jira-connector"; // Initialize Jira client const client = new JiraClient({ host: process.env.JIRA_HOST, basic_auth: { email: process.env.AUTH_EMAIL, api_token: process.env.AUTH_API_KEY } }); export default client
import "./App.css"; import { Router } from "@reach/router"; import NumberOrWord from "./components/NumberOrWord"; import Home from "./components/home"; import TextColor from "./components/TextColor"; import TextBackground from "./components/TextBackground"; function App() { return ( <Router> <Home path="/home" /> <NumberOrWord path="/:value" /> <TextColor path="/:value/:color" /> <TextBackground path="/:value/:color/:background" /> </Router> ); } export default App;
Template.locationSubmit.events({ 'submit form': function (e) { e.preventDefault(); var location = { code: $(e.target).find('[name=code]').val(), name: $(e.target).find('[name=name]').val() }; Meteor.call('locationInsert', location, function (error, result) { // display the error to the user and abort if (error) return alert(error.reason); Router.go('locationPage', {_id: result._id}); }); } });
/** * Created by hui.sun on 15/12/13. */ 'use strict'; define(['../../../app', '../../../services/logistics/lineManage/lineManageService'], function(app) { var app = angular.module('app'); app.controller('lineManageCtrl', ['$scope', '$state', '$sce','$timeout', 'lineManage', function($scope, $state, $sce,$timeout, lineManage) { $scope.addLineTitle='新增线路'; //机构名称 $scope.wlDept={ select:{}, id:'-1' }; // query moudle setting $scope.querySeting = { items: [{ type: 'text', model: 'lineId', title: '线路编号' }, { type: 'text', model: 'lineName', title: '线路名称' }, { type: 'select', model: 'tranMode', selectedModel: 'tranModeSelect', title: '运输方式' }, { type: 'select', model: 'tranType', selectedModel: 'tranTypeSelect', title: '线路类型' }], btns: [{ text: $sce.trustAsHtml('查询'), click: 'searchClick' }] }; //table头 $scope.thHeader = lineManage.getThead(); //分页下拉框 $scope.pagingSelect = [{ value: 5, text: 5 }, { value: 10, text: 10, selected: true }, { value: 20, text: 20 }, { value: 30, text: 30 }, { value: 50, text: 50 }]; //分页对象 $scope.paging = { totalPage: 1, currentPage: 1, showRows: 30, }; $scope.ifShowSelect=true; var pmsSearch = lineManage.getSearch(); pmsSearch.then(function(data) { $scope.searchModel = data.query; //设置当前作用域的查询对象 $scope.wlDept.select=data.query.wlDeptId; if($scope.wlDept.select.length>1) { $scope.wlDept.id = data.query.wlDeptId[1].id; } $scope.searchModel.tranModeSelect = -1; $scope.searchModel.tranTypeSelect = -1; $scope.lineModel.tranModeSelect=$scope.searchModel.tranMode; $scope.lineModel.tranTypeSelect=$scope.searchModel.tranType; $scope.labelName = '配送选择'; $scope.storageRDC = data.query.rdcId; $scope.storageCDC = data.query.cdcId; if(data.query.flag==1){ $scope.ifShowSelect=false; }else { $scope.ifShowSelect=true; } //获取table数据 get(); }, function(error) { console.log(error) }); //查询 $scope.searchClick = function() { $scope.paging = { totalPage: 1, currentPage: 1, showRows: $scope.paging.showRows, }; get(); } //任务类型 下拉框change $scope.orderTypeIdChange = function() { // console.log($scope.searchModel.orderTypeIdSelect) } function get() { //获取选中 设置对象参数 var opts = angular.extend({}, $scope.searchModel, {}); //克隆出新的对象,防止影响scope中的对象 opts.wlDeptId=$scope.wlDept.id; opts.tranMode = $scope.searchModel.tranModeSelect; opts.tranType = $scope.searchModel.tranTypeSelect; delete opts.tranModeSelect; delete opts.tranTypeSelect; opts.rdcId = $scope.storageSelectedRDC;//获取仓储选择第一个下拉框 opts.cdcId = $scope.storageSelectedCDC;//获取仓储选择第二个下拉框 opts.pageNo = $scope.paging.currentPage; opts.pageSize = $scope.paging.showRows; var promise = lineManage.getDataTable({ param: { query: opts } }); promise.then(function(data) { if (data.code == -1) { alert(data.message); $scope.result = []; $scope.paging = { totalPage: 1, currentPage: 1, showRows: $scope.paging.showRows, }; return false; } $scope.result = data.grid; $scope.paging = { totalPage: data.total, currentPage: $scope.paging.currentPage, showRows: $scope.paging.showRows, }; }, function(error) { console.log(error); }); } //新增路线model $scope.lineModel={ id:0, "wlDeptId":0, "lineId": "", "lineName":"", "deliveryFrequency":'', "garageAddressId":"", lineDescription:'', garageName:'', "tranMode":-1, "tranType":-1, "tranModeSelect":null, "tranTypeSelect":null, "remarks":"" } $scope.lineShowPath=true; $scope.tranTypeSelectChange= function () { setLineShowPath(); } function setLineShowPath(){ $scope.lineShowPath=true;// angular.forEach($scope.lineModel.tranTypeSelect, function (item) { if(item.id==$scope.lineModel.tranType){ if(item.name=='支线'||item.name=='干线'){ $scope.lineShowPath=false; return false } } }) } //新增路线 $scope.addLine= function () { if($scope.lineModel.tranType==-1){ alert('请选择路线类型!'); return; } if($scope.lineModel.tranMode==-1){ alert('请选择运输方式!'); return; } var reg = new RegExp("^[0-9]*$"); if(!reg.test($scope.lineModel.deliveryFrequency)){ alert("请输入正确的配送频率数字!") return false; } var postResult=angular.extend({},$scope.lineModel,{}); delete postResult.tranModeSelect; delete postResult.tranTypeSelect; lineManage.getDataTable({ param: { query:postResult } },($scope.addLineTitle=='新增线路'?'/wlLine/addWlLine':'/wlLine/updateWlLine')) .then(function (data) { alert(data.status.msg); if(data.status.code=="0000"){ get(); $('#addLine').modal('hide'); } }, function (error) { console.log(error) }); } //修改 $scope.updateLine= function (i,item) { $scope.linePathReadonly=true; salvageLineId=item.lineId; $scope.addLineTitle='修改线路'; $scope.lineModel.id=item.id; $scope.lineModel.wlDeptId=$scope.wlDept.id; $scope.lineModel.lineId=item.lineId; $scope.lineModel.lineName=item.lineName; $scope.lineModel.deliveryFrequency=item.deliveryFrequency; $scope.lineModel.garageAddressId=item.garageAddressId; $scope.lineModel.garageName=item.garageName; $scope.lineModel.lineDescription=item.lineDescription; $scope.lineModel.remarks=item.remarks; $scope.lineShowPath=true; //设置选中线路类型 angular.forEach($scope.lineModel.tranTypeSelect, function (k) { if(k.name==item.tranType) { $scope.lineModel.tranType= k.id; if(k.name=='支线'||k.name=='干线'){ $scope.lineShowPath=false; return false } return false; } }); //设置选中运输方式 angular.forEach($scope.lineModel.tranModeSelect, function (k) { if(k.name==item.tranMode) { $scope.lineModel.tranMode = k.id; return false; } }); } //查看 $scope.queryLine= function (i,item) { $scope.linePathReadonly=true; salvageLineId=item.lineId; $scope.addLineTitle='查看线路'; $scope.lineModel.id=item.id; $scope.lineModel.wlDeptId=$scope.wlDept.id; $scope.lineModel.lineId=item.lineId; $scope.lineModel.tranType=item.tranType; $scope.lineModel.tranMode=item.tranMode; $scope.lineModel.lineName=item.lineName; $scope.lineModel.deliveryFrequency=item.deliveryFrequency; $scope.lineModel.garageAddressId=item.garageAddressId; $scope.lineModel.garageName=item.garageName; $scope.lineModel.lineDescription=item.lineDescription; $scope.lineModel.remarks=item.remarks; $scope.lineShowPath=true; } //删除 $scope.deleteLine= function (i,item) { if(confirm('确定要删除吗?')){ lineManage.getDataTable({ param: { "query":{ "wlDeptId": $scope.wlDept.id, "lineId":item.lineId, "id":item.id } } },'/wlLine/delWlLine') .then(function (data) { alert(data.status.msg) if(data.status.code=="0000") { get(); } }, function (error) { console.log(error) }); } } $scope.btnAddLine= function () { $scope.addLineTitle='新增线路'; $scope.lineModel.wlDeptId=$scope.wlDept.id; $scope.lineModel.lineId=""; $scope.lineModel.lineName=""; $scope.lineModel.deliveryFrequency=""; $scope.lineModel.garageAddressId=""; $scope.lineModel.garageName=""; $scope.lineModel.tranType=-1; $scope.lineModel.tranMode=-1; $scope.lineModel.lineDescription = ''; $scope.lineModel.remarks = ''; $scope.lineModel.id = 0; } //线路路径focus $scope.linePathFocus= function () { getSalvage(); if($scope.addLineTitle!='新增线路') getSalvageByupdata(); $('#selectSalvage').modal(); } //确认选择修理厂 $scope.enterSalvage= function () { $scope.linePathReadonly=true; var str='',names=''; angular.forEach($scope.salvageRightModel, function (item) { str+=item.garageId+','; names+=item.garageName+','; }); if(str!='') { str = str.substr(0, str.length - 1); } $scope.lineModel.garageAddressId=str; if(names!='') { $scope.lineModel.garageName = names.substr(0, names.length - 1); }else $scope.lineModel.garageName=''; $('#selectSalvage').modal('hide'); } //修理厂table行点击 $scope.salvageTableRowClick= function (item) { var isGarageId=false; angular.forEach($scope.salvageRightModel, function (k) { if(k.garageId== item.garageId){ isGarageId=true; return false; } }) if(!isGarageId){ $scope.salvageRightModel.push(item); } } //修理厂地址搜索按钮 $scope.salvageSearch= function () { getSalvage(); } var salvageLineId=0; $scope.linePathReadonly=false; $scope.recAddressId='';//修理厂查询框 $scope.salvageModel=[];//修理厂地址model $scope.salvageRightModel=[];//选中右侧model //查询修理厂地址 function getSalvage(){ var opt={ param: { "query":{ "wlDeptId": $scope.wlDept.id, "recAddressId":$scope.recAddressId } } };//'/wlLine/findGarage' lineManage.getDataTable(opt,'/wlLine/getGarages') .then(function (data) { $scope.salvageModel=data.grid; //设置右侧选择高度 $timeout(function () { $('.rightSalvage').height($('.leftSalvage').height()); },300) }, function (error) { console.log(error) }); } function getSalvageByupdata(){ var opt={ param: { "query":{ "wlDeptId": $scope.wlDept.id, lineId:salvageLineId } } }; lineManage.getDataTable(opt,'/wlLine/findGarage') .then(function (data) { $scope.salvageRightModel=data.grid; }, function (error) { console.log(error) }); } //删除选中的地址 $scope.salvageClose= function (item) { $scope.salvageRightModel.splice($scope.salvageRightModel.indexOf(item),1); } //分页跳转回调 $scope.goToPage = function() { get(); } }]) });
var express = require('express'); var morgan = require('morgan'); var formidable = require("formidable"); var path = require('path'); var app = express(); var util = require('util'); app.use(morgan('combined')); var mysql = require("mysql"); var mysql = require('mysql'); var connection = mysql.createConnection({ host : 'localhost', user : 'root', password : '', database : 'db1' }); connection.connect(function(err){ if(err){ console.log(err); return; } else{ console.log('Connection established');} }); app.use(express.static(__dirname + '/ui')); var list = []; app.get('/submit',function(req,res){ if(req.query.pwd!=req.query.pwd2){ res.sendFile(path.join(__dirname, 'ui', 'failure.html'));} else{ connection.query("INSERT INTO users (fname,lname,email,pwd,username)values('"+req.query.fname+"','"+req.query.lname+"','"+req.query.email+"','"+req.query.pwd+"','"+req.query.username+"') ",function(err) { if(err){ return res.send(err); } else{ res.sendFile(path.join(__dirname, 'ui', 'success.html')); } }); } }); app.get('/', function (req, res) { res.render(path.join(__dirname, 'ui', 'index')); }); app.get('/ui/main.css', function (req, res) { res.sendFile(path.join(__dirname, 'ui/CSS', 'main.css')); }); app.get('/ui/main1.css', function (req, res) { res.sendFile(path.join(__dirname, 'ui/CSS', 'main1.css')); }); app.get('/scripts/main.js', function (req, res) { res.sendFile(path.join(__dirname, 'ui/scripts', 'main.js')); }); app.get('/scripts/skrollr.min.js', function (req, res) { res.sendFile(path.join(__dirname, 'ui/scripts', 'skrollr.min.js')); }); app.get('/images/clouds.jpg', function (req, res) { res.sendFile(path.join(__dirname, 'ui/images', 'clouds')); }); app.get('/images/balloon-2.png', function (req, res) { res.sendFile(path.join(__dirname, 'ui/images', 'balloon-2.png')); }); app.get('/ui/require.js', function (req, res) { res.sendFile(path.join(__dirname, 'ui/scripts', 'require.js')); }); app.get('/cancel1', function (req, res) { res.sendFile(path.join(__dirname, 'ui', 'cancel.html')); }); var port = 8080; // Use 8080 for local development because you might already have apache running on 80 app.listen(8080, function () { console.log(`IMAD course app listening on port ${port}!`); });
$(document).ready(function(){ // fetch all data loadTable(); // tutorial - 19 function loadTable() { $('#table_body').html(""); $.ajax({ url:"http://localhost/1.yahoo_baba_PHP_restAPI_with_ajax/16api-fetch-all.php", method:'GET', dataType:'json', success:function(reflection) { if($.trim(reflection) != "") { if(reflection.status === 'success') { var i = 0; $.each(reflection.data,function(key,value){ i++; $('#table_body').append("<tr><td>"+i+"</td> <td> "+reflection.data[key].student_name+"</td><td> "+reflection.data[key].age+"</td> <td> "+reflection.data[key].city+"</td><td><a href='' class='btn btn-success edt_btn' data-eid="+value.id+">Edit</a></td> <td><a href='' class='btn btn-danger dlt_btn' data-did="+value.id+">Delete</a></td> </tr>"); }); // console.log(reflection.data[0].student_name); } } // console.log(reflection); } }); } //2. fetch single record : show in modal box // tutorial -20 $(document).on('click','.edt_btn',function(e){ e.preventDefault(); $('#myModal').css({'display':"block"}); var studentId = $(this).data('eid'); // json encode way // 1. first make object then it converted as a stringify() var obj = { id : studentId }; var myJSON = JSON.stringify(obj); // JSON.stringify() means json_encode() $.ajax({ url:"http://localhost/1.yahoo_baba_PHP_restAPI_with_ajax/16api_fetch_single.php", method:"POST", data: myJSON, dataType:"JSON", success:function(reflection) { if($.trim(reflection) != "") { if(reflection.status == 'success') { $('#student_name').val(reflection.data[0].student_name); $('#age').val(reflection.data[0].age); $('#city').val(reflection.data[0].city); $('#student_id').val(reflection.data[0].id); // console.log(reflection.data[0].student_name); } } // console.log(reflection); } }); // console.log(myJSON); }); // tutorial - 20 $(document).on('click','.close',function(e){ e.preventDefault(); $('#myModal').css({'display':"none"}); }) // tutorial - 20 $(window).click(function(event){ if(event.target.className == 'modal_make') { $('#myModal').css({'display':"none"}); } // console.log(event.target.className); }); // 3. insert New Record.................. // tutorial - 20 $(document).on('submit','#insert_form',function(e){ e.preventDefault(); var json_form_data = jsonData($(this)); $.ajax({ url:"http://localhost/1.yahoo_baba_PHP_restAPI_with_ajax/17api-insert.php", method:"POST", async:false, data: json_form_data, dataType:'JSON', success:function(reflection) { if($.trim(reflection) != "") { if(reflection.status == 'success') { message_function("success-massage","error-massage",reflection.message,reflection.status); $('#insert_form')[0].reset(); loadTable(); } else if(reflection.status == 'error') { message_function("success-massage","error-massage", reflection.message,reflection.status); } } console.log(reflection); } }); // console.log(json_form_data); }); // 4. Update Record................ // tutorial - 20 $(document).on('submit','form#edit_form',function(e){ e.preventDefault(); var json_form_data = jsonData($(this)); $.ajax({ url:"http://localhost/1.yahoo_baba_PHP_restAPI_with_ajax/17api-update.php", method:"PUT", async:false, data: json_form_data, dataType:'JSON', success:function(reflection) { if($.trim(reflection) != "") { if(reflection.status == 'success') { message_function("modal-success-massage","modal-error-massage",reflection.message,reflection.status); $('#insert_form')[0].reset(); loadTable(); } else if(reflection.status == 'error') { message_function("modal-success-massage","modal-error-massage", reflection.message,reflection.status); } } console.log(reflection); } }); // console.log(json_form_data); }); // tutorial-21 // Delete Recored $(document).on('click','.dlt_btn',function(e){ e.preventDefault(); var clicked_btn = $(this); var studentId = $(this).data('did'); var obj = { id : studentId }; // object to json_encode converted............ var myJSON = JSON.stringify(obj); if(confirm('Are you sure to want to delete the record ??')) { $.ajax({ url:"http://localhost/1.yahoo_baba_PHP_restAPI_with_ajax/18.api-delete.php", method: 'DELETE', async:false, data: myJSON, dataType:'json', success:function(reflection) { if($.trim(reflection) != "") { if(reflection.status == 'success') { message_function("success-massage","error-massage",reflection.message,reflection.status); // $('#insert_form')[0].reset(); clicked_btn.closest('tr').fadeOut('slow'); } else if(reflection.status == 'error') { message_function("success-massage","error-massage", reflection.message,reflection.status); } } console.log(reflection); } }); } // console.log(studentId); }); // tutorial-21 $(document).on('keyup','#search',function(e){ var search_item = $(this).val(); if(search_item == "") { loadTable(); // console.log('there havenont data'); } else{ $('#table_body').html(''); $.ajax({ url:"http://localhost/1.yahoo_baba_PHP_restAPI_with_ajax/18.api-search.php?search="+search_item, method:"GET", async:false, dataType:'JSON', success:function(reflection) { if($.trim(reflection) != "") { if(reflection.status == 'error') { $('#table_body').html("<tr> <td colspan='6'> <h2> Data Not Found</h2></td></tr>"); } else if(reflection.status == 'success') { // console.log(reflection.message); var i = 0; $.each(reflection.message,function(key,value){ i++; $('#table_body').append("<tr><td>"+i+"</td> <td> "+reflection.message[key][1]+"</td><td> "+reflection.message[key][2]+"</td> <td> "+reflection.message[key][3]+"</td><td><a href='' class='btn btn-success edt_btn' data-eid="+reflection.message[key][0]+">Edit</a></td> <td><a href='' class='btn btn-danger dlt_btn' data-did="+reflection.message[key][0]+">Delete</a></td> </tr>"); // console.log(reflection.message[key][1]); }); } } console.log(reflection); } }); } console.log(search_item); }); function message_function(noti_succClass,noti_erroClass,message,status) { if(status == 'success') { $('#'+noti_succClass).html(message).slideDown('slow'); $('#'+noti_erroClass).html("").slideUp(); setTimeout(function(){ $('#'+noti_succClass).html(message).slideUp('slow'); },4000); // for reset ......... } else if(status == 'error') { $('#'+noti_erroClass).html(message).slideDown('slow'); $('#'+noti_succClass).html("").slideUp(); setTimeout(function(){ $('#'+noti_erroClass).html(message).slideUp('slow') },4000); } } function jsonData(targetForm) { // get form value into serializeArrya() var form_data = targetForm.serializeArray(); //Object Create and Dynamacally Object converted var obj = {}; $.each(form_data,function(key,value){ obj[value.name] = value.value }); // CRATE JSON ENCODED var json_string = JSON.stringify(obj); return json_string; } });
function initMap() { //web resource reference - address convert to address: https://developers.google.com/maps/documentation/geocoding/intro //web resource reference - google map with marker and info window: https://developers.google.com/maps/documentation/javascript/examples/infowindow-simple //Get address var address = $('.address').text().trim(); //Send request to google api to convert address to coordinates $.ajax({ url: 'https://maps.googleapis.com/maps/api/geocode/json?address='+address, success: function(data){ //If successfully get response data from google api, then extract latitude and longitude //as long as formatted addresss var lat = data.results[0].geometry.location.lat; var lng = data.results[0].geometry.location.lng; var formattedAddress = data.results[0].formatted_address; var coordinates = {lat: lat, lng: lng}; // Create a instance of google map var map = new google.maps.Map(document.getElementById('map'), { zoom: 14, //Set zoom level to 14 center: coordinates //Set center of the map to coordinates }); //Create template of goolgle info window var contentString = '<div><p><b>'+formattedAddress+'</b></p></div>'; //Create a instance of goole info window and set the template var infowindow = new google.maps.InfoWindow({ content: contentString }); //Create a marker var marker = new google.maps.Marker({ position: coordinates, map: map, }); //Binding the click event to marker to open info window marker.addListener('click', function() { infowindow.open(map, marker); }); }, error: function () { //When unsuccessfully get response from google map, then set a error message $('#map').html('<p style="color:red"><b>For some reason,the map can not be loaded!<b></p>') } }); }
// ver. 1 Math.radians = function (degrees) { return (degrees * Math.PI) / 180; }; function update() { ctx.clearRect(0, 0, canvas.width, canvas.height); drawPlayer(); drawFrame(); bestTime(); if (start == 1) { movement(); destroyEnemy(); destroyEffect(); enemyMovement(); drawAttackBall(); attackRange(); destroyAttackBall(); drawEnemy(); drawEater(); drawEffect(); controllEffect(); drawTime(); checkDead(); var tmp = new Date(); curTime = (tmp - startTime) / 1000; if (curTime > 30 && startAttack == 0) { attackDelay(); startAttack = 1; } } else if (start == 0) { curTime = 0; movement(); startText(); frameControll(); } else { drawTime(); endPage(); } } function attackRange() { var scale = 1000; ctx.strokeStyle = "rgba(" + attackLineColor[0] + ", " + attackLineColor[1] + ", 0, " + attackLineColor[2] + ")"; if (attackOption == 1 || attackOption == 2) { ctx.lineWidth = 3; attackX = playerX + blockSize / 2 - canvas.width / 2; attackY = playerY + blockSize / 2 - canvas.height / 2; var dist = Math.sqrt(attackX * attackX + attackY * attackY); attackX = attackX / dist; attackY = attackY / dist; ctx.beginPath(); ctx.moveTo(canvas.width / 2, canvas.height / 2); ctx.lineTo( attackX * scale + canvas.width / 2, attackY * scale + canvas.height / 2 ); // ctx.lineTo(playerX, playerY); ctx.stroke(); ctx.closePath(); } else if (attackOption == 3) { ctx.lineWidth = 6; curRad += (Math.PI * 3) / 105; attackX = Math.cos(curRad); attackY = -Math.sin(curRad); ctx.beginPath(); ctx.moveTo(canvas.width / 2, canvas.height / 2); ctx.lineTo( attackX * scale + canvas.width / 2, attackY * scale + canvas.height / 2 ); ctx.stroke(); ctx.closePath(); } } function attackDelay() { attackLineColor[2] = 1.0; // 최초 한번만 실행 if (attackDelayCount == 0) { attackCount += 1; chooseAttack(); } // red if (attackLineColor[1] == 0) attackLineColor[1] = 255; // yellow else if (attackLineColor[1] == 255) attackLineColor[1] = 0; attackDelayCount += 1; if (attackDelayCount == 8) { attackDelayCount = 0; attackLineColor[2] = 0; attack(); } else setTimeout(attackDelay, 250); } function chooseAttack() { if (attackCount % 3 == 0) attackOption = 2; else attackOption = 1; if (attackCount % 6 == 0) attackOption = 3; } function attack() { // Classic Attack if (attackOption == 1) { if (attackNum < 3) { setAttackBall(); attackNum += 1; setTimeout(attack, 200); } else { attackNum = 0; setTimeout(attackDelay, 3000); } } // Laser Attack else if (attackOption == 2) { if (attackNum < 35) { setAttackBall(); attackNum += 1; setTimeout(attack, 30); } else { attackNum = 0; setTimeout(attackDelay, 3000); } } // Spin Attack else if (attackOption == 3) { if (attackNum < 15) { setAttackBall(); attackNum += 1; setTimeout(attack, 200); } else { attackNum = 0; setTimeout(attackDelay, 3000); } } } function setAttackBall() { attackBallX.push(canvas.width / 2); attackBallY.push(canvas.height / 2); // Classic, Laser if (attackOption == 1 || attackOption == 2) { attackVecX.push(attackX); attackVecY.push(attackY); } // Spin else if (attackOption == 3) { var rad = Math.radians(attackNum * 48); attackVecX.push(Math.cos(rad)); attackVecY.push(-Math.sin(rad)); } } function controllAttackBall() { for (var i = 0; i < attackBallX.length; i++) { if (attackOption == 1 || attackOption == 3) { attackBallX[i] += attackVecX[i] * 5; attackBallY[i] += attackVecY[i] * 5; } else if (attackOption == 2) { attackBallX[i] += attackVecX[i] * 5.5; attackBallY[i] += attackVecY[i] * 5.5; } } } function drawAttackBall() { controllAttackBall(); for (var i = 0; i < attackBallX.length; i++) { ctx.beginPath(); ctx.arc(attackBallX[i], attackBallY[i], 15, 0, Math.PI * 2); ctx.fillStyle = "rgb(255, 255, 255)"; ctx.fill(); ctx.closePath(); } } function destroyAttackBall() { for (var i = 0; i < attackBallX.length; i++) { if ( !( attackBallX[i] < canvas.width && attackBallX[i] > 0 && attackBallY[i] < canvas.height && attackBallY[i] > 0 ) ) { attackBallX.splice(i, 1); attackBallY.splice(i, 1); attackVecX.splice(i, 1); attackVecY.splice(i, 1); i -= 1; } } } function endPage() { if (newBest) { ctx.font = "25px Comic Sans MS"; ctx.fillStyle = "#ff9900"; ctx.fillText("New Best!", canvas.width / 2, canvas.height / 2 - 100); if (newBestEffectAlpha > 0) { ctx.strokeStyle = "rgba(255, 153, 0, " + newBestEffectAlpha + ")"; ctx.lineWidth = 6; ctx.beginPath(); ctx.arc( canvas.width / 2, canvas.height / 2 - 100, newBestEffectSize, 0, Math.PI * 2 ); ctx.stroke(); ctx.closePath(); newBestEffectSize += 5; newBestEffectAlpha -= 1.7 / 60; } } ctx.font = "30px Comic Sans MS"; ctx.fillStyle = "white"; ctx.textAlign = "center"; ctx.fillText( "Press Space to Main.", canvas.width / 2, canvas.height / 2 + 230 ); } function bestTime() { if (!sessionStorage.getItem("bestTime")) { sessionStorage.setItem("bestTime", "0.00"); } if (start == 0) { ctx.font = "20px Comic Sans MS"; ctx.fillStyle = "#FFCC00"; ctx.fillText( "Best Time: " + sessionStorage.getItem("bestTime"), canvas.width / 2, canvas.height / 2 - 100 ); } else if (start == 1) { ctx.font = "20px Comic Sans MS"; ctx.fillStyle = "#FFCC00"; if (lastTime <= sessionStorage.getItem("bestTime")) ctx.fillText( "Best Time: " + sessionStorage.getItem("bestTime"), canvas.width / 2, canvas.height / 2 - 230 ); else ctx.fillText( "Best Time: " + lastTime, canvas.width / 2, canvas.height / 2 - 230 ); } else { ctx.font = "20px Comic Sans MS"; ctx.fillStyle = "#FFCC00"; ctx.fillText( "Best Time: " + sessionStorage.getItem("bestTime"), canvas.width / 2, canvas.height / 2 - 230 ); checkBestTime(); } } function checkBestTime() { if (lastTime > sessionStorage.getItem("bestTime")) { sessionStorage.setItem("bestTime", lastTime); newBest = 1; } } function startText() { ctx.font = "20px Comic Sans MS"; ctx.fillStyle = "#ababab"; var customized = Number(sessionStorage.getItem("customized")); if (customized == 0) { ctx.fillText( "Customize your Frame Size.", canvas.width / 2, canvas.height / 2 - 190 ); ctx.beginPath(); ctx.moveTo(canvas.width / 4 + 35, canvas.height / 2 - 13); ctx.lineTo(canvas.width / 4 + 35, canvas.height / 2 + 13); ctx.lineTo( canvas.width / 4 + 35 - (20 * Math.sqrt(3)) / 2, canvas.height / 2 ); ctx.fill(); ctx.moveTo((canvas.width * 3) / 4 - 35, canvas.height / 2 - 13); ctx.lineTo((canvas.width * 3) / 4 - 35, canvas.height / 2 + 13); ctx.lineTo( (canvas.width * 3) / 4 - 35 + (20 * Math.sqrt(3)) / 2, canvas.height / 2 ); ctx.fill(); } else { if (tooLarge == 0) ctx.fillText("Nice!", canvas.width / 2, canvas.height / 2 - 190); else ctx.fillText("Too Large!", canvas.width / 2, canvas.height / 2 - 190); ctx.fillText( "Press R to Initiallize.", canvas.width / 2, canvas.height / 2 + 100 ); } ctx.font = "30px Comic Sans MS"; ctx.fillStyle = "white"; ctx.textAlign = "center"; ctx.fillText("Avoid Blobs!", canvas.width / 2, canvas.height / 2 - 220); ctx.fillText( "Press Space to Start.", canvas.width / 2, canvas.height / 2 + 230 ); } function drawTime() { ctx.font = "25px Comic Sans MS"; ctx.fillStyle = "white"; ctx.textAlign = "center"; var time = Math.floor(curTime * 100) / 100; // 소수점 초가 없다면. if (time == Math.floor(time)) time += ".00"; // 소수점 1자리까지만 있다면. else if (time * 10 == Math.floor(time * 10)) time += "0"; lastTime = Number(time); ctx.fillText(time, canvas.width / 2, canvas.height / 2 - 200); } function frameControll() { var frameX = Number(sessionStorage.getItem("frameX")); var frameY = Number(sessionStorage.getItem("frameY")); var frameWidth = Number(sessionStorage.getItem("frameWidth")); var frameHeight = Number(sessionStorage.getItem("frameHeight")); var customized = Number(sessionStorage.getItem("customized")); if (right && coll[1]) { if (frameX + frameWidth + 2.5 > canvas.width - 1) { tooLarge = 1; } else { tooLarge = 0; frameWidth += 1; if (customized == 0) sessionStorage.setItem("customized", 1); } } if (left && coll[3]) { if (frameX - 2.5 < 0) { tooLarge = 1; } else { tooLarge = 0; frameX -= 1; frameWidth += 1; if (customized == 0) sessionStorage.setItem("customized", 1); } } if (up && coll[0]) { if (frameY - 2.5 < 0) { tooLarge = 1; } else { tooLarge = 0; frameY -= 1; frameHeight += 1; if (customized == 0) sessionStorage.setItem("customized", 1); } } if (down && coll[2]) { if (frameY + frameHeight + 2.5 > canvas.height - 1) { tooLarge = 1; } else { tooLarge = 0; frameHeight += 1; if (customized == 0) sessionStorage.setItem("customized", 1); } } sessionStorage.setItem("frameX", frameX); sessionStorage.setItem("frameY", frameY); sessionStorage.setItem("frameWidth", frameWidth); sessionStorage.setItem("frameHeight", frameHeight); } function drawFrame() { var frameX = Number(sessionStorage.getItem("frameX")); var frameY = Number(sessionStorage.getItem("frameY")); var frameWidth = Number(sessionStorage.getItem("frameWidth")); var frameHeight = Number(sessionStorage.getItem("frameHeight")); ctx.strokeStyle = "white"; ctx.lineWidth = frameBold; ctx.beginPath(); ctx.strokeRect(frameX, frameY, frameWidth, frameHeight); ctx.stroke(); ctx.closePath(); } function drawEater() { ctx.beginPath(); ctx.arc(canvas.width / 2, canvas.height / 2, eaterSize, 0, Math.PI * 2); // ctx.fillStyle = "rgba(51, 204, 51, "+eaterAlpha+")" ctx.fillStyle = "rgba(" + r + ", " + g + ", " + b + ", 0.5)"; ctx.fill(); ctx.closePath(); } function drawEnemy() { for (var i = 0; i < randX.length; i++) { ctx.beginPath(); ctx.arc(enemyX[i], enemyY[i], enemySize[i] * sizeFactor[i], 0, Math.PI * 2); ctx.fillStyle = "rgb(" + enemyColor[i][0] + ", " + enemyColor[i][1] + ", " + enemyColor[i][2] + ")"; // ctx.fillStyle = "rgba(255, 255, 255, 0.08)"; // Darkness ctx.fill(); ctx.closePath(); } } function drawPlayer() { ctx.beginPath(); ctx.rect(playerX, playerY, blockSize, blockSize); ctx.fillStyle = "red"; // ctx.fillStyle = "rgba(255, 255, 255, 0.05)"; // Darkness ctx.fill(); ctx.closePath(); } function movement() { checkCollide(); var gravity; if (start == 1) gravity = gravitation(); else gravity = [0, 0]; var x = getHorizontal(); var y = getVertical(); playerX += speed * x + gravity[0]; playerY += speed * y + gravity[1]; } function gravitation() { var scale = 1.5; var x = canvas.width / 2 - (playerX + blockSize / 2); var y = canvas.height / 2 - (playerY + blockSize / 2); var dist = Math.sqrt(x * x + y * y); if (dist < eaterSize) { // Dead start = 2; } var gravX = (x / dist) * scale; var gravY = (y / dist) * scale; return [gravX, gravY]; } function keyDownHandler(e) { // UP if (e.keyCode == 38 || e.keyCode == 87) up = true; // RIHGT if (e.keyCode == 39 || e.keyCode == 68) right = true; // DOWN if (e.keyCode == 40 || e.keyCode == 83) down = true; // LEFT if (e.keyCode == 37 || e.keyCode == 65) left = true; if (start == 0) { if (e.keyCode == 32) { start = 1; startTime = new Date(); setTimeout(setEnemy, createSpeed); } if (e.keyCode == 82) { sessionStorage.setItem("frameX", canvas.width / 4); sessionStorage.setItem("frameY", canvas.height / 4); sessionStorage.setItem("frameWidth", canvas.width / 2); sessionStorage.setItem("frameHeight", canvas.height / 2); sessionStorage.setItem("customized", 0); } } else if (start == 2) { if (e.keyCode == 32) { location.reload(); } } } function keyUpHandler(e) { // UP if (e.keyCode == 38 || e.keyCode == 87) up = false; // RIHGT if (e.keyCode == 39 || e.keyCode == 68) right = false; // DOWN if (e.keyCode == 40 || e.keyCode == 83) down = false; // LEFT if (e.keyCode == 37 || e.keyCode == 65) left = false; } function getVertical() { if (up && !down) return -1; else if (!up && down) return 1; else return 0; } function getHorizontal() { if (right && !left) return 1; else if (!right && left) return -1; else return 0; } function checkCollide() { var frameX = Number(sessionStorage.getItem("frameX")); var frameY = Number(sessionStorage.getItem("frameY")); var frameWidth = Number(sessionStorage.getItem("frameWidth")); var frameHeight = Number(sessionStorage.getItem("frameHeight")); if (playerX - frameBold / 2 <= frameX) { playerX = frameX + 2.5; coll[3] = true; } else coll[3] = false; if (playerX + blockSize + frameBold / 2 >= frameX + frameWidth) { playerX = -blockSize + frameX + frameWidth - 2.5; coll[1] = true; } else coll[1] = false; if (playerY + blockSize + frameBold / 2 >= frameY + frameHeight) { playerY = frameY + frameHeight - 2.5 - blockSize; coll[2] = true; } else coll[2] = false; if (playerY - frameBold / 2 <= frameY) { playerY = frameY + 2.5; coll[0] = true; } else coll[0] = false; } function setEnemy() { createSpeed = Math.floor(startCreateSpeed - curTime * 3); randDir = Math.floor(Math.random() * 4 + 1); var tmpSize = Math.random() * 20 + 100; enemySize.push(tmpSize); enemyColor.push([ Math.random() * 255, Math.random() * 255, Math.random() * 255, ]); if (randDir == 1) { randX.push(Math.random() * canvas.width); randY.push(-tmpSize); enemyX.push(randX[randX.length - 1]); enemyY.push(randY[randY.length - 1]); } else if (randDir == 2) { randX.push(canvas.width + tmpSize); randY.push(Math.random() * canvas.height); enemyX.push(randX[randX.length - 1]); enemyY.push(randY[randY.length - 1]); } else if (randDir == 3) { randX.push(Math.random() * canvas.width); randY.push(canvas.height + tmpSize); enemyX.push(randX[randX.length - 1]); enemyY.push(randY[randY.length - 1]); } else { randX.push(-tmpSize); randY.push(Math.random() * canvas.height); enemyX.push(randX[randX.length - 1]); enemyY.push(randY[randY.length - 1]); } // calculate ememySpeed var curX = randX[randX.length - 1]; var curY = randY[randY.length - 1]; curX = canvas.width / 2 - curX; curY = canvas.height / 2 - curY; var randSpeed = Math.random() * 2 + 4; var dist = Math.sqrt(curX * curX + curY * curY); enemySpeed.push([(curX / dist) * randSpeed, (curY / dist) * randSpeed]); enemyDist.push(dist); sizeFactor.push(1); setTimeout(setEnemy, createSpeed); } function enemyMovement() { for (var i = 0; i < randX.length; i++) { enemyX[i] += enemySpeed[i][0]; enemyY[i] += enemySpeed[i][1]; var x = enemyX[i] - randX[i]; var y = enemyY[i] - randY[i]; var curDist = Math.sqrt(x * x + y * y); sizeFactor[i] = 1 - curDist / enemyDist[i]; if (sizeFactor[i] < 0) sizeFactor[i] = 0; } } function destroyEnemy() { for (var i = 0; i < randX.length; i++) { if (sizeFactor[i] < 0.05) { setEatEffect(i); r = enemyColor[i][0]; g = enemyColor[i][1]; b = enemyColor[i][2]; randX.splice(i, 1); randY.splice(i, 1); enemyX.splice(i, 1); enemyY.splice(i, 1); enemySpeed.splice(i, 1); enemySize.splice(i, 1); enemyDist.splice(i, 1); sizeFactor.splice(i, 1); enemyColor.splice(i, 1); i -= 1; eaterSize += 0.5; if (eaterSize > 90) eaterSize = 90; } } } function checkDead() { // Enemy for (var i = 0; i < randX.length; i++) { var x = playerX + blockSize / 2 - enemyX[i]; var y = playerY + blockSize / 2 - enemyY[i]; var dist = Math.sqrt(x * x + y * y); if ( dist + 10 < (blockSize * Math.sqrt(2)) / 2 + enemySize[i] * sizeFactor[i] ) { start = 2; } } // attackBall for (var i = 0; i < attackBallX.length; i++) { var x = playerX + blockSize / 2 - attackBallX[i]; var y = playerY + blockSize / 2 - attackBallY[i]; var dist = Math.sqrt(x * x + y * y); if (dist + 3 < (blockSize * Math.sqrt(2)) / 2 + 15) { start = 2; } } } function setEatEffect(curIdx) { enemyColor[curIdx].push(1); effectSize.push(eaterSize); effectColor.push(enemyColor[curIdx]); effectSpeed.push(Math.random() * 4 + 3); } function drawEffect() { for (var i = 0; i < effectSize.length; i++) { ctx.strokeStyle = "rgba(" + effectColor[i][0] + ", " + effectColor[i][1] + ", " + effectColor[i][2] + ", " + effectColor[i][3] + ")"; ctx.lineWidth = 6; ctx.beginPath(); ctx.arc(canvas.width / 2, canvas.height / 2, effectSize[i], 0, Math.PI * 2); ctx.stroke(); ctx.closePath(); } } function controllEffect() { for (var i = 0; i < effectSize.length; i++) { effectSize[i] += effectSpeed[i]; effectColor[i][3] -= 0.3 / frame; if (effectColor[i][3] <= 0) effectColor[i][3] = 0; } } function destroyEffect() { var limit = (canvas.width / 2) * Math.sqrt(2); for (var i = 0; i < effectSize.length; i++) { if (effectSize[i] > limit) { effectSize.splice(i, 1); effectColor.splice(i, 1); effectSpeed.splice(i, 1); i -= 1; } } } var canvas = document.getElementById("myCanvas"); var timeScore = document.getElementById("timeScore"); var ctx = canvas.getContext("2d"); var frame = 1000 / 60; // 10 frame var row = 30; var column = 30; var blockSize = canvas.width / row; var playerX = blockSize * (row / 2) - 10; var playerY = blockSize * (column / 2) + 50; var curDir = 2; var speed = 3; var up = false; var left = false; var down = false; var right = false; var colPos = 0; var first = 0; var frameBold = 5; var randX = []; var randY = []; var enemyX = []; var enemyY = []; var enemySpeed = []; var enemySize = []; var enemyDist = []; var sizeFactor = []; var enemyColor = []; var effectSize = []; var effectColor = []; var effectSpeed = []; var eaterSize = 5; var r = 255; var g = 255; var b = 255; var startTime, endTime, curTime; var createSpeed; var startCreateSpeed = 500; var start = 0; var coll = [false, false, false, false]; // up, right, down, left if (!sessionStorage.getItem("frameX")) { sessionStorage.setItem("frameX", canvas.width / 4); sessionStorage.setItem("frameY", canvas.height / 4); sessionStorage.setItem("frameWidth", canvas.width / 2); sessionStorage.setItem("frameHeight", canvas.width / 2); } if (!sessionStorage.getItem("customized")) { sessionStorage.setItem("customized", 0); } var tooLarge = 0; var lastTime = 0; var newBest = 0; var eaterAlpha = 1.0; var r = 255, g = (b = 0); var attackNum = 0; var attackOption = 4; // 1: Classic 2: Laser 3: Spin 4: Infinity Laser var attackCount = 0; var attackX, attackY; var attackBallX = []; var attackBallY = []; var attackVecX = []; var attackVecY = []; var attackLineColor = [255, 0, 0]; // R, G, Alpha var attackDelayCount = 0; var startAttack = 0; var newBestEffectSize = 5; var newBestEffectAlpha = 1.0; var curRad = 0; document.addEventListener("keydown", keyDownHandler, false); document.addEventListener("keyup", keyUpHandler, false); setInterval(update, frame); //
app.controller('HomeController', ['Entry', '$scope', '$mdDialog', '$mdMedia', function(Entry, $scope, $mdDialog, $mdMedia) { var self = this; this.mobileMenu = false; this.icon = true; this.books = Entry.books; this.welcomeForm = true; this.newBookEntry = { title: '', author: '', image: Entry.imageUrl() }; this.customFullscreen = $mdMedia('xs') || $mdMedia('sm'); this.useFullScreen = ($mdMedia('sm') || $mdMedia('xs')) && self.customFullscreen; /** * Toggles mobile toolbar icon * Toggles between mobile and web book list */ this.showHideMenu = function() { self.icon = !self.icon; self.mobileMenu = !self.mobileMenu; }; /** * Hides welcome card */ this.closeCard = function () { self.welcomeForm = false; }; /** * Shows book entry form in lightbox for web * Shows entry form full-screen for mobile */ this.showDialog = function(ev) { $mdDialog.show({ controller: 'HomeController', controllerAs: 'home', templateUrl: 'views/dialog.html', parent: angular.element(document.body), targetEvent: ev, clickOutsideToClose:true, escapeToClose:true, fullscreen: self.useFullScreen }); $scope.$watch(function() { return $mdMedia('xs') || $mdMedia('sm'); }, function(wantsFullScreen) { self.customFullscreen = (wantsFullScreen === true); }); }; /** * Shows alert dialog when duplicate book is entered */ this.showAlert = function(ev) { $mdDialog.show( $mdDialog.alert() .parent(angular.element(document.body)) .clickOutsideToClose(true) .title('Watch out!') .textContent('This book is already saved!') .ariaLabel('Alert Dialog') .ok('Got it!') .targetEvent(ev) ); }; /** * Closes dialog */ this.closeDialog = function() { $mdDialog.hide(); }; /** * If book in not in books array, adds book * else calls showAlert function */ this.addBook = function() { if (Entry.isBookRead(self.newBookEntry)) { self.closeDialog(); self.showAlert(); } else { self.books.push(self.newBookEntry); self.closeDialog(); } }; }]);
(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){ //Clase People, para obtener las personas de Star Wars API class People{ constructor(){ this.path = "https://swapi.dev/api/people/"; } async getPeople(){ const response = await fetch (this.path); // const result =await response.json(); // return await result.results; return await ( await response.json() ).results; } async getPersonsSpeciesName(personObj){ const response = await fetch(personObj.species[0]); return await ( await response.json() ).name; } // async getPersonsMovies(personObj){ // console.log(personObj.films); // let movieNames; // personObj.films.map(url => { // fetch(url) // .then( a => a.json() // .then( b => movieNames.push(b.title)) // ) // }); // } async getPersonByID(id){ const response = await fetch(this.path+`${id}`); return await ( await response.json() ).results; } } module.exports = People; },{}],2:[function(require,module,exports){ //Clase Specie, para obtener las especies de Star Wars API class Specie{ constructor(){ this.path = "https://swapi.co/api/species/"; } async getSpecies(){ const response = await fetch (this.path); const result =await response.json(); return await result.results; } async getSpecieByID(id){ const response = await fetch(this.path+`${id}`); // return await response.json(); const result =await response.json(); return await (result.name); } } module.exports = Specie; },{}],3:[function(require,module,exports){ const People = require('./Classes/people.js'); const Specie = require('./Classes/specie.js'); class Info { constructor() { this.users = new People(); this.species= new Specie(); this.users.getPeople().then(data => { data.forEach(this.card, this) }, this); } card(item) { console.log(item); this.users.getPersonsSpeciesName(item).then( s_name => { console.log(s_name); var el = document.createElement('div'); el.setAttribute('class', "card"); el.innerHTML =`<div id class="container"> <h4><b>${item.name}</b></h4> <p>${s_name}</p> </div>`; //el.addEventListener('click', this.OnClick().bind(this)); el.addEventListener('click', (event) => ((arg) => { this.OnSideClick(event,item); })(item)); document.querySelector('#sidebar ul') .appendChild(el); }); } OnSideClick(event,item) { console.log("PASE AL ONCLICK") this.showPersonalInfo(item); document.querySelector('#info-bar').addEventListener('click', (event) => ((arg) => { this.showPersonalInfo(arg); })(item)); document.querySelector('#movie-bar').addEventListener('click', (event) => ((arg) => { this.showMovies(arg); })(item)); document.querySelector('#starship-bar').addEventListener('click', (event) => ((arg) => { this.showStarships(arg); })(item)); document.querySelector('#vehicle-bar').addEventListener('click', (event) => ((arg) => { this.showVehicles(arg); })(item)); } showPersonalInfo(item) { //editar la barra superior document.querySelector('#info-bar').setAttribute('class', 'active'); document.querySelector('#vehicle-bar').setAttribute('class',''); document.querySelector('#starship-bar').setAttribute('class',''); document.querySelector('#movie-bar').setAttribute('class',''); //borrar la información existente document.querySelector('#person-info').innerHTML=''; //llenar con una nueva información let info= document.createElement('div'); info.innerHTML=`<h1> Personal Info</h1> <p>Name: ${item.name}</p> <p>Height: ${item.height}</p> <p>Mass: ${item.mass}</p> <p>Hair Color: ${item.hair_color}</p> <p>Skin Color: ${item.skin_color}</p> <p>Eye Color: ${item.eye_color}</p> <p>Gender: ${item.gender}</p> <p>Birth: ${item.birth_year}</p>`; info.setAttribute('class','content-info'); document.querySelector('#person-info') .appendChild(info); } showMovies(item){ //borrar la información existente document.querySelector('#person-info').innerHTML=''; //llenar con una nueva información let info= document.createElement('div'); info.innerHTML=`<h1> Movies</h1>`; info.setAttribute('class','content-info'); document.querySelector('#person-info') .appendChild(info); //obtener la info de las pelis de la persona item.films.map(url => { fetch(url) .then( a => a.json() .then( b => { var movieEl=document.createElement('p'); movieEl.innerHTML= `${b.title}`; info.appendChild(movieEl); }) ) }); //editar la barra superior document.querySelector('#info-bar').setAttribute('class', ''); document.querySelector('#vehicle-bar').setAttribute('class',''); document.querySelector('#starship-bar').setAttribute('class',''); document.querySelector('#movie-bar').setAttribute('class','active'); } showStarships(item){ //borrar la información existente document.querySelector('#person-info').innerHTML=''; //llenar con una nueva información let info= document.createElement('div'); info.innerHTML=`<h1> StarShips </h1>`; info.setAttribute('class','content-info'); document.querySelector('#person-info') .appendChild(info); //obtener la info de las naves de la persona item.starships.map(url => { fetch(url) .then( a => a.json() .then( b => { let starshipName=document.createElement('p'); starshipName.innerHTML= `Name: ${b.name}`; info.appendChild(starshipName); let model=document.createElement('p'); model.innerHTML= `Model: ${b.model}`; info.appendChild(model); var cost=document.createElement('p'); cost.innerHTML= `Cost: ${b.cost_in_credits}`; info.appendChild(cost); var s_length=document.createElement('p'); s_length.innerHTML= `Length: ${b.length}`; info.appendChild(s_length); var crew=document.createElement('p'); crew.innerHTML= `Crew: ${b.crew}`; info.appendChild(crew); var passengers=document.createElement('p'); passengers.innerHTML= `Passengers: ${b.passengers}`; info.appendChild(passengers); var consumables=document.createElement('p'); consumables.innerHTML= `Consumables: ${b.consumables}`; info.appendChild(consumables); var s_class=document.createElement('p'); s_class.innerHTML= `Class: ${b.starship_class}`; info.appendChild(s_class); var separator = document.createElement('p'); separator.innerHTML= "======================="; info.appendChild(separator); }) ) }); //editar la barra superior document.querySelector('#info-bar').setAttribute('class', ''); document.querySelector('#vehicle-bar').setAttribute('class',''); document.querySelector('#starship-bar').setAttribute('class','active'); document.querySelector('#movie-bar').setAttribute('class',''); } showVehicles(item){ //borrar la información existente document.querySelector('#person-info').innerHTML=''; //llenar con una nueva información let info= document.createElement('div'); info.innerHTML=`<h1> Vehicles </h1>`; info.setAttribute('class','content-info'); document.querySelector('#person-info') .appendChild(info); //obtener la info de las naves de la persona item.vehicles.map(url => { fetch(url) .then( a => a.json() .then( b => { let name=document.createElement('p'); name.innerHTML= `Name: ${b.name}`; info.appendChild(name); let model=document.createElement('p'); model.innerHTML= `Model: ${b.model}`; info.appendChild(model); var cost=document.createElement('p'); cost.innerHTML= `Cost: ${b.cost_in_credits}`; info.appendChild(cost); var s_length=document.createElement('p'); s_length.innerHTML= `Length: ${b.length}`; info.appendChild(s_length); var crew=document.createElement('p'); crew.innerHTML= `Crew: ${b.crew}`; info.appendChild(crew); var passengers=document.createElement('p'); passengers.innerHTML= `Passengers: ${b.passengers}`; info.appendChild(passengers); var consumables=document.createElement('p'); consumables.innerHTML= `Consumables: ${b.consumables}`; info.appendChild(consumables); var s_class=document.createElement('p'); s_class.innerHTML= `Class: ${b.vehicle_class}`; info.appendChild(s_class); var separator = document.createElement('p'); separator.innerHTML= "======================="; info.appendChild(separator); }) ) }); //editar la barra superior document.querySelector('#info-bar').setAttribute('class', ''); document.querySelector('#vehicle-bar').setAttribute('class','active'); document.querySelector('#starship-bar').setAttribute('class',''); document.querySelector('#movie-bar').setAttribute('class',''); } } const app = new Info() ; },{"./Classes/people.js":1,"./Classes/specie.js":2}]},{},[3]);
import { useContext } from "react"; import Context from "./navigation.context"; export default function useData() { const { data } = useContext(Context); return data; }
import React from 'react'; import axios from 'axios'; import OneEmployee from "./oneEmployee"; const Employees = ({data}) => { const [Employee,setEmployee]=React.useState([]) const [TempUser,setTempUser]=React.useState(null) React.useEffect(()=> { GetEmployee() },[]) React.useEffect(()=> { data(Employee) },[Employee]) const GetEmployee = async ()=>{ let results= await axios.get("https://617aedfecb1efe00170100ca.mockapi.io/clients"); setEmployee(results.data); } const change=(e)=>{ let ids; let chosen=Employee.find((user)=>{ if(e.target.value===user.name){ ids=user.id return user } }) console.log(ids) setTempUser(chosen) } return( <> <div style={{marginLeft:'11vw'}}> <h1>Employee Status:</h1> <br/> { Employee? <div className={"employee"} > <select onChange={change}> <option>any</option> {Employee.map((person) => { return <option key={person.id} >{person.name}</option> }) } </select> </div> :"loading" } {TempUser ? <div><OneEmployee person={TempUser} /> </div>:""} </div></> ) } export default Employees;
import React, { useState, useEffect } from 'react'; import { useQuery } from '@apollo/react-hooks'; import { Card, CardGroup, Container } from 'react-bootstrap'; import { connect } from 'react-redux'; import { setBase, setPizza, clearPizza } from '../../actions/pizza'; import { addPizza } from '../../actions/pizzas'; import { setMenu, setPopCart } from '../../actions/menu'; import { GET_ALL_SPECIALTY_PIZZA_INFO } from '../../config/gqlDefines'; import './SpecialtyPizzas.css'; import PopCart from '../Cart/PopCart'; import StyledButton from '../common/Button/StyledButton'; import StyledTitle from '../common/Title/StyledTitle'; const SpecialtyPizzas = (props) => { useEffect(() => { props.setPopCart(false); }); const { loading, error, data } = useQuery(GET_ALL_SPECIALTY_PIZZA_INFO); if (error) return <p>{error.message}</p>; if (loading) return <p>Loading...</p>; //adds pizza to pizzas store const handleSubmit = (pizza) => { const currentPizza = { ...props.pizza }; const cheeses = pizza.cheeses.map((cheese) => { return { type: cheese.cheese_type, id: cheese.cheese_id, price: cheese.cheese_price, }; }); const meats = pizza.meats.map((meat) => { return { type: meat.meat_type, id: meat.meat_id, price: meat.meat_price }; }); const veggies = pizza.veggies.map((veggie) => { return { type: veggie.veggie_type, id: veggie.veggie_id, price: veggie.veggie_price, }; }); const toppings = { cheeses: cheeses, veggies: veggies, meats: meats, }; const crust = { type: pizza.crust.crust_type, id: pizza.crust.crust_id }; const sauce = { type: pizza.sauce.sauce_type, id: pizza.sauce.sauce_id }; props.setPizza({ ...currentPizza, name: pizza.pizza_name, toppings: toppings, crust: crust, sauce: sauce, basePrice: pizza.price.toFixed(2), totalPrice: pizza.price.toFixed(2), quantity: 1, }); props.setMenu(8); }; //Change to custom order // const handleCustomOrder = (e) => { // props.clearPizza(); // props.setMenu(3); // }; //Renders cards of all possible specialty pizza, when one is selected, the sizing prompt is render return ( <Container> {props.popCart ? <PopCart /> : null} <StyledTitle text="Specialty Pizzas" className="basicTitle" /> <CardGroup className="specialtyPizzaCardGroup"> {data.getAllSpecialtyPizzaInfo.map((item, id) => { // console.log(item.pizza_name); return ( <div key={item.pizza_name} className="specialtyPizzaCardWrapper"> <Card className="specialtyPizzaCard"> <Card.Body className="specialtyPizzaCardBody"> <Card.Title>{item.pizza_name}</Card.Title> <Card.Text>Crust: {item.crust.crust_type}</Card.Text> <Card.Text>Sauce: {item.sauce.sauce_type}</Card.Text> <Card.Text key={`${item.cheeses.cheese}_cheeses${id}`}> Cheese(s): {item.cheeses.map((cheese, i) => { console.log(cheese); return i === 0 ? ` ${cheese.cheese_type}` : `, ${cheese.cheese_type}`; })} </Card.Text> <Card.Text key={`${item.pizza_name}_veggies${id}`}> Veggie(s): {item.veggies.map((veggie, i) => i === 0 ? ` ${veggie.veggie_type}` : `, ${veggie.veggie_type}` )} </Card.Text> <Card.Text key={`${item.pizza_name}_meats${id}`}> Meat(s): {item.meats.map((meat, i) => i === 0 ? ` ${meat.meat_type}` : `, ${meat.meat_type}` )} </Card.Text> <Card.Text> Price of Toppings: ${item.price.toFixed(2)} </Card.Text> </Card.Body> <div className="addToCartButton"> <StyledButton type="button" onClick={(e) => handleSubmit(item)} text="Add to Cart" variant="orderChoiceButton" /> </div> </Card> </div> ); })} </CardGroup> </Container> ); }; const mapStateToProps = (state) => ({ size: state.pizza.size, sizes: state.database.sizes, popCart: state.menu.popCart, pizza: state.pizza, }); export default connect(mapStateToProps, { setMenu, addPizza, setPizza, clearPizza, setPopCart, setBase, })(SpecialtyPizzas); //same as above in class component instead and with hard coded values // class SpecialtyPizzas extends React.Component { // constructor(props) { // super(props); // this.state = { // showSizeQuantityPrompt: false, // currentPizza: null, // // data: nulls // data: [ // //sample data // { // name: 'Meats Lovers', // crust: { type: 'Hand Tossed Garlic', id: 1 }, // sauce: { type: 'Tomato', id: 1 }, // size: { type: null }, // toppings: { // cheeses: [], // veggies: [], // meats: [ // { type: 'Ham', id: 1, price: 2.5 }, // { type: 'Beef', id: 2, price: 2 }, // { type: 'Sausage', id: 4, price: 2.25 }, // { type: 'Bacon', id: 6, price: 1.75 }, // ], // }, // basePrice: 8.5, // id: 1, // }, // { // name: 'Cheese Pizza', // crust: { type: 'Hand Tossed Garlic', id: 2 }, // sauce: { type: 'Tomato', id: 1 }, // size: { type: null }, // toppings: { // cheeses: [], // veggies: [], // meats: [], // }, // basePrice: 0, // id: 2, // }, // { // name: 'Veggie Pizza', // crust: { type: 'Hand Tossed Garlic', id: 2 }, // sauce: { type: 'Tomato', id: 1 }, // size: { type: null }, // toppings: { // cheeses: [], // veggies: [ // { type: 'Mushrooms', id: 4, price: 1 }, // { type: 'Spinach', id: 5, price: 1.25 }, // { type: 'Onions', id: 2, price: 0.75 }, // { type: 'Black Olives', id: 3, price: 0.75 }, // ], // meats: [], // }, // basePrice: 3.75, // id: 2, // }, // { // name: 'Hawaiian', // crust: { type: 'Hand Tossed Garlic', id: 2 }, // sauce: { type: 'Tomato', id: 1 }, // size: { type: null }, // toppings: { // cheeses: [], // veggies: [{ type: 'Pineapple', id: 7, price: 1 }], // meats: [{ type: 'Ham', id: 1, price: 2.5 }], // }, // basePrice: 3.5, // id: 2, // }, // { // name: 'Margarita', // crust: { type: 'Hand Tossed Garlic', id: 2 }, // sauce: { type: 'Tomato', id: 1 }, // size: { type: null }, // toppings: { // cheeses: [{ type: 'Mozzarella', id: 1, price: 2 }], // veggies: [{ type: 'Spinach', id: 5, price: 1.25 }], // meats: [], // }, // basePrice: 3.25, // id: 2, // }, // ], // }; // } // componentDidMount = async () => { // this.props.setPopCart(false); // const { client } = this.props; // //const results = await client.query({ query: GET_ALL_SPECIALTY_PIZZA_INFO}) // // this.setState({ // // data: results // // }) // console.log(results) // }; // //adds pizza to pizzas store // handleSubmit = (pizza) => { // const currentPizza = { ...this.props.pizza }; // this.props.setPizza({ // ...currentPizza, // name: pizza.name, // toppings: pizza.toppings, // crust: pizza.crust, // sauce: pizza.sauce, // basePrice: pizza.basePrice.toFixed(2), // totalPrice: pizza.basePrice.toFixed(2), // quantity: 1, // }); // this.props.setMenu(8); // }; // //Change to custom order // handleCustomOrder = (e) => { // this.props.clearPizza(); // this.props.setMenu(3); // }; // //Renders cards of all possible specialty pizza, when one is selected, the sizing prompt is render // render() { // return ( // <div> // {this.props.popCart ? <PopCart /> : null} // <CardGroup> // {this.state.data.map((item) => { // return ( // <Card key={item.name} className='specialtyPizzaCard'> // <Card.Body className="specialtyPizzaCardBody"> // <Card.Title>{item.name}</Card.Title> // <Card.Text>Crust: {item.crust.type}</Card.Text> // <Card.Text>Sauce: {item.sauce.type}</Card.Text> // <Card.Text> // {item.toppings.cheeses.map((cheese, i) => // i === 0 ? `Cheese(s): ${cheese.type}` : `, ${cheese.type}` // )} // </Card.Text> // <Card.Text> // {item.toppings.veggies.map((veggie, i) => // i === 0 ? `Veggie(s): ${veggie.type}` : `, ${veggie.type}` // )} // </Card.Text> // <Card.Text> // {item.toppings.meats.map((meat, i) => // i === 0 ? `Meat(s): ${meat.type}` : `, ${meat.type}` // )} // </Card.Text> // <Card.Text> // Price of Toppings: ${item.basePrice.toFixed(2)} // </Card.Text> // </Card.Body> // <div className="addToCartButton"> <StyledButton // type="button" // onClick={(e) => this.handleSubmit(item)} // text="Add to Cart" // variant="orderChoiceButton" // /> // </div> // </Card> // ); // })} // </CardGroup> // </div> // ); // } // } // const mapStateToProps = (state) => ({ // size: state.pizza.size, // sizes: state.database.sizes, // popCart: state.menu.popCart, // pizza: state.pizza // }); // export default connect(mapStateToProps, { // setMenu, // addPizza, // setPizza, // clearPizza, // setPopCart, // setBase, // })(SpecialtyPizzas);
export const whatTheHack = { "name": "Hacker", "skills": "Hacking", "gif": "https://media.giphy.com/media/l0HlzAJstx1yNhcnS/giphy.gif" } export default whatTheHack
if (process.env.NEWRELIC_KEY) { require('newrelic'); } var express = require('express'); var app = express(); var email = require("emailjs/email"); var port = process.env.PORT || 3000; var twilioSID = process.env.TWILIO_ACCOUNT_SID || ''; var numbers = (process.env.AUTHORIZED_NUMBERS || '').split(","); var validNumbers = {}; var forwardNumber = process.env.FORWARD_NUMBER || null; var smsNumber = process.env.SMS_NUMBER || null; var emailName = process.env.EMAIL_FROM || null; var emailPw = process.env.EMAIL_FROM_PASSWORD || null; var emailTo = process.env.EMAIL_TO || null; for (var i in numbers) { validNumbers[numbers[i]] = true; } app.get('/twilio/voice', function (req, res) { var query = req.query; if (query.AccountSid == twilioSID && validNumbers[query.From]) { res.send('<?xml version="1.0" encoding="UTF-8"?>' + '<Response>' + '<Play digits="www9"/>' + (smsNumber ? '<Sms to="'+ smsNumber + '">Door opened.</Sms>' : '')+ '</Response>'); if (emailName && (emailName && emailPw && emailTo)) { // server.send fn will not retain if this snippet is outside var server = email.server.connect({ user: emailName, password: emailPw, host: "smtp.gmail.com", ssl: true }); server.send({ text: "Door opened", from: "Carrot Bot <"+ emailName + ">", to: emailTo, subject: "Door opened" }, function(err, message) { console.log(err || message); }); } } else if (query.AccountSid == twilioSID && forwardNumber) { res.send('<?xml version="1.0" encoding="UTF-8"?>' + '<Response>' + '<Dial>'+ forwardNumber + '</Dial>' + '</Response>'); } }); app.get('/heartbeat', function (req, res) { res.send('alive'); }); var server = app.listen(port, function () { console.log('Listening on port ' + server.address().port); });
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content'); var responsed; $('.numValid').bind('keypress',function(e){ var keyCode=e.which?e.which:e.keyCode; if(keyCode>=48 && keyCode<=57) { return true; } if(keyCode==8 || keyCode == 46){ return true; } return false; }); //Optional service tab --- meals Plan portion.... function clearOptMealsPlanForm(){ $('#optMealsplanTitle').val(''); $('#optAdulRate').val(''); $('#optChildRate').val(''); $('#optStartDate').val(''); $('#optEndDate').val(''); } function fnValidationOptMealsPlan(){ if($('#optMealsplanTitle').val() == ''){ alert('Please enter title'); $('#optMealsplanTitle').focus(); return false; }else if($('#optAdulRate').val() == ''){ alert('Please enter adult rate.'); $('#optAdulRate').focus(); return false; }else if($('#optChildRate').val() == ''){ alert('Please enter child rate.'); $('#optChildRate').focus(); return false; }else if($('#optStartDate').val() == ''){ alert('Please enter start date.'); $('#optStartDate').focus(); return false; }else if($('#optEndDate').val() == ''){ alert('Please enter end date.'); $('#optEndDate').focus(); return false; }else{ return true; } } $('#btnAddMealsPlan').click(function(){ $('#btnSaveOptmealsPlan').show(); $('#btnUpdateOptmealsPlan').hide(); $('#cOptionalMealsPlan').html('Add Meals Plan'); clearOptMealsPlanForm(); $('#addoptionserviceMealsPlanModal').modal().on('shown.bs.modal', function (e) {}); }); $('#btnSaveOptmealsPlan').click(function(){ if(fnValidationOptMealsPlan() == true){ $.ajax({ url: 'rates/saveOptionalMealsPlan', type: 'POST', data: { _token: CSRF_TOKEN, title: $('#optMealsplanTitle').val(), adultRate: $('#optAdulRate').val(), childRate: $('#optChildRate').val(), startDate: $('#optStartDate').val(), endDate: $('#optEndDate').val() }, success: function(response){ if(response>0){ responsed = response; clearOptMealsPlanForm(); }else{ alert('There occurs some internal problem'); window.location.reload(); } } }); if(responsed !=0){ alert('Data Save Successfully.'); $('#addoptionserviceMealsPlanModal').modal('toggle'); $.ajax({ url: 'rates/getOptionalMealsAlldata', type: 'get', dataType: 'JSON', success: function(response){ $("#tblMealsPlan tbody tr td").remove(); response.forEach(optmealsplan =>{ $("#tblMealsPlan tbody").append("<tr><td><button onclick=deleteOptMealsPlan(" + optmealsplan.optMealsID + ")><span><i class='fa fa-times' aria-hidden='true'></i></span></button></td><td><button onclick=showOptMealsPlanUpdateModal(" + optmealsplan.optMealsID + ") <span><i class='fa fa-pencil' aria-hidden='true'></i></span></button>" + "</td><td>"+ '---' + "</td><td>"+ optmealsplan.title + "</td><td>"+ optmealsplan.adultRate + "</td><td>"+ optmealsplan.childRate + "</td><td>"+ optmealsplan.startDate + "</td><td>"+ optmealsplan.endDate + "</td><td>"+ '#' +"</td></tr>"); }) } }) } } }); function showOptMealsPlanUpdateModal(id){ $('#btnSaveOptmealsPlan').hide(); $('#btnUpdateOptmealsPlan').show(); $('#cOptionalMealsPlan').html('Update Meals Plan'); $('#addoptionserviceMealsPlanModal').modal().on('shown.bs.modal', function (e) {}); $.ajax({ url: 'rates/showOptionalMealsPlanForUpdate', type: 'POST', dataType: 'JSON', data:{ _token: CSRF_TOKEN, id: id }, success: function(response){ $('#optionalMealsPlanId').val(response.optMealsID) $('#optMealsplanTitle').val(response.title); $('#optAdulRate').val(response.adultRate); $('#optChildRate').val(response.childRate); $('#optStartDate').val(response.startDate); $('#optEndDate').val(response.endDate); } }); } $('#btnUpdateOptmealsPlan').click(function(){ if(fnValidationOptMealsPlan() == true){ $.ajax({ url: 'rates/updateOptionalMealsPlan', type: 'POST', data: { _token: CSRF_TOKEN, id: $('#optionalMealsPlanId').val(), title: $('#optMealsplanTitle').val(), adultRate: $('#optAdulRate').val(), childRate: $('#optChildRate').val(), startDate: $('#optStartDate').val(), endDate: $('#optEndDate').val() }, success: function(response){ if(response>0){ responsed = response; clearOptMealsPlanForm(); } } }); if(responsed !=0){ alert('Data Update Successfully.'); $('#addoptionserviceMealsPlanModal').modal('toggle'); $.ajax({ url: 'rates/getOptionalMealsAlldata', type: 'get', dataType: 'JSON', success: function(response){ $("#tblMealsPlan tbody tr td").remove(); response.forEach(optmealsplan =>{ $("#tblMealsPlan tbody").append("<tr><td><button onclick=deleteOptMealsPlan(" + optmealsplan.optMealsID + ")><span><i class='fa fa-times' aria-hidden='true'></i></span></button></td><td><button onclick=showOptMealsPlanUpdateModal(" + optmealsplan.optMealsID + ") <span><i class='fa fa-pencil' aria-hidden='true'></i></span></button>" + "</td><td>"+ '---' + "</td><td>"+ optmealsplan.title + "</td><td>"+ optmealsplan.adultRate + "</td><td>"+ optmealsplan.childRate + "</td><td>"+ optmealsplan.startDate + "</td><td>"+ optmealsplan.endDate + "</td><td>"+ '#' +"</td></tr>"); }) } }) } } }); //Optional service tab --- meals Plan portion end.... //Optional service tab --- tranfer sercie portion start.... function clearOptTransferServiceForm(){ $('#opttrans_transferFrom').val(''); $('#opttrans_transferTo').val(''); $('#opttrans_vehicle').val(''); $('#opttrans_maxpax').val(''); $('#opttrans_rate').val(''); $('#opttrans_startDate').val(''); $('#opttrans_endDate').val(''); $('#opttsChecked').prop('checked',true); } function fnValidTransService(){ if($("input[name='opttrans_serviceType']:checked").val() == undefined){ alert('Please checked service type'); return false; }else if($('#opttrans_transferFrom').val() == ''){ alert('Please enter transfer from'); $('#opttrans_transferFrom').focus(); return false; }else if($('#opttrans_transferTo').val() == ''){ alert('Please enter transfer to'); $('#opttrans_transferTo').focus(); return false; }else if($('#opttrans_vehicle').val() == ''){ alert('Please enter vehicle number'); $('#opttrans_vehicle').focus(); return false; }else if($('#opttrans_maxpax').val() == ''){ alert('Please enter maximum pax'); $('#opttrans_maxpax').focus(); return false; }else if($('#opttrans_rate').val() == ''){ alert('Please enter rate'); $('#opttrans_rate').focus(); return false; }else if($('#opttrans_startDate').val() == ''){ alert('Please enter start date'); $('#opttrans_startDate').focus(); return false; }else if($('#opttrans_endDate').val() == ''){ alert('Please enter end date'); $('#opttrans_endDate').focus(); return false; }else{ return true; } } $('#btntransfer').click(function(){ $('#btnSaveOptTransferService').show(); $('#btnUpdateOptTransferService').hide(); $('#cOptionalMealsPlan').html('Add Tranfer Service'); clearOptTransferServiceForm(); $('#addoptionservicetransferserviceModal').modal().on('shown.bs.modal', function (e) {}); }) $('#btnSaveOptTransferService').click(function(){ if(fnValidTransService() == true){ $.ajax({ url: 'rates/saveOptionalTransferService', type: 'POST', data: { _token: CSRF_TOKEN, serviceType: $("input[name='opttrans_serviceType']:checked").val(), transferFrom: $('#opttrans_transferFrom').val(), transferTo: $('#opttrans_transferTo').val(), vehicle: $('#opttrans_vehicle').val(), maximumPax: $('#opttrans_maxpax').val(), rate: $('#opttrans_rate').val(), startDate: $('#opttrans_startDate').val(), endDate: $('#opttrans_endDate').val() }, success: function(response){ if(response>0){ responsed = response; clearOptTransferServiceForm(); }else{ alert('There occurs some internal problem'); window.location.reload(); } } }); if(responsed !=0){ alert('Data Save Successfully.'); $('#addoptionservicetransferserviceModal').modal('toggle'); $.ajax({ url: 'rates/getOptionalTransferServiceAllData', type: 'get', dataType: 'JSON', success: function(response){ $("#tbltransfer tbody tr td").remove(); response.forEach(opttransferserve =>{ $("#tbltransfer tbody").append("<tr><td><button onclick=deleteOptinalTransferService(" + opttransferserve.optionalTransferServiceID + ")><span><i class='fa fa-times' aria-hidden='true'></i></span></button></td><td><button onclick=showOptionalTransferService(" + opttransferserve.optionalTransferServiceID + ") <span><i class='fa fa-pencil' aria-hidden='true'></i></span></button>" + "</td><td>"+ (opttransferserve.serviceType == 1 ? 'Private' : 'Shared') + "</td><td>"+ opttransferserve.transferFrom + "</td><td>"+ opttransferserve.transferTo + "</td><td>"+ opttransferserve.vehicle + "</td><td>"+ opttransferserve.maximumPax + "</td><td>"+ opttransferserve.rate + "</td><td>"+ opttransferserve.startDate + "</td><td>"+ opttransferserve.endDate + "</td><td>"+ '#' +"</td></tr>"); }) } }) } } }) function showOptionalTransferService(id){ $('#btnSaveOptTransferService').hide(); $('#btnUpdateOptTransferService').show(); $('#cOptionalMealsPlan').html('Update Tranfer Service'); $('#addoptionservicetransferserviceModal').modal().on('shown.bs.modal', function (e) {}); $.ajax({ url: 'rates/getOptionalTransferserviceData', type: 'POST', dataType: 'JSON', data: { _token: CSRF_TOKEN, id: id }, success: function(response){ //console.log(response); $('#optionalTransferServiceID').val(response.optionalTransferServiceID); $("input[name=opttrans_serviceType][value='" + response.serviceType +"']").prop('checked', true); $('#opttrans_transferFrom').val(response.transferFrom); $('#opttrans_transferTo').val(response.transferTo); $('#opttrans_vehicle').val(response.vehicle); $('#opttrans_maxpax').val(response.maximumPax); $('#opttrans_rate').val(response.rate); $('#opttrans_startDate').val(response.startDate); $('#opttrans_endDate').val(response.endDate); } }) } $('#btnUpdateOptTransferService').click(function(){ if(fnValidTransService() == true){ $.ajax({ url: 'rates/UpdateOptionalTransferService', type: 'POST', data: { _token: CSRF_TOKEN, id: $('#optionalTransferServiceID').val(), serviceType: $("input[name='opttrans_serviceType']:checked").val(), transferFrom: $('#opttrans_transferFrom').val(), transferTo: $('#opttrans_transferTo').val(), vehicle: $('#opttrans_vehicle').val(), maximumPax: $('#opttrans_maxpax').val(), rate: $('#opttrans_rate').val(), startDate: $('#opttrans_startDate').val(), endDate: $('#opttrans_endDate').val() }, success: function(response){ if(response>0){ responsed = response; clearOptTransferServiceForm(); } } }); if(responsed !=0){ alert('Data Update Successfully.'); $('#addoptionservicetransferserviceModal').modal('toggle'); $.ajax({ url: 'rates/getOptionalTransferServiceAllData', type: 'get', dataType: 'JSON', success: function(response){ $("#tbltransfer tbody tr td").remove(); response.forEach(opttransferserve =>{ $("#tbltransfer tbody").append("<tr><td><button onclick=deleteOptinalTransferService(" + opttransferserve.optionalTransferServiceID + ")><span><i class='fa fa-times' aria-hidden='true'></i></span></button></td><td><button onclick=showOptionalTransferService(" + opttransferserve.optionalTransferServiceID + ") <span><i class='fa fa-pencil' aria-hidden='true'></i></span></button>" + "</td><td>"+ (opttransferserve.serviceType == 1 ? 'Private' : 'Shared') + "</td><td>"+ opttransferserve.transferFrom + "</td><td>"+ opttransferserve.transferTo + "</td><td>"+ opttransferserve.vehicle + "</td><td>"+ opttransferserve.maximumPax + "</td><td>"+ opttransferserve.rate + "</td><td>"+ opttransferserve.startDate + "</td><td>"+ opttransferserve.endDate + "</td><td>"+ '#' +"</td></tr>"); }) } }) } } }) //Optional service tab --- tranfer sercie portion end.... //Optional service tab --- Excursion or Tour portion start... function clearTourServiceForm(){ $('#optour_title').val(''); $('textarea:input[name=optour_details]').val(''); $('#optour_maxpux').val(''); $('#optour_rate').val(''); $('#optour_start').val(''); $('#optour_end').val(''); $('#optour_serviceType1').prop('checked',true); } function fnvalidTourService(){ if($("input[name='optour_serviceType']:checked").val() == undefined){ alert('Please checked service type'); return false; }else if($('#optour_title').val() == ''){ alert('Please enter Title'); $('#optour_title').focus(); return false; }else if($('textarea:input[name=optour_details]').val() == ''){ alert('Please enter transfer to'); $('textarea:input[name=optour_details]').focus(); return false; }else if($('#optour_maxpux').val() == ''){ alert('Please enter maximum pax'); $('#optour_maxpux').focus(); return false; }else if($('#optour_rate').val() == ''){ alert('Please enter rate'); $('#optour_rate').focus(); return false; }else if($('#optour_start').val() == ''){ alert('Please enter start date'); $('#optour_start').focus(); return false; }else if($('#optour_end').val() == ''){ alert('Please enter end date'); $('#optour_end').focus(); return false; }else{ return true; } } $('#btntourservice').click(function(){ $('#btnSaveOptTourService').show(); $('#btnUpdateOptTourrService').hide(); $('#cOptionalMealsPlan').html('Add Excursion/Tour Service'); clearTourServiceForm(); $('#addoptionaltourservice').modal().on('shown.bs.modal', function (e) {}); }) $('#btnSaveOptTourService').click(function(){ if(fnvalidTourService() == true){ //alert('dd'); $.ajax({ url: 'rates/saveTourService', type: 'POST', data: { _token: CSRF_TOKEN, serviceType: $("input[name='optour_serviceType']:checked").val(), title: $('#optour_title').val(), details: $('textarea:input[name=optour_details]').val(), maximumPax: $('#optour_maxpux').val(), rate: $('#optour_rate').val(), startDate: $('#optour_start').val(), endDate: $('#optour_end').val() }, success: function(response){ if(response>0){ responsed = response; clearTourServiceForm(); } } }); if(responsed !=0){ alert('Data save Successfully'); $('#addoptionaltourservice').modal('toggle'); $.ajax({ url: 'rates/getOptionalTourServiceAllData', type: 'get', dataType: 'JSON', success: function(response){ $("#tbltourservice tbody tr td").remove(); response.forEach(opttourserve =>{ $("#tbltourservice tbody").append("<tr><td><button onclick=deleteOptionalTourService(" + opttourserve.optionalTourID + ")><span><i class='fa fa-times' aria-hidden='true'></i></span></button></td><td><button onclick=showOptionalTourService(" + opttourserve.optionalTourID + ") <span><i class='fa fa-pencil' aria-hidden='true'></i></span></button>" + "</td><td>"+ (opttourserve.serviceType == 1 ? 'Private' : 'Shared') + "</td><td>"+ opttourserve.title + "</td><td>"+ opttourserve.details + "</td><td>"+ opttourserve.maximumPax + "</td><td>"+ opttourserve.rate + "</td><td>"+ opttourserve.startDate + "</td><td>"+ opttourserve.endDate + "</td><td>"+ '#' +"</td></tr>"); }) } }) } } }); function showOptionalTourService(id){ $('#btnSaveOptTourService').hide(); $('#btnUpdateOptTourrService').show(); $('#cOptionalMealsPlan').html('Update Excursion/Tour Service'); $('#addoptionaltourservice').modal().on('shown.bs.modal', function (e) {}); $.ajax({ url: 'rates/getOptionalTourServiceData', type: 'POST', dataType: 'JSON', data: { _token: CSRF_TOKEN, id: id }, success: function(response){ //console.log(response); $('#opttourserviceID').val(response.optionalTourID); $("input[name=optour_serviceType][value='" + response.serviceType +"']").prop('checked', true); $('#optour_title').val(response.title); $('textarea:input[name=optour_details]').val(response.details); $('#optour_maxpux').val(response.maximumPax); $('#optour_rate').val(response.rate); $('#optour_start').val(response.startDate); $('#optour_end').val(response.endDate); } }) } $('#btnUpdateOptTourrService').click(function(){ if(fnvalidTourService() == true){ //alert('dd'); $.ajax({ url: 'rates/UpdateTourService', type: 'POST', data: { _token: CSRF_TOKEN, id: $('#opttourserviceID').val(), serviceType: $("input[name='optour_serviceType']:checked").val(), title: $('#optour_title').val(), details: $('textarea:input[name=optour_details]').val(), vehicle: $('#optour_vehicle').val(), maximumPax: $('#optour_maxpux').val(), rate: $('#optour_rate').val(), startDate: $('#optour_start').val(), endDate: $('#optour_end').val() }, success: function(response){ if(response>0){ responsed = response; clearTourServiceForm(); } } }); if(responsed !=0){ alert('Data update Successfully'); $('#addoptionaltourservice').modal('toggle'); $.ajax({ url: 'rates/getOptionalTourServiceAllData', type: 'get', dataType: 'JSON', success: function(response){ $("#tbltourservice tbody tr td").remove(); response.forEach(opttourserve =>{ $("#tbltourservice tbody").append("<tr><td><button onclick=deleteOptionalTourService(" + opttourserve.optionalTourID + ")><span><i class='fa fa-times' aria-hidden='true'></i></span></button></td><td><button onclick=showOptionalTourService(" + opttourserve.optionalTourID + ") <span><i class='fa fa-pencil' aria-hidden='true'></i></span></button>" + "</td><td>"+ (opttourserve.serviceType == 1 ? 'Private' : 'Shared') + "</td><td>"+ opttourserve.title + "</td><td>"+ opttourserve.details + "</td><td>"+ opttourserve.maximumPax + "</td><td>"+ opttourserve.rate + "</td><td>"+ opttourserve.startDate + "</td><td>"+ opttourserve.endDate + "</td><td>"+ '#' +"</td></tr>"); }) } }) } } }); //Optional service tab --- Excursion or Tour portion end... //Optional service tab --- Other service portion start... function clearOtherService(){ $('#opt_tile').val(''); $('textarea:input[name=opt_serType]').val(''); $('#opt_details').val(''); $('#opt_maxpax').val(''); $('#opt_adultrate').val(''); $('#opt_start').val(''); $('#opt_end').val(''); $('#opt_serType1').prop('checked',true); } function fnValidOtherservice(){ if($("input[name='opt_serType']:checked").val() == undefined){ alert('Please checked service type'); return false; }else if($('#opt_tile').val() == ''){ alert('Please enter Title'); $('#opt_tile').focus(); return false; }else if($('textarea:input[name=opt_details]').val() == ''){ alert('Please enter transfer to'); $('textarea:input[name=opt_details]').focus(); return false; }else if($('#opt_maxpax').val() == ''){ alert('Please enter maximum pax'); $('#opt_maxpax').focus(); return false; }else if($('#opt_adultrate').val() == ''){ alert('Please enter rate'); $('#opt_adultrate').focus(); return false; }else if($('#opt_start').val() == ''){ alert('Please enter start date'); $('#opt_start').focus(); return false; }else if($('#opt_end').val() == ''){ alert('Please enter end date'); $('#opt_end').focus(); return false; }else{ return true; } } $('#btnAddotherService').click(function(){ $('#btnsaveOtherservice').show(); $('#btnUpdateOtherservice').hide(); $('#cOptionalMealsPlan').html('Add Other Service'); clearOtherService(); $('#addoptionalotherservice').modal().on('shown.bs.modal', function (e) {}); }) $('#btnsaveOtherservice').click(function(){ if(fnValidOtherservice() == true){ $.ajax({ url: 'rates/saveOtherservice', type: 'POST', data: { _token: CSRF_TOKEN, serviceType: $("input[name='opt_serType']:checked").val(), title: $('#opt_tile').val(), details: $('textarea:input[name=opt_details]').val(), maximumPax: $('#opt_maxpax').val(), adultRate: $('#opt_adultrate').val(), startDate: $('#opt_start').val(), endDate: $('#opt_end').val() }, success: function(response){ if(response>0){ responsed = response; clearOtherService(); } } }); if(responsed !=0){ alert('Data save Successfully'); $('#addoptionalotherservice').modal('toggle'); $.ajax({ url: 'rates/getOptionalOtherServiceAllData', type: 'get', dataType: 'JSON', success: function(response){ $("#tblotherservice tbody tr td").remove(); response.forEach(otherservice =>{ $("#tblotherservice tbody").append("<tr><td><button onclick=deleteotherservice(" + otherservice.optionalOtherServiceID + ")><span><i class='fa fa-times' aria-hidden='true'></i></span></button></td><td><button onclick=showotherserviceforUpdate(" + otherservice.optionalOtherServiceID + ") <span><i class='fa fa-pencil' aria-hidden='true'></i></span></button>" + "</td><td>"+ (otherservice.serviceType == 1 ? 'Private' : 'Shared') + "</td><td>"+ otherservice.title + "</td><td>"+ otherservice.details + "</td><td>"+ otherservice.maximumPax + "</td><td>"+ otherservice.adultRate + "</td><td>"+ otherservice.startDate + "</td><td>"+ otherservice.endDate + "</td><td>"+ '#' +"</td></tr>"); }) } }) } } }); function showotherserviceforUpdate(id){ $('#btnsaveOtherservice').hide(); $('#btnUpdateOtherservice').show(); $('#cOptionalMealsPlan').html('Update Other Service'); $('#addoptionalotherservice').modal().on('shown.bs.modal', function (e) {}); $.ajax({ url: 'rates/getOptionalotherServiceData', type: 'POST', dataType: 'JSON', data: { _token: CSRF_TOKEN, id: id }, success: function(response){ console.log(response); $('#optotherserviceID').val(response.optionalOtherServiceID); $("input[name=opt_serType][value='" + response.serviceType +"']").prop('checked', true); $('#opt_tile').val(response.title); $('textarea:input[name=opt_details]').val(response.details); $('#opt_maxpax').val(response.maximumPax); $('#opt_adultrate').val(response.adultRate); $('#opt_start').val(response.startDate); $('#opt_end').val(response.endDate); } }) } $('#btnUpdateOtherservice').click(function(){ if(fnValidOtherservice() == true){ $.ajax({ url: 'rates/updateOtherservice', type: 'POST', data: { _token: CSRF_TOKEN, id: $('#optotherserviceID').val(), serviceType: $("input[name='opt_serType']:checked").val(), title: $('#opt_tile').val(), details: $('textarea:input[name=opt_details]').val(), maximumPax: $('#opt_maxpax').val(), adultRate: $('#opt_adultrate').val(), startDate: $('#opt_start').val(), endDate: $('#opt_end').val() }, success: function(response){ if(response>0){ responsed = response; clearOtherService(); } } }); if(responsed !=0){ alert('Data update Successfully'); $('#addoptionalotherservice').modal('toggle'); $.ajax({ url: 'rates/getOptionalOtherServiceAllData', type: 'get', dataType: 'JSON', success: function(response){ $("#tblotherservice tbody tr td").remove(); response.forEach(otherservice =>{ $("#tblotherservice tbody").append("<tr><td><button onclick=deleteotherservice(" + otherservice.optionalOtherServiceID + ")><span><i class='fa fa-times' aria-hidden='true'></i></span></button></td><td><button onclick=showotherserviceforUpdate(" + otherservice.optionalOtherServiceID + ") <span><i class='fa fa-pencil' aria-hidden='true'></i></span></button>" + "</td><td>"+ (otherservice.serviceType == 1 ? 'Private' : 'Shared') + "</td><td>"+ otherservice.title + "</td><td>"+ otherservice.details + "</td><td>"+ otherservice.maximumPax + "</td><td>"+ otherservice.adultRate + "</td><td>"+ otherservice.startDate + "</td><td>"+ otherservice.endDate + "</td><td>"+ '#' +"</td></tr>"); }) } }) } } })
var i18n = angular.module('app.moya') //Confuring the locale file identirier. i18n.config(function ($translateProvider) { $translateProvider.useStaticFilesLoader({ prefix: 'app/resources/locale.',// path to translations files suffix: '.json'// suffix, currently- extension of the translations }); $translateProvider.useMissingTranslationHandlerLog(); $translateProvider.preferredLanguage('en_US');// is applied on first load });
/* * @name 使用通用介面處理 Discord 訊息 */ const MessageHandler = require( './MessageHandler.js' ); const Context = require( './Context.js' ); const discord = require( 'discord.js' ); const { getFriendlySize } = require( '../util.js' ); class DiscordMessageHandler extends MessageHandler { constructor( config = {} ) { super(); let botConfig = config.bot || {}; let discordOptions = config.options || {}; const client = require( '../../../util/bots.js' ).dcBot; this._type = 'Discord'; this._id = 'D'; this._token = botConfig.token; this._client = client; this._nickStyle = discordOptions.nickStyle || 'username'; this._keepSilence = discordOptions.keepSilence || []; this._useProxyURL = discordOptions.useProxyURL; this._relayEmoji = discordOptions.relayEmoji; const processMessage = async ( rawdata ) => { if ( !this._enabled || rawdata.author.id === client.user.id ) { return; } let text = rawdata.content; let extra = {}; if ( rawdata.attachments && rawdata.attachments.size ) { extra.files = []; for ( let [ , p ] of rawdata.attachments ) { extra.files.push( { client: 'Discord', type: 'photo', id: p.id, size: p.size, url: this._useProxyURL ? p.proxyURL : p.url } ); text += ` <photo: ${ p.width }x${ p.height }, ${ getFriendlySize( p.size ) }>`; } } if ( rawdata.reference && rawdata.reference.messageID ) { if ( rawdata.channel.id === rawdata.reference.channelID ) { let msg = await rawdata.channel.messages.fetch( rawdata.reference.messageID ); let reply = { nick: this.getNick( msg.member || msg.author ), username: msg.author.username, discriminator: msg.author.discriminator, message: this._convertToText( msg ), isText: msg.content && true, _rawdata: msg }; extra.reply = reply; } } let context = new Context( { from: rawdata.author.id, to: rawdata.channel.id, nick: this.getNick( rawdata.member || rawdata.author ), text: text, isPrivate: rawdata.channel.type === 'dm', extra: extra, handler: this, _rawdata: rawdata } ); // 檢查是不是命令 for ( let [ cmd, callback ] of this._commands ) { if ( rawdata.content.startsWith( cmd ) ) { let param = rawdata.content.trim().substring( cmd.length ); if ( param === '' || param.startsWith( ' ' ) ) { param = param.trim(); context.command = cmd; context.param = param; if ( typeof callback === 'function' ) { callback( context, cmd, param ); } this.emit( 'command', context, cmd, param ); this.emit( `command#${ cmd }`, context, param ); } } } this.emit( 'text', context ); }; client.on( 'message', processMessage ); client.on( 'ready', ( message ) => { this.emit( 'ready', message ); } ); } async say( target, message, options = {} ) { if ( !this._enabled ) { throw new Error( 'Handler not enabled' ); } else if ( this._keepSilence.indexOf( target ) !== -1 ) { return; } else { let channel = await this._client.channels.fetch( target ); return await channel.send( message ); } } async reply( context, message, options = {} ) { if ( context.isPrivate ) { return await this.say( context.from, message, options ); } else { if ( options.noPrefix ) { return await this.say( context.to, `${ message }`, options ); } else { return await this.say( context.to, `${ context.nick }: ${ message }`, options ); } } } getNick( userobj ) { if ( userobj ) { if ( userobj instanceof discord.GuildMember ) { var { nickname, id, user } = userobj; var { username } = user; } else { var { username, id } = userobj; var nickname = null; } if ( this._nickStyle === 'nickname' ) { return nickname || username || id; } else if ( this._nickStyle === 'username' ) { return username || id; } else { return id; } } else { return ''; } } async fetchUser( user ) { return await this._client.users.fetch( user ); } fetchEmoji( emoji ) { return this._client.emojis.resolve( emoji ); } _convertToText( message ) { if ( message.content ) { return message.content; } else if ( message.attachments ) { return '<Photo>'; // } else if (message.pinned_message) { // return '<Pinned Message>'; // } else if (message.new_chat_member) { // return '<New member>'; // } else if (message.left_chat_member) { // return '<Removed member>'; } else { return '<Message>'; } } async start() { if ( !this._started ) { this._started = true; } } async stop() { if ( this._started ) { this._started = false; this._client.destroy(); } } } module.exports = DiscordMessageHandler;
const { successResponse,errorResponse } = require('../helper/index'); const { Moment } = require('../models/moments'); const { User } = require('../models/users'); var mongoose = require('mongoose'); const { createImage ,deleteImage } = require('../helper/globalFunctions') const fs = require('fs'); //ADD CENTER module.exports.newMoment = async(req,res)=>{ let savedMoment = {} let user = null if (mongoose.Types.ObjectId.isValid(req.body.user)) { user = await User.findById(req.body.user) if (!user) { errorResponse(req, res, "User does not exist", 204) return; } } else { errorResponse(req, res, "Invalid User Id", 204) return; } if(!user){ errorResponse(req, res, "User does not exist", 204) return; } try { let image_name=await createImage(req.body.image,req.body.title.replace(" ","")+Date.now()) const moment = new Moment({ image: image_name, title: req.body.title, tags: req.body.tags, user: req.body.user, comment:req.body.comment }) savedMoment = await moment.save() } catch (error) { errorResponse(req, res, error, 204) } successResponse(req,res,savedMoment); }; module.exports.getAll = async (req, res) => { if (mongoose.Types.ObjectId.isValid(req.query.user)){ const momentList=await Moment.find({ user:req.query.user }) successResponse(req,res,momentList); } else{ errorResponse(req, res, "Invalid User Id", 204) return; } } module.exports.getOne = async (req, res) => { console.log(req.query.id) if (mongoose.Types.ObjectId.isValid(req.query.id)){ const moment=await Moment.findOne({_id:req.query.id}) successResponse(req,res,moment); } else{ errorResponse(req, res, "Invalid User Id", 204) return; } } function isBase64(str) { if (str ==='' || str.trim() ===''){ return false; } try { return btoa(atob(str)) == str; } catch (err) { return false; } } module.exports.update = async (req, res) => { if (mongoose.Types.ObjectId.isValid(req.query.id)){ const moment=await Moment.findOne({ _id:req.query.id }) if(!moment){ errorResponse(req, res, "Invalid Moment Id", 204) return; } if(req.body.newImage!="" && req.body.newImage!=undefined){ let image_name=await createImage(req.body.newImage,req.body.title.replace(" ","")+Date.now()) moment.image=image_name } moment.tags=req.body.tags; moment.title=req.body.title; moment.comment=req.body.comment; moment.save() successResponse(req,res,moment); } else{ errorResponse(req, res, "Invalid Moment Id", 204) return; } } module.exports.deleteImage= async (req, res) => { if (mongoose.Types.ObjectId.isValid(req.body.id)){ const moment=await Moment.findOne({ _id:req.body.id }) if(!moment){ errorResponse(req, res, "Invalid Moment Id", 204) return; } if(moment.image==req.query.name){ deleteImage(req.query.name) moment.image=undefined; moment.save() successResponse(req,res,moment); } else{ errorResponse(req, res, "Delete unsuccessful", 204) return; } } } module.exports.delete = async (req, res) => { if (mongoose.Types.ObjectId.isValid(req.query.id)) { const moment = await Moment.deleteOne({ _id: req.query.id }) if (!moment) { errorResponse(req, res, "Invalid Moment Id", 204) return; } else { successResponse(req, res, moment); } } else { errorResponse(req, res, "Invalid Moment Id", 204) return; } }
--- --- (function ($, document, undefined) { "use strict"; var mobileMenuButton = $("#mobile-menu-button"), responsiveDemonstration = $("#responsive-demonstration"), updateability = $("#updateability"), seeMoreLink = $("#see-more"); /*-----------See More Link------------*/ function seeMoreInit(){ seeMoreLink.kason_display(); } /*-----------Mobile Menu------------*/ function mobileMenuInit(){ mobileMenuButton.kason_display(); } /*-----------End Mobile Menu--------*/ function homeResponsiveDemonstrationInit(){ if (responsiveDemonstration.length > 0){ responsiveDemonstration.find('.device').eq(0).addClass('is-current'); setInterval(setNextResponsive,2000); } } function updateabilityInit(){ if (updateability.length > 0){ var devices = updateability.find('.updateable-device'); devices.each(setUpdateableDevices); setInterval(updateUpdateability,3000); } } function setUpdateableDevices(){ $(this).find('.updateable-content').clone().appendTo(this).clone().appendTo(this).clone().appendTo(this).clone().appendTo(this); } function updateUpdateability(){ var current = updateability.find('.is-current'), $currentImgs = current.find('.updateable-content'); $currentImgs.eq(1).addClass('mobile'); $currentImgs.eq(2).addClass('tablet'); $currentImgs.eq(3).addClass('laptop'); $currentImgs.eq(4).addClass('desktop'); setTimeout(setNextUpdate, 2500); } function setNextUpdate(){ var current = updateability.find('.is-current'), nextActive = current.next(); if(nextActive.length == 0){ nextActive = updateability.find('.updateable-device').eq(0); } current.removeClass('is-current').find('.updateable-content').removeClass('mobile tablet laptop desktop'); nextActive.addClass('is-current'); } function setNextResponsive(){ var current = responsiveDemonstration.find('.is-current'), nextActive = current.next(), movableScreen = $('#movable-screen'); if(nextActive.length == 0){ nextActive = responsiveDemonstration.find('.device').eq(0); } var movableScreenClassRemove = current.attr('class').replace('device','').replace('is-current',''), movableScreenClassAdd = nextActive.attr('class').replace('device',''); current.removeClass('is-current'); nextActive.addClass('is-current'); movableScreen.addClass(movableScreenClassAdd).removeClass(movableScreenClassRemove); } function contactInit(){ var $form = $('#contact-form'), $thankyou = $('#contact-form #thankyou'), // tk = "d08ba1883e084b39a46121546accac87", formGA = function(label){ ga('send', { hitType: 'event', eventCategory: 'Form', eventAction: 'click', eventLabel: label }); }, submitFunc = function(e){ var data = $form.serializeArray(); if(e.type === 'valid' && data[0].value === ''){ $.ajax({ type: 'POST', // dataType: 'jsonp', // url: "https://kason-api.herokuapp.com/message", url: "{{ site.message_url }}", data: $form.serialize() }).done(doneFunc); formGA('Success'); } e.preventDefault(); }, doneFunc = function(e){ $form.find("input, select, textarea, button").prop("disabled",true); $form.addClass('submitted'); }; $form.on('valid submit',submitFunc); } function init() { mobileMenuInit(); homeResponsiveDemonstrationInit(); // updateabilityInit(); contactInit(); seeMoreInit(); console.log("You should probably just email me at kason@kason.es already :p"); } init(); })(Foundation.zj, document);
import React from 'react'; import ReactDOM from 'react-dom'; import { BrowserRouter as Router, Route, Redirect, Switch } from 'react-router-dom'; import Header from 'components/header'; import SideNavBar from './side-nav-bar'; import Profile from './profile'; import Account from './account'; import AddReview from './add-review'; import NoMatch from './no-match'; if (module.hot) { module.hot.accept(); } const App = () => ( <Router> <div> <Header /> <div className="container pt-5 pb-5"> <div className="row"> <SideNavBar /> <Switch> <Route exact path="/home/profile" component={Profile} /> <Route exact path="/home/account" component={Account} /> <Route exact path="/home/add-review" component={AddReview} /> <Route component={NoMatch} /> </Switch> </div> </div> </div> </Router> ); const Name = ({ match }) => ( <div className="col-sm-9"> <p>{match.params.page}</p> </div> ); // App.propTypes = {}; ReactDOM.render(<App />, document.getElementById('root'));
// ==UserScript== // @name LinkReplacer // @namespace null // @description Replace link with image for freedl.org // @version 1.0.7 // @updateURL https://raw.github.com/perhapz/userscript/master/LinkReplacer.user.js // @include http://www.freedl.org/* // @include http://www.alabout.com/* // @include http://alabout.com/* // @grant GM_xmlhttpRequest // ==/UserScript== var box = document.createElement('input'); box.type = "checkbox"; box.addEventListener('click', preLoad, false); document.body.insertBefore(box, document.body.firstChild); var link = document.getElementsByTagName('a'); var pattLink = /http:\/\/(www\.)?(alabout|alafs)\.com\/j\.phtml\?url=/; pattLink.compile(pattLink); var pattSite = /mrjh\.org|pics\.dmm\.co\.jp|imgchili\.com|imgdino\.com|imageporter\.com|imagecarry\.com|imagedunk\.com|picleet\.com|picturedip\.com|piclambo\.net|yankoimages\.net|imagetwist\.com|imagehyper\.com/i; pattSite.compile(pattSite); for (var i = 0, len = link.length; i < len; i++) { if (pattLink.test(link[i].href)) { link[i].href = link[i].textContent; } var site = pattSite.exec(link[i].href); if (site) { switch (site[0]) { case 'mrjh.org': link[i].href = link[i].href.replace('gallery.php?entry=', ''); fixLink(link[i]); break; case 'pics.dmm.co.jp': fixLink(link[i]); break; case 'imgchili.com': case 'imgdino.com': case 'imageporter.com': case 'imagecarry.com': case 'imagedunk.com': case 'picleet.com': case 'picturedip.com': case 'piclambo.net': case 'imagetwist.com': case 'imagehyper.com': case 'yankoimages.net': link[i].name = 'plink'; link[i].addEventListener('mouseover', requestPic, false); break; } } } function fixLink(a) { a.name = 'plink'; a.addEventListener('mouseover', loadPic, false); } function loadPic() { var link = this; link.removeEventListener('mouseover', loadPic, false); var img = document.createElement('img'); img.src = link.href; link.removeChild(link.firstChild); link.appendChild(img); } function requestPic() { var link = this; link.removeEventListener('mouseover', requestPic, false); GM_xmlhttpRequest({ method: "GET", url: link.href, onload: function (response) { var src = response.responseText.match(/http:\/\/(img\d\d|i\d\.imgchili|img\d\.imgdino|img\d\.imagehyper\.com\/img)[^"\s]+/); var img = document.createElement('img'); if (src) { img.src = src[0]; link.href = img.src; link.removeChild(link.firstChild); link.appendChild(img); } else { link.addEventListener('mouseover', requestPic, false); } }, onerror: function () { link.addEventListener('mouseover', requestPic, false); } }); } function preLoad() { var block = document.getElementsByTagName('blockquote'); var evt = document.createEvent('MouseEvents'); evt.initEvent('mouseover', true, false); for (var i =0; i < block.length; i++) { var plink = block[i].querySelectorAll('a[name="plink"]'); if (plink[0]) { plink[0].dispatchEvent(evt); } for (var j = 1; j < plink.length; j++) { if (plink[j].previousSibling.previousSibling.name !== 'plink' && (!plink[j].nextSibling || plink[j].nextSibling.nextSibling.name !== 'plink')) { plink[j].dispatchEvent(evt); } } } }
var pageSize = 25; var boolPassword = true;//secretcopy var info_type = "trial_share"; var secret_info = ""; //alert(document.getElementById('eventId').value); /******************促銷試用活動管理主頁面****************************/ //促銷試用活動管理Model Ext.define('gigade.ShareRecordModel', { extend: 'Ext.data.Model', fields: [ { name: "share_id", type: "int" }, { name: "trial_id", type: "int" }, { name: "user_id", type: "int" }, { name: "is_show_name", type: "int" }, { name: "user_name", type: "string" }, { name: "user_gender", type: "int" }, { name: "content", type: "string" }, { name: "share_time", type: "string" }, { name: "status", type: "int" }, { name: "s_share_time", type: "string" }, { name: "event_name", type: "string" }, { name: "real_name", type: "string" }, { name: "gender", type: "string" }, { name: "after_name", type: "string" }, ] }); secret_info = "user_name;"; var ShareRecordStore = Ext.create('Ext.data.Store', { model: 'gigade.ShareRecordModel', proxy: { type: 'ajax', url: '/PromotionsAmountTrial/GetShareRecordList', reader: { type: 'json', root: 'data', totalProperty: 'totalCount' } } }); //前面選擇框 選擇之後顯示編輯刪除 var sm = Ext.create('Ext.selection.CheckboxModel', { listeners: { selectionchange: function (sm, selections) { // Ext.getCmp("shareRecord").down('#add').setDisabled(selections.length == 0); Ext.getCmp("shareRecord").down('#edit').setDisabled(selections.length == 0); } } }); ShareRecordStore.on('beforeload', function () { Ext.apply(ShareRecordStore.proxy.extraParams, { trial_id: document.getElementById("trial_id").value, relation_id: "", isSecret: true }); }); var edit_ShareRecordStore = Ext.create('Ext.data.Store', { model: 'gigade.ShareRecordModel', proxy: { type: 'ajax', url: '/PromotionsAmountTrial/GetShareRecordList', reader: { type: 'json', root: 'data', totalProperty: 'totalCount' } } }); edit_ShareRecordStore.on('beforeload', function () { Ext.apply(edit_ShareRecordStore.proxy.extraParams, { trial_id: document.getElementById("trial_id").value, relation_id: "", isSecret: false }); }); //頁面載入 Ext.onReady(function () { var shareRecord = Ext.create('Ext.grid.Panel', { id: 'shareRecord', store: ShareRecordStore, width: document.documentElement.clientWidth, columnLines: true, frame: true, columns: [ { header: "編號", dataIndex: 'share_id', width: 60, align: 'center' }, { header: "活動編號", dataIndex: 'trial_id', width: 100, align: 'center' }, { header: USERNAME, dataIndex: 'user_name', width: 80, align: 'center', renderer: function (value, cellmeta, record, rowIndex, columnIndex, store) {//secretcopy return "<span onclick='SecretLogin(" + record.data.share_id + "," + record.data.user_id + ",\"" + info_type + "\")' >" + value + "</span>"; } }, { header: SHARECONTENT, dataIndex: 'content', width: 180, align: 'center' }, { header: SHARETIME, dataIndex: 'share_time', width: 150, align: 'center' }, { header: "狀態", dataIndex: 'status', width: 150, align: 'center', renderer: function (value) { if (value == 0) { return "新建立"; } else if (value == 1) { return "顯示"; } else if (value == 2) { return "隱藏"; } else if (value == 3) { return "下檔"; } } }, ], tbar: [ { xtype: 'button', text: EDIT, id: 'edit', hidden: false, iconCls: 'icon-user-edit', disabled: true, handler: onEditClick } ], bbar: Ext.create('Ext.PagingToolbar', { store: ShareRecordStore, pageSize: pageSize, displayInfo: true, displayMsg: NOW_DISPLAY_RECORD + ': {0} - {1}' + TOTAL + ': {2}', emptyMsg: NOTHING_DISPLAY }), listeners: { scrollershow: function (scroller) { if (scroller && scroller.scrollEl) { scroller.clearManagedListeners(); scroller.mon(scroller.scrollEl, 'scroll', scroller.onElScroll, scroller); } } }, selModel: sm }); Ext.create('Ext.container.Viewport', { layout: 'fit', items: [shareRecord], renderTo: Ext.getBody(), autoScroll: true, listeners: { resize: function () { shareRecord.width = document.documentElement.clientWidth; this.doLayout(); } } }); //ToolAuthority(); QueryToolAuthorityByUrl('/PromotionsAmountTrial/ShareRecord'); ShareRecordStore.load({ params: { start: 0, limit: 25 } }); }); function SecretLogin(rid, info_id, info_type) {//secretcopy var secret_type = "5";//參數表中的"試用試吃活動" var url = "/PromotionsAmountTrial/ShareRecord"; var ralated_id = rid; //點擊機敏信息先保存記錄在驗證密碼是否需要輸入 boolPassword = SaveSecretLog(url, secret_type, ralated_id);//判斷5分鐘之內是否有輸入密碼 if (boolPassword != "-1") {//不准查看 if (boolPassword) {//超過5分鐘沒有輸入密碼 //參數1:機敏頁面代碼,2:機敏資料主鍵,3:是否彈出驗證密碼框,4:是否直接顯示機敏信息6.驗證通過后是否打開編輯窗口 7:客戶信息類型user:會員 order:訂單 vendor:供應商 8:客戶id9:要顯示的客戶信息 // function SecretLoginFun(type, relatedID, isLogin, isShow, editO, isEdit) { SecretLoginFun(secret_type, ralated_id, true, true, false, url, info_type, info_id, secret_info);//先彈出驗證框,關閉時在彈出顯示框 } else { SecretLoginFun(secret_type, ralated_id, false, true, false, url, info_type, info_id, secret_info);//先彈出驗證框,關閉時在彈出顯示框 } } } //修改 onEditClick = function () { var row = Ext.getCmp("shareRecord").getSelectionModel().getSelection(); if (row.length == 0) { Ext.Msg.alert(INFORMATION, NO_SELECTION); } else if (row.length > 1) { Ext.Msg.alert(INFORMATION, ONE_SELECTION); } else if (row.length == 1) { var secret_type = "5";//參數表中的"會員查詢列表" var url = "/PromotionsAmountTrial/ShareRecord/Edit "; var ralated_id = row[0].data.share_id; var info_id = row[0].data.user_id; boolPassword = SaveSecretLog(url, secret_type, ralated_id);//判斷5分鐘之內是否有輸入密碼 if (boolPassword != "-1") { if (boolPassword) {//驗證 SecretLoginFun(secret_type, ralated_id, true, false, true, url, info_type, info_id, secret_info);//先彈出驗證框,關閉時在彈出顯示框 } else { editFunction(ralated_id); } } //editFunction(row[0], ShareRecordStore); } }
import React, { createContext, useState } from 'react'; const AppContext = createContext() function AppContextProvider({ children }) { const [isLoading, setIsLoading] = useState(false); const [isError, setIsError] = useState(false); const value = { isLoading, isError, setIsLoading, setIsError } return ( <> <AppContext.Provider value={value}> {children} </AppContext.Provider> </> ) } export { AppContextProvider, AppContext }
//auth 'use strict'; var app = angular.module('esc.auth', []); app.factory('authInterceptor', function ($rootScope, $q, $window) { return { request: function (config) { config.headers = config.headers || {}; if ($window.sessionStorage.token) { config.headers['Authorization'] = $window.sessionStorage.token; } return config; }, responseError: function (response) { console.log(response.status); if (response.status === 401) { // handle the case where the user is not authenticated } if (response.status === 403) { var pathname = $window.location.pathname.substr($window.location.pathname.indexOf("/")+1).split(/\//)[0]; if(pathname == 'admin'){ window.location = '/admin/login'; } else window.location = '/agent/login'; } return response || $q.when(response); } }; }) .config(function ($httpProvider) { $httpProvider.defaults.headers.post['XSRF-AUTH'] = "some accessToken to be generated later"; $httpProvider.interceptors.push('authInterceptor'); });
//all input functions class Input{ constructor(){ document.onkeydown = this.handleKeyDown; document.onkeyup = this.handleKeyUp; } //dictionary for pressed keys handleKeyDown(event) { currentlyPressedKey[event.keyCode] = true; } handleKeyUp(event) { currentlyPressedKey[event.keyCode] = false; } handleInput(){ this.handleKeys(); this.handleMouse(); } handleKeys() { if(currentlyPressedKey[81]){ //Q yRot -= 1; } if(currentlyPressedKey[69]){ //E yRot += 1; } if(currentlyPressedKey[87]){ //W xRot -= 1; } if(currentlyPressedKey[83]){ //S xRot += 1; } if(currentlyPressedKey[65]){ //A zRot -= 1; } if(currentlyPressedKey[68]){ //D zRot += 1; } if(currentlyPressedKey[82]){ //R z -= 0.5; } if(currentlyPressedKey[70]){ //F z += 0.5; } } handleMouse() { canvas.onmouseup = function (ev) { //clientX and clientY calculate from top left of browser let x, y, top = 0, left = 0, obj = canvas, ob = null; while(obj && obj.tagName !== 'Body'){ top += obj.offsetTop; left += obj.offsetLeft; obj = obj.offsetParent; } //remove scrolling left -= window.pageXOffset; top -= window.pageYOffset; //calculate canvas coordinates x = ev.clientX - left; y = c_height - (ev.clientY - top); //read one pixel with RGBA let readout = new Uint8Array(readPixelsSize * readPixelsSize * 4); gl.bindFramebuffer(gl.FRAMEBUFFER, picker.pickerFrameBuffer); gl.readPixels(x - (brushSize/2), y - (brushSize/2), readPixelsSize, readPixelsSize, gl.RGBA, gl.UNSIGNED_BYTE, readout); gl.bindFramebuffer(gl.FRAMEBUFFER, null); readout = utils.filterUnique(readout); //left mouse button if(ev.which == 1){ for(let i = 0; i < cubes.length; i++){ ob = cubes[i]; if(picker.compare(readout, ob.cPicker)){ utils.handlePickedObject(ob, 1); } } } //right mouse button else if(ev.which == 3){ for(let i = 0; i < cubes.length; i++){ ob = cubes[i]; if(picker.compare(readout, ob.cPicker)){ utils.handlePickedObject(ob, 3); } } } } } }
require("dotenv").config(); let [ node, liri, command, ...input] = process.argv let fs = require("fs") let keys = require("./keys.js") let request = require("request") let Twitter = require('twitter'); if (command === 'movie-this') { request("https://www.omdbapi.com/?t=" + input + "&y=&plot=short&apikey=trilogy", function (error, response, body) { console.log('Title: ', JSON.parse(body).Title); console.log('Year: ', JSON.parse(body).Year); console.log('IMDB Rating: ', JSON.parse(body).imdbRating); console.log('Produced in: ', JSON.parse(body).Country); console.log('Rotten Tomatoes Rating: ', JSON.parse(body).Ratings[1].Value) console.log('Language: ', JSON.parse(body).Language) console.log('Plot: ', JSON.parse(body).Plot) console.log('Actors: ', JSON.parse(body).Actors) }); } if (command === 'my-tweets') { let client = new Twitter({ consumer_key: process.env.TWITTER_CONSUMER_KEY, consumer_secret: process.env.TWITTER_CONSUMER_SECRET, access_token_key: process.env.TWITTER_ACCESS_TOKEN_KEY, access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET }); let params = {screen_name: 's3vi26'}; client.get('statuses/user_timeline', params, function(error, tweets, response) { if (!error) { console.log(tweets[0].created_at, tweets[0].text) console.log(tweets[1].created_at, tweets[1].text) console.log(tweets[2].created_at, tweets[2].text) console.log(tweets[3].created_at, tweets[3].text) console.log(tweets[4].created_at, tweets[4].text) console.log(tweets[5].created_at, tweets[5].text) console.log(tweets[6].created_at, tweets[6].text) console.log(tweets[7].created_at, tweets[7].text) console.log(tweets[8].created_at, tweets[8].text) console.log(tweets[9].created_at, tweets[9].text) console.log(tweets[10].created_at, tweets[10].text) console.log(tweets[11].created_at, tweets[11].text) console.log(tweets[12].created_at, tweets[12].text) console.log(tweets[13].created_at, tweets[13].text) console.log(tweets[14].created_at, tweets[14].text) console.log(tweets[15].created_at, tweets[15].text) console.log(tweets[16].created_at, tweets[16].text) console.log(tweets[17].created_at, tweets[17].text) console.log(tweets[18].created_at, tweets[18].text) console.log(tweets[19].created_at, tweets[19].text) } }); }
var productData = [{"name":"1","url":"1.jpg","color":"Yellow","brand":"BRAND A","sold_out":"1"}, {"name":"2","url":"2.jpg","color":"Red","brand":"BRAND B","sold_out":"0"}, {"name":"3","url":"3.jpg","color":"Green","brand":"BRAND D","sold_out":"0"}, {"name":"4","url":"4.jpg","color":"Red","brand":"BRAND A","sold_out":"1"}, {"name":"5","url":"5.jpg","color":"Blue","brand":"BRAND B","sold_out":"0"}, {"name":"6","url":"6.jpg","color":"Green","brand":"BRAND C","sold_out":"0"}, {"name":"7","url":"7.jpg","color":"Red","brand":"BRAND C","sold_out":"1"}, {"name":"8","url":"8.jpg","color":"Blue","brand":"BRAND D","sold_out":"0"}, {"name":"9","url":"9.jpg","color":"Yellow","brand":"BRAND A","sold_out":"0"}, {"name":"10","url":"10.jpg","color":"Yellow","brand":"BRAND B","sold_out":"1"}, {"name":"11","url":"11.jpg","color":"Green","brand":"BRAND D","sold_out":"0"}, {"name":"12","url":"12.jpg","color":"Yellow","brand":"BRAND D","sold_out":"0"}, {"name":"13","url":"13.jpg","color":"Blue","brand":"BRAND A","sold_out":"0"}, {"name":"14","url":"14.jpg","color":"Blue","brand":"BRAND D","sold_out":"0"}, {"name":"15","url":"15.jpg","color":"Green","brand":"BRAND B","sold_out":"0"}, {"name":"16","url":"16.jpg","color":"Yellow","brand":"BRAND B","sold_out":"1"}, {"name":"17","url":"17.jpg","color":"Green","brand":"BRAND A","sold_out":"1"}, {"name":"18","url":"18.jpg","color":"Blue","brand":"BRAND D","sold_out":"1"}, {"name":"19","url":"19.jpg","color":"Green","brand":"BRAND C","sold_out":"0"}, {"name":"20","url":"20.jpg","color":"Yellow","brand":"BRAND A","sold_out":"0"} ]; window.addEventListener("load", initialize()); function initialize() { var listOption = new selectList("selectlist"); listOption.makeGrid(productData); } function selectList(id) { var that = this; this.list = document.getElementById(id); this.body = document.getElementById("body"); this.makeGrid = function(products) { this.grid = this.createGridBlock(); var count = 0, rows = 5, cols = 4; for (var i = 0; i < rows; i++) { var columnContainer = this.createColumnContainer(); for (var j = 0; j < cols; j++) { var productContainer = this.createProductContainer(columnContainer); var productImage = this.createImage(productContainer, count, products); count++; } } this.body.appendChild(this.grid); this.list.addEventListener("change", this.sortProducts.bind(that)); } this.createGridBlock = function() { var grid = document.createElement("div"); grid.id = "mygrid"; return grid; } this.createColumnContainer = function() { var columnContainer = document.createElement("div"); columnContainer.className = "columnContainer"; this.grid.appendChild(columnContainer); return columnContainer; } this.createProductContainer = function(columnContainer) { var productContainer = document.createElement("div"); productContainer.className = "productContainer"; columnContainer.appendChild(productContainer); return productContainer; } this.createImage = function(productContainer, count, products) { var productImage = document.createElement("img"); productImage.src = products[count].url; productImage.className = "productImage"; productContainer.appendChild(productImage); } this.sortProducts = function() { var index = this.list.selectedIndex; var selectedOption = this.list.options[index]; var selectedValue = selectedOption.value; var myProducts = productData; myProducts.sort(compare); function compare(val1, val2) { if (selectedOption.value == "name") { var value1 = parseInt(val1[selectedValue], 10), value2 = parseInt(val2[selectedValue], 10); } else { var value1 = val1[selectedValue], value2 = val2[selectedValue]; } if (value1 < value2) { return -1; } else if (value1 > value2) { return 1; } else { return 0; } } this.makeNewGrid(myProducts); } this.makeNewGrid = function(myProducts) { this.body.removeChild(this.grid); this.makeGrid(myProducts); } }
/** * Controller */ angular.module('ngApp.public').controller('AgentAnticipatedShipmentController', function ($scope, $translate, $state, $stateParams, $location, config, $filter, SessionService, ShipmentService, Upload, $timeout, toaster) { var setModalOptions = function () { $translate(['FrayteSuccess', 'FrayteError', 'FrayteValidation', 'ErrorGetting', 'PleaseTryLater', 'PleaseCorrectValidationErrors', 'CouldNotUpdateAnticipatedDateTime', 'AnticipatedDateTimeUpdatedSuccessfully', 'agent', 'records']).then(function (translations) { $scope.TitleFrayteSuccess = translations.FrayteSuccess; $scope.TitleFrayteError = translations.FrayteError; $scope.TitleFrayteValidation = translations.FrayteValidation; $scope.TextCouldNotUpdateAnticipatedDateTime = translations.CouldNotUpdateAnticipatedDateTime; $scope.TextPleaseTryLater = translations.PleaseTryLater; $scope.TextAnticipatedDateTimeUpdatedSuccessfully = translations.AnticipatedDateTimeUpdatedSuccessfully; $scope.TextValidation = translations.PleaseCorrectValidationErrors; $scope.TextErrorGettingAgentRecord = translations.ErrorGetting + " " + translations.agent + " " + translations.records; }); }; $scope.updateAnticipatedDetail = { ShipmentId: 0, AnticipatedDeliveryDate: new Date(), AnticipatedDeliveryTime: '', OtherCustomIssues: '', IsUnexpectedDelay: false, UnexpectedClearance: null }; $scope.unexpectedComment = function (Comment) { if (!Comment) { $scope.updateAnticipatedDetail.UnexpectedClearance = null; } }; $scope.AgentAnticipating = function (isValid) { if (isValid) { if ($state.current.name === "public.shipper-anticipated") { ShipmentService.UpdateShipperAnticipatedDetail($scope.updateAnticipatedDetail).then(function (response) { if (response.status == 200) { toaster.pop({ type: 'success', title: $scope.TitleFrayteSuccess, body: $scope.TextAnticipatedDateTimeUpdatedSuccessfully, showCloseButton: true }); //Redirect to mail page after 4 second. $timeout(function () { $state.go('home.welcome'); }, 4000); } else { toaster.pop({ type: 'error', title: $scope.TitleFrayteError, body: $scope.TextCouldNotUpdateAnticipatedDateTime + " " + $scope.TextPleaseTryLater, showCloseButton: true }); } }); } else { ShipmentService.UpdateDestinatingAgentAnticipatedDetail($scope.updateAnticipatedDetail).then(function (response) { if (response.status == 200) { toaster.pop({ type: 'success', title: $scope.TitleFrayteSuccess, body: $scope.TextAnticipatedDateTimeUpdatedSuccessfully, showCloseButton: true }); //Redirect to mail page after 4 second. $timeout(function () { $state.go('home.welcome'); }, 4000); } else { toaster.pop({ type: 'error', title: $scope.TitleFrayteError, body: $scope.TextCouldNotUpdateAnticipatedDateTime + " " + $scope.TextPleaseTryLater, showCloseButton: true }); } }); } } else { toaster.pop({ type: 'warning', title: $scope.TitleFrayteValidation, body: $scope.TextValidation, showCloseButton: true }); } }; $scope.openCalender = function ($event) { $scope.status.opened = true; }; $scope.status = { opened: false }; $scope.confirmationCode = ''; //$scope.shipmentId = ''; var getShipmentDetail = function (id) { ShipmentService.GetShipmentShipperReceiverDetail(id).then(function (response) { $scope.FrayteCargoWiseSo = response.data.FrayteCargoWiseSo; $scope.ShipperInfo = response.data.Shipper; $scope.ShipperAddressInfo = response.data.ShipperAddress; $scope.ReceiverInfo = response.data.Receiver; $scope.ReceiverAddressInfo = response.data.ReceiverAddress; }, function () { toaster.pop({ type: 'error', title: $scope.TitleFrayteError, body: $scope.TextErrorGettingAgentRecord, showCloseButton: true }); }); }; function init() { // set Multilingual Modal Popup Options setModalOptions(); $scope.updateAnticipatedDetail.ShipmentId = $stateParams.shipmentId; var id = $stateParams.shipmentId; getShipmentDetail(id); } init(); });
besgamApp .controller("blog-menu", function( $scope, blogContent, $location ) { blogContent.get( 'posts', { page:1, per_page:5 } ).then( function( posts ) { $scope.recentposts = posts.data; }); blogContent.get( 'categories' ).then( function( categories ) { $scope.categories = categories.data; }); blogContent.get( 'tags', { orderby:'count', per_page:20, order:'desc' } ).then( function( tags ) { $scope.tags = tags.data; }); $scope.search = function(text) { if(text!=undefined) location.href="./blog/search/"+text+"/1/"; }; });
/* * Copyright (c) 2014 Adobe Systems Incorporated. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ define(function (require, exports, module) { "use strict"; var React = require("react"), Fluxxor = require("fluxxor"), FluxMixin = Fluxxor.FluxMixin(React), Immutable = require("immutable"); var Rotate = require("jsx!./Rotate"), Flip = require("jsx!./Flip"), Label = require("jsx!js/jsx/shared/Label"), Gutter = require("jsx!js/jsx/shared/Gutter"), strings = require("i18n!nls/strings"), collection = require("js/util/collection"); var RotateFlip = React.createClass({ mixins: [FluxMixin], propTypes: { document: React.PropTypes.object, layers: React.PropTypes.arrayOf(React.PropTypes.object) }, shouldComponentUpdate: function (nextProps) { var getRelevantProps = function (props) { var document = props.document; return collection.pluckAll(document.layers.selected, ["id", "bounds"]); }; return !Immutable.is(getRelevantProps(this.props), getRelevantProps(nextProps)); }, render: function () { return ( <div className="formline"> <Label title={strings.TOOLTIPS.SET_ROTATION}> {strings.TRANSFORM.ROTATE} </Label> <Gutter /> <Rotate {...this.props} /> <Gutter /> <Flip {...this.props} /> <Gutter /> </div> ); } }); module.exports = RotateFlip; });
import riot from 'riot' import {userService, projectService} from 'services' import {notificationManager} from 'utils' riot.mixin('star-project', { starProject: function (project) { if (!userService.isLoggedIn()) { notificationManager.notify('Please login to star projects', 'danger') return } const original = Object.assign({}, project) project.starred = !project.starred project.starsCount += project.starred ? 1 : -1 const verb = project.starred ? 'star' : 'unstar' projectService[verb](project.id, project.starred) .catch(e => { Object.assign(project, original) notificationManager.notify(`Failed to ${verb} project`, 'danger') }).finally(() => this.update()) } })
let style = ["Джаз", "Блюз"]; console.log(style); style.push("Рок-н-ролл"); console.log(style); // let centerElem = Math.ceil(style.length / 2) - 1; style[Math.ceil(style.length / 2) - 1] = "Классика"; console.log(style); style.shift(); console.log(style); style.unshift("Рэп", "Рэгги"); console.log(style); // function sumInput() { // let numbers = []; // while (true) { // let value = prompt("Введите число", 0); // // Прекращаем ввод? // if (value === "" || value === null || !isFinite(value)) break; // numbers.push(+value); // } // let sum = 0; // for (let number of numbers) { // sum += number; // } // return sum; // } // alert( sumInput() ); // let arr = []; // let result = 0; // function sumInput() { // for (let i = 0; i < 100; i++) { // arr[i] = +prompt('Enter element...', ''); // console.log(arr); // if (arr[i] == '') break; // }; // return result = arr.reduce((sum, current) => sum + current, 0); // }; // alert(sumInput()); // function getMaxSubSum(arr) { // let maxSum = 0; // let partialSum = 0; // for (let item of arr) { // для каждого элемента массива // partialSum += item; // добавляем значение элемента к partialSum // maxSum = Math.max(maxSum, partialSum); // запоминаем максимум на данный момент // if (partialSum < 0) partialSum = 0; // ноль если отрицательное // } // return maxSum; // }; // alert(getMaxSubSum([-1, 2, 3, 9, 11])); //сортировка чисел // let arr = [1, 2, 66, 23, 15, 3, 56, 32]; // arr.sort((a, b) => a - b); // alert(arr); // 1, 2, 15 // сумма элементов массива в одну строчку // let arr = [1, 2, 3, 4, 5]; // let result = arr.reduce((sum, current) => sum + current, 0); // alert(result); // 15 function camelize(str) { // let arrStr = str.split('-'); // console.log(str); // for (let i = 1; i < arrStr.length; i++) { // let partArrStr = arrStr[i].split(''); // partArrStr[0] = partArrStr[0].toUpperCase(); // arrStr[i] = partArrStr.join(''); // }; // return str = arrStr.join(''); const mapFunc = (word, index) => index == 0 ? word : word[0].toUpperCase() + word.slice(1) return str .split('-') .map(mapFunc) .join(''); }; // alert(camelize("background-color")); // alert(camelize('list-style-image')); // alert(camelize("-webkit-transition")); // let arr = [5, 3, 8, 1]; function filterRange(arr, a, b) { return arr.filter(item => (item <= b && item >= a)); }; // let filtered = filterRange(arr, 1, 7); // alert(filtered); // 3,1 (совпадающие значения) // alert(arr); // 5,3,8,1 (без изменений) // let arr = [5, 3, 8, 1]; function filterRangeInPlace(arr, a, b) { for (let i = 0; i < arr.length; i++) { if (arr[i] < a || arr[i] > b) { arr.splice(i, 1) } } }; // filterRangeInPlace(arr, 1, 4); // alert(arr); // let randomNum = randomInteger(1, 100); // arr.push(12, 53, 23, 74, 27, 18,); // alert(arr.sort((a, b) => b - a));//сортировка чисел по убыванию // let arr = ["HTML", "JavaScript", "CSS"]; // let sortedArr = copySorted(arr); function copySorted(arr) { return arr.concat().sort(); }; // alert(arr); // alert(sortedArr); function Calculator() { let operators = [ ['+', (a, b) => a + b], ['-', (a, b) => a - b], ]; this.calculate = function (str) { let res partStr = str.split(" "); for (let key of operators) { if (key[0] == partStr[1]) { res = key[1]((+partStr[0]), (+partStr[2])); } } return res; } this.addMethod = function (name, func) { operators.push([name, func]) } }; // let calc = new Calculator; // alert(calc.calculate("3 - 7")); // 10 // let powerCalc = new Calculator; // powerCalc.addMethod("*", (a, b) => a * b); // powerCalc.addMethod("/", (a, b) => a / b); // powerCalc.addMethod("**", (a, b) => a ** b); // let result = powerCalc.calculate("2 / 3"); // alert(result); // 8 // let vasya = { name: "Вася", surname: "Пупкин", id: 1 }; // let petya = { name: "Петя", surname: "Иванов", id: 2 }; // let masha = { name: "Маша", surname: "Петрова", id: 3 }; // let users = [vasya, petya, masha]; // let usersMapped = users.map(user => ({ // fullName: `${user.name} ${user.surname}`, // id: user.id // })) // console.log(usersMapped) // alert(usersMapped[0].id) // 1 // alert(usersMapped[0].fullName) // Вася Пупкин let vasya = { name: "Вася", age: 25 }; let petya = { name: "Петя", age: 30 }; let masha = { name: "Маша", age: 28 }; // let arr = [vasya, petya, masha]; // console.log(arr) // arr.sort((a,b) => a.age - b.age) function sortByAge(arr) { return arr.sort((a, b) => a.age - b.age) } // sortByAge(arr); // console.log(arr) // // теперь: [vasya, masha, petya] // alert(arr[0].name); // Вася // alert(arr[1].name); // Маша // alert(arr[2].name); // Петя // let arr = [1, 2, 3]; function randomInteger(min, max) { let rand = min + Math.random() * (max - min); return Math.floor(rand); } // arr.sort((a, b) => Math.random()) function shuffle(arr) { for (let i = 0; i < arr.length; i++) { arr[i] = randomInteger(1, 4) if (!(arr[i] == arr[i + 1])) { continue; } else arr[i] = randomInteger(1, 4) } return arr } // shuffle(arr); // console.log(arr) function unique(arr) { return Array.from(new Set(arr)) } let values = ["Hare", "Krishna", "Hare", "Krishna", "Krishna", "Krishna", "Hare", "Hare", ":-O" ]; // alert(unique(values)); // Hare,Krishna,:-O function aclean(arr) { let map = new Map() for (let word of arr) { let sorted = word.toLowerCase().split('').sort().join('') map.set(sorted, word) } return Array.from(map.values()) } let arr = ["nap", "teachers", "cheaters", "PAN", "ear", "era", "hectares"]; // alert(aclean(arr)); // "nap,teachers,ear" or "PAN,cheaters,era" let messages = [ { text: 'Hello', from: 'John' }, { text: 'How goes?', from: 'John' }, { text: 'See you soon', from: 'Alice' } ] let readMessages = new WeakSet(); readMessages.add(messages[0]) readMessages.add(messages[1]) readMessages.add(messages[0]) // alert('Read message 0: ' + readMessages.has(messages[0])) // messages.shift() let dateReadMessages = new WeakMap() dateReadMessages.set(messages[0], new Date(2021, 4, 0)) // alert(dateReadMessages.get(messages[0])) let salaries = { 'John': 100, 'Pete': 300, 'Mary': 250 } function topSalaries(obj) { let max = 0 let maxName = null for (const [name, salary] of Object.entries(obj)) { if (max < salary) { max = salary; maxName = name } } return maxName } function sumSalaries(obj) { return Object.values(obj).reduce((a, b) => a + b, 0) // let result = 0 // for (let value of Object.values(obj)) { // result = result + value // } return result } let user = { name: 'John', years: 30 } function cout(obj) { return Object.keys(obj).length } alert(cout(user)) alert(sumSalaries(salaries)) alert(topSalaries(salaries)) let { name, years: age, isAdmin = false } = user alert(name) alert(age) alert(isAdmin) let now = new Date() console.log(now)
import app from '../../../app'; import ItemView from '../../../base/view/page'; import LoginForm from '../../login-form/view/item'; export default class LoginView extends ItemView { constructor (options) { super(Object.assign({ template: app.template('item/login'), className: 'login-container is-hidden', regions: { form: '.login-form' }, events: { 'click .js-close' : 'hideLogin' } }, options)); this.listenTo(app, 'ajax:authError', this.showLogin); this.listenTo(app, 'login:error', this.onRender); this.listenTo(app, 'login:success', this.hideLogin); } onRender () { super.onRender(); this.getRegion('form').show(new LoginForm()); } showLogin () { this.$el.removeClass('is-hidden'); } hideLogin () { this.$el.addClass('is-hidden'); } }
import { createStore, applyMiddleware } from "redux"; import thunk from "../middlewares/thunk"; const initialValue = { listPost: [], listUser: [], detailPost: {}, }; function reducer(state = initialValue, action) { switch (action.type) { case "FETCH_POSTS": return { ...state, listPost: action.posts }; case "FETCH_USERS": return { ...state, listUser: action.users }; case "FETCH_DETAIL": return { ...state, detailPost: action.detail }; default: return state; } } export const store = createStore(reducer, applyMiddleware(thunk));
import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Stepper from '@material-ui/core/Stepper'; import Step from '@material-ui/core/Step'; import StepLabel from '@material-ui/core/StepLabel'; import Button from '@material-ui/core/Button'; import Typography from '@material-ui/core/Typography'; import './App.css'; import FormControlLabel from '@material-ui/core/FormControlLabel'; import FormGroup from "reactstrap/lib/FormGroup"; import {Checkbox} from "@material-ui/core"; import {Col, Layout, Menu, Row} from "antd"; import Switch from "@material-ui/core/Switch"; import TimeInput from 'material-ui-time-picker' import moment, {max, min} from "moment"; import 'react-dates/initialize'; import { DateRangePicker} from 'react-dates'; import 'react-dates/lib/css/_datepicker.css'; import TextField from '@material-ui/core/TextField'; import { Redirect } from 'react-router'; var k = 0 ; var i = 0; var w = window.innerWidth; var h = window.innerHeight; var mondays = []; var tuesdays = [] ; var wednesdays = [] ; var thursdays = [] ; var fridays = [] ; var satrudays = [] ; var sundays = [] ; var mini1 = null; var mini2 = 0; var maxi1 = null; var maxi2 = 0; export const theminmax = [ ]; export const daysoutwork = [ ]; export const startend = [ ]; export const duree = [] ; export const mydata = [ ]; export const data = [ ]; export const jours = [ ]; var s2=null; var s1=null; const now = moment('2020-07-01'); export default class GestionAgenda extends React.Component { state = { activeStep: 0, CheckedLundi:false, CheckedMardi:false, CheckedMercredi:false, CheckedJeudi:false, CheckedVendredi:false, CheckedSamedi:false, CheckedDimanche:false, switchlundi:false, lundidebut:null, lundipause:null, lundiretour:null, lundifin : null, switchmardi:false, mardidebut:null, mardipause:null, mardiretour:null, mardifin : null, switchmercredi:false, mercredidebut:null, mercredipause:null, mercrediretour:null, mercredifin : null, switchjeudi:false, jeudidebut:null, jeudipause:null, jeudiretour:null, jeudifin : null, switchvendredi:false, vendredidebut:null, vendredipause:null, vendrediretour:null, vendredifin : null, switchsamedi:false, samedidebut:null, samedipause:null, samediretour:null, samedifin : null, switchdimanche:false, dimanchedebut:null, dimanchepause:null, dimancheretour:null, dimanchefin : null, visitetime:null, startDate:null, endDate:null, focusedInput:null, redirect:false, compteurk : 0 , compteuri : 0 , }; getNumberOfSteps() { return 4; } getStepContent(step) { switch (step) { case 0: return ( <div > <h1 style={{alignSelf:'center',textAlign:'center',fontSize:35,fontWeight:'Bold',marginTop:h/20,marginBottom:h/10}}>Choisir les jours lequels vous travaillez</h1> <FormGroup style={{marginLeft:w/12,marginBottom:h/10,alignSelf:'center'}} row={true}> <FormControlLabel style={{marginLeft:w/100}} control={<Checkbox color={'primary'} name="CheckedLundi" />} label="Lundi" checked={this.state.CheckedLundi} onChange={() =>this.setState({ CheckedLundi: !this.state.CheckedLundi })} /> <FormControlLabel style={{marginLeft:w/100}} control={<Checkbox color={'primary'} name="CheckedMardi" />} label="Mardi" checked={this.state.CheckedMardi} onChange={() =>this.setState({ CheckedMardi: !this.state.CheckedMardi })} /> <FormControlLabel style={{marginLeft:w/100}} control={<Checkbox color={'primary'} name="CheckedMercredi" />} label="Mercredi" checked={this.state.CheckedMercredi} onChange={() =>this.setState({ CheckedMercredi: !this.state.CheckedMercredi })} /> <FormControlLabel style={{marginLeft:w/100}} control={<Checkbox color={'primary'} name="CheckedJeudi" />} label="Jeudi" checked={this.state.CheckedJeudi} onChange={() =>this.setState({ CheckedJeudi: !this.state.CheckedJeudi })} /> <FormControlLabel style={{marginLeft:w/100}} control={<Checkbox color={'primary'} name="CheckedVendredi" />} label="Vendredi" checked={this.state.CheckedVendredi} onChange={() =>this.setState({ CheckedVendredi: !this.state.CheckedVendredi })} /> <FormControlLabel style={{marginLeft:w/100}} control={<Checkbox color={'primary'} name="CheckedSamedi" />} label="Samedi" checked={this.state.CheckedSamedi} onChange={() =>this.setState({ CheckedSamedi: !this.state.CheckedSamedi })} /> <FormControlLabel style={{marginLeft:w/100}} control={<Checkbox color={'primary'} name="CheckedDimanche" />} label="Dimanche" checked={this.state.CheckedDimanche} onChange={() =>this.setState({ CheckedDimanche: !this.state.CheckedDimanche })} /> </FormGroup> </div> ); case 1: return ( <div> <h1 style={{alignSelf:'center',textAlign:'center',fontSize:30,fontWeight:'Bold',marginBottom:h/80}}>Réglez vos horaires du travail</h1> <Row className={'formulairepage2'} style={{ marginTop:h/20,marginBottom:h/20}}> { this.state.CheckedLundi===true? <Col style={{marginLeft:5,width:w/9,height:h/2.5,alignSelf:'center',backgroundColor:"white"}}> <h4 style={{textAlign:'center',fontSize:20,marginTop:h/50}}>Lundi</h4> <div style={{marginLeft:w/25}} > <Switch size={"small"} color="default" name="checkedA" checked={this.state.switchlundi} onChange={() =>this.setState({ switchlundi: !this.state.switchlundi })} inputProps={{ 'aria-label': 'secondary checkbox' }} /> </div> { this.state.switchlundi===false? <div> <h3 style={{textAlign:'center',fontSize:14,color:'#367787'}}>Séance unique</h3> <text style={{marginLeft:w/35}}>Heure Debut</text> <div style={{marginLeft:w/25,width:40,height:40}}> <TimeInput mode='24h' value={this.state.lundidebut} onChange={(date) =>this.setState({ lundidebut: date })} /> </div> <text style={{marginLeft:w/30}}>Heure Fin</text> <div style={{marginLeft:w/25,width:40,height:40}}> <TimeInput mode='24h' value={this.state.lundifin} onChange={(date) =>this.setState({ lundifin: date })} /> </div> </div> : <div> <h3 style={{textAlign:'center',fontSize:14,color:'#367787'}}>Double séance</h3> <text style={{marginLeft:w/100}}>Heure Debut/Pause</text> <Row> <div style={{marginLeft:w/60,width:40,height:40}}> <TimeInput mode='24h' value={this.state.lundidebut} onChange={(date) =>this.setState({ lundidebut: date })} /> </div> <div style={{marginLeft:w/60,width:40,height:40}}> <TimeInput mode='24h' value={this.state.lundipause} onChange={(date) =>this.setState({ lundipause: date })} /> </div> </Row> <text style={{marginLeft:w/80}}>Heure Retour/Fin</text> <Row> <div style={{marginLeft:w/60,width:40,height:40}}> <TimeInput mode='24h' value={this.state.lundiretour} onChange={(date) =>this.setState({ lundiretour: date })} /> </div> <div style={{marginLeft:w/60,width:40,height:40}}> <TimeInput mode='24h' value={this.state.lundifin} onChange={(date) =>this.setState({ lundifin: date })} /> </div> </Row> </div> } </Col> :null} { this.state.CheckedMardi===true? <Col style={{marginLeft:5,width:w/9,height:h/2.5,alignSelf:'center',backgroundColor:"white"}}> <h4 style={{textAlign:'center',fontSize:20,marginTop:h/50}}>Mardi</h4> <div style={{marginLeft:w/25}} > <Switch size={"small"} color="default" name="checkedA" checked={this.state.switchmardi} onChange={() =>this.setState({ switchmardi: !this.state.switchmardi })} inputProps={{ 'aria-label': 'secondary checkbox' }} /> </div> { this.state.switchmardi===false? <div> <h3 style={{textAlign:'center',fontSize:14,color:'#367787'}}>Séance unique</h3> <text style={{marginLeft:w/35}}>Heure Debut</text> <div style={{marginLeft:w/25,width:40,height:40}}> <TimeInput mode='24h' value={this.state.mardidebut} onChange={(date) =>this.setState({ mardidebut: date })} /> </div> <text style={{marginLeft:w/30}}>Heure Fin</text> <div style={{marginLeft:w/25,width:40,height:40}}> <TimeInput mode='24h' value={this.state.mardifin} onChange={(date) =>this.setState({ mardifin: date })} /> </div> </div> : <div> <h3 style={{textAlign:'center',fontSize:14,color:'#367787'}}>Double séance</h3> <text style={{marginLeft:w/100}}>Heure Debut/Pause</text> <Row> <div style={{marginLeft:w/60,width:40,height:40}}> <TimeInput mode='24h' value={this.state.mardidebut} onChange={(date) =>this.setState({ mardidebut: date })} /> </div> <div style={{marginLeft:w/60,width:40,height:40}}> <TimeInput mode='24h' value={this.state.mardipause} onChange={(date) =>this.setState({ mardipause: date })} /> </div> </Row> <text style={{marginLeft:w/80}}>Heure Retour/Fin</text> <Row> <div style={{marginLeft:w/60,width:40,height:40}}> <TimeInput mode='24h' value={this.state.mardiretour} onChange={(date) =>this.setState({ mardiretour: date })} /> </div> <div style={{marginLeft:w/60,width:40,height:40}}> <TimeInput mode='24h' value={this.state.mardifin} onChange={(date) =>this.setState({ mardifin: date })} /> </div> </Row> </div> } </Col>:null} { this.state.CheckedMercredi===true? <Col style={{marginLeft:5,width:w/9,height:h/2.5,alignSelf:'center',backgroundColor:"white"}}> <h4 style={{textAlign:'center',fontSize:20,marginTop:h/50}}>Mercredi</h4> <div style={{marginLeft:w/25}} > <Switch size={"small"} color="default" name="checkedA" checked={this.state.switchmercredi} onChange={() =>this.setState({ switchmercredi: !this.state.switchmercredi })} inputProps={{ 'aria-label': 'secondary checkbox' }} /> </div> { this.state.switchmercredi===false? <div> <h3 style={{textAlign:'center',fontSize:14,color:'#367787'}}>Séance unique</h3> <text style={{marginLeft:w/35}}>Heure Debut</text> <div style={{marginLeft:w/25,width:40,height:40}}> <TimeInput mode='24h' value={this.state.mercredidebut} onChange={(date) =>this.setState({ mercredidebut: date })} /> </div> <text style={{marginLeft:w/30}}>Heure Fin</text> <div style={{marginLeft:w/25,width:40,height:40}}> <TimeInput mode='24h' value={this.state.mercredifin} onChange={(date) =>this.setState({ mercredifin: date })} /> </div> </div> : <div> <h3 style={{textAlign:'center',fontSize:14,color:'#367787'}}>Double séance</h3> <text style={{marginLeft:w/100}}>Heure Debut/Pause</text> <Row> <div style={{marginLeft:w/60,width:40,height:40}}> <TimeInput mode='24h' value={this.state.mercredidebut} onChange={(date) =>this.setState({ mercredidebut: date })} /> </div> <div style={{marginLeft:w/60,width:40,height:40}}> <TimeInput mode='24h' value={this.state.mercredipause} onChange={(date) =>this.setState({ mercredipause: date })} /> </div> </Row> <text style={{marginLeft:w/80}}>Heure Retour/Fin</text> <Row> <div style={{marginLeft:w/60,width:40,height:40}}> <TimeInput mode='24h' value={this.state.mercrediretour} onChange={(date) =>this.setState({ mercrediretour: date })} /> </div> <div style={{marginLeft:w/60,width:40,height:40}}> <TimeInput mode='24h' value={this.state.mercredifin} onChange={(date) =>this.setState({ mercredifin: date })} /> </div> </Row> </div> } </Col> :null} { this.state.CheckedJeudi===true? <Col style={{marginLeft:5,width:w/9,height:h/2.5,alignSelf:'center',backgroundColor:"white"}}> <h4 style={{textAlign:'center',fontSize:20,marginTop:h/50}}>Jeudi</h4> <div style={{marginLeft:w/25}} > <Switch size={"small"} color="default" name="checkedA" checked={this.state.switchjeudi} onChange={() =>this.setState({ switchjeudi: !this.state.switchjeudi })} inputProps={{ 'aria-label': 'secondary checkbox' }} /> </div> { this.state.switchjeudi===false? <div> <h3 style={{textAlign:'center',fontSize:14,color:'#367787'}}>Séance unique</h3> <text style={{marginLeft:w/35}}>Heure Debut</text> <div style={{marginLeft:w/25,width:40,height:40}}> <TimeInput mode='24h' value={this.state.jeudidebut} onChange={(date) =>this.setState({ jeudidebut: date })} /> </div> <text style={{marginLeft:w/30}}>Heure Fin</text> <div style={{marginLeft:w/25,width:40,height:40}}> <TimeInput mode='24h' value={this.state.jeudifin} onChange={(date) =>this.setState({ jeudifin: date })} /> </div> </div> : <div> <h3 style={{textAlign:'center',fontSize:14,color:'#367787'}}>Double séance</h3> <text style={{marginLeft:w/100}}>Heure Debut/Pause</text> <Row> <div style={{marginLeft:w/60,width:40,height:40}}> <TimeInput mode='24h' value={this.state.jeudidebut} onChange={(date) =>this.setState({ jeudidebut: date })} /> </div> <div style={{marginLeft:w/60,width:40,height:40}}> <TimeInput mode='24h' value={this.state.jeudipause} onChange={(date) =>this.setState({ jeudipause: date })} /> </div> </Row> <text style={{marginLeft:w/80}}>Heure Retour/Fin</text> <Row> <div style={{marginLeft:w/60,width:40,height:40}}> <TimeInput mode='24h' value={this.state.jeudiretour} onChange={(date) =>this.setState({ jeudiretour: date })} /> </div> <div style={{marginLeft:w/60,width:40,height:40}}> <TimeInput mode='24h' value={this.state.jeudifin} onChange={(date) =>this.setState({ jeudifin: date })} /> </div> </Row> </div> } </Col> : null } { this.state.CheckedVendredi===true? <Col style={{marginLeft:5,width:w/9,height:h/2.5,alignSelf:'center',backgroundColor:"white"}}> <h4 style={{textAlign:'center',fontSize:20,marginTop:h/50}}>Vendredi</h4> <div style={{marginLeft:w/25}} > <Switch size={"small"} color="default" name="checkedA" checked={this.state.switchvendredi} onChange={() =>this.setState({ switchvendredi: !this.state.switchvendredi })} inputProps={{ 'aria-label': 'secondary checkbox' }} /> </div> { this.state.switchvendredi===false? <div> <h3 style={{textAlign:'center',fontSize:14,color:'#367787'}}>Séance unique</h3> <text style={{marginLeft:w/35}}>Heure Debut</text> <div style={{marginLeft:w/25,width:40,height:40}}> <TimeInput mode='24h' value={this.state.vendredidebut} onChange={(date) =>this.setState({ vendredidebut: date })} /> </div> <text style={{marginLeft:w/30}}>Heure Fin</text> <div style={{marginLeft:w/25,width:40,height:40}}> <TimeInput mode='24h' value={this.state.vendredifin} onChange={(date) =>this.setState({ vendredifin: date })} /> </div> </div> : <div> <h3 style={{textAlign:'center',fontSize:14,color:'#367787'}}>Double séance</h3> <text style={{marginLeft:w/100}}>Heure Debut/Pause</text> <Row> <div style={{marginLeft:w/60,width:40,height:40}}> <TimeInput mode='24h' value={this.state.vendredidebut} onChange={(date) =>this.setState({ vendredidebut: date })} /> </div> <div style={{marginLeft:w/60,width:40,height:40}}> <TimeInput mode='24h' value={this.state.vendredipause} onChange={(date) =>this.setState({ vendredipause: date })} /> </div> </Row> <text style={{marginLeft:w/80}}>Heure Retour/Fin</text> <Row> <div style={{marginLeft:w/60,width:40,height:40}}> <TimeInput mode='24h' value={this.state.vendrediretour} onChange={(date) =>this.setState({ vendrediretour: date })} /> </div> <div style={{marginLeft:w/60,width:40,height:40}}> <TimeInput mode='24h' value={this.state.vendredifin} onChange={(date) =>this.setState({ vendredifin: date })} /> </div> </Row> </div> } </Col> : null } { this.state.CheckedSamedi===true? <Col style={{marginLeft:5,width:w/9,height:h/2.5,alignSelf:'center',backgroundColor:"white"}}> <h4 style={{textAlign:'center',fontSize:20,marginTop:h/50}}>Samedi</h4> <div style={{marginLeft:w/25}} > <Switch size={"small"} color="default" name="checkedA" checked={this.state.switchsamedi} onChange={() =>this.setState({ switchsamedi: !this.state.switchsamedi })} inputProps={{ 'aria-label': 'secondary checkbox' }} /> </div> { this.state.switchsamedi===false? <div> <h3 style={{textAlign:'center',fontSize:14,color:'#367787'}}>Séance unique</h3> <text style={{marginLeft:w/35}}>Heure Debut</text> <div style={{marginLeft:w/25,width:40,height:40}}> <TimeInput mode='24h' value={this.state.samedidebut} onChange={(date) =>this.setState({ samedidebut: date })} /> </div> <text style={{marginLeft:w/30}}>Heure Fin</text> <div style={{marginLeft:w/25,width:40,height:40}}> <TimeInput mode='24h' value={this.state.samedifin} onChange={(date) =>this.setState({ samedifin: date })} /> </div> </div> : <div> <h3 style={{textAlign:'center',fontSize:14,color:'#367787'}}>Double séance</h3> <text style={{marginLeft:w/100}}>Heure Debut/Pause</text> <Row> <div style={{marginLeft:w/60,width:40,height:40}}> <TimeInput mode='24h' value={this.state.samedidebut} onChange={(date) =>this.setState({ samedidebut: date })} /> </div> <div style={{marginLeft:w/60,width:40,height:40}}> <TimeInput mode='24h' value={this.state.samedipause} onChange={(date) =>this.setState({ samedipause: date })} /> </div> </Row> <text style={{marginLeft:w/80}}>Heure Retour/Fin</text> <Row> <div style={{marginLeft:w/60,width:40,height:40}}> <TimeInput mode='24h' value={this.state.samediretour} onChange={(date) =>this.setState({ samediretour: date })} /> </div> <div style={{marginLeft:w/60,width:40,height:40}}> <TimeInput mode='24h' value={this.state.samedifin} onChange={(date) =>this.setState({ samedifin: date })} /> </div> </Row> </div> } </Col> : null } { this.state.CheckedDimanche===true? <Col style={{marginLeft:5,width:w/9,height:h/2.5,alignSelf:'center',backgroundColor:"white"}}> <h4 style={{textAlign:'center',fontSize:20,marginTop:h/50}}>Dimanche</h4> <div style={{marginLeft:w/25}} > <Switch size={"small"} color="default" name="checkedA" checked={this.state.switchdimanche} onChange={() =>this.setState({ switchdimanche: !this.state.switchdimanche })} inputProps={{ 'aria-label': 'secondary checkbox' }} /> </div> { this.state.switchdimanche===false? <div> <h3 style={{textAlign:'center',fontSize:14,color:'#367787'}}>Séance unique</h3> <text style={{marginLeft:w/35}}>Heure Debut</text> <div style={{marginLeft:w/25,width:40,height:40}}> <TimeInput mode='24h' value={this.state.dimanchedebut} onChange={(date) =>this.setState({ dimanchedebut: date })} /> </div> <text style={{marginLeft:w/30}}>Heure Fin</text> <div style={{marginLeft:w/25,width:40,height:40}}> <TimeInput mode='24h' value={this.state.dimanchefin} onChange={(date) =>this.setState({ dimanchefin: date })} /> </div> </div> : <div> <h3 style={{textAlign:'center',fontSize:14,color:'#367787'}}>Double séance</h3> <text style={{marginLeft:w/100}}>Heure Debut/Pause</text> <Row> <div style={{marginLeft:w/60,width:40,height:40}}> <TimeInput mode='24h' value={this.state.dimanchedebut} onChange={(date) =>this.setState({ dimanchedebut: date })} /> </div> <div style={{marginLeft:w/60,width:40,height:40}}> <TimeInput mode='24h' value={this.state.dimanchepause} onChange={(date) =>this.setState({ dimanchepause: date })} /> </div> </Row> <text style={{marginLeft:w/80}}>Heure Retour/Fin</text> <Row> <div style={{marginLeft:w/60,width:40,height:40}}> <TimeInput mode='24h' value={this.state.dimancheretour} onChange={(date) =>this.setState({ dimancheretour: date })} /> </div> <div style={{marginLeft:w/60,width:40,height:40}}> <TimeInput mode='24h' value={this.state.dimanchefin} onChange={(date) =>this.setState({ dimanchefin: date })} /> </div> </Row> </div> } </Col> : null} </Row> </div> ); case 2: return ( <div > <h1 style={{alignSelf:'center',textAlign:'center',fontSize:35,fontWeight:'Bold',marginBottom:h/20}}>Choisir la dureé de votre visite</h1> <Row className={'formulairepage2'} style={{marginBottom:h/4,alignSelf:'center'}}> <TextField onChange={(event) =>this.setState({ visitetime:event.target.value })} required={true} id="outlined-basic" type="number" label="Minutes" variant="outlined" /> </Row> </div> ); case 3: return ( <div > <h1 style={{alignSelf:'center',textAlign:'center',fontSize:35,fontWeight:'Bold',marginBottom:h/20}}>Appliquer ces réglages</h1> <Row className={'formulairepage2'} style={{marginBottom:h/4,alignSelf:'center'}} row={true}> <DateRangePicker small={false} disableScroll={true} startDatePlaceholderText={"De"} endDatePlaceholderText={"Jusqu'a"} startDate={this.state.startDate} // momentPropTypes.momentObj or null, startDateId="your_unique_start_date_id" // PropTypes.string.isRequired, endDate={this.state.endDate} // momentPropTypes.momentObj or null, endDateId="your_unique_end_date_id" // PropTypes.string.isRequired, onDatesChange={({ startDate, endDate }) => this.setState({ startDate, endDate })} // PropTypes.func.isRequired, focusedInput={this.state.focusedInput} // PropTypes.oneOf([START_DATE, END_DATE]) or null, onFocusChange={focusedInput => this.setState({ focusedInput })} // PropTypes.func.isRequired, firstDayOfWeek={1} displayFormat={"DD/MM/yyyy"} /> </Row> </div> ); } } Makemin =()=>{ let min = 24; if ( (this.state.CheckedLundi===true)) {if ((this.state.lundidebut!==null)&&(this.state.lundidebut.getHours()<min)) {min = this.state.lundidebut.getHours();}} if ( (this.state.CheckedMardi===true)) {if ((this.state.mardidebut!==null)&&(this.state.mardidebut.getHours()<min)) {min = this.state.mardidebut.getHours();}} if ( (this.state.CheckedMercredi===true)) {if ((this.state.mercredidebut!==null)&&(this.state.mercredidebut.getHours()<min)) {min = this.state.mercredidebut.getHours();}} if ( (this.state.CheckedJeudi===true)) {if ((this.state.jeudidebut!==null)&&(this.state.jeudidebut.getHours()<min)) {min = this.state.jeudidebut.getHours();}} if ( (this.state.CheckedVendredi===true)) {if ((this.state.vendredidebut!==null)&&(this.state.vendredidebut.getHours()<min)) {min = this.state.vendredidebut.getHours();}} if ( (this.state.CheckedSamedi===true)) {if ((this.state.samedidebut!==null)&&(this.state.samedidebut.getHours()<min)) {min = this.state.samedidebut.getHours();}} if ( (this.state.CheckedDimanche===true)) {if ((this.state.dimanchedebut!==null)&&(this.state.dimanchedebut.getHours()<min)) {min = this.state.dimanchedebut.getHours();}} theminmax.push(min) ; mini1 = min ; } MakeMax =()=>{ let max = 0; if ( (this.state.CheckedLundi===true)) {if ((this.state.lundifin!==null)&&(this.state.lundifin.getHours()>max)) {max = this.state.lundifin.getHours()+1;}} if ((this.state.CheckedMardi===true)) {if ((this.state.mardifin!==null)&&(this.state.mardifin.getHours()>max)) {max = this.state.mardifin.getHours()+1;}} if ( (this.state.CheckedMercredi===true)) {if ((this.state.mercredifin!==null)&&(this.state.mercredifin.getHours()>max)) {max = this.state.mercredifin.getHours()+1;}} if ( (this.state.CheckedJeudi===true)) {if ((this.state.jeudifin!==null)&&(this.state.jeudifin.getHours()>max)) {max = this.state.jeudifin.getHours()+1;}} if ( (this.state.CheckedVendredi===true)) {if ((this.state.vendredifin!==null)&&(this.state.vendredifin.getHours()>max)) {max = this.state.vendredifin.getHours()+1;}} if ( (this.state.CheckedSamedi===true)) {if ((this.state.samedifin!==null)&&(this.state.samedifin.getHours()>max)) {max = this.state.samedifin.getHours()+1;}} if ( (this.state.CheckedDimanche===true)) {if ((this.state.dimanchefin!==null)&&(this.state.dimanchefin.getHours()>max)) {max = this.state.dimanchefin.getHours()+1;}} theminmax.push(max+1) ; maxi1 = max+1 ; } handleNext = () => { const { activeStep } = this.state; if ((activeStep===0)&&((this.state.CheckedLundi===true)||(this.state.CheckedMardi===true)||(this.state.CheckedMercredi===true)||(this.state.CheckedJeudi===true)||(this.state.CheckedVendredi===true)||(this.state.CheckedSamedi===true)||(this.state.CheckedDimanche===true))) this.setState({ activeStep: activeStep + 1 }); if ((activeStep===2)) { this.Makemin(); this.setState({ activeStep: activeStep + 1, }); duree.push(this.state.visitetime); } if ((activeStep===3)) { this.setState({ activeStep: activeStep + 1 }); startend.push(this.state.startDate); startend.push(this.state.endDate); s1=this.state.startDate ; s2 = this.state.startDate this.MakeMax() ; } if ((activeStep===3)&&(this.state.startDate===null)&&(this.state.endDate===null)) { alert('Il faut choisir une durée'); this.setState({ activeStep: activeStep }); } if ((activeStep===1)) this.setState({ activeStep: activeStep + 1 }); if ((activeStep===1)) { if (this.state.CheckedDimanche===false) {daysoutwork.push(0)} if (this.state.CheckedLundi===false) {daysoutwork.push(1)} if (this.state.CheckedMardi===false) {daysoutwork.push(2)} if (this.state.CheckedMercredi===false) {daysoutwork.push(3)} if (this.state.CheckedJeudi===false) {daysoutwork.push(4)} if (this.state.CheckedVendredi===false) {daysoutwork.push(5)} if (this.state.CheckedSamedi===false) {daysoutwork.push(6)} } }; handleBack = () => { const { activeStep } = this.state; this.setState({ activeStep: activeStep - 1, }); }; handleOnquitter = async () => { { if((this.state.CheckedLundi===true)) { const b=this.state.endDate; let now = moment(this.state.startDate); this.makeappointments(this.state.activeStep,this.state.CheckedLundi,this.state.lundidebut,this.state.lundifin,this.state.lundipause,this.state.lundiretour,this.state.switchlundi,now,b,mondays,1);} if((this.state.CheckedMardi===true)) { const b=this.state.endDate; let now = moment(this.state.startDate); await this.makeappointments(this.state.activeStep,this.state.CheckedMardi,this.state.mardidebut,this.state.mardifin,this.state.mardipause,this.state.mardiretour,this.state.switchmardi,now,b,tuesdays,2);} if((this.state.CheckedMercredi===true)) { const b=this.state.endDate; let now = moment(this.state.startDate); await this.makeappointments(this.state.activeStep,this.state.CheckedMercredi,this.state.mercredidebut,this.state.mercredifin,this.state.mercredipause,this.state.mercrediretour,this.state.switchmercredi,now,b,wednesdays,3);} if((this.state.CheckedJeudi===true)) { const b=this.state.endDate; let now = moment(this.state.startDate); await this.makeappointments(this.state.activeStep,this.state.CheckedJeudi,this.state.jeudidebut,this.state.jeudifin,this.state.jeudipause,this.state.jeudiretour,this.state.switchjeudi,now,b,thursdays,4);} if((this.state.CheckedVendredi===true)) { const b=this.state.endDate; let now = moment(this.state.startDate); await this.makeappointments(this.state.activeStep,this.state.CheckedVendredi,this.state.vendredidebut,this.state.vendredifin,this.state.vendredipause,this.state.vendrediretour,this.state.switchvendredi,now,b,fridays,5);} if((this.state.CheckedSamedi===true)) { const b=this.state.endDate; let now = moment(this.state.startDate); await this.makeappointments(this.state.activeStep,this.state.CheckedSamedi,this.state.samedidebut,this.state.samedifin,this.state.samedipause,this.state.samediretour,this.state.switchsamedi,now,b,satrudays,6);} if((this.state.CheckedDimanche===true)) { const b=this.state.endDate; let now = moment(this.state.startDate); await this.makeappointments(this.state.activeStep,this.state.CheckedDimanche,this.state.dimanchedebut,this.state.dimanchefin,this.state.dimanchepause,this.state.dimancheretour,this.state.switchdimanche,now,b,sundays,0);} } this.setState({redirect: true}); } makeappointments=(as,cd,dd,df,dp,dr,sd,start,ed,tab,numberday)=>{ if ((as>=3)&&(cd===true)&&(dd!==null)&&(df!==null)&&(dp!==null)&&(dr!==null)&&(sd===true)) { i=0; let std = start ; { while (std.week() <= ed.week() ) { if (std.day()===numberday) { tab.push(std.date()); std.add(1, 'days'); if (mini2 < dd.getMinutes()+0) {mydata.push( { title: 'Hors Travail', startDate: new Date(std.year()+0, std.month()+0,tab[i]+0, dp.getHours()+0, dp.getMinutes()+0), endDate: new Date(ed.year()+0, ed.month()+0, tab[i]+0,dr.getHours()+0, dr.getMinutes()+0), id: k, type: 1, } ); } k=k+1; mydata.push( { title: 'Hors Travail1', startDate: new Date(std.year()+0, std.month()+0,tab[i]+0, mini1+0, mini2+0), endDate: new Date(ed.year()+0, ed.month()+0, tab[i]+0,dd.getHours()+0, dd.getMinutes()+0), id: k, type: 1, } ); k=k+1; mydata.push( { title: 'Hors Travail2', startDate: new Date(std.year()+0, std.month()+0,tab[i]+0, df.getHours()+0, df.getMinutes()+0), endDate: new Date(ed.year()+0, ed.month()+0, tab[i]+0,maxi1+0, maxi2+0), id: k, type: 1, } ); k=k+1; i = i+1 } if (std.day()!==numberday) {std.add(1, 'days');} } } } if ((as>=3)&&(cd===true)&&(dd!==null)&&(df!==null)&&(sd===false)) { i=0; let std = start ; { while (std.week() <= ed.week() ) { if (std.day()===numberday) { tab.push(std.date()); std.add(1, 'days'); if (mini2 < dd.getMinutes()+0) { mydata.push( { title: 'Hors Travail', startDate: new Date(std.year()+0, std.month()+0,tab[i]+0, mini1+0, mini2+0), endDate: new Date(ed.year()+0, std.month()+0, tab[i]+0,dd.getHours()+0, dd.getMinutes()+0), id: k, type: 1, } );} k= k+1; mydata.push( { title: 'Hors Travail1', startDate: new Date(std.year()+0, std.month()+0,tab[i]+0, df.getHours()+0, df.getMinutes()+0), endDate: new Date(ed.year()+0, ed.month()+0, tab[i]+0,maxi1+0, maxi2+0), id: k, type: 1, } ); k= k+1; i = i+1 } if (std.day()!==numberday) {std.add(1, 'days');} } } } } render() { const { activeStep } = this.state; if (this.state.redirect) { return <Redirect push to="/Agenda" />; } return ( <React.Fragment style={{ background: '#fff', padding: 24, minHeight:h/1.1,backgroundColor:'#ebebeb' }} > <Stepper style={{backgroundColor:'transparent' }} activeStep={activeStep}> <Step key={0}> <StepLabel>Step1</StepLabel> </Step> <Step key={1}> <StepLabel>Step2</StepLabel> </Step> <Step key={2}> <StepLabel>Step3</StepLabel> </Step> <Step key={3}> <StepLabel>Step4</StepLabel> </Step> </Stepper> <div> {activeStep === this.getNumberOfSteps() ? ( <div className={'formulairepage2'}> <h1 style={{alignSelf:'center',textAlign:'center',fontSize:35,fontWeight:'Bold',marginTop:h/10,marginBottom:h/10,color:"#367787"}}>✓✓✓ Votre agenda est bien configurée ✓✓✓</h1> <h1 style={{alignSelf:'center',textAlign:'center',fontSize:35,fontWeight:'Bold',marginTop:h/10,marginBottom:h/10,color:"#367787"}}>{this.maxtiming}</h1> <div style={{marginLeft:w/2.8,marginBottom:h/10,alignSelf:'center'}}> <button variant="outlined" color="primary" onClick={()=>{this.handleOnquitter().then()}} style={{marginLeft:w/40}} > Quitter </button> </div> </div> ) : ( <div> { // Populate the content pane based on the active step this.getStepContent(activeStep) } <div style={{marginLeft:w/3.3,marginBottom:h/10,alignSelf:'center'}}> <Button variant="outlined" color="default" onClick={this.handleBack} > Précédent </Button> <Button variant="outlined" color="primary" onClick={this.handleNext} style={{marginLeft:w/20}} > {activeStep === this.getNumberOfSteps() - 1 ? 'Terminer' : 'Suivant'} </Button> </div> </div> )} </div> </React.Fragment> ); } }
var Game = require('./game'); Game.prototype.gameOverMenu = function(keysDown) { for (var key in keysDown) { var value = Number(key); if (value === 13) { this.startNewMatch(); } if (value === 77) { this.scoreboard.resetMatchScore(); } if (value === 27) { this.returnToMainMenu(); } } }; Game.prototype.renderBackground = function(keysDown) { if(this.difficulty === "normal"){ var background = {beach: "http://i.imgur.com/gDJx6ws.jpg", mars: "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dc/PIA17944-MarsCuriosityRover-AfterCrossingDingoGapSanddune-20140209.jpg/1280px-PIA17944-MarsCuriosityRover-AfterCrossingDingoGapSanddune-20140209.jpg", underWater: "http://www.publicdomainpictures.net/pictures/140000/velka/seabed-underwater-1443611137nes.jpg", minions: "https://s-media-cache-ak0.pinimg.com/originals/59/45/06/594506d41c836f70139b90a0f67e1563.gif", lotr: "https://media.giphy.com/media/c5iRPkrIqDHQk/giphy.gif", unicorn: "http://f.owledge.de/mlp/PFUDOR_dancing_fullres.gif", mountains: "https://lonelyplanetimages.imgix.net/a/g/hi/t/12dec8938220093eb7f1fdb8a9ce40b8-the-rocky-mountains.jpg?sharp=10&vib=20&w=1200", technicolor: "http://i.imgur.com/CcKD4Jd.gif", matrix: "https://reneweddesign.files.wordpress.com/2015/07/matrix-2.gif?w=1280&h=1024&crop=1"}; for (var key in keysDown) { var value = Number(key); if (value === 49) { this.changeBackgroundImage(background.beach); } if (value === 50) { this.changeBackgroundImage(background.mars); } if (value === 51) { this.changeBackgroundImage(background.underWater); } if (value === 52) { this.changeBackgroundImage(background.minions); } if (value === 53) { this.changeBackgroundImage(background.lotr); } if (value === 54) { this.changeBackgroundImage(background.unicorn); } if (value === 55) { this.changeBackgroundImage(background.mountains); } if (value === 56) { this.changeBackgroundImage(background.technicolor); } if (value === 57) { this.changeBackgroundImage(background.matrix); } if (value === 27) { this.returnToMainMenu(); } } } }; Game.prototype.mainMenu = function(keysDown) { for (var key in keysDown) { var value = Number(key); if (value === 78) { this.startNormalMode(); this.player2.slime.ai = false; } if (value === 90) { this.startNormalMode(); this.player2.slime.ai = true; } if (value === 88) { this.startInsaneMode(); this.player2.slime.ai = true; } if (value === 73) { this.startInsaneMode(); this.player2.slime.ai = false;} if (value === 81) { this.showInstructions = true; } } }; Game.prototype.displayInstructions = function(keysDown) { for (var key in keysDown) { var value = Number(key); if (value === 13) { this.showInstructions = false; } } }; module.exports = Game;
/* * * * Complete the API routing below * * */ 'use strict'; require('dotenv').config(); var expect = require('chai').expect; var MongoClient = require('mongodb').MongoClient; var ObjectId = require('mongodb').ObjectID; function connect(callback) { MongoClient.connect(process.env.DB, function(err, db) { if(err) console.error(err); callback(db); console.log("Server connected"); }); } module.exports = function (app) { app.route('/api/issues/:project') .get(function (req, res){ var project = req.params.project; var queries = req.query; if(project) { connect((db) => { db.collection(project).find(req.query).toArray(function(err, results) { if(err) console.error(err); res.send(results); }) }) } else { res.status(500).send("cannot find project issue colection name in request query url") } }) .post(function (req, res) { var project = req.params.project; var data = req.body; if(project && data.issue_title && data.issue_text && data.created_by) { var issueData; var date = new Date(); connect((db) => { db.collection(project).findOne({issue_title: data.issue_title}, function(err, issue) { if(err) console.error(err); if(issue) { res.status(500).send("issue already exists"); } else { issueData = req.body; issueData.created_on=date.toString(); issueData.updated_on = date.toString(); issueData.open=data.open ? data.open : true; issueData.assigned_to=data.assigned_to ? data.assigned_to : ""; issueData.status_text=data.status_text ? data.status_text : ""; issueData._id = new ObjectId(); db.collection(project).insertOne(issueData, function(err, issue) { if(err) console.error(err); res.send(issue.ops[0]); }) } }) }) } else { res.status(500).send("cannot find one of the required keys for request body: issue_title, issue_text, created_by") } }) .put(function (req, res){ var project = req.params.project; var data = req.body || {}; var issueData = {}; if(Object.keys(data).length <= 1) { res.status(500).send("no updated field sent"); } else if(project && data._id && data._id.length == 24) { var issueId = data._id; delete data._id; for(const key in data) { issueData[key] = data[key]; } issueData.updated_on = new Date().toString(); connect((db) => { db.collection(project).updateOne({_id: ObjectId(issueId)}, {$set: issueData}, {upsert: false}, function(err, issue) { if(err){ console.error(err); res.status(500).send("could not update " + data._id) } else { res.send("successfully updated"); } }) }) } else { res.status(500).send("cannot find _id in request body") } }) .delete(function (req, res){ var project = req.params.project; if(project && req.body._id) { connect((db) => { db.collection(project).deleteOne({_id: req.body._id}, function(err, db_res) { if(err) { console.error(err); res.status(500).send("could not delete " + req.body._id) } else { res.send("deleted " +req.body._id) } }) }) } else { res.send("_id error") } }); };
import { expect } from "chai"; import { cleanIt, jsdom, hideConsoleError, getSinon as sinon } from "../index"; describe("Test reshow-unit-dom", () => { beforeEach(() => { jsdom(); }); afterEach(() => { cleanIt(); }); it("basic testt", () => { /*your test code*/ cleanIt(); expect(document.body.innerHTML).to.equal(""); }); }); describe("Test hideConsoleError", () => { it("test throw", () => { hideConsoleError(true); expect(() => console.error("foo")).to.throw("foo"); }); it("test spy", () => { const spy = sinon().spy(() => {}); hideConsoleError(spy); console.error("foo"); expect(spy.called).to.be.true; }); });
const mongoose = require('mongoose'); const BattleshipsStateSchema = mongoose.Schema({ room: { type: mongoose.Schema.Types.ObjectId, }, playerOneState: Object, playerTwoState: Object }); BattleshipsStateSchema.statics.destroy = function(room, cb) { return this.findOneAndDelete({ room: room }, cb); } BattleshipsStateSchema.statics.updateState = function(room, update, cb) { return this.findOneAndUpdate({ room: room }, update, { upsert: true, new: true }).lean().exec(cb); } mongoose.model('BattleshipsState', BattleshipsStateSchema);
var thumb164="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";
import { assert, match, spy, stub } from 'sinon'; import { expect } from 'chai'; import proxyquire from 'proxyquire'; describe('session', () => { let mod, deps, FileNames, filenamesInstance; beforeEach(() => { filenamesInstance = { resolveSession: stub().returns('session.json') }; FileNames = { build: stub().returns(filenamesInstance) }; deps = { '../config': { FileNames: FileNames }, '../config/types': { fromPath: stub().returns([]) }, 'fs-extra': { existsSync: stub().returns(false) } }; mod = proxyquire('../../../../lib/question/session', deps); }) describe('build', () => { beforeEach(() => { mod.Session.build('dir', { args: true }); }); it('calls Filenames.build', () => { assert.calledWith(FileNames.build, { args: true }); }); it('calls resolveSession', () => { assert.calledWith(filenamesInstance.resolveSession, 'dir'); }); it('calls existsSync', () => { assert.calledWith(filenamesInstance.resolveSession, 'dir'); }); }); describe('reload', () => { let s; beforeEach(() => { s = new mod.Session('dir/session.json'); deps['fs-extra'].existsSync.returns(true); s.reload(); }); it('calls fromPath', () => { assert.calledWith(deps['../config/types'].fromPath, 'dir/session.json'); }); }); });
import index from './components/index' import { connect } from 'react-redux' const TmOptionContainer = connect()(index) export default TmOptionContainer
module.exports = () => { const validator = require('validator'); function loginInput(data) { const response = { message: {}, isValid: true, }; data.email = data.email ? data.email : ''; if (!validator.isEmail(data.email)) { response['message']['email'] = 'Invalid email!'; } if (!data.email) { response['message']['email'] = 'Email field is required!'; } if (Object.keys(response['message']).length) { response['isValid'] = false; } return response; } function RegisterInput(data) { const response = { message: {}, isValid: true, }; data.email = data.email ? data.email : ''; if (!validator.isEmail(data.email)) { response['message']['email'] = 'Invalid email!'; } if (!data.email) { response['message']['email'] = 'Email field is required!'; } if (!data.name) { response['message']['name'] = 'Name field is required!'; } if (Object.keys(response['message']).length) { response['isValid'] = false; } return response; } return { loginInput, RegisterInput, }; };
jsonRacks = {"fNames": [], "fRacks" : [] }; var boatsThatAreOnWater = []; var boatsThatAreOnWaterExtra = []; function FillRacks(elementRacks) { var countBoats = 0; var countDamaged = 0; var countOut = 0; console.log("RACKS " + jsonRacks.fNames); var total = "<table id=\"boathouse\">"; total += "<tr><td>\n"; for (var i=0; i<jsonRacks.fNames.length; i+=1) { if (i == 0 || i == 2 || i == 4 || i == 6) { total += "</td></tr><tr><td>\n"; } console.log("RACKS " + i + " is " + jsonRacks.fNames); total += " <div class=\"" + jsonRacks.fNames[i][1] + "\" id=\"" + jsonRacks.fNames[i][0] + "\">\n"; total += " <ul>\n"; total += " <li class=\"bay\">" + jsonRacks.fNames[i][0] + "</li>\n"; var rightOf = (i==1 || i==3 || i==5 || i==7 || i == 9); for (var j=jsonRacks.fRacks[i].length-1; j >= 0; j-=1 ) { var name = jsonRacks.fRacks[i][j][0]; var grade = jsonRacks.fRacks[i][j][1]; var uppers = name.toUpperCase(); var index = boatsThatAreOnWater.indexOf(uppers); var classes = ""; if (index >= 0) { classes = "red "; countOut += 1; } if (grade == "damaged") { classes += "damaged "; countDamaged +=1; } if (classes) { total += " <li class=\"" + classes + "\">"; } else { total += " <li>"; } if (index >= 0) { total += "<a href=\"#\">" + "<span class=\"tooltip\">" + boatsThatAreOnWater[index] + " out since " + boatsThatAreOnWaterExtra[index][0] + " at " + boatsThatAreOnWaterExtra[index][1] + "</span></a>"; } if (name == "&nbsp;") { total += name; } else if (!grade) { total += name; countBoats +=1; } else if (rightOf) { countBoats +=1; total += name + "&nbsp;<img height=\"16\" src=\"https://srecko.ca/ARC/images/cat-" + grade + ".png\">"; } else { countBoats +=1; total += "<img height=\"16\" src=\"https://srecko.ca/ARC/images/cat-" + grade + ".png\">&nbsp;" + name; } total += "</li>\n"; } total += " </ul>\n"; total += " </div><!-- " + jsonRacks.fNames[i][0] + " -->\n"; } total += "</td></tr></table>\n"; console.log("TOTAL IS " + total); document.getElementById(elementRacks).innerHTML = total; var stats = "" + countBoats + " boats"; if (countDamaged) { stats += ", " + countDamaged + " damaged"; } if (countOut) { stats += ", " + countOut + " on the water"; } return stats; } function UpdateStatus(jsonIn) { boatsThatAreOnWater = []; boatsThatAreOnWaterExtra = []; //boatsThatAreOnWater = ["4+ FINLESS '52", "4X DYNAMIC",]; //boatsThatAreOnWaterExtra = [["Today","9am"],["Also today", "8am"],]; if ("entry" in jsonIn.feed) { var entries = jsonIn.feed.entry; for (var i=0; i<entries.length; i+=1) { boatsThatAreOnWater.push(entries[i].gsx$boat.$t.toUpperCase()); boatsThatAreOnWaterExtra.push([entries[i].gsx$date.$t, entries[i].gsx$time.$t]); } } } function AssignedBoats(jsonIn) { var entries = jsonIn.feed.entry; console.log("HERE IS THE INCOMING JSON " + entries); var i; jsonRacks.fNames = []; jsonRacks.fRacks = []; for (var i = 0; i < 9; i++) { jsonRacks.fRacks.push([["&nbsp;",""], ["&nbsp;",""], ["&nbsp;",""], ["&nbsp;",""], ["&nbsp;",""], ["&nbsp;",""], ["&nbsp;",""], ["&nbsp;",""], ["&nbsp;",""],]); jsonRacks.fNames.push(["", ""]); } console.log("RACKS INITIAL " + jsonRacks.fRacks.length + " = " + jsonRacks.fRacks); console.log("NAMES INITIAL " + jsonRacks.fNames.length + " = " + jsonRacks.fNames); for (var i=0; i<entries.length; i+=1) { var boat = ("" + entries[i].gsx$boats.$t).toLowerCase() .split(' ').map(word => word.charAt(0).toUpperCase() + word.substring(1)) .join(' ').replace("Ii", "II"); console.log("TOWER ENTRY " + entries[i].gsx$tower.$t); var tower_def = entries[i].gsx$tower.$t.split(" - "); console.log("TOWER DEF " + tower_def.length + " = " + tower_def); var tower_name = tower_def[0]; var tower = parseInt(tower_def[2]); var leftOrRight = "X"; if (tower_name[1] == "W") { leftOrRight = "L"; } else if (tower_name[1] == "E") { leftOrRight = "R"; } console.log("BOAT " + boat + " TOWER_DEF " + tower_name + " and index " + tower + " LorR " + leftOrRight); var rack = parseInt(("" + entries[i].gsx$rack.$t).split(" / ")[0]); var type = entries[i].gsx$type.$t; var grade = entries[i].gsx$grade.$t.toLowerCase(); console.log("RACK " + rack + " TYPE " + type + " GRADE " + grade); if (tower >= 0 && rack >= 0) { console.log("TOWER INDEX " + tower + " out of " + jsonRacks.fNames.length); if (jsonRacks.fNames[tower][0] == "") { jsonRacks.fNames[tower][0] = tower_name; // This one gives us the correct CSS - racksL or racksR jsonRacks.fNames[tower][1] = "racks" + leftOrRight; } while (jsonRacks.fRacks[tower].length <= rack) { jsonRacks.fRacks[tower].push(["&nbsp;",""]); } if (jsonRacks.fRacks[tower][rack][0] != "&nbsp;") { console.log("Clobber " + tower + ", " + rack + " with " + boat); } jsonRacks.fRacks[tower][rack] = [type + " " + boat, grade]; } } } function DockStatus(jsonIn) { var entries = jsonIn.feed.entry; var el = document.getElementById("dockstatus"); if (el) { el.innerHTML = entries[0].gsx$dockstatus.$t; } el = document.getElementById("dockstatusdetails"); if (el) { el.innerHTML = entries[1].gsx$dockstatus.$t; } }
import React, { useState, useEffect } from 'react' import { Layout, Button, Divider, Form, Switch, notification, Typography, Input } from 'antd' import Module from '../../../Components/Module' import { useSelector, useDispatch } from 'react-redux' import socket from '../../../Services/socket' import api from '../../../Services/api' const { Title } = Typography const WatsonSettingsPage = () => { const [loading, setLoading] = useState(false) const settings = useSelector(state => state.Settings) const dispatch = useDispatch() const changeSettings = data => { dispatch({ type: 'CHANGE_SETTINGS_DATA', Settings: data }) } const getData = async () => { socket.emit('settings') socket.on('settings', changeSettings) } const getSetting = (name) => { let setting = settings.find(v => v.name === name) return setting ? setting.value : null } const handleChange = ({ name, value }) => { let x = settings.filter(v => v.name !== name) x.push({name, value}) changeSettings(x) } const handleSubmit = () => { setLoading(true) settings.forEach(async ({ name, value }) => { try { await api.post('/setting', { name,value }) } catch (e) { notification.error({ message: `Failed to save setting ${name} with value ${value}!` }) } }) notification.success({ message: 'Settings updated successfully!' }) setLoading(false) } useEffect(() => { getData() }, []) const formLayout = { labelCol: { span: 5 }, wrapperCol: { span: 19 } } return ( <Layout> <Module> <Button onClick={handleSubmit} loading={loading} type='primary'>Save settings</Button> </Module> <Module title={<Title level={4}>IBM Watson</Title>}> <Divider/> <Form {...formLayout}> <Form.Item label='Service enabled'> <Switch checked={getSetting('watson_enabled')} onChange={(value) => handleChange({ name: 'watson_enabled', value })}/> </Form.Item> <Form.Item label='Watson key'> <Input value={getSetting('watson_key')} onChange={(e) => handleChange({ name: 'watson_key', value: e.target.value })} placeholder='Insert Watson key here'/> </Form.Item> <Form.Item label='Watson URL'> <Input value={getSetting('watson_url')} onChange={(e) => handleChange({ name: 'watson_url', value: e.target.value })} placeholder='Insert Watson URL here'/> </Form.Item> </Form> <Module bordered={true} title={<Title level={4}>Prepaid</Title>}> <Form {...formLayout}> <Form.Item label='Assistant ID'> <Input value={getSetting('watson_id')} onChange={(e) => handleChange({ name: 'watson_id', value: e.target.value })} placeholder='Insert Watson prepaid cards assistant ID here'/> </Form.Item> </Form> </Module> <Module bordered={true} title={<Title level={4}>Steam</Title>}> <Form {...formLayout}> <Form.Item label='Assistant ID'> <Input value={getSetting('watson_steam_id')} onChange={(e) => handleChange({ name: 'watson_steam_id', value: e.target.value })} placeholder='Insert Watson Steam assistant ID here'/> </Form.Item> </Form> </Module> </Module> </Layout> ) } export default WatsonSettingsPage
describe('user input', function () { beforeEach(function () { browser.get('demo/index.html'); }); it('Should be with the initial value', function () { var pageTitle = element(by.id('span-result')); expect(pageTitle.getText()).toBe('Contador: 0'); }); it('Should be with the value 1 after one press ente', function () { var enterInput = element(by.id('input-enter')); enterInput.click(); browser.actions().sendKeys(protractor.Key.ENTER).perform(); var pageTitle = element(by.id('span-result')); expect(pageTitle.getText()).toBe('Contador: 1'); }); it('Should be with the value 4 after four press enter', function () { var enterInput = element(by.id('input-enter')); enterInput.click(); browser.actions().sendKeys(protractor.Key.ENTER).perform(); browser.actions().sendKeys(protractor.Key.ENTER).perform(); browser.actions().sendKeys(protractor.Key.ENTER).perform(); browser.actions().sendKeys(protractor.Key.ENTER).perform(); var pageTitle = element(by.id('span-result')); expect(pageTitle.getText()).toBe('Contador: 4'); }); });
function smallestCommons(arr) { var result; var mult = 0; var first; var last; var numbers = []; if (arr[0] === arr[1]) { return arr[0]; } var sortedArr = arr.sort(function(a, b) { return a - b; }); first = sortedArr[0]; last = sortedArr[1]; for (var i = last; i >= first; i--) { numbers.push(i); } while (true) { mult += 1; result = arr[0] * mult; for (var i = 0, length = numbers.length; i < length; i++) { if (result % numbers[i]) { break; } else if (i === length - 1) { return result; } } } } module.exports = smallestCommons;
import React, {useState} from 'react'; import firebase from "./firebase"; const Person = ({personInformations}) => { const [name, setName] = useState(personInformations.name); const onUpdate = () => { const db = firebase.firestore(); db.collection("people").doc(personInformations.id).set({...personInformations, name}); }; const onDelete = () => { const db = firebase.firestore(); db.collection("people").doc(personInformations.id).delete(); }; return ( <div style={{margin: "20px 0"}}> <input value={name} onChange={event => setName(event.target.value)} /> <button onClick={onUpdate}>UPDATE</button> <button onClick={onDelete}>DELETE</button> </div> ); }; export default Person;
import React, { Component } from 'react'; import NavBar from '../src/components/navBar'; import './App.scss'; import Footer from "../src/components/footer"; import { Route, BrowserRouter as Router, Link, Switch } from 'react-router-dom'; import ReactGA from 'react-ga'; import Home from './components/Project' import Prices from './components/prices' import VCita from './components/vcita' ReactGA.initialize('UA-193645917-1'); ReactGA.pageview(window.location.pathname + window.location.search); export default function App() { return ( <div> <NavBar /> <Switch> <Route exact from="/" render={(props) => <Home {...props} />} /> <Route exact path="/prices" render={(props) => <Prices {...props} />} /> <Route exact path="/vcita" render={(props) => <VCita {...props} />} /> </Switch> <Footer/> </div> ); }
import React from 'react' import axios from "axios"; import { Link } from 'react-router-dom' import { ToastContainer, toast } from 'react-toastify'; import CarsRow from './CarsRow'; class CarAdd extends React.Component { constructor(props) { super(props); this.driver_id = props.match.params.id; this.state = { cars: [] } } componentDidMount = () => { this.fetchCars() } fetchCars = () => { console.log("fetch cars"); axios.get(`http://localhost:3001/drivers/${this.driver_id}/cars`) .then((response) => { console.log(response.data); this.setState({ cars: response.data.cars, }) }).catch((error) => { console.log(error); }) } handleUpdate = (id, driver_data) => { console.log("save Driver"); axios.put(`http://localhost:3001/drivers/${id}/cars`, driver_data) .then((response) => { console.log(response); toast.success(response.data.message); this.fetchCars(); }).catch((error) => { let status = error.response.status; let message = error.response.data.message; console.log(status, message); if (error.response) { toast.warn(message) } else if (error.request) { // `error.request` is an instance of XMLHttpRequest in the browser and an instance of // http.ClientRequest in node.js toast.error(message) } else { // Something happened in setting up the request that triggered an Error toast.error(message) } }) } handleAdd = () => { } render() { let { cars } = this.state; let cars_list = cars.map((car) => <CarsRow key={car.id} car={car} handleUpdate={this.handleUpdate} /> ); return ( <div className="container"> <div className="row justify-content-end"> <div class="col-1"> <button type="button" className="btn btn-primary" onClick={this.handleAdd}>Add</button> </div> </div> <div className="row"> <table className="table drivers-table"> <caption>Cars</caption> <thead> <tr> <th>id</th> <th>Model</th> <th>Active</th> <th>Type</th> <th>Amenities</th> <th>Actions</th> </tr> </thead> <tbody> {cars_list} </tbody> </table> </div> <ToastContainer autoClose={2000} /> </div> ) } } export default CarAdd
import React, { Component } from "react"; import { Link } from "react-router-dom"; class Product extends Component { onDelete = product => { //eslint-disable-next-line if (confirm("Do you want to delete this product")) { this.props.onDelete(product); } }; render() { var { product, index } = this.props; return ( <tr> <td>{index + 1}</td> <td>{product.name}</td> <td>{product.status === true ? "Còn hàng" : "Hết hàng"}</td> <td>{product.price}$</td> <td> <Link to={`/product/${product.id}/edit`} className="btn btn-warning"> <i className="fa fa-edit" /> Edit </Link> <button className="btn btn-danger m-l" onClick={() => this.onDelete(product.id)} > <i className="fa fa-close" /> Delete </button> </td> </tr> ); } } export default Product;
wms.controller('UserMasterListCtrl', function ($scope, $http, $location, $filter, $q, UserService, Auth) { $scope.last_status = 'Created'; $scope.lastitem = {}; $scope.detail = {} $scope.header = {} $scope.expand = 0 $scope.squeeze = 100 var app_parameters = Auth.getAppParameters() var client = app_parameters.client; var warehouse = app_parameters.warehouse; var baseUrl = '/user_master_maintenance'; $scope.warehouse = [ {value: 'WH1', text: 'PDC'}, {value: 'WH2', text: 'WDC'} ]; $scope.roles = [ {value: 'admin', text: 'Admin'}, {value: 'warehouse_manager', text: 'Warehouse Manager'}, {value: 'warehouse_associate', text: 'Warehouse Associate'}, ]; $scope.search_items = [ {value: 'user_name', text: 'User Name'}, {value: 'user_id', text: 'User Id'} ]; $scope.search_choice = $scope.search_items[0] $scope.choose = function(choice) { $scope.search_choice = choice; $scope.item_list = [] angular.forEach($scope.items, function(item) { $scope.item_list.push(item["user_header"][$scope.search_choice.value]); }); } $scope.item = 'new user'; $scope.header_template = { name: 'header_template', url: '/templates/user_maintenance/user_header.html' }; $scope.detail_template = { name: 'detail_template', url: '/templates/user_maintenance/user_detail.html' }; $scope.showUser = function(show, user, user_detail_id) { var url = baseUrl + '/'+ user + '.json' $http.get(url).success(function(data) { $scope.user_header = data.user_header $scope.user_details = data.user_detail console.log($scope.user_header); if (show == 'Header') { $scope.header.show = true $scope.detail.show = false } else { $scope.detail.show = true $scope.header.show = false angular.forEach($scope.user_details, function (user_detail) { if (user_detail.id == user_detail_id) { $scope.user_detail = user_detail; } }); } }); $scope.expand = 50 $scope.squeeze = 50 $scope.selected_header_id = user $scope.selected_detail_id = user_detail_id } $scope.hideUser= function() { $scope.header.show= false $scope.detail.show= false $scope.expand = 0 $scope.squeeze = 100 }; $scope.toggleExpand = function(item) { item.show = !item.show; lastitem = item; }; $scope.expand = function(item) { item.show = true; }; $scope.editUser= function(header_id, detail_id) { var url = baseUrl + '/edit/'+ header_id + '/' if(detail_id != null) { url += detail_id } $location.path(url); } $scope.updateHeader = function(data, el, id) { var d = $q.defer(); var url = baseUrl + '/'+ id d = UserService.updateResource(data, el, id, url, $scope, d); return d.promise; }; $scope.init = function() { var url = baseUrl + '.json?client=' + client + '&warehouse='+ warehouse; $http.get(url).success(function(data) { $scope.items = data; $scope.item_list = [] $scope.filter_from_object = "user_header" $scope.filter_from_field = "user_name" UserService.set_page($scope); $scope.status('*All'); angular.forEach($scope.items, function(item) { $scope.item_list.push(item["user_header"][$scope.search_choice.value]); }); }); }; $scope.init(); });
'use strict'; const Service = require('egg').Service; class UserService extends Service { async findOne(params) { const user = await this.app.mysql.get('tbl_widm_user', params); return { user }; } } module.exports = UserService;