text
stringlengths
7
3.69M
import ContainerFirebase from "../../Containers/ContainerFirebase.js"; class ProductosDaoFirebase extends ContainerFirebase { constructor() { super('productos'); } } export default ProductosDaoFirebase
const { Command } = require("discord-akairo"); const { CreateEmbed } = require("../../Utility/CreateEmbed"); const fetch = require("node-fetch"); module.exports = class QuoteCommand extends Command { constructor() { super("quote", { aliases: ["quote", "aq", "animequote"], description: { content: "return an anime quote", usage: "quote", example: ["quote"], }, category: "anime", cooldown: 3000, }); } /** * * @param {import('discord.js').Message} msg * @returns */ async exec(msg) { try { const body = await fetch("https://animechan.vercel.app/api/random"); let resp = await body.json(); let embed = CreateEmbed("info", resp.quote).setTitle(resp.character); msg.reply({ embeds: [embed], allowedMentions: { repliedUser: false } }); } catch (e) { this.client.logger.error(e.message); msg.channel.send(CreateEmbed("warn", "⛔ | An error occured")); } } };
import styled from "styled-components"; import Dialog from "~/components/atoms/dialog/Dialog"; const StyledIconGallery = styled(Dialog)` .icon-collection { display: flex; margin: -4px; flex-wrap: wrap; .icon-button { border-radius: 3px; margin: 4px; width: 42px; height: 42px; border: solid 1px #e0e0e0; } } `; export {StyledIconGallery};
const express = require('express'); const { body, validationResult } = require('express-validator'); const { isAuth, isAdmin } = require("../config/auth"); const BookController = require('../controllers/BookController'); const User = require('../models/User'); const router = express.Router(); router.get('/books', isAuth, BookController.findAllBooks); router.get('/books/:id', isAuth, isAdmin, BookController.findBookById); router.get('/book_num/:id', isAuth, isAdmin, BookController.numberOfBooks); router.post('/add-new', [ body('price') .isNumeric() , body('name') .isLength({ min: 3, max: 15 }) .isAlphanumeric() .trim(), body('description') .isLength({min:10,max:150}), body('price') .isNumeric({ min: 1, max: 10000 }), body('quantity') .isNumeric({ min: 1, max: 10 }), body('pages') .isNumeric({ min: 10, max: 50000 }) ], isAuth, BookController.addNew); router.post('/edit-book', isAuth, BookController.postEditProduct); router.post('/book_inc/:id', isAuth, BookController.AddOneBook); router.post('/book_dec/:id', isAuth, BookController.RemoveOneBook); router.delete('/delete-book', isAuth, BookController.postDeleteProduct); router.get('/values', isAuth, BookController.getMoney); module.exports = router;
chrome.browserAction.onClicked.addListener(function(tab) { chrome.tabs.sendMessage(tab.id, { command: "LoadReviews" }, function(msg) { console.log("Response", msg); }); });
var server = require("net") ; server.createServer(onRequest).listen(8080) ; console.log("Server is up and running") ; var clients = new Array() ; function onRequest(socket) { clients.push(socket) ; socket.on('data', function(data) { for (var i = 0 ; i < clients.length ; i ++) { if (clients[i] == socket) continue ; clients[i].write(data) ; } }) ; socket.on('end', function() { var i = clients.indexOf(socket) ; clients.splice(i, 1) ; }) ; }
import React from 'react' import ReactDOM from 'react-dom' class Home extends React.Component { render() { return ( <div className='home'> <h1>Pokemon times!</h1> <img src='images/rapidash.png' className='pokemon' alt='A horse type Pokemon named Rapidash'/> <input className='search-box' type='text' placeholder='Enter the name of a Pokemon...'/> <button type className='button'>Search NOW!</button> </div> ) } } const app = document.getElementById('app') ReactDOM.render(<Home />, app)
import 'common' import Vue from 'vue' // import axios from 'axios' import VueResource from 'vue-resource' import App from './Index.vue' // 生产环境提示,这里设置成了false Vue.config.productionTip = false // Vue.prototype.$http = axios Vue.use(VueResource); // 全局注册 //解决click点击300毫秒延时问题 import FastClick from 'fastclick'; FastClick.attach(document.body); // 4. 创建、挂载根实例 new Vue({ render: h => h(App), data: { eventHub: new Vue() // 事件(中心)枢纽 } }).$mount('#app')
/** * Created by hanqian18790 on 2017/2/15. */ require.config({ //path映射那些不直接放置于baseUrl下的模块名 paths: { "angular":"lib/angular/angular.min", "angularRoute":"lib/angular-route/angular-route", //"bootstrap":"", "app":"app.module", "appConfig":"app.config", "module1Module":"module1/module1.module", "module1Ctrl":"module1/module1", "module2Module":"module2/module2.module", //"module2Ctrl":"module2/module2", }, //shim: 为那些没有使用define()来声明依赖关系、设置模块的"浏览器全局变量注入"型脚本做依赖和导出配置。 shim: { "angular": { exports: "angular" }, "angularRoute": { deps: ['angular'], exports: "angularRoute" }, "app": { deps: ['angular','angularRoute'], exports: "app" }, "appConfig": { deps: ['app'], exports: "appConfig" }, "module1Module": { exports: "module1Module" }, "module1Ctrl": { exports: "module1Ctrl" }, "module2Module": { exports: "module2Module" } } }); require( [ "angular", "angularRoute", "app", "appConfig", "module1Module", "module1Ctrl", "module2Module", ], function (angular) { console.log("----------"); angular.bootstrap(document, ["app"]); });
(function (window) { 'use strict'; function View(template) { this.template = template; } View.prototype.render = function (viewCmd, parameter) { var viewCommands; var self = this; viewCommands = { }; viewCommands[viewCmd](); }; View.prototype.bind = function (event, handler) { var self = this; switch (event) { } }; // Export to window window.app = window.app || {}; window.app.View = View; }(window));
var canvas = document.getElementById("myCanvas") var Game = { ctx: canvas.getContext("2d"), ballRadius: 10, x: canvas.width / 2, y: canvas.height - 30, dx: 2, dy: -2, paddleHeight: 75, paddleWidth: 10, paddleY: (canvas.height - this.paddleHeight) / 2, aiPaddleY: (canvas.height - this.paddleHeight) / 2, upPressed: false, downPressed: false, userScore: 0, aiScore: 0, keyDownHandler: function (e) { if (e.key == "Down" || e.key == "ArrowDown") { this.upPressed = true; } else if (e.key == "Up" || e.key == "ArrowUp") { this.downPressed = true; } }, keyUpHandler: function (e) { if (e.key == "Down" || e.key == "ArrowDown") { this.upPressed = false; } else if (e.key == "Up" || e.key == "ArrowUp") { this.downPressed = false; } }, drawCircle: function () { this.ctx.beginPath(); this.ctx.arc(canvas.width / 2, canvas.height / 2, 80, 0, Math.PI * 2); this.ctx.strokeStyle = "#fff"; this.ctx.stroke(); this.ctx.closePath(); }, resetBall: function () { this.x = canvas.width / 2; this.y = canvas.height / 2; this.dx = -(this.dx); }, drawUserScore: function () { this.ctx.font = "50px Arial"; this.ctx.fillStyle = "#fff"; this.ctx.fillText(this.userScore, 240, 80); }, drawAIScore: function () { this.ctx.font = "50px Arial"; this.ctx.fillStyle = "#fff"; this.ctx.fillText(this.aiScore, 430, 80); }, drawBall: function () { this.ctx.beginPath(); this.ctx.arc(this.x, this.y, this.ballRadius, 0, Math.PI * 2); this.ctx.fillStyle = "#fff"; this.ctx.fill(); this.ctx.closePath(); }, drawPaddle: function () { this.ctx.beginPath(); this.ctx.rect(0, this.paddleY, this.paddleWidth, this.paddleHeight); this.ctx.fillStyle = "#fff"; this.ctx.fill(); this.ctx.closePath(); }, drawAIpaddle: function () { this.ctx.beginPath(); this.ctx.rect(canvas.width - this.paddleWidth, this.aiPaddleY, this.paddleWidth, this.paddleHeight); this.ctx.fillStyle = "#fff"; this.ctx.fill(); this.ctx.closePath(); }, draw: function () { this.ctx.clearRect(0, 0, canvas.width, canvas.height); this.drawBall(); this.drawUserScore(); this.drawAIScore(); this.drawPaddle(); this.drawAIpaddle(); if (this.x + this.dx > canvas.width - this.ballRadius) { //To be modified to cancel increasing the score when the AI paddle hits the ball if (this.y > this.aiPaddleY && this.y < this.aiPaddleY + this.paddleHeight) { this.dx = -(this.dx); } else { ++this.userScore; this.resetBall() } } else if (this.x + this.dx < this.ballRadius) { if (this.y > this.paddleY && this.y < this.paddleY + this.paddleHeight) { this.dx = -(this.dx); } else { ++this.aiScore; this.resetBall() } } if (this.y + this.dy > canvas.height - this.ballRadius || this.y + this.dy < this.ballRadius) { this.dy = -(this.dy); } if (this.upPressed) { this.paddleY += 7; if (this.paddleY + this.paddleHeight > canvas.height) { this.paddleY = canvas.height - this.paddleHeight; } } else if (this.downPressed) { this.paddleY -= 7; if (this.paddleY < 0) { this.paddleY = 0; } } //Move the AI Paddle let computerLevel = 0.1; this.aiPaddleY = (((this.y - (this.aiPaddleY + this.paddleHeight / 2))) * 0.5); this.x += this.dx; this.y += this.dy; } } (function(){ ;document.addEventListener("keydown", Game.keyDownHandler, false); ;document.addEventListener("keyup", Game.keyUpHandler, false); ;var interval = setInterval(Game.draw, 10); })();
import * as types from '../actions/ActionTypes'; import initialState from './InitialState'; import Util from '../util'; export default function tenanstLeaseReducer(state = initialState, action) { switch (action.type) { case types.GET_TENANT_LEASE_SUCCESS: var leaseList= Util.getLeaseList(action.tenantData); return Object.assign({}, state, {leaseData: leaseList}, {leaseInfo: action.tenantData}); case types.GET_TENANTS_SUCCESS: return Object.assign({}, state, {tenants: action.tenants}); default: return state; } }
var requestURL = ' https://ghibliapi.herokuapp.com/films'; var request = new XMLHttpRequest(); var button = document.querySelector('button'); var movieList = document.querySelector('main'); var watchList = document.querySelector('.watchlist'); request.open('GET', requestURL); request.responseType = 'json'; request.send(); request.onload = function () { const movies = request.response; console.log(movies); showMovies(movies); } /* laat de films zien */ function showMovies(movies) { /* door de array met movies loopen */ for (let i = 0; i < 20; i++) { /* een container om de elementen van een film in te stoppen */ var filmDate = document.createElement('button'); let theMovie = document.createElement('article'); /* de elementen van een film */ let release_date = document.createElement('p'); let title = document.createElement('h2'); let description = document.createElement('p'); /* de elementen van de film vullen */ release_date.textContent = movies[i]['release_date']; title.textContent = movies[i]['title']; description.textContent = movies[i]['description']; /* de elementen aan de container toevoegen */ filmDate.appendChild(release_date); theMovie.appendChild(title); theMovie.appendChild(description); /* de container aan de main toevoegen */ document.body.querySelector("main").appendChild(filmDate); document.body.querySelector("main").appendChild(theMovie); /* Als er op de datum wordt geklikt, laat dan de info van de bijbehorende film zien */ filmDate.addEventListener('click', toggleMovieInfo); } } /* film laten zien functie */ function toggleMovieInfo(event) { var hetArticleNaDeButton = this.nextElementSibling; hetArticleNaDeButton.classList.toggle("show"); } /* sortable plugin om een watchlist te maken */ new Sortable(movieList, { group: 'shared', // set both lists to same group animation: 150 }); new Sortable(watchList, { group: 'shared', animation: 150 }); /* foto'tje onderaan veranderen */ var achtergrond = document.getElementById('achtergrond'); var ghibliFotos = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20']; var huidigeAchtergrond = 0; var maxAchtergrond = ghibliFotos.length; /* vorige en volgende met de pijltjes toetsen wat loopt */ function volgendeAchtergrond() { huidigeAchtergrond = huidigeAchtergrond + 1; if (huidigeAchtergrond >= maxAchtergrond) { huidigeAchtergrond = 0; } achtergrond.src = 'img/' + ghibliFotos[huidigeAchtergrond] + '.jpg'; } function vorigeAchtergrond() { huidigeAchtergrond = huidigeAchtergrond - 1; if (huidigeAchtergrond < 0) { huidigeAchtergrond = maxAchtergrond - 1; } achtergrond.src = 'img/' + ghibliFotos[huidigeAchtergrond] + '.jpg'; } /* het indrukken van de pijltjes toetsen. 37 is pijltje links en 39 is pijltje rechts */ document.onkeydown = function (e) { if (e.which == 37) { vorigeAchtergrond(e); } else if (e.which == 39) { volgendeAchtergrond(e); } };
const chai = require('chai'); const chaiHttp = require('chai-http'); // const asset = require('assert'); const server = require('../server/server').server; // const should = chai.should(); const port = 4080 chai.use(chaiHttp); describe('server', function() { before(done => { server.listen(port); done() }); })
import dispatcher from './dispatcher'; export default class Action { wrapRequest(promise, successConst, errorConst) { return promise.then( (data) => { this.dispatch(successConst, data); return data; }, (error) => { this.dispatch(errorConst, error); throw error; } ); } dispatch(actionType, data) { dispatcher.dispatch({ actionType: actionType, data: data }); } }
var business = {}, repository = { comment : require("./../repositories/commentRepository"), post : require("./../repositories/postRepository") }; business.create = function (req , res) { var comment = req.body, post = comment.post; delete comment.post; repository.comment.create(comment) .save(function (err, data){ if (err) res.handlerJson(err) else { var query = {_id : post}, mod = {"$push" : {comments : data._id}}; repository.post.update(query, mod) .exec(function (err, data){ if (err) res.handlerJson(err) else res.handlerJson(data) }) } }) } module.exports = business;
$(document).ready(function () { $('.custom').hide(); $("#custom_parent").change(function () { if ($(this).val() == "show") { $('.custom').show(); } else { $('.custom').hide(); } }); }); $(document).ready(function () { $('.custom1').hide(); $("#custom_parent1").change(function () { if ($(this).val() == "show") { $('.custom1').show(); } else { $('.custom1').hide(); } }); }); $(document).ready(function () { $('.custom2').hide(); $("#custom_parent2").change(function () { if ($(this).val() == "show") { $('.custom2').show(); } else { $('.custom2').hide(); } }); });
module.exports = { baseURL: 'http://170.78.75.70/api', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json; charset=utf-8' } };
//var path = require('path'); //var fs = require('fs'); //var lib = path.join(path.dirname(fs.realpathSync(__filename)), './lib'); //var server = require(lib + '/server.js'); //var request_handler = require(lib + '/request_handler.js'); //server.start_server('localhost', 8090, request_handler.request_handler); var express = require('express'); var formidable = require('formidable'); var email = require('mailer'); var app = express(); app.use(express.static(__dirname + '/public')); app.configure(function(){ app.use(express.bodyParser()); app.use(app.router); }); app.get('/', function (request, response) { response.redirect('msafwat.html'); }); app.get('/send_email_get', function (request, response) { response.setHeader('Content-Type', 'application/json'); response.send(JSON.stringify({ username: request.query.username, email: request.query.email, subject: request.query.subject, body: request.query.body })); }); app.post('/send_email', function (request, response) { if (request.method.toLowerCase() == 'post') { var d = request.body; email.send({ host : "smtp.gmail.com", port : "465", ssl : true, //domain : "i-visionblog.com", to : "mostafa.safwat.1@gmail.com", from : "mostafa.safwat.1@gmail.com", subject : "Moustafa Safwat - Senior Software Developer - CV", text: "Username: " + d.username + "\nEmail: " + d.email + "\nSubject: " + d.subject + "\nMessage: " + d.body + "\nTitle: " + d.title, html: "<span>Username: " + d.username + "</span><br/><span>Email: " + d.email + "</span><br/><span>Subject: " + d.subject + "</span><br/><span>Message: " + d.body + "</span><br/><span>Title: " + d.title + "</span>", authentication : "login", // auth login is supported; anything else $ username : 'mostafa.safwat.1@gmail.com', password : '' }, function(err, result){ if(err){ response.send("error occured"); } else { response.send("Email Sent");} }); // }); } }); app.listen(8080);
$(document).ready(function(){ 'use strict'; //alert('goo'); $('.nav-item').on('click', function(){ $(this).children('.nav-link').addClass('active').parent().siblings().children('.nav-link').removeClass('active'); $('#userRole').val($(this).data('role')); }); });
'use strict'; /** * Gulp Dependencies */ var gulp = require('gulp'); var util = require('gulp-util'); var $ = require('gulp-load-plugins')(); var sass = require('gulp-sass'); var autoprefixer = require('gulp-autoprefixer'); var sourcemaps = require('gulp-sourcemaps'); var sequence = require('gulp-sequence'); var production = util.env.production; /** * Styles compiler task */ gulp.task('styles', function() { gulp.src(['sass/styles.scss']) // .pipe(sourcemaps.init({ loadMaps: true })) .pipe(sass().on('error', sass.logError)) // .pipe(autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4')) // .pipe(production ? minifyCss(): util.noop()) // .pipe(production ? util.noop(): sourcemaps.write('./')) .pipe(gulp.dest('./css/')); }); /** * Watcher task */ gulp.task('watch', function() { gulp.watch('./sass/**/*.scss', ['styles']); }); /** * Development task */ gulp.task('dev', ['default', 'watch']); /** * Default task */ gulp.task('default', sequence('styles'));
import React from 'react'; import { Route } from "react-router-dom" import './App.css'; import Sidebar from './Sidebar'; import Welcome from './Welcome'; import ContextEx from './contextEx'; import ReducersEx from './Reducers'; function App() { return ( <div className="layout"> <div className="navbar"><strong>Mi's React examples</strong></div> <Sidebar></Sidebar> <div className="content"> <Route exact path="/" component={Welcome}></Route> <Route exact path="/context" component={ContextEx}></Route> <Route exact path="/reducers" component={ReducersEx}></Route> </div> </div> ); } export default App;
import React from 'react'; import PropTypes from 'prop-types'; import { withStyles } from '@material-ui/core/styles'; import Grid from '@material-ui/core/Grid'; import IdeaCard from './Card/Card' import Discussion from './Discussion' import "../w3.css"; import NewPost from './NewPost'; import SortBar from './SortBar'; const styles = theme => ({ root: { flexGrow: 1, margin: '0 auto', maxWidth: '120vh', paddingTop: '2vh', }, }); class IdeaFeed extends React.Component { constructor(props) { super(props) this.handler = this.handler.bind(this) this.closer = this.closer.bind(this) this.filter = this.filter.bind(this) this.del = this.del.bind(this) this.state = { list: [], discussion: false, openIdea: -1, } } componentDidMount() { fetch('/api/get/idea') .then(results => { return results.json(); }).then(data => { let random = JSON.stringify(data); //let dataArray = this.state.list.splice(); let fetchedData = [] for(var i = 0; i < data.length; i++) { let voteDirection = null; if(data[i]["votes"] && data[i]["votes"].length > 0) { voteDirection = data[i]["votes"][0]["is_upvote"]; } let randomIdea = { title: data[i]["title"], description: data[i]["content"], net_votes: data[i]["net_votes"], photo_url: data[i]["photo_url"], id: data[i]["id"], voteDirection: voteDirection, author: data[i]["userNetid"] }; fetchedData = [randomIdea,...fetchedData]; } this.setState({ list: fetchedData }); }); } componentWillReceiveProps(nextProps) { let request = '/api/get/idea/search/' + nextProps["query"] if(nextProps["query"] === '' || nextProps["query"] === null) { request = '/api/get/idea' } fetch(request) .then(results => { return results.json(); }).then(data => { let random = JSON.stringify(data); //let dataArray = this.state.list.splice(); let fetchedData = [] for(var i = 0; i < data.length; i++) { let voteDirection = null; if(data[i]["votes"] && data[i]["votes"].length > 0) { voteDirection = data[i]["votes"][0]["is_upvote"]; } let randomIdea = { title: data[i]["title"], description: data[i]["content"], net_votes: data[i]["net_votes"], photo_url: data[i]["photo_url"], id: data[i]["id"], voteDirection: voteDirection, author: data[i]["userNetid"] }; fetchedData = [randomIdea,...fetchedData]; } this.setState({ list: fetchedData }); }); } handler(param) { this.setState({ discussion: true, openIdea: param, }); } closer() { this.setState({ discussion: false, openIdea: -1, }); } filter(param){ this.setState({ list: param }); } del(){ this.componentDidMount(); } render () { const { classes } = this.props; var elements = this.state.list.map((item, id) => <IdeaCard discussion={this.handler} key={item.id} title={item.title} description={item.description} net_votes={item.net_votes} photo_url={item.photo_url} id={item.id} author={item.author} user={this.props.user} voteDirection={item.voteDirection} isLoggedInFunc={this.props.isLoggedInFunc} del={this.del}/>) if (this.state.discussion) { return ( <div> <Discussion idea={this.state.openIdea} close={this.closer} refresh={this.handler} user={this.props.user}/> </div> ); } else { return ( <div> <div className="w3-bar"> <SortBar className="w3-bar-item" filter={this.filter}/> <NewPost className="w3-bar-item" isLoggedInFunc={this.props.isLoggedInFunc}/> </div> {elements} </div> ); } } } export default withStyles(styles)(IdeaFeed);
const listadoRoles = ['Administrador', 'Usuario', 'Invitado']; const roles = { "Administrador": { "users": ["index", "new", "show", "edit", "delete"], "grupos": ["index", "new", "show", "edit", "delete"] }, "Usuario": { }, "Invitado": { } }; module.exports = {listadoRoles, roles};
'use strict'; var React = require('react-native'); var TourDetail = require('./TourDetail'); var Dimensions = require('Dimensions'); var windowSize = Dimensions.get('window'); var utils = require('../lib/utility'); var CreateTour = require('./CreateTour'); var styles = require('../lib/stylesheet'); var UIImagePickerManager = require('NativeModules').UIImagePickerManager; var { View, Text, Component, TouchableHighlight, AsyncStorage, NativeModules } = React; class SelectImage extends Component { /** * Creates an instance of SelectImage. * Allows the user to select or take a photo. Photo is translated into Base64 and uploaded to the database. * @constructor * @this {SelectImage} */ constructor(props) { super(props); this.state = { tourId: this.props.tourId || null, placeId: this.props.placeId || null, addPlaceView: this.props.addPlaceView || false, createTourView: this.props.createTourView || false, isRoutingFromEditPlace: this.props.isRoutingFromEditPlace || false }; } /** * This method is triggered when "Select Image" is pressed. It will launch an option to choose from * library or take a new photo utilizing a react-native module called UIImagePicker */ launchCamera () { var options = { title: 'Select a Tour Photo', cancelButtonTitle: 'Cancel', takePhotoButtonTitle: 'Take Photo...', chooseFromLibraryButtonTitle: 'Choose from Library...', maxHeight: 500, quality: 1, allowsEditing: true, noData: false, storageOptions: { skipBackup: true } }; UIImagePickerManager.showImagePicker(options, (didCancel, response) => { if(!didCancel) { this.submitSelection(response.data.toString()) if (response.takePhotoButtonTitle) { UIImagePickerManager.launchCamera(options, (didCancel, response) => { this.submitSelection(response.data.toString()) }); } } }); } /** * This method is triggered when a photo is selected or taken. It makes a post request to either tours/tourphoto * or tours/placephoto depending on the state. After post request has been made, navigator will route back to * ViewCreatedTour view. * @param encodedData - Base 64 encoding passed in from the UIImagePicker module */ submitSelection(encodedData) { var ViewCreatedTour = require('./ViewCreatedTour') var reqType = 'addTourPhoto'; var component = this; var props = { tourId: this.state.tourId, editMode: true }; var options = { reqParam: this.state.tourId, reqBody: { encodedData: encodedData } }; if(this.state.placeId !== null) { reqType = 'addPlacePhoto' options.reqParam = this.state.placeId } var that = this; utils.makeRequest(reqType, component, options) .then(response => { that.routeToNextComponent(); }) } routeToNextComponent() { if(this.props.createTourView || this.props.isRoutingFromEditPlace) { this.viewTour(); } else { this.viewRecordAudio(); } } viewRecordAudio() { var RecordAudio = require('./RecordAudio'); var props = { tourId: this.state.tourId, placeId: this.state.placeId } this.props.navigator.push({ title: "Your Tour", component: RecordAudio, passProps: props, leftButtonTitle: " " }) } /** * This method is triggered from pressing the skip option from the CreateTour route. It will replace this component * with the ViewCreatedTour component. */ viewTour() { var ViewCreatedTour = require('./ViewCreatedTour'); var tourId = this.state.tourId; this.props.navigator.push({ title: "Your Tour", component: ViewCreatedTour, passProps: {tourId: tourId, editMode: true}, leftButtonTitle: " " }); } /** * This renders if the previous component is from AddPlace or CreateTour to give the user an option to skip. * The AddPlace view will skip to the audio component while the CreateTour view will route to the ViewCreatedTour view. * @returns {XML} */ renderSkipOption () { if(this.state.createTourView) { return ( <View style={ [styles.mainContainer, {marginTop: 0}]}> <TouchableHighlight onPress={ this.launchCamera.bind(this) } underlayColor="#727272"> <View style={ [styles.mainButton, {width: 200, alignItems: 'center', marginBottom: 20}] }> <Text style={ styles.whiteFont }>Select Image</Text> </View> </TouchableHighlight> <TouchableHighlight onPress={ this.routeToNextComponent.bind(this) } underlayColor="#727272"> <View style={ [styles.mainButton, {width: 200, alignItems: 'center', marginBottom: 20}] }> <Text style={ styles.whiteFont }>Skip</Text> </View> </TouchableHighlight> </View> ) } else { return ( <View style={ [styles.mainContainer, {marginTop: 0}]}> <TouchableHighlight onPress={ this.launchCamera.bind(this) } underlayColor="#727272"> <View style={ [styles.mainButton, {width: 200, alignItems: 'center', marginBottom: 20}] }> <Text style={ styles.whiteFont }>Select Image</Text> </View> </TouchableHighlight> <TouchableHighlight onPress={ this.routeToNextComponent.bind(this) } underlayColor="#727272"> <View style={ [styles.mainButton, {width: 200, alignItems: 'center', marginBottom: 20}] }> <Text style={ styles.whiteFont }>Skip</Text> </View> </TouchableHighlight> </View> ); } } render() { if(this.state.addPlaceView || this.state.createTourView) { return this.renderSkipOption(); } else { return ( <View style={ [styles.mainContainer, {marginTop: 0}] }> <TouchableHighlight onPress={ this.launchCamera.bind(this) } underlayColor="#727272"> <View style={ [styles.mainButton, {width: 200, alignItems: 'center', marginBottom: 20}] }> <Text style={ styles.whiteFont }>Select Image</Text> </View> </TouchableHighlight> </View> ); } } }; module.exports = SelectImage;
/* @function: Create an array of values of a particular key presnt in array of Objects @parameter: arrObj: Array of objects @parameter: key: the key in object whose values need to be in the result array */ export const createArrayKeys = (arrObj, key) => { return arrObj.map(item => item[key]); }
import React, {Fragment} from 'react'; let paragraphs = props => { return ( <Fragment> <p className={props.info.type}> {props.info.text} </p> </Fragment> ) } export default paragraphs;
/* eslint-disable no-unused-vars,import/no-duplicates */ import axios from "axios/index"; import * as productAction from "./product.actions"; import { takeEvery, put, select } from "redux-saga/effects"; import customToastify from "../../customFunction/customToastify"; import { postRequest } from "../../api"; import { loader } from "../../components/Loader/Loader"; function *getAllProduct() { loader.show() try { const result = yield postRequest("getAllProducts", { }); yield put(productAction.setAllProduct(result.products)); } catch (error) { if (!error) { customToastify(error.message, "error"); } else { customToastify(error, "error"); } loader.hide(); } } export function* watchProduct() { yield takeEvery(productAction.getAllProductSaga, getAllProduct); }
const express = require('express'); //express 열어 보면 http 서버를 쓰고 있음. 내부적으로! const path = require('path');//경로를 확실히 하기 위해. /* 1. app을 만든다름 2. app에 관련된 설정을 set으로 해줌 3. 공통 미들웨어를 넣어주고 4. 라우터를 넣어줌(범위 넓을 수록 뒤로) 5. 그다음 에러 미들웨어를 넣어 줌 */ const app = express(); app.set('port', process.env.PORT || 3000);//서버에 속성을 심는것! port가 전역 변수가 됨 //포트를 입력 하지 않으면 기본적으로 3000 // SET PORT=80 이라고 터미널에 쳐서 바꿀 수 있지만 이렇게 하는 거 좋지 않음(다른 프로그램 할때도 80으로 될 수도 있기때문) app.use((req, res, next) => {//여기 함수가 미들웨어임. 라우터에 미들웨어를 장착 console.log('1번 모든 요청에 실행하고싶어요'); //메소드와 주소가 있는것을 라우터라 하는데 모든 라우터에 다 실행 되는 미들웨어임 next();//next를 넣어야 요청된 라우터 까지 같이 실행됨(다음 라우터 중에 일치 하는 것) //기본적으로 위에서 아래로 실행 되지만 미들웨어들은 next를 해줘야 다음 미들웨어로 넘어감 }, (req, res, next) => { console.log('2번 모든 요청에 실행하고싶어요'); next(); }, (req, res, next) => { console.log('3번 모든 요청에 실행하고싶어요'); next(); }, (req, res, next) => { //throw new Error('에러가 났어요'); //에러 몇번째 줄이라 표시됨. //express는 기본적으로 알아서 에러 처리해줌 //하지만 너무 상세하게 서버를 공개해서 에러 알려주기때문에 //직접 에러 처리를 해줘야한다. try{ console.log('에러어'); throw new Error('에러어어'); } catch(error){ next(error); //next()에 인수가 없으면 다음 미들웨어로 넘어가지만 //error 인수가 들어가 있으면 바로 에러처리 미들웨어로 넘어감 //next('route')를 한다면 같은 라우터에 다음 미들웨어가 아니라 //다른 라우터에 미들웨어가 실행됨 //다음 라우터 부터 다시 찾게 됨. //if문 같은거 안에다 넣을 수 있음. } });//모든 라우터에 다 실행되어서 중복을 피함 //메소드와 주소가 있는것을 라우터라함. //app.use('/about', ...)이라 하면 about에서만 실행됨! //req, res, next가 있는 '함수'를 미들웨어라함. //미들웨어를 한개에 여러개 넣어줄 수 있음. //next()를 만나면 밑으로 쭉 내려감(다음 미들웨어로.) app.get('/', (req, res) =>{//요청의 메소드와 url / if문으로 도배하지 않아도 됨. //res.sendFile(path.join(__dirname,'index.html')); //경로를 확실히 해서 html 서빙도 간단하게 express로 가능. //한 라우터에서 여러번 send할수 없다. //sendFile, send, json //next통해서 2번이상 나와도 에러남.(한개의 라우터에 하나만 !!) //이미 응답을 한번 보내면 끝남. //요청한번에 응답은 한번임!!! //응답 보낸다음 res.writeHead 뒤 늦게 해도 에러 //express는 http의 writeHead와 end를 합쳐둔것. //여기서도 쓸 수는 있음. (기본 http것 쓰는것 추천하지 않음) //res.json({hello: 'kim70273'}); return re.json...이라면 밑에가 실행 안됨 //console.log('hello'); res.json은 리턴이 아님 따라서 콘솔로그도 찍힘 // res.json({hellp:'kim70273'}); //res.writeHead(200, {'Content-Type': 'application/json'}); //res.end(JSON.stringify({hello: 'kim70273'})); express에서 이코드를 줄여준것. //나중에 헤더도 다른식으로 작성하니 express식으로 사용하기! //api서버를 만들면 res.json을 많이 씀. //웹 서버는 res.sendFile을 많이 씀 //res.render() 이것도 응답을 보내는것. }); //get에도 next가 있다. //라우터에 미들웨어를 장착함 app.post('/', (req, res) =>{ res.send('Hello Express'); }); app.get('/category/:name', (req, res) => {//와일드카드를 쓴것. res.send(`hello ${req.params.name}`); //next를 안해줬으니 여기서 끝남. }); app.get('/category/Javascript', (req, res) => { res.send(`hello`);//와일드카드 밑에 이렇게 쓰면 //이 부분이 안나옴. 위에서부터 아래로 실행 되기 때문임. //와일드카드는 보통 다른 미들웨어보다 아래에 위체 해야됨. }); //위에서 부터 아래로 실행 되지만 /about 이 주소라면 //위에것들은 일치하지 않아서 실행 안됨 app.get('/about', (req, res) =>{//안 만들어 둔것 express가 알아서 에러 처리해줌 res.send('Hello Express');// /abouta라 하면 에러 }); app.get('*', (req, res) =>{//모든 Get 요청!( 맨 위에 있으면 안됨) res.send('Hello Express');// });//범위가 넓은 라우터들은 밑에다가 넣어주도록한다. //와일드카드 라우터가 있으면 404가 뜨지 않음 //404처리도 따로 커스터마이징 해줄 수 있음.(기본적 제공은 됨), 라우터들 모두 검색 했는데 안 뜬 것. app.use((req,res, next) => { res.status(404).send('404지롱'); // 다른 미들웨어에 기본적으로 status(200)이 생략 되어 있다. // 200은 성공 // 서버쪽에서 400이라도 브라우저에 200이라고 할수도 있음.(이렇게 보안 위협 낮출 수 있음) // 코드가 해커들한테 힌드가 되지 않도록. (그래서 실무에서 200번대를 많이 써줌. or 404로 통일) //이런식으로 404에러도 직접 커스터마이징 가능 //라우터들 모두 검색 했는데 안떴는것! }); //서버는 비동기이면서 노드는 싱글 스레드니까 에러처리를 잘 해줘야한다. app.use((err, req, res, next) => {//에러 미들웨어! //err가 들어가고 반드시 생략없이 '4개'가 들어가 있어야됨.!!! console.error(err); res.status(500).send('에러났지롱. 근데 안알려주지롱 핳');//서버에러 500번대는 보안적위협을 없애고 쓰는게 좋다 //다른 숫자로 통일해 줄 수도 있음.(해커들에게 보안 공격을 당하는것을 예방하기 위해.) //매개 변수가 다르면 자바스크립트에서 다른 함수로 인식. //무슨 에러인지는 서버창에서만 기록! }) //express가 제공하는 기본 에러처리를 사용하면 서버구조를 너무 노출하게함. app.listen(app.get('port'), () => {//port심어둔 것을 가져 올 수 있다. console.log(app.get('port'),'번 포트에서 대기 중'); });
/* @flow */ import type { ChildrenProps } from '../dist/formik'; export default function bind< Values: { +[string]: mixed }, N: $Keys<Values>, Props: ChildrenProps<Values> >( props: Props, name: N ): { value: $ElementType<$ElementType<Props, 'values'>, N> } { const values: Values = props.values; return { value: values[name] || '', onChange: props.handleChange(name), onBlur: props.handleBlur(name), error: Boolean(props.touched[name] === true && props.errors[name]), helperText: props.touched[name] === true ? props.errors[name] && props.errors[name].toString() : '', }; }
String.prototype.toAlternatingCase = function () { var stringArray = this.toString().split(""); for(var i = 0; i < stringArray.length; i++) { if(stringArray[i].toString().charCodeAt() >= 65 && stringArray[i].toString().charCodeAt() <= 90){ stringArray[i] = stringArray[i].toString().toLowerCase(); } else if (stringArray[i].toString().charCodeAt() >= 97 && stringArray[i].toString().charCodeAt() <= 122){ stringArray[i] = stringArray[i].toString().toUpperCase(); } } return stringArray.join(""); }
const router = require("express").Router(); const profileRoutes = require("./profile"); const bucketRoutes = require("./bucket"); const matchingRoutes = require("./matching"); // Profile routes router.use("/profile", profileRoutes); router.use("/bucket", bucketRoutes); router.use("/matching", matchingRoutes); module.exports = router;
var constants = require('../middlewares/constants'); var bcrypt = require('bcryptjs'); var jwt = require('jsonwebtoken'); var db = require('./db'); module.exports = { insert: function(doc, callback){ doc.date= new Date(); db.Chat.insert(doc, function (err, newDoc) { if(callback){ callback(err, newDoc); } }); }, find: function(callback){ db.Chat.find({}).sort({ date: -1 }).limit(100).exec(function (err, docs) { if(callback){ callback(err, docs.reverse()); } }); } };
var maps; var mapNamesServlet = "/transpool/Trip/getMapNames"; var addRequestTripServlet = "/transpool/Trip/addRequestTrip"; $(function () { $.ajax({ url: mapNamesServlet, timeout: 3000, success: function (data) { maps = data.maps; $.each(maps, function (key, value) { var option = $("#map").append("<option></option>").children().last(); option.attr("id", key.replace(/\s/g, '')); option.text(key); }); }, error: function (error) { alert("failed to get response from server"); } }); $("#map").on('change', function () { initStops($("#map option:selected").text()); }); $('#arrival').click(function () { if ($(this).prop("checked") === true) { $("#checkout").prop("checked", false); } }); $('#checkout').click(function () { if ($(this).prop("checked") === true) { $("#arrival").prop("checked", false); } }); $("#form").submit(function () { if (checkValidation() === false) return false; else sendAjax(); return false; }); $("#back").click(function () { $(location).attr('href', '../map/map.html'); return false; }) }); function checkValidation() { var success = true; var dayStart = $("#daystart").val(); if (dayStart === "" || parseInt(dayStart, 10) != dayStart || dayStart < 1) { success = false; setError("must be a positive number", $("#alert-day")); } else cleanError($("#alert-day")); var hour = $("#hour").val(); if (hour === "" || parseInt(hour, 10) != hour || hour < 0 || hour > 23) { setError("must be between 0-23", $("#alert-hours")); success = false; } else cleanError($("#alert-hours")); var minutes = $("#minutes").val(); if (minutes === "" || parseInt(minutes, 10) != minutes || minutes < 0 || minutes > 59 || minutes % 5 !== 0) { setError("must be between 0-59 and divide by 5", $("#alert-minutes")); success = false; } else cleanError($("#alert-minutes")); if (($('#arrival').prop("checked") === false && $('#checkout').prop("checked") === false)) { setError("must choose arrival/checkout", $("#alert-arrival_checkout")); success = false; } else cleanError($("#alert-arrival_checkout")); var flexible = $("#flexibale").val(); if (flexible === "" || parseInt(flexible, 10) != flexible || flexible < 0) { success = false; setError("must be a non-negetive integer", $("#alert-flexibale")); } else cleanError($("#alert-flexibale")); if (($("#source option:selected").text() == $("#destination option:selected").text()) || $("#source option:selected").text() == "Source" || $("#destination option:selected").text() == "Destination" ) { setError( "invalid route",$("#alert-station")); success = false; } else cleanError($("#alert-station")); return success; } function setError(text, alert) { if (!alert.hasClass("alert-danger")) { alert.addClass("alert-danger"); } alert.text(text); } function cleanError(alert) { alert.removeClass("alert-danger"); alert.text(""); } function initStops(map) { $("#source").empty(); $("#source").append("<option></option>").children().last().text("Source"); $("#destination").empty(); $("#destination").append("<option></option>").children().last().text("Destination"); if (map == "Choose map") return; $.each(maps, function (key, value) { if (key == map) { $.each(value, function (index, name) { var source = $("#source").append("<option></option>").children().last(); var destination = $("#destination").append("<option></option>").children().last(); source.text(name); destination.text(name); }); } }); } function sendAjax() { $.ajax({ method: 'POST', data: createFormData(), url: addRequestTripServlet, processData: false, // Don't process the files contentType: false, // Set content type to false as jQuery will tell the server its a query string request timeout: 4000, error: function (e) { alert.text("error connecting to server"); }, success: function (data) { alert("Trip offer added successfully"); $(location).attr('href', '../map/map.html'); } }); } function createFormData() { var formData = new FormData(); formData.append("mapName", $("#map option:selected").text()); formData.append("source", $("#source option:selected").text()); formData.append("destination", $("#destination option:selected").text()); formData.append("dayStart", $("#daystart").val()); formData.append("hour", $("#hour").val()); formData.append("minutes", $("#minutes").val() || ""); formData.append("flexible", $("#flexibale").val()); formData.append("checkout", $('#checkout').prop("checked")); formData.append("flexTrip", $('#flex').prop("checked")); return formData; }
import Plugin from '@ckeditor/ckeditor5-core/src/plugin'; import { createDropdown, addListToDropdown } from '@ckeditor/ckeditor5-ui/src/dropdown/utils'; import WikiFormView from './ui/wikiformview'; import Collection from '@ckeditor/ckeditor5-utils/src/collection'; import Model from '@ckeditor/ckeditor5-ui/src/model'; import wikiIcon from './theme/icons/wiki.svg'; import axios from 'axios'; /** * Wiki plugin */ export default class Wiki extends Plugin { static get pluginName() { return 'wiki'; } init() { const editor = this.editor; /** * The form view displayed inside the drop-down */ this.form = new WikiFormView(getFormValidators(editor.t), editor.locale); // creation and setup of the dropdown editor.ui.componentFactory.add('wiki', locale => { const dropdown = createDropdown(locale); this._setUpDropdown(dropdown, this.form); this._setUpForm(this.form, dropdown); return dropdown; }); } _setUpDropdown(dropdown, form) { const editor = this.editor; const t = editor.t; const button = dropdown.buttonView; dropdown.panelView.children.add(form); button.set({ label: t('Insert wiki'), icon: wikiIcon, tooltip: true }); // Note: Use the low priority to make sure the following listener starts working after the // default action of the drop-down is executed (i.e. the panel showed up). Otherwise, the // invisible form/input cannot be focused/selected. button.on('open', () => { // Make sure that each time the panel shows up, the URL field remains in sync with the value of // the command. If the user typed in the input, then canceled (`urlInputView#value` stays // unaltered) and re-opened it without changing the value of the media command (e.g. because they // didn't change the selection), they would see the old value instead of the actual value of the // command. form.url = ''; form.urlInputView.select(); form.focus(); }, { priority: 'low' }); dropdown.on('submit', () => { if (form.isValid()) { findWiki(); } }); dropdown.on('change:isOpen', () => form.resetFormStatus()); dropdown.on('cancel', () => closeUI()); function closeUI() { let panelContent = dropdown.panelView.element.childNodes; let panelContentArr = Array.from(panelContent); editor.editing.view.focus(); dropdown.isOpen = false; // remove list items in the panel when dropdown closes if (panelContentArr.length !== 1) { panelContent[1].remove(); } } function findWiki() { axios.get("https://jsonplaceholder.typicode.com/posts?_limit=7") .then(response => { const items = new Collection(); let dataP = response.data; let panelContent = dropdown.panelView.element.childNodes; let panelContentArr = Array.from(panelContent); // removes list items in the panel before showing new items if (panelContentArr.length !== 1) { panelContent[1].remove(); } // restricts the items shown in the panel to 5 items if (dataP.length <= 5) { for (let i = 0; i < dataP.length; i++) { items.add({ type: "button", model: new Model({ label: dataP[i].title, withText: true }) }); } } else { for (let i = 0; i < 5; i++) { items.add({ type: "button", model: new Model({ label: dataP[i].title, withText: true }) }); } } // adding items to dropdown panel addListToDropdown(dropdown, items); //wiki items list const wikiList = dropdown.listView.element.childNodes; // tracks which item is selected and returns the data accordingly wikiList.forEach(function (value, index) { wikiList[index].addEventListener("click", function () { editor.model.change(writer => { const insertPosition = editor.model.document.selection.getFirstPosition(); const wikiTitle = dataP[index].title; const wikiLink = dataP[index].body; writer.insertText(wikiTitle, { linkHref: wikiLink }, insertPosition); closeUI(); }); }); }); }); } } _setUpForm(form, dropdown) { form.delegate('submit', 'cancel').to(dropdown); } } function getFormValidators(t) { return [ form => { if (!form.url.length) { return t('عنوان نباید خالی باشد'); } } ] }
import React, { Component } from 'react'; class Contact extends Component{ render(){ return( <section id="contact" className="s-contact target-section"> <div className="overlay"></div> <div className="row narrow section-intro"> <div className="col-full"> <h3>Contact</h3> <h1>Say Hello.</h1> </div> </div> <div className="row contact__main"> <div className="col-six tab-full"> <h4 className="h06">Name</h4> <p>Stillmen Vallian </p> <h4 className="h06">Address</h4> <p> Jalan Bukit Jarian No.46A<br/> Bandung, Jawa Barat<br/> 40141 Indonesia </p> <h4 className="h06">Phone</h4> <p>Phone / Whatsapp: (+62) 7788 90 7788 </p> <h4 className="h06">Email</h4> <p>stillmen.v@gmail.com </p> </div> </div> </section> ) } } export default Contact;
module.exports={ database:{ host:"localhost", port:"3306", database:"yunmis", user:"root", password:"admin" }, wechat:{ appID:"wx847eeb267f845616", appSecret:"b2448d99ecd929427ceda76ea4986fe5", token:"WXToken20180518yinhaicom", apiDomain:"https://api.weixin.qq.com/", apiURL:{ //基础接口的access_token "accessTokenApi":"%scgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", //自定义创建菜单 "createMenu":"%scgi-bin/menu/create?access_token=%s", //网页授权的access_token "authAccessToken":"%ssns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code", //拉取用户信息 "userInfo":"%ssns/userinfo?access_token=%s&openid=%s&lang=zh_CN", //创建二维码ticket "qrcodeTicket":"%scgi-bin/qrcode/create?access_token=%s", //通过ticket换取二维码 "showQRcode":"https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=%s", //客服接口-发送消息 "customerService":"%scgi-bin/message/custom/send?access_token=%s", //获取jsapi_ticket "jsapiTicket":"%scgi-bin/ticket/getticket?access_token=%s&type=jsapi" } }, };
//main price code const mainprice = document.getElementById('mainprice').innerText; //memory code const macbookmemory = document.getElementById('mack-memory'); document.getElementById('8gbmemory').addEventListener('click',function(){ macbookmemory.innerText = '0'; update() }); document.getElementById('16gbmemory').addEventListener('click',function(){ macbookmemory.innerText = '180'; update() }); //storage code const macbookstorage = document.getElementById('mack-storage'); document.getElementById('256gbstorage').addEventListener('click',function(){ macbookstorage.innerText = '0'; update() }); document.getElementById('512gbstorage').addEventListener('click',function(){ macbookstorage.innerText = '100'; update() }); document.getElementById('1tbstorage').addEventListener('click',function(){ macbookstorage.innerText = '180'; update() }); //delivery code const delivery = document.getElementById('delivery-cost'); document.getElementById('freedelivery').addEventListener('click',function(){ delivery.innerText = '0'; update() }); document.getElementById('expressdelivery').addEventListener('click',function(){ delivery.innerText = '20'; update() }); //update total code const totalPrice = document.getElementById('total-price'); const bottomTotalPrice = document.getElementById('bottom-price'); function update(){ const mackBookMemory = parseFloat(macbookmemory.innerText); const mackBookStorage = parseFloat(macbookstorage.innerText); const deliveryCost = parseFloat(delivery.innerText); const mainPrice = parseFloat(mainprice); const mackBookTotalPrice = mackBookMemory + mackBookStorage + deliveryCost + mainPrice; totalPrice.innerText = mackBookTotalPrice; bottomTotalPrice.innerText = mackBookTotalPrice; } //promo code document.getElementById('promo-button').addEventListener('click',function(){ const promoField = document.getElementById('promofield'); const promoInput = promoField.value; if(promoInput == 'stevekaku'){ const discountPrice = parseInt(totalPrice.innerText) - (parseInt(totalPrice.innerText)*20)/100; bottomTotalPrice.innerText = discountPrice; } else{ alert("Invalid Promo Code"); } promoField.value = ''; });
async function changeStatus(index, state) { var response = await fetch('http://localhost:3000/led/', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({ state: state==0?"off":"on", id: index }) }); var respJSON = await response.json(); if (!respJSON.hasOwnProperty("error")) updateHtml(index, respJSON.state); } function updateHtml(index, state) { document.getElementById('Led' + index).src = '/images/lamp_' + state + '.jpg'; document.getElementById('Led' + index).setAttribute('onclick', 'changeStatus(' + index + ',' + state + ')'); }
(function () { define(['jquery', 'bootstrap', '/Scripts/modules/puajax.js'], function ($, bootstrap, ajax) { ProductSearch = { initSearch: function (selector) { var searchSelector = selector + '.search-panel'; $(searchSelector + ' .dropdown-menu').find('a').click(function (e) { e.preventDefault(); var param = $(this).attr("href").replace("#", ""); var concept = $(this).text(); $(searchSelector + ' span#search_concept').text(concept); $('.input-group #search_param').val(param); }); // Load Facets ProductSearch.search('/api/Sitecore/common/LoadFacets', {}, function (data) { //Build Facets if (data.result) { var facets = ''; $.each(data.result, function (i, item) { facets += ProductSearch.buildTags(item.Count, ProductSearch.toTitleCasing(item.Name), 'producttype'); }); $(selector + ' .filters').html(facets); } }, function (err) { // Log error }); $(document).on('click', selector + " .search," + selector + " .filters input[type='checkbox']", function () { var facets = ProductSearch.getSelectedFilters(selector); var strProducts = ''; $.each(facets, function (i, item) { strProducts += '|' + item.value }); var searchData = { searchTerm: $(selector + " .searchTxt").val(), productType: strProducts }; ProductSearch.search('/api/Sitecore/common/SearchResult', searchData, function (data) { console.log(data); var result = data.result; var productList = ''; if (result) { $.each(result, function (i, item) { productList += ProductSearch.buildProduct(item); }); $(selector + " .product-list").html(productList); } }, function (err) { // Log error }); }); }, search: function (url, searchdata, successCallback, failCallback) { ajax.postData(url, searchdata, successCallback, failCallback); }, buildTags: function (tagCount, tag, taggroup) { return '<li class="list-group-item">' + ' <input type="checkbox" value="' + tag + '" data-taggroup ="' + taggroup + '">' + '<span class="tag tag-default tag-pill float-xs-right">' + tagCount + '</span>' + tag + '</li>'; }, buildProduct: function (productData) { return '<h1>' + productData.ItemName + '</h1>' + '<p>' + productData.Appetite + '</p>' //<div> // <span class="badge badge-success">Posted 2012-08-02 20:47:04</span> // <div class="pull-right"> // <span class="label">alice</span> <span class="label">story</span> // <span class="label">blog</span> <span class="label">personal</span> // </div> //</div> + '<hr>'; }, toTitleCasing: function (str) { return str.replace(/(?:^|\s)\w/g, function (match) { return match.toUpperCase(); }) }, getSelectedFilters: function (selector) { var selected = []; $(selector + ' .filters input:checked').each(function () { selected.push({ value: $(this).val(), group: $(this).data('taggroup') }); }); return selected; } } return ProductSearch }) })();
function validar04() { if (document.calform.email.value=="") { alert("Ingrese Email."); document.calform.email.focus(); return false; } if (document.calform.nombre.value=="") { alert("Ingrese Nombre."); document.calform.nombre.focus(); return false; } if (document.calform.telefono.value=="") { alert("Ingrese Telefono."); document.calform.telefono.focus(); return false; } if (document.calform.pass.value=="") { alert("Ingrese Codigo."); document.calform.pass.focus(); return false; } return true; } function registracion() { if (document.calform.email.value=="") { alert("Ingrese Email."); document.calform.email.focus(); return false; } if (document.calform.razon.value=="") { alert("Ingrese Raz&oacute;n Social"); document.calform.razon.focus(); return false; } if (document.calform.nombreFantasia.value=="") { alert("Ingrese Nombre de Fantasia"); document.calform.nombreFantasia.focus(); return false; } if (document.calform.nombre.value=="") { alert("Ingrese Nombre"); document.calform.nombre.focus(); return false; } if (document.calform.direccion.value=="") { alert("Ingrese Direcci&oacute;n"); document.calform.direccion.focus(); return false; } if (document.calform.localidad.value=="") { alert("Ingrese Localidad"); document.calform.localidad.focus(); return false; } if (document.calform.provincia.value=="") { alert("Ingrese Provincia"); document.calform.provincia.focus(); return false; } if (document.calform.codTelefono.value=="") { alert("Ingrese Cod. Area"); document.calform.codTelefono.focus(); return false; } if (document.calform.telefono.value=="") { alert("Ingrese Telefono."); document.calform.telefono.focus(); return false; } if (document.calform.codCelular.value=="") { alert("Ingrese Cod. Area Celular"); document.calform.codCelular.focus(); return false; } if (document.calform.celular.value=="") { alert("Ingrese Celular."); document.calform.celular.focus(); return false; } if (document.calform.cuit.value=="") { alert("Ingrese CUIT"); document.calform.cuit.focus(); return false; } return true; } $(document).ready(function() { /* * Examples - images */ $("a#example1").fancybox(); $("a#example2").fancybox({ 'overlayShow' : false, 'transitionIn' : 'elastic', 'transitionOut' : 'elastic' }); $("a#example3").fancybox({ 'transitionIn' : 'none', 'transitionOut' : 'none' }); $("a#example4").fancybox({ 'opacity' : true, 'overlayShow' : false, 'transitionIn' : 'elastic', 'transitionOut' : 'none' }); $("a#example5").fancybox(); $("a#example6").fancybox({ 'titlePosition' : 'outside', 'overlayColor' : '#000', 'overlayOpacity' : 0.9 }); $("a#example7").fancybox({ 'titlePosition' : 'inside' }); $("a#example8").fancybox({ 'titlePosition' : 'over' }); $("a[rel=example_group]").fancybox({ 'transitionIn' : 'none', 'transitionOut' : 'none', 'titlePosition' : 'over', 'titleFormat' : function(title, currentArray, currentIndex, currentOpts) { return '<span id="fancybox-title-over">Image ' + (currentIndex + 1) + ' / ' + currentArray.length + (title.length ? ' &nbsp; ' + title : '') + '</span>'; } }); /* * Examples - various */ $("#various1").fancybox({ 'titlePosition' : 'inside', 'transitionIn' : 'none', 'transitionOut' : 'none' }); $("#various2").fancybox(); $("#various3").fancybox({ 'width' : '75%', 'height' : '75%', 'autoScale' : false, 'transitionIn' : 'none', 'transitionOut' : 'none', 'type' : 'iframe' }); $("#various4").fancybox({ 'padding' : 0, 'autoScale' : false, 'transitionIn' : 'none', 'transitionOut' : 'none' }); $("#various5").fancybox({ 'width' : '75%', 'height' : '75%', 'autoScale' : false, 'transitionIn' : 'none', 'transitionOut' : 'none', 'type' : 'iframe' }); $("#various6").fancybox({ 'padding' : 0, 'autoScale' : false, 'transitionIn' : 'none', 'transitionOut' : 'none' }); $("#various7").fancybox({ 'padding' : 0, 'autoScale' : false, 'transitionIn' : 'none', 'transitionOut' : 'none' }); $("#various8").fancybox({ 'padding' : 0, 'autoScale' : false, 'transitionIn' : 'none', 'transitionOut' : 'none' }); $("#various10").fancybox({ 'width' : '75%', 'height' : '75%', 'autoScale' : false, 'transitionIn' : 'none', 'transitionOut' : 'none', 'type' : 'iframe' }); $("#various11").fancybox({ 'width' : '75%', 'height' : '75%', 'autoScale' : false, 'transitionIn' : 'none', 'transitionOut' : 'none', 'type' : 'iframe' }); $("#various12").fancybox({ 'width' : '75%', 'height' : '75%', 'autoScale' : false, 'transitionIn' : 'none', 'transitionOut' : 'none', 'type' : 'iframe' }); $("#various13").fancybox({ 'width' : '75%', 'height' : '75%', 'autoScale' : false, 'transitionIn' : 'none', 'transitionOut' : 'none', 'type' : 'iframe' }); $("#various14").fancybox({ 'width' : '75%', 'height' : '75%', 'autoScale' : false, 'transitionIn' : 'none', 'transitionOut' : 'none', 'type' : 'iframe' }); $("#various15").fancybox({ 'width' : '75%', 'height' : '75%', 'autoScale' : false, 'transitionIn' : 'none', 'transitionOut' : 'none', 'type' : 'iframe' }); $("#various16").fancybox({ 'width' : '75%', 'height' : '75%', 'autoScale' : false, 'transitionIn' : 'none', 'transitionOut' : 'none', 'type' : 'iframe' }); $("#various17").fancybox({ 'width' : '75%', 'height' : '75%', 'autoScale' : false, 'transitionIn' : 'none', 'transitionOut' : 'none', 'type' : 'iframe' }); }); var colors = new Array( "#7b7b7b", "#7b7b7b" , "#ffffff"); // Set the basic color var basicColor = "#7b7b7b"; // Set the global vars to their initial state var curColIdx = 0; var curElem; var mousePosX = 0; var mousePosY = 0; // Set the glow speed var speed = 1; // Initialize glower scripts function init() { // ie only :p if (!document.layers) { document.onmouseover = determine_tag; document.onmouseout = end_glow; check_state(); } } // Stop the glowing of a link function end_glow() { if (curElem) { // Reset values curElem.style.color = basicColor; curColIdx = 0; curElem = false; } } // Stop the glowing of a link function start_glow(ev) { // If element does not exist, return if (!curElem) return; ev = curElem; // determine which color is being used tempCol = ev.style.color; if (tempCol == basicColor) { // Reset colorindex curColIdx = 0; } if (!tempCol) { // Color not yet set, set index to 0 curColIdx = 0; tempCol = basicColor; } else { // Search current color itemN = colors.length; for (f = 0; f < itemN; f++) { if (colors[f] == tempCol) { // Color found, update counter if (f >= (itemN-1)) { // Jump to first color curColIdx = 0; } else { // Increase color index with one curColIdx = f + 1; } } // end if: check for color }// end if: search color }// end if: initiate search // set color ev.style.color = colors[curColIdx]; } function determine_tag() { ev = window.event.srcElement; mousePosX = window.event.offsetX; mousePosY = window.event.offsetY; tag = ev.tagName; // Respond to anchor tags only if (tag == "A") { if (curElem) { curElem = false; return; } curElem = ev; } else { curElem = false; } } function check_state() { if (curElem) { start_glow(); } // Object is selected, glow if (!curElem) end_glow();// Object is not selected, do not glow // Set timer window.setTimeout("check_state()", speed); } ///////////////////////////////// function MM_openBrWindow(theURL,winName,features) { //v2.0 window.open(theURL,winName,features); } function ojo2() { var a=confirm("Se borrar&aacute; este registro") if (a==1) {return true;} else {return false;} } function ojo3() { var a=confirm("Se borrar&aacute; la novedad.") if (a==1) {return true;} else {return false;} } //------------------------------------------- // Cambia el estilo de los Links cuando se hace click function ClickMenu(i,cont, estilo) { for (n=1; n<(cont+1); n++) { var menux = document.getElementById('menu_'+n); menux.className = estilo; } var Idmenu = document.getElementById('menu_'+i); Idmenu.className = 'MenuClick' } //------------------------------------------------------- // solo numeros, si no es numero devuelve false ---------- function numero(cadena) { var str = "1234567890"; for(cont = 0;cont < cadena.length;cont++) { tmp = cadena.substring(cont,cont+1); if (str.indexOf (tmp,0)== -1) return(false); } return(true); } //--------------------------------------------------------- // FUNCION PARA EL MENU DE ACCESOS -------- function Acceso(URL,WinName,Opciones) { if (URL != '' ) { var combo = document.getElementById('ACCESOS'); window.open(URL,WinName,Opciones); combo.selectedIndex = 0 } } //-------------------------------------------- // abre ventana nueva segun parametros recibidos-------- function NewWin(URL,WinName,Opciones) { window.open(URL,WinName,Opciones); } //-------------------------------------------- // maximiza ventana -------------------------------- function maxi() { window.innerWidth = screen.width; window.innerHeight = screen.height; window.screenX = 0; window.screenY = 0; alwaysLowered = false; } //-------------------------------------------- // imprimir ------------------------------------- function WinImprime() { window.print(); window.close(); } //-------------------------------------------- //--------------------------------------------------------------- function redir(url) { if (url != '' ) { this.location.replace(url); } } //--------------------------------------------------------------- //--------------------------------------------------------------- function RedirParam(url,param) { if (param != '' ) { //alert(url+param); this.location.replace(url+param); } } //--------------------------------------------------------------- //-------------------------------------------- function CheckMail(emailStr) { var emailPat=/^(.+)@(.+)$/ var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]" var validChars="\[^\\s" + specialChars + "\]" var firstChars=validChars var quotedUser="(\"[^\"]*\")" var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/ var atom="(" + firstChars + validChars + "*" + ")" var word="(" + atom + "|" + quotedUser + ")" var userPat=new RegExp("^" + word + "(\\." + word + ")*$") var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$") var matchArray=emailStr.match(emailPat) if (matchArray==null) return false; var user=matchArray[1] var domain=matchArray[2] if (user.match(userPat)==null) return false; var domainArray=domain.match(domainPat) if (domainArray==null) return false; var atomPat=new RegExp(atom,"g") var domArr=domain.match(atomPat) var len=domArr.length if (domArr[domArr.length-1].length<2 || domArr[domArr.length-1].length>3) return false; if (domArr[domArr.length-1].length==3 && len<2) return false; } //-------------------------------------------- // *********** FUNCIONES DE FECHA ********************************** // año bisiesto, si es bisiesto devuelve true ---------- function bisiesto(Vanio) { if (Vanio % 4 == 0) return true; else return false; } //-------------------------------------------- //cantidad de dias para cada mes--------------- function dias_mes(vMES, vANIO) { var vm = parseInt(vMES); switch (vm) { case 1: return 31; break; case 2: return 29; break; case 3: return 31; break; case 4: return 30; break; case 5: return 31; break; case 6: return 30; break; case 7: return 31; break; case 8: return 31; break; case 9: return 30; break; case 10: return 31; break; case 11: return 30; break; case 12: return 31; break; default: return 31; } } // valida fechas---------------------------------------- function validafecha(REQ,dia,mes,anio) { if ( (REQ==1) && ( (dia=="") || (mes=="") || (anio=="") ) ) { return (false); } if ( dia > dias_mes(mes) ) { return (false); } if ((mes == 2) && ( (bisiesto(anio) == false) && (dia > 28) ) ) { return (false); } } // ****************************************************** // EXPANDE O CONTRAE OBJETOS ---------------------- function Expandir(NomObj,estilo) { var objeto = document.getElementById(NomObj); if ( objeto.className == 'contraido' ) objeto.className = estilo ; else objeto.className = 'contraido'; //objeto.className = objeto.className == "contraido" ? estilo : "contraido"; //tblDepo.className = tblDepo.className == "contraido" ? "expandido" : "contraido"; } //----------------------------------------------- // Confirma la eliminaci&oacute;n de items en CheckBox ---------- function CheckBorrar(form) { var cant = form.contador.value; var n=0; for (i=1;i<=cant;i=i+1) { var chbox = form.elements["Borrar_"+i]; if (chbox.checked) { n = (n+1); } } if (n>0) { return confirm("¿ Confirma que va a ELIMINAR los Items seleccionados ?"); } } //----------------------------------------------- // Valida Campos Requeridos ---------- function esVacio(FormName,campo,txtalerta) { var campo = document.forms[FormName].elements[campo]; var trimcampo = campo.value.replace(/^\s+|\s+$/g,''); if (trimcampo=='') { alert("Debe completar " + txtalerta); campo.focus(); return (true); } } //----------------------------------------------- // solo numeros, NUEVO!! ---------- function NoEsNumero(FormName,campo,txtalerta) { var campo = document.forms[FormName].elements[campo]; var cadena = campo.value; var ERROR = false; var str = "1234567890"; for(cont = 0;cont < cadena.length;cont++) { tmp = cadena.substring(cont,cont+1); if (str.indexOf (tmp,0)== -1) ERROR=true; } if (ERROR==true) { alert('Debe completar ' +txtalerta+ ' con N&uacute;meros' ); campo.focus(); return(true); } } //--------------------------------------------------------- // valida fechas NUEVO!! ----------------------------------- function evalFecha(REQ,FormName,DIA,MES,ANIO) { var ERROR = false; var campo = document.forms[FormName].elements[DIA]; var dia = document.forms[FormName].elements[DIA].value; var mes = document.forms[FormName].elements[MES].value; var anio = document.forms[FormName].elements[ANIO].value; if ( (REQ==1) && ( (dia=='') || (mes=='') || (anio=='') ) ) { ERROR=true; } if ( dia > dias_mes(mes) ) { ERROR=true; } if ((mes == 2) && ( (bisiesto(anio) == false) && (dia > 28) ) ) { ERROR=true; } if (ERROR==true) { alert('La Fecha es incorrecta'); campo.focus(); return(true); } } //----------------------------------------------------------------- //------------------------RICARDO --------------------------------- //----------------------------------------------------------------- // En campos TEXTAREA PERMITE HASTA CIERTA CANTIDAD DE CARACTERES function textCounter(field,cntfield,maxlimit) { if (field.value.length > maxlimit) field.value = field.value.substring(0, maxlimit); else cntfield.value = maxlimit - field.value.length; } // EMPLEOS function CheckAll() { for (var i=0;i<document.MultiOp.elements.length;i++) { var e=document.MultiOp.elements[i]; if (e.name != 'allbox') e.checked=document.MultiOp.allbox.checked; } } function check() { var aux; for (var i=0; i<document.formulario.elements.length; i++) { if (document.formulario.elements[i].name.substring(0,1)=="#") { if (document.formulario.elements[i].checked==true) { aux=1; } } } if (aux!=1) { alert("Debe elegir al menos un alumno"); return false; } else { return true; } } function CheckAll() { for (var i=0;i<document.formulario.elements.length;i++) { var e=document.formulario.elements[i]; if (e.name != 'allbox') e.checked=document.formulario.allbox.checked; } } function formu() { if (check(document.formulario)) { document.formulario.action="_SistemaBusqueda3.asp?flag=1"; document.formulario.submit(); } } ////////////////////////////////////// browserType=navigator.appName.charAt(0)+navigator.appVersion.charAt(0) function launchWindow(myURL,myWidth,myHeight) { if (browserType=="N2") { siteWindow=window.open("","","toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=0,width="+myWidth+",height="+myHeight); siteWindow.opener=self; siteWindow=myURL } if (browserType.charAt(0)=="M") { siteWindow=window.open(myURL,"","toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=0,width="+myWidth+",height="+myHeight); siteWindow.opener=self; } else { siteWindow=window.open(myURL,"","toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=0,width="+myWidth+",height="+myHeight); siteWindow.opener=self; } setTimeout("siteWindow.focus();",200); } ///////////// function check(formu) { var iano1 var eano1 var iano2 var eano2 var iano3 var eano3 var iano4 var eano4 if (formu.elements.iano1.value > formu.elements.eano1.value) { alert("Fecha de Egreso Erronea "+formu.elements.iano1.value + " " + formu.elements.eano1.value); formu.elements.iano1.focus(); return false } if (formu.elements.iano2.value > formu.elements.eano2.value) { alert("Fecha de Egreso Erronea "+formu.elements.iano2.value + " " + formu.elements.eano2.value); formu.elements.iano2.focus(); return false } if (formu.elements.iano3.value > formu.elements.eano3.value) { alert("Fecha de Egreso Erronea "+formu.elements.iano3.value + " " + formu.elements.eano3.value); formu.elements.iano3.focus(); return false } if (formu.elements.iano4.value > formu.elements.eano4.value) { alert("Fecha de Egreso Erronea "+formu.elements.iano4.value + " " + formu.elements.eano4.value); formu.elements.iano4.focus(); return false } } //------------------------------------------- // function AddText(form, Action) { var AddTxt=""; var txt=""; if(Action==1){ txt=prompt("Texto para el Encabezado 1.","Texto"); if(txt!=null) AddTxt="<h4>"+txt+"</h4>\r\n"; } if(Action==2){ txt=prompt("Texto para el Encabezado 2.","Texto"); if(txt!=null) AddTxt="<h5>"+txt+"</h5>\r\n"; } if(Action==3){ txt=prompt("Texto para el Encabezado 3.","Texto"); if(txt!=null) AddTxt="<h3>"+txt+"</h3>\r\n"; } if(Action==4){ txt=prompt("Texto en Negrita.","Texto"); if(txt!=null) AddTxt="<b>"+txt+"</b>"; } if(Action==5){ txt=prompt("Texto en Cursiva","Texto"); if(txt!=null) AddTxt="<i>"+txt+"</i>"; } if(Action==6) AddTxt="\r\n<p>"; if(Action==7) AddTxt="<br>\r\n"; if(Action==8) AddTxt="<hr>\r\n"; if(Action==9){ txt=prompt("URL del V&iacute;nculo.","http://"); if(txt!=null){ AddTxt="<a href="+txt+">"; txt=prompt("Texto que debe Mostrar el V&iacute;nculo","Texto"); AddTxt+=txt+"</a>\r\n"; } } if(Action==10){ txt=prompt("E-mail:",""); if(txt!=null){ AddTxt="<a href=mailto:"+txt+">"; txt=prompt("Texto que debe Mostrar el V&iacute;nculo del e-mail","Texto"); AddTxt+=txt+"</a>\r\n"; } } form.Descripcion.value+=AddTxt; } function ojo() { var a=confirm("Se borrar&aacute; el registro") if (a==1) {return true;} else {return false;} } function vacio(test) { if (test.ingreso.value=="") {alert ("Debe ingresar una Secci&oacute;n") return false;} else {return true;} } function check_posicion(formu) { var ar = new Array(); var igual=0; for (var i=0; i<formu.elements.length; i++){ if (formu.elements[i].name.substring(0,1)=="#"){ if (formu.elements[i].value==""){ alert("Debe completar todas las posiciones de las secciones"); // + formu.elements[i].name.substr(1)); formu.elements[i].focus() return false; break; } for (j=0; j<formu.elements[i].value.length; j++) { if ((formu.elements[i].value.substring(j,j+1) != "0") && (formu.elements[i].value.substring(j,j+1) != "1") && (formu.elements[i].value.substring(j,j+1) != "2") && (formu.elements[i].value.substring(j,j+1) != "3") && (formu.elements[i].value.substring(j,j+1) != "4") && (formu.elements[i].value.substring(j,j+1) != "5") && (formu.elements[i].value.substring(j,j+1) != "6") && (formu.elements[i].value.substring(j,j+1) != "7") && (formu.elements[i].value.substring(j,j+1) != "8") && (formu.elements[i].value.substring(j,j+1) != "9")) { alert("Debe completar las posiciones con un n&uacute;mero"); formu.elements[i].focus() return false; break; } } for (var j=0; j<i; j++) { if (formu.elements[i].value==ar[j]) { igual=1; } } if (igual==1) { alert("Dos Secciones no pueden tener la misma posici&oacute;n"); formu.elements[i].focus() return false; break; } else { ar[i] = formu.elements[i].value; } } } } function MM_preloadImages() { //v3.0 var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array(); var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++) if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}} } function MM_swapImgRestore() { //v3.0 var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc; } function MM_findObj(n, d) { //v4.01 var p,i,x; if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) { d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);} if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n]; for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document); if(!x && d.getElementById) x=d.getElementById(n); return x; } function MM_swapImage() { //v3.0 var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3) if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];} } //////////////////////////////////////////////////////////////////////////////////////// function checkrequired(which) { var pass=true; if (document.images) { for (i=0;i<which.length;i++) { var tempobj=which.elements[i]; if (tempobj.name.substring(0,8)=="required") { if (((tempobj.type=="text"||tempobj.type=="textarea")&& tempobj.value=='')||(tempobj.type.toString().charAt(0)=="s"&& tempobj.selectedIndex==0)) { pass=false; break; } } } } if (!pass) { shortFieldName=tempobj.name.substring(8,30).toUpperCase(); if(shortFieldName=="CODNOVIOS"){ shortFieldName= "Codigo "; } if(shortFieldName=="DATEBOX"){ shortFieldName= "FECHA DEL ALTA "; } if(shortFieldName=="DATEBOX2"){ shortFieldName= "FECHA DE BAJA "; } if(shortFieldName=="DATEBOX3"){ shortFieldName= "FECHA DE CUMPLEAÑOS NOVIO "; } if(shortFieldName=="DATEBOX4"){ shortFieldName= "FECHA DE CUMPLEAÑOS NOVIA "; } if(shortFieldName=="DATEBOX5"){ shortFieldName= "FECHA DE ENLACE "; } if(shortFieldName=="APELLIDONOVIO"){ shortFieldName= "APELLIDO DEL NOVIO "; } if(shortFieldName=="NOMBRENOVIO"){ shortFieldName= "NOMBRE DEL NOVIO "; } if(shortFieldName=="APELLIDONOVIA"){ shortFieldName= "APELLIDO DE LA NOVIA "; } if(shortFieldName=="NOMBRENOVIA"){ shortFieldName= "NOMBRE DE LA NOVIA "; } if(shortFieldName=="EMAILNOVIO"){ shortFieldName= "EMAIL DEL NOVIO "; } if(shortFieldName=="EMAILNOVIA"){ shortFieldName= "EMAIL DE LA NOVIA "; } if(shortFieldName=="PASSWORDNOVIOS"){ shortFieldName= "PASSWORD DE LOS NOVIOS "; } if(shortFieldName=="PASSWORDINVITADOS"){ shortFieldName= "PASSWORD DE LOS INVITADOS "; } alert("Completar "+shortFieldName+"."); return false; } else return true; } function checkrequired2(which) { var pass=true; if (document.images) { for (i=0;i<which.length;i++) { var tempobj=which.elements[i]; if (tempobj.name.substring(0,8)=="required") { if (((tempobj.type=="text"||tempobj.type=="textarea")&& tempobj.value=='')||(tempobj.type.toString().charAt(0)=="s"&& tempobj.selectedIndex==0)) { pass=false; break; } } } } if (!pass) { shortFieldName=tempobj.name.substring(8,30).toUpperCase(); alert("Completar "+shortFieldName+"."); return false; } else return true; }
/* Only this comment to remove, no empty lines nor spaces. */var a = 1 var x = 0 if (a) { x++ }
module.exports = { configureServer: require('./server').configureServer };
const express = require('express') const cors = require('cors') const { exec } = require('child_process') const fs = require('fs') const app = express() app.use(cors()) app.use(express.json()) const header = fs.readFileSync('header.py') app.post('/', (req, res, next) => { const script = header + '\n' + req.body.script fs.writeFile('tmp.py', script, (err) => { if (err) { res.send({ error: err }) return } exec('python3 pyboard.py tmp.py', (err) => { if (err) { res.send({ error: err }) return } res.send({ ok: true }) }) }) // let commands = req.body.script // .replace(/\n+/g, '\n') // .split('\n') // .join(' ~ ') // let stdout = '' // let stderr = '' // commands = `~ ${commands} ~` // const cmd = spawn('rshell', [ // 'repl', // commands // ]) // cmd.stdout.on('data', (data) => { // stdout += `${data}` // console.log(`stdout: ${data}`); // }); // cmd.stderr.on('data', (data) => { // stderr += `${data}` // console.error(`stderr: ${data}`); // }); // cmd.on('close', (code) => { // console.log('Hi') // res.send({ // stdout, // stderr, // ok: true // }) // }) }) app.listen(4000, () => { console.log('Server running on port 4000'); })
const request = require('request') class Helpers { /** * Trim URL to the left * * @param string * @param charlist * @returns {XML|*|void} */ static trimLeft(string, charlist) { if (charlist === undefined) charlist = '\s' return string.replace(new RegExp('^[' + charlist + ']+'), '') } /** * Trim URL to the right * * @param string * @param charlist * @returns {XML|*|void} */ static trimRight(string, charlist) { if (charlist === undefined) charlist = '\s' return string.replace(new RegExp('[' + charlist + ']+$'), '') } /** * Check if two URLs are equal * * @param url1 * @param url2 * @returns {boolean} */ static urlsEqual(url1, url2) { return this.trimRight(url1, '/') === this.trimRight(url2, '/') } /** * Async sleep for @param ms * * @param ms * @returns {Promise} */ static sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)) } /** * Get random quote from 'Quotes on Design' API service * @returns {Promise} */ static getQuote() { return new Promise(function (resolve, reject) { request('http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1', function (error, res, body) { if (!error && res.statusCode === 200) { resolve(Helpers.stripTags(JSON.parse(body)[0].content)) } else { reject(error) } }) }) } static stripTags(html){ return html.replace(/<[^>]+>/g, '') } static wrapError(error) { return { name: error.name, message: error.message } } } module.exports = Helpers
var test = require('tape') var fmt = require('../').transform var noops = [ { str: 'if (!opts) opts = {}\n', msg: 'noop on single line conditional assignment' }, { str: 'var g = { name: f, data: fs.readFileSync(f).toString() }\n', msg: 'noop on single line object assignment' } ] test('singleline noop expressions', function(t) { t.plan(noops.length) noops.forEach(function(obj) { t.equal(fmt(obj.str), obj.str, obj.msg) }) })
import React from 'react' // 引入编辑器组件 import BraftEditor from 'braft-editor' // 引入编辑器样式 import 'braft-editor/dist/index.css' class Editor extends React.Component { onChange = (value) => { } onTab = (e) => { e.preventDefault() } render() { return ( <div className="my-component"> <BraftEditor onChange={ this.onChange } placeholder="输入内容.." onTab={ this.onTab } controls={ [ 'undo', 'redo', 'separator', 'font-size', 'text-color', 'superscript', 'subscript', 'strike-through', 'link', 'blockquote', 'hr', 'emoji', 'media', 'separator', 'clear', ] } /> </div> ) } } export default Editor
// homebridge-hue/lib/HueClient.js // // Homebridge plug-in for Philips Hue and/or deCONZ. // Copyright © 2018-2023 Erik Baauw. All rights reserved. 'use strict' const events = require('events') const { HttpClient, OptionParser, semver, timeout } = require('homebridge-lib') const os = require('os') const deconzMacPrefixes = ['00212E'] const hueMacPrefixes = ['001788', 'ECB5FA'] // API errors that could still cause (part of) the PUT command to be executed. const nonCriticalApiErrorTypes = [ 6, // parameter not available 7, // invalid value for parameter 8, // paramater not modifiable 201 // paramater not modifiable, device is set to off ] // Estmate the number of Zigbee messages resulting from PUTting body. function numberOfZigbeeMessages (body = {}) { let n = 0 if (Object.keys(body).includes('on')) { n++ } if ( Object.keys(body).includes('bri') || Object.keys(body).includes('bri_inc') ) { n++ } if ( Object.keys(body).includes('xy') || Object.keys(body).includes('ct') || Object.keys(body).includes('hue') || Object.keys(body).includes('sat') || Object.keys(body).includes('effect') ) { n++ } return n === 0 ? 1 : n } /** Hue API error. * @hideconstructor * @extends HttpClient.HttpError * @memberof HueClient */ class HueError extends HttpClient.HttpError { /** The API error type. * @type {?integer} * @readonly */ get type () {} /** The API error description. * @type {?string} * @readonly */ get description () {} /** The API error is non-critical. * Part of the PUT command might still be executed. * @type {?boolean} * @readonly */ get nonCritical () {} } /** Hue API response. * @hideconstructor * @extends HttpClient.HttpResponse * @memberof HueClient */ class HueResponse extends HttpClient.HttpResponse { /** An object containing the `"success"` API responses. * @type {object} * @readonly */ get success () {} /** A list of `"error"` API responses. * @type {object[]} * @readonly */ get errors () {} } /** REST API client for Hue bridge, deCONZ gateway, and compatible servers. * * See the [Hue API](https://developers.meethue.com/develop/get-started-2/) * and [deCONZ API](https://dresden-elektronik.github.io/deconz-rest-doc/) * documentation for a better understanding of the APIs. * @extends HttpClient */ class HueClient extends HttpClient { static get HueError () { return HueError } static get HueResponse () { return HueResponse } /** Check if bridgeid is for a deCONZ gateway. * @param {string} bridgeid - The bridge ID. * @returns {boolean} */ static isDeconzBridgeId (bridgeid) { return deconzMacPrefixes.includes(bridgeid.slice(0, 6)) } /** Check if bridgeid is for a Hue bridge. * @param {string} bridgeid - The bridge ID. * @returns {boolean} */ static isHueBridgeId (bridgeid) { return hueMacPrefixes.includes(bridgeid.slice(0, 6)) } /** Create a new instance of a HueClient. * * The caller is expected to verify that the given host is a reachable Hue * bridge or deCONZ gateway, by calling * {@link HueDiscovery#config HueDiscovery#config()} and passing the * response as `params.config`.<br> * The caller is expected to persist the username (API key), * passing it as `params.username`. * If no API key is known {@link HueClient#createuser createuser()} can * be called to create one.<br> * The client is expected to persist the fingerprint of the self-signed SSL * certificate of gen-2 Hue bridge, passing it as `params.fingerprint`. * If no `fingerprint` is known, it will be pinned on the first request to * the Hue bridge, typically the call to * {@link HueClient#createuser createuser()}. * It can be obtained through the {@link HueClient#fingerprint fingerprint} * property. * * @param {object} params - Parameters. * @param {?string} params.config - The bridge/gateway public configuration, * i.e. the response of {@link HueDiscovery#config HueDiscovery#config()}. * @param {?string} params.fingerprint - The fingerprint of the pinned * self-signed SSL certificate of the Hue bridge * with firmware v1.24.0 or greater. * @param {boolean} [params.forceHttp=false] - Force HTTP instead of HTTPS * for Hue bridge with firmware v1.24.0 and greater. * @param {!string} params.host - Hostname/IP address and port of the Hue * bridge or deCONZ gateway. * @param {boolean} [params.keepAlive=false] - Keep server connection(s) * open. * @param {integer} [params.maxSockets=20] - Throttle requests to maximum * number of parallel connections. * @param {boolean} [params.phoscon=false] - Mimic Phoscon web app to use * deCONZ gateway API extensions. * @param {integer} [params.timeout=5] - Request timeout (in seconds). * @param {?string} params.username - The API key of the Hue bridge or * deCONZ gateway. * @param {integer} [params.waitTimePut=50] - The time (in milliseconds), * after sending a PUT request, to wait before sending another PUT request. * @param {integer} [params.waitTimePutGroup=1000] - The time (in * milliseconds), after sending a PUT request, to wait before sending * another PUT request. * @param {integer} [params.waitTimeResend=300] - The time, in milliseconds, * to wait before resending a request after an ECONNRESET, an http status * 503, or an api 901 error. */ constructor (params = {}) { const _options = { keepAlive: false, maxSockets: 20, timeout: 5, waitTimePut: 50, waitTimePutGroup: 1000, waitTimeResend: 300 } const optionParser = new OptionParser(_options) optionParser .objectKey('config', true) .stringKey('fingerprint', true) .boolKey('forceHttp') .stringKey('host', true) .boolKey('keepAlive') .intKey('maxSockets', 1, 20) .boolKey('phoscon') .intKey('timeout', 1, 60) .stringKey('username', true) .intKey('waitTimePut', 0, 50) .intKey('waitTimePutGroup', 0, 1000) .intKey('waitTimeResend', 0, 1000) .parse(params) if (_options.fingerprint != null) { _options.https = true } _options.isDeconz = false _options.isHue = false if (HueClient.isHueBridgeId(_options.config.bridgeid)) { if (semver.gte(_options.config.apiversion, '1.24.0')) { _options.https = true } _options.isHue = true } else if (HueClient.isDeconzBridgeId(_options.config.bridgeid)) { _options.isDeconz = true } const options = { host: _options.host, json: true, keepAlive: _options.keepAlive, maxSockets: _options.maxSockets, path: '/api', timeout: _options.timeout } if (_options.phoscon) { // options.headers = { Accept: 'application/vnd.ddel.v1' } options.headers = { Accept: 'application/vnd.ddel.v3,application/vnd.ddel.v2,application/vnd.ddel.v1.1' } } if (_options.username) { options.path += '/' + _options.username } if (_options.https && !_options.forceHttp) { options.https = true options.selfSignedCertificate = true if (semver.gte(_options.config.apiversion, '1.48.0')) { _options.isHue2 = true } } if (_options.isDeconz) { options.validStatusCodes = [200, 400, 403, 404] } super(options) this._options = _options this.waitForIt = false this.setMaxListeners(30) } /** The ID (Zigbee mac address) of the Hue bridge or deCONZ gateway. * @type {string} * @readonly */ get bridgeid () { return this._options.config.bridgeid } /** The fingerprint of the self-signed SSL certificate of the Hue bridge with * firmware v1.24.0 or greater. * * @type {string} */ get fingerprint () { return this._options.fingerprint } set fingerprint (value) { this._options.fingerprint = value } /** True when connected to a deCONZ gateway. * @type {boolean} * @readonly */ get isDeconz () { return this._options.isDeconz } /** True when connected to a Hue bridge. * @type {boolean} * @readonly */ get isHue () { return this._options.isHue } /** True when connected to a Hue bridge with API v2. * @type {boolean} * @readonly */ get isHue2 () { return this._options.isHue2 } /** Server (base) path, `/api/`_username_. * @type {string} * @readonly */ get path () { return super.path } /** The API key. * @type {string} */ get username () { return this._options.username } set username (value) { this._options.username = value let path = '/api' if (value != null) { path += '/' + value } super.path = path } // =========================================================================== /** Issue a GET request of `/api/`_username_`/`_resource_. * * @param {string} resource - The resource.<br> * This might be a resource as exposed by the API, e.g. `/lights/1/state`, * or an attribute returned by the API, e.g. `/lights/1/state/on`. * @return {*} response - The JSON response body converted to JavaScript. * @throws {HueError} In case of error. */ async get (resource) { if (typeof resource !== 'string' || resource[0] !== '/') { throw new TypeError(`${resource}: invalid resource`) } let path = resource.slice(1).split('/') switch (path[0]) { case 'lights': if (path.length === 3 && path[2] === 'connectivity2') { path = [] break } // falls through case 'groups': if (path.length >= 3 && path[2] === 'scenes') { resource = '/' + path.shift() + '/' + path.shift() + '/' + path.shift() if (path.length >= 1) { resource += '/' + path.shift() } break } // falls through case 'schedules': case 'scenes': case 'sensors': case 'rules': case 'resourcelinks': case 'touchlink': if (path.length > 2) { resource = '/' + path.shift() + '/' + path.shift() break } path = [] break case 'config': case 'capabilities': if (path.length > 1) { resource = '/' + path.shift() break } // falls through default: path = [] break } let { body } = await this.request('GET', resource) for (const key of path) { if (typeof body === 'object' && body != null) { body = body[key] } } if (body == null && path.length > 0) { throw new Error( `/${path.join('/')}: not found in resource ${resource}` ) } return body } /** Issue a PUT request to `/api/`_username_`/`_resource_. * * HueClient throttles the number of PUT requests to limit the Zigbee traffic * to 20 unicast messsages per seconds, or 1 broadcast message per second, * delaying the request when needed. * @param {string} resource - The resource. * @param {*} body - The body, which will be converted to JSON. * @return {HueResponse} response - The response. * @throws {HueError} In case of error, except for non-critical API errors. */ async put (resource, body) { if (this.waitForIt) { while (this.waitForIt) { try { await events.once(this, '_go') } catch (error) {} } } const timeout = numberOfZigbeeMessages(body) * ( resource.startsWith('/groups') ? this._options.waitTimePutGroup : this._options.waitTimePut ) if (timeout > 0) { this.waitForIt = true setTimeout(() => { this.waitForIt = false this.emit('_go') }, timeout) } return this.request('PUT', resource, body) } /** Issue a POST request to `/api/`_username_`/`_resource_. * * @param {string} resource - The resource. * @param {*} body - The body, which will be converted to JSON. * @return {HueResponse} response - The response. * @throws {HueError} In case of error. */ async post (resource, body) { return this.request('POST', resource, body) } /** Issue a DELETE request of `/api/`_username_`/`_resource_. * @param {string} resource - The resource. * @param {*} body - The body, which will be converted to JSON. * @return {HueResponse} response - The response. * @throws {HueError} In case of error. */ async delete (resource, body) { return this.request('DELETE', resource, body) } // =========================================================================== /** Create an API key and set {@link HueClient#username username}. * * Calls {@link HueClient#post post()} to issue a POST request to `/api`. * * Before calling `createuser`, the link button on the Hue bridge must be * pressed, or the deCONZ gateway must be unlocked. * @return {string} username - The newly created API key. * @throws {HueError} In case of error. */ async createuser (application) { if (typeof application !== 'string' || application === '') { throw new TypeError(`${application}: invalid application name`) } const username = this._options.username const body = { devicetype: `${application}#${os.hostname().split('.')[0]}` } this.username = null try { const response = await this.post('/', body) this.username = response.success.username return this.username } catch (error) { this.username = username throw (error) } } /** Unlock the gateway to allow creating a new API key. * * Calls {@link HueClient#put put()} to issue a PUT request to * `/api/`_username_`/config`. * On a Hue bridge, this is the API equivalent of pressing the link button. * * Note that as of firmware v1.31.0, the gen-2 Hue bridge no longer allows * unlocking the bridge through the API. * @return {HueResponse} response - The response. * @throws {HueError} In case of error. */ async unlock () { if (this.isDeconz) { return this.put('/config', { unlock: 60 }) } return this.put('/config', { linkbutton: true }) } /** Initiate a touchlink pairing (Hue bridge) * or touchlink scan (deCONZ gateway). * * When connected to a Hue bridge, calls {@link HueClient#put put()} to issue * a PUT request to `/api/`_username_`/config` to initiate touchlink pairing. * This is the API equivalent of holding the link button on the Hue bridge. * * Note that deCONZ doesn't support touchlink pairing, only touchlink scan, * identify, and reset. * When connected to a deCONZ gateway, calls {@link HueClient#post post()} * to issue a POST request to `/api/`_username_`/touchlink/scan`, * to initiate a touchlink scan. * As the ConBee II and RaspBee II firmware lack support for touchlink, * this will only work for the original ConBee and RaspBee. * To see the results of the scan, issue a GET request of * `/api/`_username_`/touchlink/scan`. * The ID returned in the scan results is needed to touchlink identify or * reset the device. * To issue a touchlink identify, issue a POST request of * `/api/`_username_`/touchlink/`_ID_`/identify`. * To issue a touchlink reset, issue a POST request to * `/api/`_username_`/touchlink/`_ID_`/reset`. * @return {HueResponse} response - The response. * @throws {HueError} In case of error. */ async touchlink () { if (this.isDeconz) { return this.post('/touchlink/scan') } return this.put('/config', { touchlink: true }) } /** Search for new devices. * * When connected to a Hue bridge, calls {@link HueClient#post post()} to * issue a POST request to `/api/`_username_`/lights`, to enable pairing of * new Zigbee devices. * * When connected to a deCONZ gateway, calls {@link HueClient#put put()} to * issue a PUT request to `/api/`_username_`/config`, to enable pairing of * new Zigbee devices. * * To see the newly paired devices, issue a GET request of * `/api/`_username_`/lights/new` and/or `/api/`_username_`/sensor/new` * @return {HueResponse} response - The response. * @throws {HueError} In case of error. */ async search () { if (this.isDeconz) { return this.put('/config', { permitjoin: 120 }) } return this.post('/lights') } /** Restart the bridge or gateway. * When connected to a Hue bridge, calls {@link HueClient#put put()} to * issue a PUT request to `/api/`_username_`/config`, to reboot the Hue * bridge. * * When connected to a deCONZ gateway, calls {@link HueClient#post post()} * to issue a POST request to `/api/`_username_`/config/restartapp`, to * restart the deCONZ gateway. * * @return {HueResponse} response - The response. * @throws {HueError} In case of error. */ async restart () { if (this.isDeconz) { return this.post('/config/restartapp') } return this.put('/config', { reboot: true }) } // =========================================================================== /** Check Hue bridge self-signed SSL certificate * * @throws {Error} For invalid SSL certificate. */ checkCertificate (cert) { if (Object.keys(cert).length > 0) { if (this._options.fingerprint != null) { if (cert.fingerprint256 !== this._options.fingerprint) { throw new Error('SSL certificate fingerprint mismatch') } return } if ( cert.subject == null || cert.subject.C !== 'NL' || cert.subject.O !== 'Philips Hue' || cert.subject.CN.toUpperCase() !== this.bridgeid || cert.issuer == null || cert.issuer.C !== 'NL' || cert.issuer.O !== 'Philips Hue' || ( cert.issuer.CN.toUpperCase() !== this.bridgeid && cert.issuer.CN !== 'root-bridge' ) || ('00' + cert.serialNumber).slice(-16) !== this.bridgeid ) { throw new Error('invalid SSL certificate') } // Pin certificate. this._options.fingerprint = cert.fingerprint256 } } /** Issue an HTTP request to the Hue bridge or deCONZ gateway. * * This method does the heavy lifting for {@link HueClient#get get()}, * {@link HueClient#put put()}, {@link HueClient#post post()}, and * {@link HueClient#delete delete()}. * It shouldn't be called directly. * * @param {string} method - The method for the request. * @param {!string} resource - The resource for the request. * @param {?*} body - The body for the request. * @return {HueResponse} response - The response. * @throws {HueError} In case of error. */ async request (method, resource, body = null, retry = 0) { try { const response = await super.request(method, resource, body) if (response.headers['content-length'] === '0') { response.body = null } response.errors = [] response.success = {} if (Array.isArray(response.body)) { for (const id in response.body) { const e = response.body[id].error if (e != null && typeof e === 'object') { response.errors.push({ type: e.type, description: e.description }) const error = new Error(`${e.address}: api error ${e.type}: ${e.description}`) error.request = response.request error.type = e.type error.description = e.description error.nonCritical = nonCriticalApiErrorTypes.includes(error.type) /** Emitted for each API error returned by the Hue bridge * or deCONZ gateway. * * @event HueClient#error * @param {HueError} error - The error. */ this.emit('error', error) if (!error.nonCritical) { throw error } } const s = response.body[id].success if (s != null && typeof s === 'object') { for (const path of Object.keys(s)) { const a = path.split('/') const key = a[a.length - 1] response.success[key] = s[path] } } } } return response } catch (error) { if ( error.code === 'ECONNRESET' || error.statusCode === 503 || error.type === 901 ) { if (error.request != null && this._options.waitTimeResend > 0 && retry < 5) { error.message += ' - retry in ' + this._options.waitTimeResend + 'ms' this.emit('error', error) await timeout(this._options.waitTimeResend) return this.request(method, resource, body, retry + 1) } } throw error } } } module.exports = HueClient
import IntroView from "../views/static-screens/intro-view"; export default class WelcomeScreen { constructor() { this.intro = new IntroView(); } get element() { return this.intro.element; } }
import { MsalAuthProvider, LoginType } from "react-aad-msal"; const tenant = "rakole.onmicrosoft.com"; const signInPolicy = "B2C_1_reactsignup"; const applicationID = "2af3af4d-47c8-4ae5-bc09-8821d8d755a9"; const reactRedirectUri = "http://localhost:3000"; const tenantSubdomain = tenant.split(".")[0]; const instance = `https://${tenantSubdomain}.b2clogin.com/tfp/`; const signInAuthority = `${instance}${tenant}/${signInPolicy}`; // Msal Configurations const signInConfig = { auth: { authority: signInAuthority, clientId: applicationID, /*redirectUri: reactRedirectUri,*/ validateAuthority: false }, cache: { cacheLocation: "sessionStorage", storeAuthStateInCookie: true } }; // Authentication Parameters const authenticationParameters = { scopes: [ "https://graph.microsoft.com/Directory.Read.All", "https://rakole.onmicrosoft.com/api/user_impersonation" ] }; // Options const options = { loginType: LoginType.Redirect, tokenRefreshUri: window.location.origin + "/auth.html" }; export const signInAuthProvider = new MsalAuthProvider( signInConfig, authenticationParameters, options );
import React, { Component } from 'react'; import Masonry from 'react-masonry-infinite'; import shortid from 'shortid'; import './App.css'; import searchData from './data/data.json' class Popup extends React.Component { render() { return ( <div className='popup'> <div className='popup_inner'> <div className="row"> <img className="col" src={this.props.img.src}></img> <div className="col detail scroll-bar"> <div className="closeBtn" onClick={this.props.closePopup}><i className="fa fa-times fa-3x"></i></div> <h1>{this.props.name}</h1> <h2>viết bởi: {this.props.username}</h2> <div> <p className="title">Nguyên liệu:</p> <ul className="content"> {this.props.ingredients.map((item, index) => <li key={index}>{item}</li>)} </ul> </div> <div> <p className="title">Các bước:</p> <ul className="content"> {this.props.steps.map((item, index) => <li key={index}>{item}</li>)} </ul> </div> </div> </div> </div> </div> ); } } class SearchResults extends Component { constructor(props) { super(props); this.state = { hasMore: true, elements: [], load: true, showPopUp: false, dataPopUp: {}, isLiked: false, searchResults: [] }; } // generateElements = (keyword) => [...Array(10).keys()].map((item, index) => { // this.setState.searchResults = data.filter(item => this.searchFor(keyword, item)) // const newImg = new Image() // const imgs = this.state.searchResults.map(item => item.img) // newImg.src = imgs[index][0] // return { // key: shortid.generate(), // img: newImg, // username: this.state.searchResults[index].username, // name: this.state.searchResults[index].name, // ingredients: this.state.searchResults[index].ingredients, // steps: this.state.searchResults[index].steps, // isLiked: false, // }; // }); // componentWillMount(keyword) { // this.setState(state => ({ // elements: state.elements.concat(this.generateElements(keyword)) // })) // } // componentDidMount() { // this.setState(state => ({ // searchResults: state.elements // })) // } // componentWillUnmount = () => { // this.setState({ // elements: [] // }) // } // loadMore = (keyword) => setTimeout(() => this.setState(state => ({ // elements: state.elements.concat(this.generateElements(keyword)), // })), 2500); generateElements = () => [...Array(10).keys()].map((item, index) => { console.log(); const newImg = new Image() const imgs = searchData.map(item => item.img) newImg.src = imgs[index][0] return { key: shortid.generate(), img: newImg, username: searchData[index].username, name: searchData[index].name, ingredients: searchData[index].ingredients, steps: searchData[index].steps, isLiked: false, }; }); componentWillMount() { this.setState(state => ({ elements: state.elements.concat(this.generateElements()) })) } componentDidMount() { this.setState(state => ({ searchResults: state.elements })) } componentWillUnmount = () => { this.setState({ elements: [] }) } loadMore = () => setTimeout(() => this.setState(state => ({ elements: state.elements.concat(this.generateElements()), })), 2500); clickLike = (key) => { this.setState({ dataPopUp: this.state.elements.map(item => item.isLiked = item.key === key ? item.key === key && !item.isLiked : item.isLiked), }); } togglePopup = (key) => { this.setState({ dataPopUp: this.state.elements.filter(item => item.key === key)[0], showPopup: !this.state.showPopup }); } change_alias(alias) { let str = alias; str = str.toLowerCase(); str = str.replace(/à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ/g, "a"); str = str.replace(/è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ/g, "e"); str = str.replace(/ì|í|ị|ỉ|ĩ/g, "i"); str = str.replace(/ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ/g, "o"); str = str.replace(/ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ/g, "u"); str = str.replace(/ỳ|ý|ỵ|ỷ|ỹ/g, "y"); str = str.replace(/đ/g, "d"); str = str.replace(/!|@|%|\^|\*|\(|\)|\+|\=|\<|\>|\?|\/|,|\.|\:|\;|\'|\"|\&|\#|\[|\]|~|\$|_|`|-|{|}|\||\\/g, " "); str = str.replace(/ + /g, " "); str = str.trim(); return str; } searchFor = (keyword, item) => { return this.change_alias(item.name).toLowerCase().includes(this.change_alias(keyword).toLowerCase()); } componentWillReceiveProps({keyword}) { this.setState({ searchResults : keyword === '' ? this.state.elements : this.state.elements.filter(item => this.searchFor(keyword, item) === true) }) } render() { // console.log(this.state.elements) // const { keyword } = this.props // console.log(keyword) // const searchResults = keyword === '' ? this.state.elements : this.state.elements.filter(item => this.searchFor(keyword, item) === true) const {searchResults} = this.state // console.log('searchResults', searchResults) return ( <div> <div className="container"> {this.state.elements ? (<Masonry className="masonry" hasMore={this.state.hasMore} loader={ <div className="sk-folding-cube"> <div className="sk-cube1 sk-cube" /> <div className="sk-cube2 sk-cube" /> <div className="sk-cube4 sk-cube" /> <div className="sk-cube3 sk-cube" /> </div> } loadMore={this.loadMore} > { this.state.elements.map(item => ( <div key={item.key} className="post" style={{ height: `${item.img.height / item.img.width * 456.14 + 122}` }}> <h2>{item.username}</h2> <img className="post-img" src={item.img.src} alt="" onClick={() => this.togglePopup(item.key)} style={{ cursor: "pointer" }} /> <div className="post-body"> <ul className="post-react flex flex-wrap align-items-center"> <li><i className={item.isLiked ? "fa fa-heart fa-3x" : "fa fa-heart-o fa-3x"} onClick={() => this.clickLike(item.key)} style={{ cursor: "pointer" }}></i></li> <li><i className="fa fa-comments-o fa-3x"></i></li> <li><i className="fa fa-share-alt fa-3x"></i></li> </ul> <h1 className="post-content">{item.name}</h1> </div> </div> )) } </Masonry>) : null} </div> {this.state.showPopup ? <Popup img={this.state.dataPopUp.img} name={this.state.dataPopUp.name} ingredients={this.state.dataPopUp.ingredients} steps={this.state.dataPopUp.steps} username={this.state.dataPopUp.username} closePopup={this.togglePopup.bind(this)} /> : null } </div> ); } } export default SearchResults;
import Col from 'react-bootstrap/Col'; import Container from 'react-bootstrap/Container'; import FileDetailsList from "../components/FileDetailsList"; import React from 'react'; import Row from 'react-bootstrap/Row'; const FilesPage = ({ match }) => { const { params = {} } = match; const { fileName = null } = params; return ( <Container> <Row> <Col> <h1>File Details</h1> </Col> </Row> <Row> <Col> <FileDetailsList fileName={fileName} /> </Col> </Row> </Container> ); }; export default FilesPage;
function update_select_list(new_options, select_list){ var option_array = new_options.split("|"); var i = 0; select_list.length = 0; for(var j=0; j < option_array.length-1; j++){ var option = option_array[j].split(","); var selected = Boolean(parseInt(option[2])); select_list[j] = new Option(option[0], option[1], false, selected); //for testing and debugging //select_list.options[option_array.length-1+j] = new Option(option[2].toString() +" "+ selected.toString()); //select_list.options[option_array.length-1+j] = new Option("Link Label: " + linklabel + " Label Text:" + label_text); } show_hide_linkfields(select_list); } function show_advanced(hide){ var select_list = document.iform["interfaces[]"].options; var adv_rows = parseInt($('adv_rows').innerHTML); var adv_show = Boolean(parseInt($('adv_show').innerHTML)); var status = Boolean(parseInt(hide)); if (status){ $('advanced_').hide(); for(var j=0; j < adv_rows; j++){ var advanced = "advanced_" + j.toString(); $(advanced).show(); } $('adv_show').innerHTML = "1"; show_hide_linkfields(select_list); } else { $('advanced_').show(); for(var j=0; j < adv_rows; j++){ var advanced = "advanced_" + j.toString(); $(advanced).hide(); } $('adv_show').innerHTML = "0"; show_hide_linkfields(select_list); } } function show_hide_linkfields(options){ var i = 0; var port_count = parseInt($('port_count').innerHTML); var adv_show = Boolean(parseInt($('adv_show').innerHTML)); for(var j=0; j < port_count; j++){ var count = j.toString(); var type = $('type').value; var link = "link" + count; var lnklabel = "linklabel" + count; var bw = "bandwidth" + count; var bwlabel = "bwlabel" + count; var mtu = "mtu" + count; var mru = "mru" + count; var mrru = "mrru" + count; var ipfields = "ip_fields" + count; var gwfields = "gw_fields" + count; var localip = "localip" + count; var localiplabel = "localiplabel" + count; var subnet = "subnet" + count; var gateway = "gateway" + count; var gatewaylabel = "gatewaylabel" + count; $(ipfields, gwfields ,link).invoke('hide'); $(subnet).disabled = true; $(bw).name = "bandwidth[]"; $(mtu).name = "mtu[]"; $(mru).name = "mru[]"; $(mrru).name = "mrru[]"; $(localip).name = "localip[]"; $(subnet).name = "subnet[]"; $(gateway).name = "gateway[]"; while(i < options.length){ if (options[i].selected ){ $(lnklabel).innerHTML = "Link Parameters (" + options[i].value + ")"; $(bwlabel).innerHTML = "Bandwidth (" + options[i].value + ")"; $(bw).name = "bandwidth[" + options[i].value + "]"; $(mtu).name = "mtu[" + options[i].value + "]"; $(mru).name = "mru[" + options[i].value + "]"; $(mrru).name = "mrru[" + options[i].value + "]"; $(localiplabel).innerHTML = "Local IP (" + options[i].value + ")"; $(gatewaylabel).innerHTML = "Gateway (" + options[i].value + ")"; $(localip).name = "localip[" + options[i].value + "]"; $(subnet).name = "subnet[" + options[i].value + "]"; $(gateway).name = "gateway[" + options[i].value + "]"; if (type == 'ppp' && adv_show){ $(ipfields, gwfields).invoke('show'); } if (type == 'pptp' || type == 'l2tp'){ $(subnet).disabled = false; $(ipfields, gwfields).invoke('show'); } if (adv_show){ $(link).show(); } i++; break; } i++; } } } function updateType(t){ var serialports = $('serialports').innerHTML; var ports = $('ports').innerHTML; var select_list = document.iform["interfaces[]"].options; $('adv_show').innerHTML = "0"; show_advanced('0'); switch(t) { case "select": { $('ppp','pppoe','ppp_provider','phone_num','apn_').invoke('hide'); select_list.length = 0; select_list[0] = new Option("Select Link Type First",""); break; } case "ppp": { update_select_list(serialports, select_list); $('select','pppoe').invoke('hide'); $('ppp_provider','phone_num','apn_').invoke('show'); country_list(); break; } case "pppoe": { update_select_list(ports, select_list); $('select','ppp','ppp_provider','phone_num','apn_').invoke('hide'); break; } case "l2tp": case "pptp": { update_select_list(ports, select_list); $('select','ppp','pppoe','ppp_provider','phone_num','apn_').invoke('hide'); break; } default: select_list.length = 0; select_list[0] = new Option("Select Link Type First",""); break; } if (t == "pppoe" || t == "ppp"){ $(t).show(); } } function show_reset_settings(reset_type) { if (reset_type == 'preset') { Effect.Appear('pppoepresetwrap', { duration: 0.0 }); Effect.Fade('pppoecustomwrap', { duration: 0.0 }); } else if (reset_type == 'custom') { Effect.Appear('pppoecustomwrap', { duration: 0.0 }); Effect.Fade('pppoepresetwrap', { duration: 0.0 }); } else { Effect.Fade('pppoecustomwrap', { duration: 0.0 }); Effect.Fade('pppoepresetwrap', { duration: 0.0 }); } } function country_list() { $('country').childElements().each(function(node) { node.remove(); }); $('provider').childElements().each(function(node) { node.remove(); }); $('providerplan').childElements().each(function(node) { node.remove(); }); new Ajax.Request("getserviceproviders.php",{ onSuccess: function(response) { var responseTextArr = response.responseText.split("\n"); responseTextArr.sort(); responseTextArr.each( function(value) { var option = new Element('option'); country = value.split(":"); option.text = country[0]; option.value = country[1]; $('country').insert({ bottom : option }); }); } }); $('trcountry').setStyle({display : "table-row"}); } function providers_list() { $('provider').childElements().each(function(node) { node.remove(); }); $('providerplan').childElements().each(function(node) { node.remove(); }); new Ajax.Request("getserviceproviders.php",{ parameters: {country : $F('country')}, onSuccess: function(response) { var responseTextArr = response.responseText.split("\n"); responseTextArr.sort(); responseTextArr.each( function(value) { var option = new Element('option'); option.text = value; option.value = value; $('provider').insert({ bottom : option }); }); } }); $('trprovider').setStyle({display : "table-row"}); $('trproviderplan').setStyle({display : "none"}); } function providerplan_list() { $('providerplan').childElements().each(function(node) { node.remove(); }); $('providerplan').insert( new Element('option') ); new Ajax.Request("getserviceproviders.php",{ parameters: {country : $F('country'), provider : $F('provider')}, onSuccess: function(response) { var responseTextArr = response.responseText.split("\n"); responseTextArr.sort(); responseTextArr.each( function(value) { if(value != "") { providerplan = value.split(":"); var option = new Element('option'); option.text = providerplan[0] + " - " + providerplan[1]; option.value = providerplan[1]; $('providerplan').insert({ bottom : option }); } }); } }); $('trproviderplan').setStyle({display : "table-row"}); } function prefill_provider() { new Ajax.Request("getserviceproviders.php",{ parameters: {country : $F('country'), provider : $F('provider'), plan : $F('providerplan')}, onSuccess: function(response) { var xmldoc = response.responseXML; var provider = xmldoc.getElementsByTagName('connection')[0]; $('username').setValue(''); $('password').setValue(''); if(provider.getElementsByTagName('apn')[0].firstChild.data == "CDMA") { $('phone').setValue('#777'); $('apn').setValue(''); } else { $('phone').setValue('*99#'); $('apn').setValue(provider.getElementsByTagName('apn')[0].firstChild.data); } $('username').setValue(provider.getElementsByTagName('username')[0].firstChild.data); $('password').setValue(provider.getElementsByTagName('password')[0].firstChild.data); } }); }
function salir() { if (navigator.app) { navigator.app.exitApp(); } else if (navigator.device) { navigator.device.exitApp(); } }
$(document).ready(function() { //Cargar el carro function load_cart() { var wrapper = $('#cart_wrapper'), action = 'get'; //Peticion ajax $.ajax({ url: 'ajax.php', type: 'POST', dataType: 'JSON', data: { action }, beforeSend: function() { wrapper.waitMe(); } }).done(function(res){ if(res.status == 200) { wrapper.html(res.data); } console.log(res); }).fail(function(err) { Swal.fire('Ups!', 'Ocurrio un error','error'); return false; }).always(function(){ console.log('Ejecutando always'); setTimeout(function() { wrapper.waitMe('hide'); }, 3500); }); }; load_cart(); //Agregar al carro al dar click al boton //Actualizar las cantidades del carro si el producto ya existe dentro //Actualizar carro del input //Barrar elemento del carro //Vaciar carro //Realizar pago });
import React, { useEffect, useState } from "react"; import { Button, Container, Table, Form, FormGroup, Row, Col, Label, Input, Modal, ModalBody, ModalHeader, ModalFooter } from "reactstrap"; import { useDataProvider, Loading, Error } from "react-admin"; function getFormattedDate(date) { let year = date.getFullYear(); let month = (1 + date.getMonth()).toString().padStart(2, "0"); let day = date .getDate() .toString() .padStart(2, "0"); return month + "/" + day + "/" + year; } export const ReportList = props => { const dataProvider = useDataProvider(); const [reports, setReports] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(); const [modalOpen, setModalOpen] = useState(false); const [toDelete, setToDelete] = useState(false); useEffect(() => { dataProvider .getReports() .then(({ data }) => { setReports(data); }) .catch(e => setError(e)); setLoading(false); }, [dataProvider]); const onDelete = async () => { setLoading(true); setModalOpen(false); if (toDelete) { dataProvider .removeReport(toDelete) .then(res => { setLoading(false); }) .catch(e => { setError(e); setLoading(false); }); } }; if (loading) return <Loading />; if (error) return <Error />; if (!reports) return null; return ( <Container className="mt-4"> <Button className="mb-2 float-right" onClick={() => props.history.push("/reports/create")} > New </Button> <Table striped hover style={{ fontSize: "14px" }}> <thead> <tr> <th scope="col">Key</th> <th scope="col">Issuer</th> <th scope="col">pH</th> <th scope="col">Hardness</th> <th scope="col">TDS</th> <th scope="col">Company</th> <th scope="col">Date</th> <th scope="col">Signed</th> <th></th> </tr> </thead> <tbody> {reports.map((report, k) => { return ( <tr key={k}> <td style={{ color: "blue", cursor: "pointer" }} onClick={() => props.history.push(`/reports/${report.key}`)} > <u>{report.key.slice(0, 8)}</u> </td> <td style={{ color: "blue", cursor: "pointer" }} onClick={() => props.history.push(`/users/${report.sender}`)} > <u>{report.sender.slice(0, 8)}</u> </td> <td>{report.ph}</td> <td>{report.hardness}</td> <td>{report.tds}</td> <td>{report.companyName}</td> <td>{getFormattedDate(new Date(report.timestamp * 1000))}</td> <td>{report.signed ? "true" : "false"}</td> <td> <Button color="danger" size="sm" onClick={() => { setToDelete(report.key); setModalOpen(true); }} > Delete </Button> </td> </tr> ); })} </tbody> </Table> {modalOpen && ( <Modal isOpen={modalOpen} toggle={() => setModalOpen(!modalOpen)}> <ModalHeader toggle={() => setModalOpen(!modalOpen)}> Confirmation </ModalHeader> <ModalBody> <p>Are you sure you want to delete this report?</p> <ModalFooter className="text-center"> <Button color="primary" onClick={() => onDelete()}> YES </Button>{" "} <Button color="secondary" onClick={() => setModalOpen(false)}> NO </Button> </ModalFooter> </ModalBody> </Modal> )} </Container> ); }; export const NewReport = props => { const dataProvider = useDataProvider(); const [report, setReport] = useState({ signed: false }); const [loading, setLoading] = useState(false); const [error, setError] = useState(); const onCreate = async () => { setLoading(true); if (report) { dataProvider .newReport(report) .then(res => { props.history.push("/reports"); }) .catch(e => setError(e)); setLoading(false); } }; if (loading) return <Loading />; if (error) return <h1>Error</h1>; return ( <Container> <Form className="m-3" tag="h5"> <FormGroup> <Row className="align-items-center"> <Col sm={3} xs={3}> <Label for="ph">pH</Label> </Col> <Col sm={6} xs={8}> <Input type="number" name="ph" id="ph" placeholder="pH" onChange={e => setReport({ ...report, ph: e.target.value })} value={report.ph || ""} /> </Col> </Row> <Row className="align-items-center"> <Col sm={3} xs={3}> <Label for="hardness">Hardness</Label> </Col> <Col sm={6} xs={8}> <Input type="number" name="hardness" id="hardness" placeholder="hardness" onChange={e => setReport({ ...report, hardness: e.target.value }) } value={report.hardness || ""} /> </Col> </Row> <Row className="align-items-center"> <Col sm={3} xs={3}> <Label for="tds">TDS</Label> </Col> <Col sm={6} xs={8}> <Input type="number" name="tds" id="tds" placeholder="tds" onChange={e => setReport({ ...report, tds: e.target.value })} value={report.tds || ""} /> </Col> </Row> <Row className="align-items-center"> <Col sm={3} xs={3}> <Label for="companyName">Company Name</Label> </Col> <Col sm={6} xs={8}> <Input type="text" name="companyName" id="companyName" placeholder="Name of Company" onChange={e => setReport({ ...report, companyName: e.target.value }) } value={report.companyName || ""} /> </Col> </Row> <Row className="mt-2"> <Col sm={3} xs={3}> <Label for="signed">Signed</Label> </Col> <Col sm={6} xs={8}> <Input className="ml-2" type="checkbox" name="signed" id="signed" checked={report.signed} onChange={e => setReport({ ...report, signed: e.target.checked }) } /> </Col> </Row> <br /> <Button color="primary" onClick={onCreate}> Create Report </Button> </FormGroup> </Form> </Container> ); }; export const EditReport = props => { const dataProvider = useDataProvider(); const [report, setReport] = useState({ signed: false }); const [loading, setLoading] = useState(true); const [error, setError] = useState(); useEffect(() => { dataProvider .getReport(props.match.params.id) .then(({ data }) => { data.key = props.match.params.id; setReport(data); setLoading(false); }) .catch(e => setError(e)); }, [dataProvider, props.match.params.id]); const onEdit = async () => { setLoading(true); if (report) { console.log(report); dataProvider .updateReport(report) .then(res => { props.history.push("/reports"); }) .catch(e => setError(e)); setLoading(false); } }; if (error) return <h1>Error</h1>; if (loading) return <Loading />; return ( <Container> <Form className="m-3" tag="h5"> <FormGroup> <Row className="align-items-center"> <Col sm={3} xs={3}> <Label for="ph">pH</Label> </Col> <Col sm={6} xs={8}> <Input readOnly type="number" name="ph" id="ph" placeholder="pH" value={report.ph || ""} /> </Col> </Row> <Row className="align-items-center"> <Col sm={3} xs={3}> <Label for="hardness">Hardness</Label> </Col> <Col sm={6} xs={8}> <Input readOnly type="number" name="hardness" id="hardness" value={report.hardness || ""} /> </Col> </Row> <Row className="align-items-center"> <Col sm={3} xs={3}> <Label for="tds">TDS</Label> </Col> <Col sm={6} xs={8}> <Input readOnly type="number" name="tds" id="tds" value={report.tds || ""} /> </Col> </Row> <Row className="align-items-center"> <Col sm={3} xs={3}> <Label for="company">Company Name</Label> </Col> <Col sm={6} xs={8}> <Input readOnly type="text" name="company" id="company" value={report.companyName || ""} /> </Col> </Row> <Row className="mt-2"> <Col sm={3} xs={3}> <Label for="signed">Signed</Label> </Col> <Col sm={6} xs={8}> <Input className="ml-2" type="checkbox" name="signed" id="signed" checked={report.signed} onChange={e => setReport({ ...report, signed: e.target.checked }) } /> </Col> </Row> <br /> <Button color="primary" onClick={onEdit}> Update Report </Button> </FormGroup> </Form> </Container> ); };
import React from 'react'; import { mount } from 'enzyme'; import { MemoryRouter } from 'react-router-dom'; import toJson from 'enzyme-to-json'; import AddEntryForm from '../../containers/AddEntryForm'; import Root from '../../root'; let wrapped; let wrapped1; const type = 'update'; const match = { params: { id: 2 } } beforeEach(() => { wrapped = mount( <Root> <MemoryRouter initialEntries={[{ key: 'testKey' }]}> <AddEntryForm /> </MemoryRouter> </Root>, ); wrapped1 = mount( <Root> <MemoryRouter initialEntries={[{ key: 'testKey' }]}> <AddEntryForm type={type} match={match} /> </MemoryRouter> </Root>, ); }); afterEach(() => wrapped.unmount()); afterEach(() => wrapped1.unmount()); describe('Add Entry Form UI', () => { describe('render features', () => { test('container should render as expected', () => { const tree = toJson(wrapped); expect(tree).toMatchSnapshot(); }); test('container should render as expected when in update mode', () => { const tree = toJson(wrapped1); expect(tree).toMatchSnapshot(); }); it('has two input fields and a button', () => { expect(wrapped.find('input').length).toEqual(1); expect(wrapped.find('textarea').length).toEqual(1); expect(wrapped.find('button').length).toEqual(2); }); }); describe('when typing into fields', () => { beforeEach(() => { wrapped.find('input').first().simulate('change', { target: { id: 'title', value: 'title' } }); wrapped.find('textarea').first().simulate('change', { target: { id: 'content', value: 'content' } }); wrapped.update(); }); it('shows that text has been entered into the title field', () => { expect(wrapped.find('input').first().prop('value')).toEqual('title'); }); it('shows that text has been entered into the content field', () => { expect(wrapped.find('textarea').first().prop('value')).toEqual('content'); }); it('empties fields when form is submitted', () => { wrapped.find('form').simulate('submit'); wrapped.update(); expect(wrapped.find('input').first().prop('value')).toEqual(''); expect(wrapped.find('textarea').first().prop('value')).toEqual(''); }); }); }); describe('Add Entry Form client-side validation', () => { beforeEach(() => { wrapped.find('input').first().simulate('change', { target: { id: 'title', value: '' } }); wrapped.find('textarea').first().simulate('change', { target: { id: 'content', value: '' } }); wrapped.update(); }); it('shows error messages if both fields are empty', () => { wrapped.find('form').simulate('submit'); wrapped.update(); expect(wrapped.find('.entryError').at(1).text()).toEqual('Please enter a title'); expect(wrapped.find('.entryError').at(2).text()).toEqual('Please enter some content'); }); });
import Phaser from 'phaser' import WebFont from 'webfontloader' export default class extends Phaser.State { init () {} preload () { this.load.image('preloader', '../assets/images/loading_bar.png') } render () { this.state.start('Splash') } }
const mongoose = require('mongoose'); const winston = require('../winston-config'); const { Schema } = mongoose; /** * The DB Schema for a TV Show Episode. * @type {Schema} */ const EpisodeSchema = new Schema({ watchListItem: { type: Schema.Types.ObjectId, ref: 'watchListItem', }, tmdbEpisodeID: { type: String }, seasonNumber: { type: Number }, episodeNumber: { type: Number }, airDate: { type: Date }, name: { type: String }, description: { type: String }, image: { type: String }, watched: { type: Boolean, default: false }, }); /** * Toggle a TV Show Episode as being watched or unwatched. * @param {String} episodeID The ID (primary key) for the episode in the DB. * @return {Episode} An instance of the Episode model for the given episode. */ EpisodeSchema.statics.toggleWatched = function (episodeID) { return this.findById(episodeID) .then((episode) => { episode.watched = !episode.watched; return episode.save().then(() => { // Check if the watchListItem needs to be updated to mark watched: true // in case all episodes are now watched. const WatchListItem = mongoose.model('watchListItem'); WatchListItem.checkIfWatched(episode.watchListItem); return episode; }); }).catch((err) => { winston.error(err); }); }; /** * Export the Model. */ mongoose.model('episode', EpisodeSchema);
export default { data() { return { loading: false, activities: {}, wbs_id: 0 }; }, methods: { loadActivities() { if (this.wbs_id) { this.loading = true; $.ajax({ url: '/api/cost/activity-log/' + this.wbs_id, dataType: 'json', cache: true }).success(response => { this.loading = false; this.activities = response; }).error(() => { this.loading = false; this.activities = {}; }); } } }, events: { wbs_changed(params) { this.wbs_id = params.selection; this.loadActivities(); }, }, filters: { isEmptyObject(obj) { return Object.keys(obj).length !== 0; } } };
const path = require('path'); const slugify = require('slugify') const { createFilePath } = require(`gatsby-source-filesystem`) // Create propers node fields to differentiate Mdx blog posts from the carbon-theme // Mdx pages exports.onCreateNode = ({ node, actions, getNode }) => { const { createNodeField } = actions if(node.internal.type !== `Mdx`){ return } const fileNode = getNode(node.parent) const source = fileNode.sourceInstanceName const slug = createFilePath({ node, getNode, basePath: source }) createNodeField({ node, name: "slug", value: slug, }) // Create a field to set the language from the source if (node.internal.type === `Mdx` && source === 'blog' ) { createNodeField({ node, name: "language", value: 'en', }) } if (node.internal.type === `Mdx` && source === 'blog-fr' ) { createNodeField({ node, name: "language", value: 'fr', }) } } const createPosts = (createPage, edges) => { edges.forEach(({ node }) => { createPage({ path: `/blog/${node.fields.language}${node.fields.slug}`, component: path.resolve(`./src/templates/post.js`), context: { id: node.id, }, }); }); }; const createBlog = (createPage, edges) => { ['en', 'fr'].map( lang => { createPage({ path: `/blog/${lang}`, component: path.resolve(`./src/templates/blog.js`), context: { language: lang }, }); }) } exports.createPages = async ({ actions, graphql, reporter }) => { const result = await graphql(` query { allMdx(filter: {fields: {language: {in: ["en", "fr"]}}}) { edges { node { id excerpt(pruneLength: 250) body fields { language slug } frontmatter { category } } } } } `) if (result.errors) { reporter.panic(result.errors) } const { edges } = result.data.allMdx; createPosts(actions.createPage, edges); createBlog(actions.createPage, edges); // Then we use the result to return an array with all categories const allCategories = edges.map(({node}) => node.frontmatter.category) // Remove duplicates const categories = [...new Set(allCategories)] // Finally we create one page for each category categories.forEach(category => { const slug = slugify(category) actions.createPage({ path: `/category/${slug}`, component: path.resolve(`src/templates/category.js`), context: { category: category, slug: slug } }) }) } exports.onCreateWebpackConfig = ({ actions }) => { actions.setWebpackConfig({ resolve: { modules: [path.resolve(__dirname, 'src'), 'node_modules'], alias: { $components: path.resolve(__dirname, 'src/components'), }, }, }); }; exports.createSchemaCustomization = ({ actions, schema }) => { const { createTypes } = actions const typeDefs = [ "type Mdx implements Node { frontmatter: MdxFrontmatter }", schema.buildObjectType({ name: "MdxFrontmatter", fields: { title: "String!", slug: "String!", language: "String!", translation: "Boolean!", date:{ type: "Date!", extensions: { dateformat: {}, } }, description: "String!", category: "String!", categorySlug: { type: "String", resolve: source => slugify(source.category), }, keywords: "[String]!", card:{ type: "File", extensions: { fileByRelativePath: {}, } }, banner: { type: "File", extensions: { fileByRelativePath: {}, } }, related: "[String]", }, }), ] createTypes(typeDefs) }
/* * @Author: baby * @Date: 2016-03-02 08:41:53 * @Last Modified by: baby * @Last Modified time: 2016-07-12 09:58:47 */ 'use strict'; var gulp = require('gulp'); // 引入gulp // 引入组件 var jshint = require('gulp-jshint'); // 检查js var babel = require('gulp-babel'); // 编译es6/es7 var del = require('del'); // 删除 var gulpSequence = require('gulp-sequence'); // 顺序执行 var paths = { // scripts: ['client/js/**/*.coffee', '!client/external/**/*.coffee'], js: ['src/js/*.js'], css: ['src/css/*.css'], sass: ['src/sass/*.scss'], images: ['src/images/**/*'], html: ['src/html/**/*'] }; // Not all tasks need to use streams // A gulpfile is just another node program and you can use any package available on npm gulp.task('clean', function() { // You can use multiple globbing patterns as you would with `gulp.src` return del(['dist']); }); // 检查js脚本的任务 gulp.task('lint',function() { return gulp.src(paths.js) // .pipe(plumber()) .pipe(jshint()) .pipe(jshint.reporter('default')); }); gulp.task('babel', function() { return gulp.src('src/app.js') .pipe(babel()) .pipe(gulp.dest('dist')); }); // 定义默认任务,执行gulp会自动执行的任务 // gulp.task('default', // [ // // 'watch', // 'lint', // 'scripts', // 'sass', // 'css', // 'images', // 'html', // 'rev' // ]); gulp.task('default',gulpSequence('lint','clean',['babel']));
(function(){ var problem = { title: "Spam man", description: "Something funny...", task: "Match all the strings that are email addresses.", examples: { "thomas@example.com" : true, "Notanemail@example" : false, "ragerdragonman1337@9gf8ghj3.net" : true }, tests: { "test@example.com" : true, "aaaaaaaaaaaaaa" : false, "testcases@r" : false, "hello.com" : false, "jabba@tatooine.hutt" : true, "harry_potter@" : false, "slytherin@hogwarts." : false, }, } function loadProblem(problem){ var eid = document.getElementById // Set problem description elements eid("problem_title").value = problem.title eid("problem_description").value = problem.description eid("problem_task").value = problem.task // Set the examples (table?) } function addTestResult(test, expected, results){ var table = document.getElementById("test_results") var row = table.insertRow(-1) row.insertCell(0).innerHTML = test row.insertCell(1).innerHTML = expected row.insertCell(2).innerHTML = results } function evaluateRegex(){ var regex = document.getElementById("regex").value document.getElementById("test_table").hidden = false document.getElementById("test_results").innerHTML = "" // Set the tests Object.keys(problem.tests).forEach(function(key){ var matched = (key.search("^"+regex+"$") == 0 ? true : false) addTestResult(key, problem.tests[key], matched) }) } window.evaluateRegex = evaluateRegex })()
function Human(age = 18) { this.age = age; } Human.prototype.run = function () { console.log('the human is running~'); } function Boy() { Human.call(this); this.sex = 'boy'; } Boy.prototype = new Human(); Boy.prototype.jump = function () { console.log('the boy is jumping~'); } // Boy.prototype.constructor = Boy; // test let theBoy = new Boy(); console.log(theBoy.run()); console.log(theBoy.jump()); console.log(theBoy instanceof Boy);
/** * store actions * action 内部是异步逻辑,提交 mutations 改变状态 * @params context:与 store 实例具有相同方法和属性的 context 对象 */ export default { }
// Ajax GET请求封装 function myAjax(options){ var xhr = new XMLHttpRequest(); xhr.open('GET', options.url + options.data.dataType + options.data.index, true); xhr.onload = function(){ if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){ var ret = JSON.parse(xhr.responseText); options.onSuccess(ret); }else{ options.onError.onError1(); } }; xhr.onerror = function(){ options.onError.onError2(); }; xhr.send(); } // 设置自定义事件 var EventCenter = { on: function(type, handler){ document.addEventListener(type ,handler); }, fire: function(type, data){ return document.dispatchEvent(new CustomEvent(type, { detail: data })); } }; // 底部导航条渲染 var Footer = { // 初始化 init: function(){ this.footer = document.querySelector('footer'); this.carousel = document.querySelector('footer .carousel'); this.ulBox = document.querySelector('footer .carousel ul'); this.leftBtn = document.querySelector('footer .icon-fanhui'); this.rightBtn = document.querySelector('footer .icon-gengduo'); this.count = 0; this.bind(); this.render(); }, bind: function(){ var _this = this; window.addEventListener('resize', function(){ _this.setStyle(); }); // 底部导航滑动 this.leftBtn.addEventListener('click', function(){ _this.slideLeft(); }); this.rightBtn.addEventListener('click', function(){ _this.slideRight(); }); // 事件代理 document.querySelector('.carousel ul').addEventListener('click', function(e){ var el = e.target; el = el.tagName.toUpperCase == 'LI' ? el : el.parentNode; el.classList.add('active'); // 获取兄弟节点 var siblings = []; var allChild = el.parentNode.children; for(var i = 0; i < allChild.length; i++){ if( allChild[i] != el ){ siblings.push( allChild[i] ); } } siblings.forEach(function(part){ part.classList.remove('active'); }); // 点击向 Main 区域发送 channel_id EventCenter.fire('select-albumn', { channelId: el.getAttribute('channel_id'), channelName: el.getAttribute('channel_name') }); }); }, render: function(){ var _this = this; // Ajax 获取封面内容 myAjax({ url:'http://api.jirengu.com/', data:{ dataType: 'fm/getChannels.php', index: '' }, onSuccess: function(ret){ _this.renderFooter(ret.channels); }, onError: { onError1: function(){ alert('服务器异常!封面获取失败'); }, onError2: function(){ alert('网络异常!封面获取失败'); } } }); }, // 底部渲染 renderFooter: function(channels){ var html = ''; channels.forEach(function(element){ html += '<li channel_id='+ element.channel_id + ' channel_name='+ element.name + '>'; html += '<div class="cover" style="background-image:url('+ element.cover_small +')"></div>'; html += '<h3>'+ element.name +'</h3>'; html += '</li>'; return html; }); // 用 innerHTML 好像有风险,需要更好的解决办法。 this.ulBox.innerHTML = html; this.setStyle(); }, // 让底部获取的封面变成一排显示。 setStyle: function(){ // 得到获取封面的个数 var channelCount = document.querySelectorAll('.carousel ul li').length; var oneChannel = document.querySelector('.carousel ul li'); // 获取单个封面宽度包括外 margin。 var channelWidth = oneChannel.offsetWidth; channelWidth += parseFloat(window.getComputedStyle(oneChannel).getPropertyValue('margin-left')); channelWidth += parseFloat(window.getComputedStyle(oneChannel).getPropertyValue('margin-right')); // 设置 ul 宽度满足所有的 li this.channelWidth = channelWidth; this.ulBox.style.width = channelCount * channelWidth + 'px'; }, // 底部滑动效果实现 slideLeft: function(){ //显示器能容下几个li var carouselWidth = this.carousel.offsetWidth; var liCount = Math.floor(carouselWidth / this.channelWidth); if(this.count > 0) { this.count--; this.ulBox.style.left = -this.count * liCount * this.channelWidth + 'px'; } }, slideRight: function(){ var carouselWidth = this.carousel.offsetWidth; var liCount = Math.floor(carouselWidth / this.channelWidth); if(carouselWidth - this.ulBox.offsetLeft < this.ulBox.offsetWidth){ this.count++; this.ulBox.style.left = -this.count * liCount * this.channelWidth + 'px'; } } }; // 主要区域 var Main = { init: function(){ this.audio = new Audio(); this.audio.autoplay = true; this.btnReturn = document.querySelector('.btn-return'); this.btn = document.querySelector('.btn-play'); this.next = document.querySelector('.btn-next'); this.download = document.querySelector('.icon-xiazai'); this.lyric = document.querySelector('.progress p'); this.progressBar = document.querySelector('.progress-bar'); this.innerProgressBar = document.querySelector('.progress-bar-inner'); this.bind(); }, bind: function(){ var _this = this; EventCenter.on('select-albumn', function(object){ _this.channelId = object.detail.channelId; _this.channelName = object.detail.channelName; _this.loadMusic(); }); // 循环播放功能 this.btnReturn.addEventListener('click', function(){ if( _this.audio.loop === false){ _this.audio.loop = true; _this.btnReturn.classList.add('loop-active'); }else { _this.audio.loop = false; _this.btnReturn.classList.remove('loop-active'); } }); // 播放暂停功能 this.btn.addEventListener('click', function(){ if( this.classList.contains('icon-bofangqi-bofang') ){ _this.audio.play(); this.classList.remove('icon-bofangqi-bofang'); this.classList.add('icon-bofangqi-zanting'); }else { _this.audio.pause(); this.classList.remove('icon-bofangqi-zanting'); this.classList.add('icon-bofangqi-bofang'); } }); // 下一首功能 this.next.addEventListener('click', function(){ _this.loadMusic(); }); // 下载歌曲 this.download.addEventListener('click', function(){ window.location.assign(_this.audio.src); }); // 监听歌曲的播放暂停 this.audio.addEventListener('play', function(){ // 本想用 setTimeout 模拟循环,但不知道如何清除,先用 setInterval,待解决! clearInterval(_this.songPlayed); _this.songPlayed = setInterval(function(){ _this.updateSongStatus(); }, 1000); }); this.audio.addEventListener('pause', function(){ clearInterval(_this.songPlayed); }); // 音乐结束时播放下一首 this.audio.addEventListener('ended', function(){ _this.loadMusic(); }); // 点击进度条滑动 this.progressBar.addEventListener('click', function(e){ _this.audio.currentTime = (e.offsetX / this.offsetWidth) * _this.audio.duration; }); }, loadMusic: function(){ var _this = this; // Ajax 获取歌曲内容 myAjax({ url:'http://api.jirengu.com/', data:{ dataType: 'fm/getSong.php?', index: 'channel='+ _this.channelId }, onSuccess: function(ret){ _this.song = ret.song[0]; _this.setMusic(); _this.loadLyric(); }, onError: { onError1: function(){ alert('服务器异常!歌曲获取失败'); }, onError2: function(){ alert('网络异常!歌曲获取失败'); } } }); }, loadLyric: function(){ var _this = this; // Ajax 获取歌词内容 myAjax({ url:'http://jirenguapi.applinzi.com/', data:{ dataType: 'fm/getLyric.php?', index: '&sid='+ _this.song.sid }, onSuccess: function(ret){ var lyricObj = {}; // 歌词拆解 ret.lyric.split('\n').forEach(function(line){ var time = line.match(/\d{2}:\d{2}/); var lyric = line.replace(/\[.+\]/, ''); if(Array.isArray(time)){ time.forEach(function(time){ lyricObj[time] = lyric; }); } }); _this.lyricObj = lyricObj; }, onError: { onError1: function(){ alert('服务器异常!歌曲获取失败'); }, onError2: function(){ alert('网络异常!歌曲获取失败'); } } }); }, setMusic: function(){ this.btn.classList.remove('icon-bofangqi-bofang'); this.btn.classList.add('icon-bofangqi-zanting'); this.audio.src = this.song.url; document.querySelector('.tag span').innerText = this.channelName; document.querySelector('.detail h1').innerText = this.song.title; document.querySelector('.author').innerText = this.song.artist; document.querySelector('figure').style.backgroundImage = 'URL('+ this.song.picture +')'; document.querySelector('.bg').style.backgroundImage = 'URL('+ this.song.picture +')'; }, // 歌曲播放时要做的事,如进度条、歌曲时间跟着改变。 updateSongStatus: function(){ var min = Math.floor(this.audio.currentTime / 60) ; var sec = Math.floor(this.audio.currentTime % 60) + ''; sec = (sec.length == 2 ? sec : '0'+sec); this.lyric.innerText = min + ':' + sec; this.innerProgressBar.style.width = (this.audio.currentTime / this.audio.duration)*100 + '%'; // 歌词设置 var hasLyric = this.lyricObj['0'+min+':'+sec]; if(hasLyric){ document.querySelector('.lyric').innerText = hasLyric; } } }; Footer.init(); Main.init();
module.exports = [ { key: 'dashboard', name: 'Dashboard', icon: 'laptop', }, { key: 'users', name: 'User Manage', icon: 'user', }, { key: 'request', name: 'Request', icon: 'api', }, { key: 'UIElement', name: 'UI Element', icon: 'camera-o', clickable: false, child: [ { key: 'iconfont', name: 'IconFont', icon: 'heart-o', }, { key: 'dataTable', name: 'DataTable', icon: 'database', }, { key: 'dropOption', name: 'DropOption', icon: 'bars', }, { key: 'search', name: 'Search', icon: 'search', }, { key: 'editor', name: 'Editor', icon: 'edit', }, { key: 'layer', name: 'layer (Function)', icon: 'credit-card', }, ], }, { key: 'chart', name: 'Recharts', icon: 'code-o', child: [ { key: 'lineChart', name: 'LineChart', icon: 'line-chart', }, { key: 'barChart', name: 'BarChart', icon: 'bar-chart', }, { key: 'areaChart', name: 'AreaChart', icon: 'area-chart', }, ], }, { key: 'navigation', name: 'Test Navigation', icon: 'setting', child: [ { key: 'navigation1', name: 'Test Navigation1', }, { key: 'navigation2', name: 'Test Navigation2', child: [ { key: 'navigation21', name: 'Test Navigation21', }, { key: 'navigation22', name: 'Test Navigation22', }, ], }, ], }, ]
/* eslint-disable prefer-const,no-labels,no-inner-declarations */ import { groups as defaultGroups, customGroup } from '../../groups' import { MIN_SEARCH_TEXT_LENGTH, NUM_SKIN_TONES } from '../../../shared/constants' import { requestIdleCallback } from '../../utils/requestIdleCallback' import { hasZwj } from '../../utils/hasZwj' import { emojiSupportLevelPromise, supportedZwjEmojis } from '../../utils/emojiSupport' import { applySkinTone } from '../../utils/applySkinTone' import { halt } from '../../utils/halt' import { incrementOrDecrement } from '../../utils/incrementOrDecrement' import { DEFAULT_NUM_COLUMNS, FONT_FAMILY, MOST_COMMONLY_USED_EMOJI, TIMEOUT_BEFORE_LOADING_MESSAGE } from '../../constants' import { uniqBy } from '../../../shared/uniqBy' import { summarizeEmojisForUI } from '../../utils/summarizeEmojisForUI' import * as widthCalculator from '../../utils/widthCalculator' import { checkZwjSupport } from '../../utils/checkZwjSupport' import { requestPostAnimationFrame } from '../../utils/requestPostAnimationFrame' import { tick } from 'svelte' import { requestAnimationFrame } from '../../utils/requestAnimationFrame' import { uniq } from '../../../shared/uniq' // public export let skinToneEmoji export let i18n export let database export let customEmoji export let customCategorySorting // private let initialLoad = true let currentEmojis = [] let currentEmojisWithCategories = [] // eslint-disable-line no-unused-vars let rawSearchText = '' let searchText = '' let rootElement let baselineEmoji let tabpanelElement let searchMode = false // eslint-disable-line no-unused-vars let activeSearchItem = -1 let message // eslint-disable-line no-unused-vars let skinTonePickerExpanded = false let skinTonePickerExpandedAfterAnimation = false // eslint-disable-line no-unused-vars let skinToneDropdown let currentSkinTone = 0 let activeSkinTone = 0 let skinToneButtonText // eslint-disable-line no-unused-vars let pickerStyle // eslint-disable-line no-unused-vars let skinToneButtonLabel = '' // eslint-disable-line no-unused-vars let skinTones = [] let currentFavorites = [] // eslint-disable-line no-unused-vars let defaultFavoriteEmojis let numColumns = DEFAULT_NUM_COLUMNS let isRtl = false let scrollbarWidth = 0 // eslint-disable-line no-unused-vars let currentGroupIndex = 0 let groups = defaultGroups let currentGroup let databaseLoaded = false // eslint-disable-line no-unused-vars let activeSearchItemId // eslint-disable-line no-unused-vars // // Utils/helpers // const focus = id => { rootElement.getRootNode().getElementById(id).focus() } // fire a custom event that crosses the shadow boundary const fireEvent = (name, detail) => { rootElement.dispatchEvent(new CustomEvent(name, { detail, bubbles: true, composed: true })) } // eslint-disable-next-line no-unused-vars const unicodeWithSkin = (emoji, currentSkinTone) => ( (currentSkinTone && emoji.skins && emoji.skins[currentSkinTone]) || emoji.unicode ) // eslint-disable-next-line no-unused-vars const labelWithSkin = (emoji, currentSkinTone) => ( uniq([(emoji.name || unicodeWithSkin(emoji, currentSkinTone)), ...(emoji.shortcodes || [])]).join(', ') ) // Detect a skintone option button const isSkinToneOption = element => /^skintone-/.test(element.id) // // Determine the emoji support level (in requestIdleCallback) // emojiSupportLevelPromise.then(level => { // Can't actually test emoji support in Jest/JSDom, emoji never render in color in Cairo /* istanbul ignore next */ if (!level) { message = i18n.emojiUnsupportedMessage } }) // // Set or update the database object // $: { // show a Loading message if it takes a long time, or show an error if there's a network/IDB error async function handleDatabaseLoading () { let showingLoadingMessage = false const timeoutHandle = setTimeout(() => { showingLoadingMessage = true message = i18n.loadingMessage }, TIMEOUT_BEFORE_LOADING_MESSAGE) try { await database.ready() databaseLoaded = true // eslint-disable-line no-unused-vars } catch (err) { console.error(err) message = i18n.networkErrorMessage } finally { clearTimeout(timeoutHandle) if (showingLoadingMessage) { // Seems safer than checking the i18n string, which may change showingLoadingMessage = false message = '' // eslint-disable-line no-unused-vars } } } if (database) { /* no await */ handleDatabaseLoading() } } // // Global styles for the entire picker // /* eslint-disable no-unused-vars */ $: pickerStyle = ` --font-family: ${FONT_FAMILY}; --num-groups: ${groups.length}; --indicator-opacity: ${searchMode ? 0 : 1}; --num-skintones: ${NUM_SKIN_TONES};` /* eslint-enable no-unused-vars */ // // Set or update the customEmoji // $: { if (customEmoji && database) { console.log('updating custom emoji') database.customEmoji = customEmoji } } $: { if (customEmoji && customEmoji.length) { groups = [customGroup, ...defaultGroups] } else if (groups !== defaultGroups) { groups = defaultGroups } } // // Set or update the preferred skin tone // $: { async function updatePreferredSkinTone () { if (databaseLoaded) { currentSkinTone = await database.getPreferredSkinTone() } } /* no await */ updatePreferredSkinTone() } $: skinTones = Array(NUM_SKIN_TONES).fill().map((_, i) => applySkinTone(skinToneEmoji, i)) /* eslint-disable no-unused-vars */ $: skinToneButtonText = skinTones[currentSkinTone] $: skinToneButtonLabel = i18n.skinToneLabel.replace('{skinTone}', i18n.skinTones[currentSkinTone]) /* eslint-enable no-unused-vars */ // // Set or update the favorites emojis // $: { async function updateDefaultFavoriteEmojis () { defaultFavoriteEmojis = (await Promise.all(MOST_COMMONLY_USED_EMOJI.map(unicode => ( database.getEmojiByUnicodeOrName(unicode) )))).filter(Boolean) // filter because in Jest tests we don't have all the emoji in the DB } if (databaseLoaded) { /* no await */ updateDefaultFavoriteEmojis() } } $: { async function updateFavorites () { console.log('updateFavorites') const dbFavorites = await database.getTopFavoriteEmoji(numColumns) const favorites = await summarizeEmojis(uniqBy([ ...dbFavorites, ...defaultFavoriteEmojis ], _ => (_.unicode || _.name)).slice(0, numColumns)) currentFavorites = favorites } if (databaseLoaded && defaultFavoriteEmojis) { /* no await */ updateFavorites() } } // // Calculate the width of the emoji grid. This serves two purposes: // 1) Re-calculate the --num-columns var because it may have changed // 2) Re-calculate the scrollbar width because it may have changed // (i.e. because the number of items changed) // 3) Re-calculate whether we're in RTL mode or not. // // The benefit of doing this in one place is to align with rAF/ResizeObserver // and do all the calculations in one go. RTL vs LTR is not strictly width-related, // but since we're already reading the style here, and since it's already aligned with // the rAF loop, this is the most appropriate place to do it perf-wise. // // eslint-disable-next-line no-unused-vars function calculateEmojiGridStyle (node) { return widthCalculator.calculateWidth(node, width => { /* istanbul ignore next */ if (process.env.NODE_ENV !== 'test') { // jsdom throws errors for this kind of fancy stuff // read all the style/layout calculations we need to make const style = getComputedStyle(rootElement) const newNumColumns = parseInt(style.getPropertyValue('--num-columns'), 10) const newIsRtl = style.getPropertyValue('direction') === 'rtl' const parentWidth = node.parentElement.getBoundingClientRect().width const newScrollbarWidth = parentWidth - width // write to Svelte variables numColumns = newNumColumns scrollbarWidth = newScrollbarWidth // eslint-disable-line no-unused-vars isRtl = newIsRtl // eslint-disable-line no-unused-vars } }) } // // Update the current group based on the currentGroupIndex // $: currentGroup = groups[currentGroupIndex] // // Set or update the currentEmojis. Check for invalid ZWJ renderings // (i.e. double emoji). // $: { async function updateEmojis () { console.log('updateEmojis') if (!databaseLoaded) { currentEmojis = [] searchMode = false } else if (searchText.length >= MIN_SEARCH_TEXT_LENGTH) { const currentSearchText = searchText const newEmojis = await getEmojisBySearchQuery(currentSearchText) if (currentSearchText === searchText) { // if the situation changes asynchronously, do not update currentEmojis = newEmojis searchMode = true } } else if (currentGroup) { const currentGroupId = currentGroup.id const newEmojis = await getEmojisByGroup(currentGroupId) if (currentGroupId === currentGroup.id) { // if the situation changes asynchronously, do not update currentEmojis = newEmojis searchMode = false } } } /* no await */ updateEmojis() } // Some emojis have their ligatures rendered as two or more consecutive emojis // We want to treat these the same as unsupported emojis, so we compare their // widths against the baseline widths and remove them as necessary $: { const zwjEmojisToCheck = currentEmojis .filter(emoji => emoji.unicode) // filter custom emoji .filter(emoji => hasZwj(emoji) && !supportedZwjEmojis.has(emoji.unicode)) if (zwjEmojisToCheck.length) { // render now, check their length later requestAnimationFrame(() => checkZwjSupportAndUpdate(zwjEmojisToCheck)) } else { currentEmojis = currentEmojis.filter(isZwjSupported) requestAnimationFrame(() => { // Avoid Svelte doing an invalidation on the "setter" here. // At best the invalidation is useless, at worst it can cause infinite loops: // https://github.com/nolanlawson/emoji-picker-element/pull/180 // https://github.com/sveltejs/svelte/issues/6521 // Also note tabpanelElement can be null if the element is disconnected // immediately after connected, hence `|| {}` (tabpanelElement || {}).scrollTop = 0 // reset scroll top to 0 when emojis change }) } } function checkZwjSupportAndUpdate (zwjEmojisToCheck) { const rootNode = rootElement.getRootNode() const emojiToDomNode = emoji => rootNode.getElementById(`emo-${emoji.id}`) checkZwjSupport(zwjEmojisToCheck, baselineEmoji, emojiToDomNode) // force update currentEmojis = currentEmojis // eslint-disable-line no-self-assign } function isZwjSupported (emoji) { return !emoji.unicode || !hasZwj(emoji) || supportedZwjEmojis.get(emoji.unicode) } async function filterEmojisByVersion (emojis) { const emojiSupportLevel = await emojiSupportLevelPromise // !version corresponds to custom emoji return emojis.filter(({ version }) => !version || version <= emojiSupportLevel) } async function summarizeEmojis (emojis) { return summarizeEmojisForUI(emojis, await emojiSupportLevelPromise) } async function getEmojisByGroup (group) { console.log('getEmojiByGroup', group) if (typeof group === 'undefined') { return [] } // -1 is custom emoji const emoji = group === -1 ? customEmoji : await database.getEmojiByGroup(group) return summarizeEmojis(await filterEmojisByVersion(emoji)) } async function getEmojisBySearchQuery (query) { return summarizeEmojis(await filterEmojisByVersion(await database.getEmojiBySearchQuery(query))) } $: { // consider initialLoad to be complete when the first tabpanel and favorites are rendered /* istanbul ignore next */ if (process.env.NODE_ENV !== 'production' || process.env.PERF) { if (currentEmojis.length && currentFavorites.length && initialLoad) { initialLoad = false requestPostAnimationFrame(() => performance.measure('initialLoad', 'initialLoad')) } } } // // Derive currentEmojisWithCategories from currentEmojis. This is always done even if there // are no categories, because it's just easier to code the HTML this way. // $: { function calculateCurrentEmojisWithCategories () { if (searchMode) { return [ { category: '', emojis: currentEmojis } ] } const categoriesToEmoji = new Map() for (const emoji of currentEmojis) { const category = emoji.category || '' let emojis = categoriesToEmoji.get(category) if (!emojis) { emojis = [] categoriesToEmoji.set(category, emojis) } emojis.push(emoji) } return [...categoriesToEmoji.entries()] .map(([category, emojis]) => ({ category, emojis })) .sort((a, b) => customCategorySorting(a.category, b.category)) } // eslint-disable-next-line no-unused-vars currentEmojisWithCategories = calculateCurrentEmojisWithCategories() } // // Handle active search item (i.e. pressing up or down while searching) // /* eslint-disable no-unused-vars */ $: activeSearchItemId = activeSearchItem !== -1 && currentEmojis[activeSearchItem].id /* eslint-enable no-unused-vars */ // // Handle user input on the search input // $: { requestIdleCallback(() => { searchText = (rawSearchText || '').trim() // defer to avoid input delays, plus we can trim here activeSearchItem = -1 }) } // eslint-disable-next-line no-unused-vars function onSearchKeydown (event) { if (!searchMode || !currentEmojis.length) { return } const goToNextOrPrevious = (previous) => { halt(event) activeSearchItem = incrementOrDecrement(previous, activeSearchItem, currentEmojis) } switch (event.key) { case 'ArrowDown': return goToNextOrPrevious(false) case 'ArrowUp': return goToNextOrPrevious(true) case 'Enter': if (activeSearchItem !== -1) { halt(event) return clickEmoji(currentEmojis[activeSearchItem].id) } else if (currentEmojis.length) { activeSearchItem = 0 } } } // // Handle user input on nav // // eslint-disable-next-line no-unused-vars function onNavClick (group) { rawSearchText = '' searchText = '' activeSearchItem = -1 currentGroupIndex = groups.findIndex(_ => _.id === group.id) } // eslint-disable-next-line no-unused-vars function onNavKeydown (event) { const { target, key } = event const doFocus = el => { if (el) { halt(event) el.focus() } } switch (key) { case 'ArrowLeft': return doFocus(target.previousSibling) case 'ArrowRight': return doFocus(target.nextSibling) case 'Home': return doFocus(target.parentElement.firstChild) case 'End': return doFocus(target.parentElement.lastChild) } } // // Handle user input on an emoji // async function clickEmoji (unicodeOrName) { const emoji = await database.getEmojiByUnicodeOrName(unicodeOrName) const emojiSummary = [...currentEmojis, ...currentFavorites] .find(_ => (_.id === unicodeOrName)) const skinTonedUnicode = emojiSummary.unicode && unicodeWithSkin(emojiSummary, currentSkinTone) await database.incrementFavoriteEmojiCount(unicodeOrName) fireEvent('emoji-click', { emoji, skinTone: currentSkinTone, ...(skinTonedUnicode && { unicode: skinTonedUnicode }), ...(emojiSummary.name && { name: emojiSummary.name }) }) } // eslint-disable-next-line no-unused-vars async function onEmojiClick (event) { const { target } = event if (!target.classList.contains('emoji')) { return } halt(event) const id = target.id.substring(4) // replace 'emo-' or 'fav-' prefix /* no await */ clickEmoji(id) } // // Handle user input on the skintone picker // // eslint-disable-next-line no-unused-vars async function onSkinToneOptionsClick (event) { const { target } = event if (!isSkinToneOption(target)) { return } halt(event) const skinTone = parseInt(target.id.slice(9), 10) // remove 'skintone-' prefix currentSkinTone = skinTone skinTonePickerExpanded = false focus('skintone-button') fireEvent('skin-tone-change', { skinTone }) /* no await */ database.setPreferredSkinTone(skinTone) } // eslint-disable-next-line no-unused-vars async function onClickSkinToneButton (event) { skinTonePickerExpanded = !skinTonePickerExpanded activeSkinTone = currentSkinTone if (skinTonePickerExpanded) { halt(event) requestAnimationFrame(() => focus(`skintone-${activeSkinTone}`)) } } // To make the animation nicer, change the z-index of the skintone picker button // *after* the animation has played. This makes it appear that the picker box // is expanding "below" the button $: { if (skinTonePickerExpanded) { skinToneDropdown.addEventListener('transitionend', () => { skinTonePickerExpandedAfterAnimation = true // eslint-disable-line no-unused-vars }, { once: true }) } else { skinTonePickerExpandedAfterAnimation = false // eslint-disable-line no-unused-vars } } // eslint-disable-next-line no-unused-vars function onSkinToneOptionsKeydown (event) { if (!skinTonePickerExpanded) { return } const changeActiveSkinTone = async nextSkinTone => { halt(event) activeSkinTone = nextSkinTone await tick() focus(`skintone-${activeSkinTone}`) } switch (event.key) { case 'ArrowUp': return changeActiveSkinTone(incrementOrDecrement(true, activeSkinTone, skinTones)) case 'ArrowDown': return changeActiveSkinTone(incrementOrDecrement(false, activeSkinTone, skinTones)) case 'Home': return changeActiveSkinTone(0) case 'End': return changeActiveSkinTone(skinTones.length - 1) case 'Enter': // enter on keydown, space on keyup. this is just how browsers work for buttons // https://lists.w3.org/Archives/Public/w3c-wai-ig/2019JanMar/0086.html return onSkinToneOptionsClick(event) case 'Escape': halt(event) skinTonePickerExpanded = false return focus('skintone-button') } } // eslint-disable-next-line no-unused-vars function onSkinToneOptionsKeyup (event) { if (!skinTonePickerExpanded) { return } switch (event.key) { case ' ': // enter on keydown, space on keyup. this is just how browsers work for buttons // https://lists.w3.org/Archives/Public/w3c-wai-ig/2019JanMar/0086.html return onSkinToneOptionsClick(event) } } // eslint-disable-next-line no-unused-vars async function onSkinToneOptionsFocusOut (event) { // On blur outside of the skintone options, collapse the skintone picker. // Except if focus is just moving to another skintone option, e.g. pressing up/down to change focus const { relatedTarget } = event if (!relatedTarget || !isSkinToneOption(relatedTarget)) { skinTonePickerExpanded = false } }
import React, { Component } from 'react'; import { Document, Page } from "react-pdf/dist/entry.webpack"; import { Button, Checkbox, Form } from 'semantic-ui-react'; import axios from 'axios'; import { Redirect } from 'react-router-dom'; import { Header, Segment, Grid, Divider } from 'semantic-ui-react' import Axios from 'axios'; var jsonData; console.log("JsonData", jsonData); class Edit extends Component { constructor(props) { super(props); var myVar = this.props.jsonData.data.data.data; console.log('The props: ', this.props); // sync state and props together this.state = { trackingNumber: myVar.trackingNumber, status: myVar.status, deliveryDate: myVar.deliveryDate, shipDate: myVar.shipDate, shipcity: myVar.shipcity, shipState: myVar.shipState, shipCountry: myVar.shipCountry, reference: myVar.reference, submitted: false } this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleChange = (e) => { this.setState({ [e.target.name]: e.target.value }); } handleSubmit(event) { const { trackingNumber, reference } = this.state; // go get the values in the form this.setState({ submitted: true }) console.log("State", this.state); //post var formObj = this.state; axios.post('http://localhost:3030/receiving/update', { formObj }) } render() { var myVar = this.state; var pdfPath = "http://localhost:3030/" + myVar.trackingNumber + ".pdf"; if (this.state.submitted === false) { return ( <header className="App-header"> <Segment size="massive" inverted> <hr width="1450px"></hr> <Grid columns={2} relaxed='very'> <Grid.Column> <div> <embed src={pdfPath} width="680px" height="750px" align="left" /> </div> </Grid.Column> <Grid.Column> <Form onSubmit={this.handleSubmit} inverted> <Form.Field> <label>Tracking Number</label> <input name='trackingNumber' value={this.state.trackingNumber} onChange={this.handleChange} /> </Form.Field> <Form.Field> <label>Status</label> <input defaultValue={myVar.status} onChange={this.handleChange} name='status' /> </Form.Field> <Form.Field> <label>Delivery Date</label> <input defaultValue={myVar.deliveryDate} onChange={this.handleChange} name='deliveryDate' /> </Form.Field> <Form.Field> <label>Shipped Date</label> <input defaultValue={myVar.shipDate} onChange={this.handleChange} name='shipDate' /> </Form.Field> <Form.Field> <label>City</label> <input defaultValue={myVar.shipcity} onChange={this.handleChange} name='shipcity' /> </Form.Field> <Form.Field> <label>State</label> <input type="text" list="states" placeholder={myVar.shipState} onChange={this.handleChange} name='shipState' /> <datalist id="states"> <option value="AL">Alabama</option> <option value="AK">Alaska</option> <option value="AZ">Arizona</option> <option value="AR">Arkansas</option> <option value="CA">California</option> <option value="CO">Colorado</option> <option value="CT">Connecticut</option> <option value="DE">Delaware</option> <option value="DC">District Of Columbia</option> <option value="FL">Florida</option> <option value="GA">Georgia</option> <option value="HI">Hawaii</option> <option value="ID">Idaho</option> <option value="IL">Illinois</option> <option value="IN">Indiana</option> <option value="IA">Iowa</option> <option value="KS">Kansas</option> <option value="KY">Kentucky</option> <option value="LA">Louisiana</option> <option value="ME">Maine</option> <option value="MD">Maryland</option> <option value="MA">Massachusetts</option> <option value="MI">Michigan</option> <option value="MN">Minnesota</option> <option value="MS">Mississippi</option> <option value="MO">Missouri</option> <option value="MT">Montana</option> <option value="NE">Nebraska</option> <option value="NV">Nevada</option> <option value="NH">New Hampshire</option> <option value="NJ">New Jersey</option> <option value="NM">New Mexico</option> <option value="NY">New York</option> <option value="NC">North Carolina</option> <option value="ND">North Dakota</option> <option value="OH">Ohio</option> <option value="OK">Oklahoma</option> <option value="OR">Oregon</option> <option value="PA">Pennsylvania</option> <option value="RI">Rhode Island</option> <option value="SC">South Carolina</option> <option value="SD">South Dakota</option> <option value="TN">Tennessee</option> <option value="TX">Texas</option> <option value="UT">Utah</option> <option value="VT">Vermont</option> <option value="VA">Virginia</option> <option value="WA">Washington</option> <option value="WV">West Virginia</option> <option value="WI">Wisconsin</option> <option value="WY">Wyoming</option> </datalist> </Form.Field> <Form.Field> <label>Country</label> <input type="text" list="countries" placeholder={myVar.shipCountry} onChange={this.handleChange} name='shipCountry' /> <datalist id="countries"> <option value="US"></option> <option value="CA"></option> <option value="UK"></option> <option value="MX"></option> </datalist> </Form.Field> <Form.Field> <label>Invoice Number#</label> <input name='reference' defaultValue={myVar.reference} onChange={this.handleChange} /> </Form.Field> <Button type='submit'>Submit</Button> </Form> </Grid.Column> </Grid> <Divider vertical >Edit</Divider> </Segment> </header> ); } else if (this.state.submitted === true) { return <Redirect to='/' /> } } } export default Edit;
import fs from 'fs'; import dotenv from 'dotenv'; import { genEncryptKey, genEncryptKeyName } from './keyGen'; const defaultenv = () => { let path = `.env`.trim(); if (fs.existsSync(path)) { let envConfig = dotenv.parse(fs.readFileSync(path)); for (var k in envConfig) { process.env[k] = envConfig[k]; } } }; const loaddotenv = () => { if (process.env.DMPENV) { let path = `.env.${process.env.DMPENV}`.trim(); if (fs.existsSync(path)) { let envConfig = dotenv.parse(fs.readFileSync(path)); for (var k in envConfig) { process.env[k] = envConfig[k]; } } else { defaultenv(); } } else { defaultenv(); } // encrypt req/res process.env['DATA_ENCRYPT_KEY'] = genEncryptKey(); process.env['DATA_ENCRYPT_KEY_NAME'] = genEncryptKeyName(); }; export { loaddotenv };
export default { "en-US": { "mek.radial": "Radial", "mek.dynamicLinkWidth": "Dynamic link width", "mek.turnOnPathSelect": "Turn on linked selection", "mek.turnOffPathSelect": "Turn off linked selection", "mek.excludeDescendants": "Split totals", "mek.includingDescendants": "(total)", "mek.showNullNodes": "Show null nodes" }, "sv-SE": { "mek.radial": "Radiell", "mek.dynamicLinkWidth": "Dynamisk länkbredd", "mek.turnOnPathSelect": "Slå på länkade urval", "mek.turnOffPathSelect": "Slå av länkade urval", "mek.excludeDescendants": "Separera totalen", "mek.includingDescendants": "(totalt)", "mek.showNullNodes": "Visa null-noder" } };
angular.module("EcommerceModule").controller("HeaderController", function ($scope, $mdDialog, $cookies, $state, $window, MainpageService, CartService){ $scope.info; $scope.loginStatus = $cookies.getObject("token") === undefined ? false : true; $scope.keyWord; $scope.CategoryData = []; $scope.SubCategoryData = []; this.BASEURL = "http://localhost:8080/" this.doSearch = function(key){ if(key.which === 13 ) window.location.href = "#!/search/"+$scope.keyWord; } var getCategory = function (callback1, callback2){ MainpageService.httpGetCategory().then( function(response){ $scope.CategoryData = response.data.object; callback1(callback2); }, function(error){ console.log(error); }) } var getSubCategory = function (callback){ MainpageService.httpGetSubCategory().then( function(response){ $scope.SubCategoryData = response.data.object; callback(); }, function(error){ console.log(error); }) } var solveCategory = function(){ for(var j = 0; j<$scope.CategoryData.length; j++){ $scope.CategoryData[j].subcategory = []; } var j = 0; for(var i = 0 ; i<$scope.SubCategoryData.length; i++){ for(; j<$scope.CategoryData.length; j++){ if($scope.SubCategoryData[i].categoryDTO.idCategory == $scope.CategoryData[j].idCategory){ $scope.CategoryData[j].subcategory.push($scope.SubCategoryData[i]); break; } } } } this.logout = function(){ MainpageService.logOut($cookies.getObject("token")[1]).then( function(response){ $cookies.remove("token"); $window.location.href= "/abcClientApp/"; }, function(error){ $cookies.remove("token"); $window.location.href= "/abcClientApp/"; } ) } this.openManagerProductPage = function(){ $state.go("producerManagement.managementProduct"); } this.openCart = function(){ $state.go("userManagement.cart"); } var getInfo = function(){ var object = $cookies.getObject("token"); if(object !== undefined){ $scope.info = object[0]; } } this.checkProducerRole = function(){ var object = $cookies.getObject("token"); if(object!== undefined && object[0].role !== "PRODUCER"){ return false; } return true; } getInfo(); getCategory(getSubCategory, solveCategory); });
$(function() { // ------------------------------------------------------------------------ // Utility Functions // ------------------------------------------------------------------------ // Display the infobox with a message function infoBoxMessage( message, duration ) { // Default of 3 seconds for a message duration = (typeof duration !== 'undefined') ? duration : 3000; $('.pd-infobox') .finish() // Stop any current animation .fadeOut( 10 ) // Fade out quickly in case there was a message already .text( message ) .fadeIn( 400 ) .delay( duration ) .fadeOut( 400 ); }; function getSongTitle() { // If its a song name that doesn't marquee around var ret = $('.nowPlayingTopInfo__current__trackName div div' ).text(); // If it's a marquee then get the name this way. if ( $('.nowPlayingTopInfo__current__trackName .Marquee__wrapper__content__child' ).length > 0 ) { ret = $('.nowPlayingTopInfo__current__trackName .Marquee__wrapper__content__child' )[0].innerText; } return ret; } // Send the download request/song information to background.js function downloadSong() { console.log({ station : $('.StationListItem__content--current span').text(), title : getSongTitle(), artist : $('.nowPlayingTopInfo__current__artistName').text(), album : $('.nowPlayingTopInfo__current__albumName' ).text(), albumArt : $("div[data-qa='album_active_image']").css('background-image').replace(/^url\(["']?/, '').replace(/["']?\)$/, '') }); chrome.runtime.sendMessage({ station : $('.StationListItem__content--current span').text(), title : getSongTitle(), artist : $('.nowPlayingTopInfo__current__artistName').text(), album : $('.nowPlayingTopInfo__current__albumName' ).text(), albumArt : $("div[data-qa='album_active_image']").css('background-image').replace(/^url\(["']?/, '').replace(/["']?\)$/, '') }, function( response ) {} ); } // 'sleeps' until the song data updates at which point the song can be downloaded lastTimeout = null; lastTitle = ""; continuous = false; function waitForSongData() { console.log('looking for song data', lastTitle, getSongTitle()); // In case we are already looping - possible when skipping a song quickly clearTimeout( lastTimeout ); // If the song data isn't there 'sleep' for a second if (lastTitle == getSongTitle()) { lastTimeout = setTimeout( waitForSongData, 1000 ); return; }; console.log('song data found'); // if we are in continuous mode then download the song // Try waiting a second because it seems like titles are getting pulled wrong. if ( continuous ){ setTimeout(downloadSong, 1000); } // only re-enable the download button if we aren't continuously downloading songs else { $('.pd-download-single').prop("disabled", false); } // Either way update the text on the download button because it looks nice $('.pd-download-single').text("Download - " + getSongTitle() ); }; // ------------------------------------------------------------------------ // I'm Still Listening - Need to wait and see what the new message looks like // ------------------------------------------------------------------------ // Function to click the "I'm still listening" button function keepListening() { console.log( $('.StillListeningBody button') ); console.log( "Still listening click!" ); // Need's the [0], which is inconsistent with using the browser console, but oh well. $('.StillListeningBody button')[0].click(); }; // Watch the body for when the still listening button is added to it. // https://github.com/MiniDude22/jquery-observe $('body').observe( 'added', '.StillListeningBody', function( record ){ setTimeout( keepListening, 3000 ); }); // ------------------------------------------------------------------------ // Add controls // ------------------------------------------------------------------------ // Wait for the controls to load $('body').observe( 'added', '.Tuner__Control__ThumbDown', function( record ){ // Append the continuous download button next to the pandora logo $('.Tuner__Control__ThumbDown').before('<div class="Tuner__Control Tuner__Control_Download"><button class="pd-download-continuous">Start Continuous Download</button></div>'); // Append the download button left of the Thumbs Down // initially disabled... Will be enabled when the song loads and is ready to download $('.Tuner__Control__ThumbDown').before('<div class="Tuner__Control Tuner__Control_Download"><button class="pd-download-single" disabled=disabled>Download</button></div>'); // Add the info box to the body which will be displayed later $('body').append('<div class="pd-infobox"></div>'); // Add functionality to the download button. $('.pd-download-single').click(() => { downloadSong() }); // Make the continuous button toggleable $('.pd-download-continuous').click(() => { if ( continuous ){ $('.pd-download-continuous').text( "Start Continuous Download" ); $('.pd-download-single').prop("disabled", false); } else { $('.pd-download-continuous').text( "Stop Continuous Download" ); $('.pd-download-single').prop("disabled", true); } continuous = !continuous; }); // Message handler for messages from background.js chrome.runtime.onMessage.addListener(( request, sender, sendResponse ) => { console.log( request ); if ( request.type == "info" ) { infoBoxMessage( request.data ); }; if ( request.type == "disableDownloadButton" ) { $('.pd-download-single').prop("disabled", true ); }; if ( request.type == "enableDownloadButton" ) { $('.pd-download-single').prop("disabled", false); }; if ( request.type == "newSong" ) { $('.pd-download-single').prop("disabled", true); // lastTitle = getSongTitle(); waitForSongData(); }; }); }); });
// Created By Fabian Becerra // Mail: fabian.becerra@runcode.co // Company: Runcode Ingeniería SAS const mongoose = require('mongoose'); const roleSchema = new mongoose.Schema({ name: { type: String, required: [true, 'Por favor ingrese el nombre'] }, description: String, users: [ { type: mongoose.Schema.Types.ObjectId, ref: "User" } ], active: { type: Boolean, default: true, select: false } }); roleSchema.pre(/^find/, function(next) { // this points to the current query this.find({ active: { $ne: false } }); next(); }); const Role = mongoose.model('Role', roleSchema); module.exports = Role;
import React, { Component, Suspense } from 'react'; import { AppAside, AppFooter, AppHeader, AppSidebar, AppSidebarFooter, AppSidebarForm, AppSidebarHeader, AppSidebarMinimizer, AppBreadcrumb2 as AppBreadcrumb, AppSidebarNav2 as AppSidebarNav, } from '@coreui/react'; const DefaultFooter = React.lazy(() => import('./Footer')); const DefaultHeader = React.lazy(() => import('./Header')); let ViewPage = React.lazy(() => import('../proposal/view')); if (localStorage.getItem('role') == 3) { ViewPage = React.lazy(() => import('../proposal/create')); } class DefaultLayout extends Component { constructor(props) { super(props); this.label = "View Proposals"; if (localStorage.getItem('role') == 3) { this.label = "Create Proposal"; } } loading = () => <div className="animated fadeIn pt-1 text-center">Loading...</div> signOut(e) { e.preventDefault(); localStorage.removeItem('role'); localStorage.removeItem('name'); localStorage.removeItem('avatar'); window.location.href = '/'; // history.push('/'); } render() { return ( <div className="app"> <AppHeader fixed> <Suspense fallback={this.loading()}> <DefaultHeader onLogout={e=>this.signOut(e)}/> </Suspense> </AppHeader> <div className="app-body"> <AppSidebar fixed display="lg"> <AppSidebarHeader /> <AppSidebarForm /> <Suspense> <ul> <li>{this.label}</li> </ul> </Suspense> <AppSidebarFooter /> <AppSidebarMinimizer /> </AppSidebar> <main className="main"> <ViewPage/> </main> </div> <AppFooter> <Suspense fallback={this.loading()}> <DefaultFooter /> </Suspense> </AppFooter> </div> ); } } export default DefaultLayout;
const {lsb}=require("../lsb") it("lsb returns correct value",()=>{ expect(lsb(12)).toBe(4); expect(lsb(1)).toBe(1); expect(lsb(2)).toBe(2); expect(lsb(3)).toBe(1); expect(lsb(4)).toBe(4); expect(lsb(5)).toBe(1); })
function MenyItems (props) { return ( <button id={props.name} className="menyItems">{props.name}</button> ) } export default MenyItems
import { useState } from 'react'; export default function AuthToken() { const getToken = () => { const tokenString = window.localStorage.getItem('token'); return tokenString; }; const getUser = () => { const userData = window.localStorage.getItem('user_data'); return JSON.parse(userData); } const [token, setToken] = useState(getToken()); const [user, setUser] = useState(getUser()); const saveToken = (userToken) => { window.localStorage.setItem('token', userToken); setToken(userToken); }; const saveUser = (jsonData) => { console.log("Saving Token") window.localStorage.setItem('user_data', JSON.stringify(jsonData)); setUser(jsonData); } const deleteToken = () => { window.localStorage.removeItem('token'); setToken(); } const deleteUser = () => { window.localStorage.removeItem('user_data'); setUser(); } return { setUser: saveUser, removeUser: deleteUser, setToken: saveToken, removeToken: deleteToken, user, token } }
import React, { lazy, Suspense } from 'react'; import { Route } from 'react-router-dom'; import Header from './components/Header/Header'; const HomePage = lazy(() => import('./components/HomePage/HomePage')); const MoviesPage = lazy(() => import('./components/HomePage/MoviesPage')); const MovieDetailsPage = lazy(() => import('./components/MovieDetailsPage/MovieDetailsPage'), ); function App() { return ( <div> <Header /> <Suspense fallback={<div>Завантаження...</div>}> <Route exact path="/" component={HomePage} /> <Route exact path="/movies" component={MoviesPage} /> <Route path="/movies/:movieId" component={MovieDetailsPage} /> </Suspense> </div> ); } export default App;
Template.teams.helpers({ teams: function() { return Teams.find({game_id: this._id}); }, display: function() { const uid = Meteor.userId(); // console.log(uid); return uid && (!this.players || !this.players.some(function(p) { return p._id === uid; })); } }); Template.teams.events({ 'submit': function(e) { e.preventDefault(); let name = $('#teamName').val(); console.log('teamCreate: ', name); Meteor.call('teamCreate', this._id, name); $('#teamName').val(''); $('.teams-modal').hide(); }, 'click .join': function(e) { Meteor.call('teamJoin', this.game_id, e.target.getAttribute("data-teamId")); $('.teams-modal').hide(); }, 'click .cancel': function() { $('.teams-modal').hide(); } }); Template.team.helpers({ members: function() { return this.members; }, display: function() { return Meteor.userId() && (!this.game().players || !this.game().players.some(function(p) { return p._id === Meteor.userId() })); } });
import React, { useEffect, useState } from "react"; import { ModalTimeOff } from "../modal-timeoff/ModalTimeOff"; import { firebaseTools } from "../../utils/firebase"; export const DaysOffLayout = () => { const [daysOff, setDaysOff] = useState({ everyYearVacation: 0, leaveWithoutPay: 0, sickLeave: 0, remoteWork: 0, conference: 0 }); useEffect(() => { firebaseTools.daysOff().then(a => {setDaysOff(a)}); }, []); const items = [ {typeLabel: "everyYearVacation", daysLabel: daysOff.everyYearVacation}, {typeLabel: "leaveWithoutPay", daysLabel: daysOff.leaveWithoutPay}, {typeLabel: "sickLeave", daysLabel: daysOff.sickLeave}, {typeLabel: "remoteWork", daysLabel: daysOff.remoteWork}, {typeLabel: "conference", daysLabel: daysOff.conference} ]; return ( <div> {items.map((item, idx) => { return ( <ModalTimeOff key={idx} typeLabel={item["typeLabel"]} daysLabel={item["daysLabel"]} /> ); })} </div> ) };
export const GET_CAR_LIST = 'car2GoRules/GET_CAR_LIST';
import Axios from 'axios'; import { SHIPMENT_CONSUME_ERROR, SHIPMENT_CREATE_FAILURE, SHIPMENT_CREATE_REQUEST, SHIPMENT_CREATE_SUCCESS, SHIPMENT_DELETE_REQUEST, SHIPMENT_DELETE_SUCCESS, SHIPMENT_GET_ALL_FAILURE, SHIPMENT_GET_ALL_REQUEST, SHIPMENT_GET_ALL_SUCCESS, SHIPMENT_UPDATE_FAILURE, SHIPMENT_UPDATE_REQUEST, SHIPMENT_UPDATE_SUCCESS, } from './index'; export const getAllShipments = () => ({ types: [SHIPMENT_GET_ALL_REQUEST, SHIPMENT_GET_ALL_SUCCESS, SHIPMENT_GET_ALL_FAILURE], request: () => Axios.get('/api/shipment/'), shouldSkip: (state) => state.shipments.isFetching, }); export const createShipment = (data) => ({ types: [SHIPMENT_CREATE_REQUEST, SHIPMENT_CREATE_SUCCESS, SHIPMENT_CREATE_FAILURE], request: () => Axios.post('/api/shipment/', data), shouldSkip: (state) => state.shipments.isCreating, }); export const updateShipment = (data) => ({ types: [SHIPMENT_UPDATE_REQUEST, SHIPMENT_UPDATE_SUCCESS, SHIPMENT_UPDATE_FAILURE], payload: { id: data.id }, request: () => Axios.put(`/api/shipment/${data.id}/`, data), shouldSkip: (state) => state.shipments.isUpdating, }); export const deleteShipment = (data) => ({ types: [SHIPMENT_DELETE_REQUEST, SHIPMENT_DELETE_SUCCESS, SHIPMENT_DELETE_SUCCESS], payload: { id: data.id }, request: () => Axios.delete(`/api/shipment/${data.id}/`, { data: data }), shouldSkip: (state) => state.isDeleting, }); export const consumeShipmentError = () => ({ type: SHIPMENT_CONSUME_ERROR, });
//resolve or reject can be called only once and only one of them //will be called. whichever is called first respective callback //function will be called. //the best thing about promises is that you will never end up //calling your callbacks twice.and there will not be a lot of //'if' and 'else' statements. // var promise = new Promise((resolve,reject) => { // setTimeout(() => { // //resolve('hey! it worked'); // reject('Sorry! it failed'); // },2000); // }); // promise.then((msg) => { // console.log('Success: ',msg); // }, // (errorMsg) => { // console.log('Error: ',errorMsg); // }) //here we will be defining an aync function which will take //input and return promise var asyncAdd = (a,b) => { return new Promise((resolve,reject) => { setTimeout(() => { if(typeof(a)==='number' && typeof(b)==='number'){ resolve(a+b); } else{ reject('Inputs should be numbers'); } },1500); }) } asyncAdd(2,4).then((result) => { console.log("Result: ",result); return asyncAdd(result,33); }).then((res) => { console.log("result: ",res); }).catch((errorMsg) => { console.log('arguments must be numbers'); })
/** * 展开二级评论 */ function collapseComments(e) { var id = $(e).attr("data-id"); $("#comment-body-"+id).append("<div class='col-lg-12 col-md-12 col-sm-12 col-sm-12 collapse sub-comments'\n" + " id='comment-"+id+"'></div>") if ($("#comment-" + id).hasClass("in")) { //折叠二级评论 $("#comment-" + id).removeClass("in"); $(e).removeClass("active"); $(".btn-comment2").remove() $("#comment-"+id).remove() } else { $.ajax({ type: "GET", url: "/comment/"+id, contentType: "application/json", dataType: "json", success: function (msg) { $.each(msg,function (i,comment) { var $comment = $( " <div class='col-lg-12 col-md-12 col-sm-12 col-sm-12 media'>\n" + " <div class='media-left'>\n" + " <span href=#>\n" + " <img class='media-object img-rounded' src="+comment.user.avatarUrl+" alt=...>\n" + " </span>\n" + " </div>\n" + " <div class='media-body'>\n" + " <span>\n" + " <h5 class='media-heading'>"+comment.user.name+"</h5>\n" + " </span>\n" + " <div>"+comment.content+"</div>\n" + " <div class='menu'>\n" + " <span class='pull-right'\n" + " >"+formatDate(new Date(comment.gmtCreate))+"</span>\n" + " </div>\n" + " </div>\n" + " <hr class='col-lg-12 col-md-12 col-sm-12 col-sm-12'>\n" + " </div>"); $("#comment-"+id).append($comment); }); $("#comment-"+id).append($(" <div class='col-lg-12 col-md-12 col-sm-12 col-sm-12 btn-comment2'>\n" + " <input type='hidden' id='comment-id' value='"+id+"'>\n" + " <input type='text' id='comment2-content' class='form-control' placeholder='评论一下......'>\n" + " <button type='button' class='btn btn-success pull-right' onclick='post2Comment()'>评论\n" + " </button>\n" + " </div>")) } }); //打开二级评论 $("#comment-" + id).addClass("in"); $(e).addClass("active"); } } function formatDate(now) { var year=now.getFullYear(); var month=now.getMonth()+1; var date=now.getDate(); return year+"-"+month+"-"+date; } function comment(targetId,content,type) { if (!content) { alert("评论不能为空~~~") return; } $.ajax({ type: "POST", url: "/comment", contentType: "application/json", dataType: "json", data: JSON.stringify({ "parentId": targetId, "content": content, "type": type }), success: function (msg) { if (msg.code == 200) { $(".comment-section").hide(); window.location.reload(); } else { if (msg.code == 2003) { var isAccepted = confirm(msg.message); if (isAccepted) { window.open("https://github.com/login/oauth/authorize?client_id=af36ccbaf9f845f7d2e7&redirect_uri=http://localhost:8080/callback&scope=user&state=1") window.localStorage.setItem("closeable", "true"); } } else { alert(msg.message) } } } }); } /** *发送评论内容 */ function post() { var id = $("#question_id").val(); var content = $("#comment-content").val(); comment(id,content,1) } /** * 发送二级评论 */ function post2Comment() { var content = $("#comment2-content").val(); var id = $("#comment-id").val(); comment(id,content,2) } function selectTag(value) { var preValue = $("#tag").val(); if(preValue == ""){ $("#tag").val($(value).attr("data-tag")) }else { var tags = preValue.split(","); for(var i=0;i<tags.length;i++){ if(tags[i] == $(value).attr("data-tag")){ return; } } $("#tag").val(preValue+","+$(value).attr("data-tag")) } } function showSelectTag() { $("#selectTag").show(); } function hideSelectTag() { // 点击空白消失 $.onclick=function(){ $("#selectTag").hide(); } } //计时函数 function timeCount(val,timeleft){ timeleft-=1 if (timeleft>0){ $(val).html(timeleft+" 秒后重发"); setTimeout(timeCount(val,timeleft),1000); } else { $(val).html("重新发送"); timeleft=60 //重置等待时间 $(val).removeAttr("disabled"); } } function getConfirmCode(val) { var phoneNumbers = $("#phoneNumbers").val(); $(val).attr("disabled",true); var timeleft = 60; $.ajax({ type: "GET", url: "/sms/"+phoneNumbers, success: function (msg) { alert(msg); } }); timeCount(val,timeleft); }
import React from 'react' export default class extends React.Component { render () { const { error, children } = this.props const errorStringified = JSON.stringify(error, null, 2) const message = errorStringified === '{}' ? error.toString() : errorStringified return ( <div className='error'> <pre>{message}</pre> {children} </div> ) } }
require("dotenv").config(); const fs = require("fs"); fs.writeFileSync( "env.ts", ` export const ENV = { GRAPHQL_API_URL: '${process.env.GRAPHQL_API_URL}', GRAPHQL_API_TOKEN: '${process.env.GRAPHQL_API_TOKEN}' }; ` );
const {readdirSync} = require('fs-extra'); const {resolve, extname} = require('path'); const indir = resolve('./contents/'); module.exports = function getArticleIndex() { const localeContents = {}; const dir = readdirSync(indir); for (let locale of dir) { localeContents[locale] = readdirSync(`${indir}/${locale}/article`) .filter(filename => extname(filename) === '.md'); } return localeContents; };
import { fromJS } from 'immutable'; import * as actionTypes from './constant'; import { getBannerList, getRecommendList } from '../../../api/request'; export const updateBannerList = (data) => ({ type: actionTypes.CHANGE_BANNER, data: fromJS(data) }) export const updateRecommendList = (data) => ({ type: actionTypes.CHANGE_RECOMMEND_LIST, data: fromJS(data) }) export const updateEnterLoading = (data) => ({ type: actionTypes.CHANGE_ENTER_LOADING, data }); export const _getBannerList = () => { return (dispatch) => { getBannerList().then(data => { dispatch(updateBannerList(data.banners)); }).catch(()=>{ console.log('banner数据传输错误') }) } } export const _getRecommendList = () => { return (dispatch) => { getRecommendList().then(data => { dispatch(updateRecommendList(data.result)); dispatch(updateEnterLoading(false)); }).catch(()=>{ console.log('推荐歌单数据传输错误') }) } }
import React, { Component } from 'react' import ReactDOM from 'react-dom' const TextInput = React.forwardRef((props, ref) => ( <input type="text" placeholder="Hello to forwardRef" ref={ref} /> )) const inputRef = React.createRef() class App extends Component { constructor(props) { super(props) this.myRef = React.createRef() } handleSubmit = event => { event.preventDefault() alert('input value is:' + inputRef.current.value) } render() { return ( <form onSubmit={this.handleSubmit}> <TextInput ref={inputRef} /> <button type="submit">Submit</button> </form> ) } } ReactDOM.render(<App />, document.querySelector('#root'))
/* * @Description: * @Author: yamanashi12 * @Date: 2019-05-29 10:55:24 * @LastEditTime: 2020-12-01 14:15:39 * @LastEditors: Please set LastEditors */ import { mapState } from 'vuex' import * as httpAgent from '@/utils/http' import { apiResolver } from '@/views/lego/utils/apiResolver' import { useCodeEvent } from '@/views/lego/utils' export default { computed: { ...mapState({ isEdit: state => state.manage.isEdit }), options() { return this.item.optionsType === 1 ? this.apiOptions : this.item.options } }, data() { return { apiOptions: [] } }, mounted() { // 值的转换 this.mapperValue() // 代码组件 - 自定义生命周期 - 初始化 created useCodeEvent(this.item, 'componentCreated', this)(this.query, this.item, this.$store.getters['manage/idModule']) // 获取接口枚举数据,解析转换 if (!this.isEdit) { this.getOptions() } }, beforeDestroy() { // 代码组件 - 自定义生命周期 - 销毁前 created useCodeEvent(this.item, 'componentWillDestroy', this)(this.item, this.$store.getters['manage/idModule']) }, methods: { /** * @method: value映射值转化,number或string类型 * @param {type} * @return: * @Author: yamanashi12(yamanashi12@qq.com) * @Date: 2019-08-28 10:40:33 */ mapperValue() { if (this.item.optionsType === 2) { if (Array.isArray(this.item.value)) { try { const arr = [] this.item.value.forEach(item => arr.push(this.getValue(item))) // 处理value的转换 this.$set(this.item, 'value', arr) } catch (error) { console.log(error) } } else { // 处理value的转换 this.$set(this.item, 'value', this.getValue(this.item.value)) } // 处理数据源 this.$set(this.item, 'options', this.item.options.map(item => ({ label: item.label, value: this.getValue(item.value) }))) } }, // 数字 、 字符串 类型转化 getValue(value) { if (!value && value !== 0) return '' try { if (this.item.valueType === 'number') { const num = parseInt(value, 10) return Number.isNaN(num) ? value : num } return value.toString() } catch (_) { return '' } }, /** * @method: 接口获取数据或数字类型处理 * @param {type} * @return: * @Author: yamanashi12(yamanashi12@qq.com) * @Date: 2019-08-28 10:40:51 */ getOptions() { if (this.item.optionsType === 1 && this.item.valueKey && this.item.labelKey && this.item.apiUrl) { const { url, type, requestQuery, option } = apiResolver(this.item.apiUrl) const httpParams = { ...requestQuery } // 代码组件 - 自定义生命周期 - 接口请求之前 beforeSend useCodeEvent(this.item, 'componentBeforeSend', this)(httpParams, this.item, this.$store.getters['manage/idModule']) httpAgent[type](url, httpParams, { context: this, noAuth: true, cache: 6000, preview302: true, ...option }).then((res) => { // 代码组件 - 自定义生命周期 - 接口请求后 afterSend useCodeEvent(this.item, 'componentAfterSend', this)(res.data, this.item, this.$store.getters['manage/idModule']) let dataEnum = [] if (this.item.dataKey) { dataEnum = res.data[this.item.dataKey] } else { dataEnum = res.data } if (!Array.isArray(dataEnum)) { throw new Error(`配置错误:枚举数据类型错误 -> ${this.item.id},`) } this.apiOptions = dataEnum.map(item => ( { label: item[this.item.labelKey], value: item[this.item.valueKey] } )) }).catch(() => { this.item.options = [] }) } else if (this.item.optionsType === 2 && this.item.valueType === 'number') { this.item.options.forEach((item) => { try { const num = parseInt(item.value, 10) this.$set(item, 'value', Number.isNaN(num) ? item.value : num) } catch (error) { if (process.env.NODE_ENV === 'development') { console.log(error) } } return item }) } }, handleChange() { } } }
import asyncHandler from "express-async-handler"; import Category from "../models/categoryModel.js"; import Variation from "../models/variationModel.js"; import SubVariation from "../models/subVariationModel.js"; // @desc Fetch all Category // @route GET /api/Category // @access Public const getCategory = asyncHandler(async (req, res) => { const category = await Category.find() .populate({ path: "variations", select: "name", populate: { path: "subVariations", select: "name", }, }) .select("name") .exec(); res.json({ category }); }); // @desc Fetch single Category // @route GET /api/Category/:id // @access Public const getCategoryById = asyncHandler(async (req, res) => { const category = await Category.findById(req.params.id).populate("variation"); if (category) { res.json(category); } else { res.status(404); throw new Error("Category not found"); } }); // // @desc Delete a Category // // @route DELETE /api/Category/:id // // @access Private/Admin const deleteCategory = asyncHandler(async (req, res) => { const category = await Category.findById(req.params.id); if (category) { await category.remove(); res.json({ message: "Category removed" }); } else { res.status(404); throw new Error("Category not found"); } }); // // @desc Create a Category // // @route POST /api/Category // // @access Private/Admin const createCategory = asyncHandler(async (req, res) => { const category = new Category({ name: "Sample name", }); const createdCategory = await category.save(); res.status(201).json(createdCategory); }); // // @desc Update a Category // // @route PUT /api/Category/:id // // @access Private/Admin const updateCategory = asyncHandler(async (req, res) => { const { name, variations } = req.body; const category = await Category.findById(req.params.id); if (category) { category.name = name; category.variations = variations; // console.log(category); const updatedCategory = await category.save(); // console.log(updateCategory); res.json(updatedCategory); } else { res.status(404); throw new Error("Category not found"); } }); export { getCategory, createCategory, getCategoryById, deleteCategory, updateCategory, };
import React from "react"; import PopupWithForm from "./PopupWithForm"; function EditProfilePopup(props) { //const currentUser = React.useContext(UserContext); const [name, setName] = React.useState(""); const [occupation, setOccupation] = React.useState(""); function handleNameChange(e) { setName(e.target.value); } function handleOccupationChange(e) { setOccupation(e.target.value); } function handleSubmit(e) { e.preventDefault(); props.onProfileUpdate({name: name, about: occupation}); } return ( <PopupWithForm name="edit-profile" title="Edit profile" buttonText="Save" isOpen={props.isOpen} onClose={props.onClose} onSubmit={handleSubmit} > <label className="modal__label"> <input id="profile-name" type="text" name="name" className="modal__input form__name-input" placeholder="name" minLength="2" maxLength="40" onChange={handleNameChange} value={name} required /> <span id="profile-name-error" className="modal__error"></span> </label> <label className="modal__label"> <input id="profile-occupation" type="text" name="occupation" className="modal__input form__job-input" placeholder="occupation" minLength="2" maxLength="200" onChange={handleOccupationChange} value={occupation} required /> <span id="profile-occupation-error" className="modal__error"></span> </label> </PopupWithForm> ); } export default EditProfilePopup;
addLoadEvent(initPage); addLoadEvent(submitBtn); var frequencyTable = new Array( "a", "a", "a", "a", "a", "a", "a", "a", "b", "c", "c", "c", "d", "d", "d", "e", "e", "e", "e", "e", "e", "e", "e", "e", "e", "e", "e", "f", "f", "g", "g", "h", "h", "h", "h", "h", "h", "i", "i", "i", "i", "i", "i", "i", "j", "k", "l", "l", "l", "l", "m", "m", "n", "n", "n", "n", "n", "n", "o", "o", "o", "o", "o", "o", "o", "o", "p", "p", "q", "q", "q", "q", "q", "q", "r", "r", "r", "r", "r", "r", "s", "s", "s", "s", "s", "s", "s", "s", "t", "t", "t", "u", "u", "v", "v", "w", "x", "y","y", "z" ); function initPage () { //显示单词面板 showWords(); } function showWords () { var letterbox = document.getElementById('letterbox'); a_word = letterbox.getElementsByTagName('a'); for(var i=0;i<a_word.length;i++) { var index = Math.floor( Math.random()*100 ); var randomWord = frequencyTable[index]; var classname0 = a_word[i].className.split(' ')[0]; var classname1 = a_word[i].className.split(' ')[1]; var newClassName = classname0 + ' ' + classname1 + ' l' + randomWord; a_word[i].className = newClassName; a_word[i].onclick = clickWord; } } var currentWord = document.getElementById('currentWord'); var wordListBg = document.getElementById('wordListBg'); //点击单词事件 function clickWord () { var word = this.className.split(' ')[2].substr(1,1); if(currentWord.childNodes.length==0) { var p = document.createElement('p'); var text = document.createTextNode(word); p.appendChild(text); currentWord.appendChild(p); }else{ currentWord.firstChild.firstChild.nodeValue += word; } //禁用已经点击的贴块 this.className += ' disabled'; //已经点击的贴块,点击事件为空 this.onclick = ''; } function submitBtn () { var submit_a = document.getElementById('submit').getElementsByTagName('a')[0]; submit_a.onclick = subFun; } function subFun () { if(currentWord.childNodes.length==0) { alert('请在左侧选择单词后,在点击提交按钮'); }else{ //更新左边单词区域 showWords(); //去掉点击按钮上面区域中的内容 var cur_p = currentWord.firstChild; var cur_word = currentWord.firstChild.firstChild.nodeValue; currentWord.removeChild(cur_p); //ajax var word_score = requestObject(); if (word_score == null) { alert('不能获取ajax对象'); return; } var url = "lookup-word.php?word=" + escape(cur_word); word_score.open('GET',url,true); word_score.onreadystatechange = function() { if(word_score.readyState==4 && word_score.status==200){ var response = word_score.responseText; if(response=='-1'){ alert('请输入合法单词'); }else{ //点击按钮上面区域中的内容 挪到 点击按钮下面区域 var crt_p = document.createElement('p'); crt_p.appendChild( document.createTextNode(cur_word) ); var wordList = document.getElementById('wordList'); wordList.appendChild(crt_p); //积分累加 var response_score = Number( response.substring(7) ); var score_div = document.getElementById('score'); var score = Number( score_div.firstChild.nodeValue.split(' ')[1] ); score += response_score; score_div.firstChild.nodeValue = 'Score: ' + score; } } } word_score.send(null); } }
function get_context(canvas_id){ if (!Modernizr.canvas){ alert('Your browser does not support HTML5 Canvas'); return null; } var b_canvas = document.getElementById(canvas_id); return b_canvas.getContext('2d'); } function set_line_style(ctx,style) { var ss = ctx.strokeStyle, lw = ctx.lineWidth; ctx.strokeStyle = style.color; ctx.lineWidth = style.width; ctx.beginPath(); return {color: ss, width: lw}; } function set_font_style(ctx, style){ var ofont = ctx.font, obaseline = ctx.textBaseline, oalign = ctx.textAlign; ctx.font = style.font; ctx.textBaseline = style.base; ctx.textAlign = style.align; return {font: ofont, base: obaseline, align: oalign}; } function draw_x(ctx, x0, y0, step, xpts) { var yd = 10; set_line_style(ctx, {color:'#000', width:2}); set_font_style(ctx, {font:'bold 12px san-serif',base:'top',align:'left'}); ctx.moveTo(x0, y0 - yd); ctx.lineTo(x0, y0); for (var x=x0, i=0; i<xpts.length;x+=step,i++) { ctx.moveTo(x, y0 - yd); ctx.lineTo(x, y0); ctx.lineTo(x + step, y0); ctx.fillText(xpts[i][0]+'-'+xpts[i][1], x, y0); } ctx.stroke(); } function draw_y(ctx, x0, y0, step, pts, w, d) { set_line_style(ctx, {color:'#000', width:2}); set_font_style(ctx, {font:'bold 12px san-serif',base:'top',align:'right'}); ctx.moveTo(x0, y0); ctx.lineTo(x0, 0); ctx.stroke(); set_line_style(ctx, {color:'#ccc', width:1}); var l = 1; for (var y=y0-step, i=0; i<pts; y-=step, i++) { ctx.moveTo(x0, y); ctx.lineTo(w, y); ctx.fillText(l, x0-2, y-6); l ++; } ctx.stroke(); } function draw_d(ctx, x0, y0, xstep, aheight, maxy, xpts) { var x = x0, y = y0; set_line_style(ctx, {color:'#00F', width:4}); ctx.moveTo(x, y); for (var i=1; i<xpts.length; i++) { if (xpts[i][2] < 0) break; x += xstep; y = aheight - xpts[i][2] * aheight / maxy; ctx.lineTo(x, y); } ctx.stroke(); } /** * Draw BurnDown chart for the input dataset. * @param int maxy max Y * @param Array xpts [[month,day,Y],..] */ function draw_burndown_chart(canvas_id, maxy, xpts) { var ctx = get_context(canvas_id); var lmargin = 40, awidth = ctx.canvas.width - lmargin, bmargin = 20, aheight = ctx.canvas.height - bmargin; var xstep = awidth / xpts.length, ystep = aheight / maxy; draw_x(ctx, lmargin, aheight, xstep, xpts); draw_y(ctx, lmargin, aheight, ystep, maxy, ctx.canvas.width, aheight / maxy); //draw diagonal line var ostyle = set_line_style(ctx,{color:'#F00',width:1}); ctx.moveTo(lmargin, 0); ctx.lineTo(ctx.canvas.width-xstep, aheight); ctx.stroke(true); set_line_style(ctx, ostyle); draw_d(ctx, lmargin, 0, xstep, aheight, maxy, xpts); }
console.log("register file is read!"); if (navigator.serviceWorker){ navigator.serviceWorker.register("/js/sw.js").then(regsitration =>{ console.log("Service worker registered!: "+regsitration.scope); }).catch(err => { console.log("Service worker registeration failed!: "+err); }); }
/** * @author 田鑫龙 v1.0 */ module.exports = { load: { css: ['resources/css/weui.css', 'resources/css/zan.css', 'resources/css/iconfont.css'], js: ['resources/js/jquery.min.js', 'resources/js/weui.js', 'resources/js/load.js', 'resources/js/zan.js', 'resources/js/ajax.js'] }, index: { css: ['resources/css/single_page.css', 'resources/js/commons/swiper/css/swiper-3.4.2.min.css'], js: ['resources/js/commons/wxSign.js', 'resources/js/single_page.js', 'resources/js/commons/swiper/js/swiper-3.4.2.jquery.min.js', 'resources/js/business/index.js'] }, personal: { js: ['resources/js/commons/wxSign.js', 'resources/js/business/personal/personal.js'] }, info: { js: ['resources/js/commons/wxSign.js', 'resources/js/business/personal/info.js'] }, chat: { js: ['resources/js/commons/wxSign.js', 'resources/js/commons/im/webim.config.js', 'resources/js/commons/im/strophe-1.2.8.js', 'resources/js/commons/im/websdk-1.4.10.js', 'resources/js/commons/loadIM.js', 'resources/js/business/chat/chat.js' ] }, chat_list: { js: ['resources/js/commons/wxSign.js', 'resources/js/business/chat/chat_list.js'] }, discovery: { css: ['resources/js/commons/swiper/css/swiper-3.4.2.min.css'], js: ['resources/js/commons/wxSign.js', 'resources/js/commons/swiper/js/swiper-3.4.2.jquery.min.js', 'resources/js/business/discovery/discovery.js'] }, doctor_coupon_online_list: { css: ['resources/js/business/doctor/calendar.static.css'], js: ['resources/js/commons/wxSign.js', 'resources/js/business/doctor/calendar.static.js', 'resources/js/business/doctor/common.js', 'resources/js/business/doctor/doctor_coupon_online_list.js'] }, doctor_coupon_list: { css: ['resources/js/business/doctor/calendar.static.css'], js: ['resources/js/commons/wxSign.js', 'resources/js/business/doctor/calendar.static.js', 'resources/js/business/doctor/common.js', 'resources/js/business/doctor/doctor_coupon_list.js'] }, doctor_hospital_list: { css: ['resources/js/business/doctor/calendar.static.css'], js: ['resources/js/commons/wxSign.js', 'resources/js/business/doctor/calendar.static.js', 'resources/js/business/doctor/common.js', 'resources/js/business/doctor/doctor_hospital_list.js'] }, doctor_recently_list: { css: ['resources/js/business/doctor/calendar.static.css'], js: ['resources/js/commons/wxSign.js', 'resources/js/business/doctor/calendar.static.js', 'resources/js/business/doctor/common.js', 'resources/js/business/doctor/doctor_recently_list.js'] }, doctor_2day_list: { css: ['resources/css/single_page.css'], js: ['resources/js/commons/wxSign.js', 'resources/js/single_page.js', 'resources/js/business/doctor/common.js', 'resources/js/business/doctor/doctor_2day_list.js'] }, doctor_city_list: { css: ['resources/js/business/doctor/calendar.static.css'], js: ['resources/js/commons/wxSign.js', 'resources/js/business/doctor/common.js', 'resources/js/business/doctor/doctor_city_list.js'] }, doctor_online_list: { js: ['resources/js/commons/wxSign.js', 'resources/js/business/doctor/common.js', 'resources/js/business/doctor/doctor_online_list.js'] }, doctor_list: { css: ['resources/js/business/doctor/calendar.static.css'], js: ['resources/js/commons/wxSign.js', 'resources/js/business/doctor/calendar.static.js', 'resources/js/business/doctor/doctor_list.js'] }, doctor_detail: { js: ['resources/js/commons/wxSign.js', 'resources/js/commons/qrcode.js', 'resources/js/business/doctor/doctor_detail.js'] }, doctor_introduct: { js: ['resources/js/commons/wxSign.js', 'resources/js/business/doctor/doctor_introduct.js'] }, hospital_list: { js: ['resources/js/commons/wxSign.js', 'resources/js/business/hospital/hospital_list.js'] }, hospital_inst: { js: ['resources/js/commons/wxSign.js', 'resources/js/business/hospital/hospital_inst.js'] }, hospital_detail: { js: ['resources/js/commons/wxSign.js', 'resources/js/business/doctor/common.js', 'resources/js/business/hospital/hospital_detail.js'] }, illness_list: { js: ['resources/js/commons/wxSign.js', 'resources/js/business/doctor/common.js', 'resources/js/business/illness/illness_list.js'] }, };
angular.module('app') .controller('HotelListController', function ($rootScope, $stateParams, $location, $rootScope, $state, HotelService, CountryService) { const vm = this; vm.hotelDataLoaded = false; vm.pageNumber = $stateParams.pageNumber; vm.countriesNames = CountryService.getAllNames(); vm.hotelName = $rootScope.hotelName; vm.countryName = $rootScope.countryName; vm.completeCountry = string => { vm.hideCountryList = false; var output = []; angular.forEach(vm.countriesNames, function(country) { if(string == undefined) { string = ''; } else if(country.toLowerCase().indexOf(string.toLowerCase()) >= 0) { output.push(country); } }); vm.filterCountry = output; } vm.fillCountryTextbox = function(string) { vm.countryName = string; vm.hideCountryList = true; vm.countryIsChosen = true; } const removeClassButtons = () => { angular.element(document.querySelector("#firstButton")).removeClass("active"); angular.element(document.querySelector("#secondButton")).removeClass("active"); angular.element(document.querySelector("#thirdButton")).removeClass("active"); angular.element(document.querySelector("#fourthButton")).removeClass("active"); angular.element(document.querySelector("#fifthButton")).removeClass("active"); } const setNumberButtons = pageNum => { removeClassButtons(); if(pageNum === 1 || pageNum === 2 || pageNum === 3) { vm.numButton = 3; if(pageNum === 1) { angular.element(document.querySelector("#firstButton")).addClass("active"); } else if(pageNum === 2) { angular.element(document.querySelector("#secondButton")).addClass("active"); } else if(pageNum === 3) { angular.element(document.querySelector("#thirdButton")).addClass("active"); } } else if(pageNum === vm.totalPages - 2 || pageNum === vm.totalPages - 1 || pageNum === vm.totalPages) { vm.numButton = vm.totalPages - 2; if(pageNum === vm.totalPages - 2) { angular.element(document.querySelector("#thirdButton")).addClass("active"); } else if(pageNum === vm.totalPages - 1) { angular.element(document.querySelector("#fourthButton")).addClass("active"); } else if(pageNum === vm.totalPages) { angular.element(document.querySelector("#fifthButton")).addClass("active"); } } else { vm.numButton = vm.pageNumber; angular.element(document.querySelector("#thirdButton")).addClass("active"); } } const checkVisibleButtons = pageInfo => { vm.disableFirstPage = pageInfo.first; vm.disablePreviousPage = pageInfo.first; vm.disableNextPage = pageInfo.last; vm.disableLastPage = pageInfo.last; if(pageInfo.totalPages === 1) { vm.showSecondButton = true; vm.showThirdButton = true; vm.showFourthButton = true; vm.showFifthButton = true; } else if(pageInfo.totalPages === 2) { vm.showSecondButton = false; vm.showThirdButton = true; vm.showFourthButton = true; vm.showFifthButton = true; } else if(pageInfo.totalPages === 3) { vm.showSecondButton = false; vm.showThirdButton = false; vm.showFourthButton = true; vm.showFifthButton = true; } else if(pageInfo.totalPages === 4) { vm.showSecondButton = false; vm.showThirdButton = false; vm.showFourthButton = false; vm.showFifthButton = true; } else { vm.showSecondButton = false; vm.showThirdButton = false; vm.showFourthButton = false; vm.showFifthButton = false; } } const setHotlAndTopImgData = result => { vm.fileArray = result.fileList[0]; vm.pageInfo = result.hotelList[0]; vm.hotelArray = vm.pageInfo.content; checkVisibleButtons(vm.pageInfo); if(vm.pageInfo.totalElements === 0) { vm.resultFound = true; } else { vm.hotelDataLoaded = true; vm.resultFound = false; } var oneImg; for(oneImg in vm.fileArray) { vm.hotelArray[oneImg].imgSrc = vm.fileArray[oneImg]; } } const setHotelAndTopImg = result => { vm.hotelDataLoaded = false; vm.pageNumber = result.hotelList[0].number + 1; vm.totalPages = result.hotelList[0].totalPages; if($location.path() === '/admin/hotels') { setHotlAndTopImgData(result); setNumberButtons(vm.pageNumber); } else if(vm.pageNumber >= 1 && vm.pageNumber <= vm.totalPages) { setHotlAndTopImgData(result); setNumberButtons(vm.pageNumber); } else { $location.path(`/admin/hotels/page/1`); } } vm.confirmMsg = 'Are you sure to delete this hotel ? \n \n' + 'This can lead to serious consequences, \n' + 'for instance, delete existing bookings.'; const errorCallback = err => { vm.msg=`${err.data.message}`; }; const deleteCallback = () => { $state.reload(); } vm.deleteHotel = (hotel) => { HotelService.deleteHotel(hotel) .$promise .then(deleteCallback) .catch(errorCallback); }; if(vm.pageNumber) { if(vm.pageNumber < 1 || vm.pageNumber > vm.totalPages) { $location.path(`/admin/hotels`); } vm.hotelsAndTopImgArray = HotelService .getAllHotelsByNameAndCountry(vm.pageNumber, vm.hotelName, vm.countryName); vm.hotelsAndTopImgArray.$promise.then(setHotelAndTopImg); } else { vm.hotelsAndTopImgArray = HotelService.getAllHotelsAndMainImg(); vm.hotelsAndTopImgArray.$promise.then(setHotelAndTopImg); } vm.search = () => { $rootScope.hotelName = vm.hotelName; $rootScope.countryName = vm.countryName; if(vm.pageNumber === 1) { vm.hotelsAndTopImgArray = HotelService .getAllHotelsByNameAndCountry(vm.pageNumber, vm.hotelName, vm.countryName); vm.hotelsAndTopImgArray.$promise.then(setHotelAndTopImg); } else { vm.pageNumber = 1; $location.path(`/admin/hotels/page/${vm.pageNumber}`); } }; vm.loadPage = buttonNumber => { if(buttonNumber >= 1 && buttonNumber <= vm.totalPages) { vm.pageNumber = buttonNumber; $rootScope.hotelName = vm.hotelName; $rootScope.countryName = vm.countryName; $location.path(`/admin/hotels/page/${vm.pageNumber}`); } }; vm.firstPage = () => { vm.loadPage(1); } vm.previousPage = () => { if(vm.pageNumber > 1) { vm.pageNumber--; vm.loadPage(vm.pageNumber); } }; vm.nextPage = () => { if(vm.pageNumber < vm.totalPages) { vm.pageNumber++; vm.loadPage(vm.pageNumber); } }; vm.lastPage = () => { vm.loadPage(vm.totalPages); }; vm.redirectToHotelEdit = hotelId => { $location.path(`/admin/hotels-edit/${hotelId}`); }; vm.redirectToRooms = hotelId => { $location.path(`/admin/hotels/${hotelId}/rooms`); }; vm.redirectToAdvantages = hotelId => { $location.path(`/admin/hotels/${hotelId}/advantages`); }; });
// @flow import * as React from 'react'; import { View } from 'react-native'; import { Text, StyleSheet, TextIcon, TouchableWithoutFeedback, } from '@kiwicom/mobile-shared'; import { Translation } from '@kiwicom/mobile-localization'; import { defaultTokens } from '@kiwicom/mobile-orbit'; type Props = {| +onPress: () => void, +formattedAddress: string, |}; export default function MarkerLocationButton(props: Props) { return ( <View style={styles.container}> <TouchableWithoutFeedback onPress={props.onPress}> <View style={styles.locationButton}> <TextIcon code="$" style={styles.icon} /> <Text numberOfLines={1} style={ props.formattedAddress != '' ? styles.locationText : styles.placeholderText } > {props.formattedAddress != '' ? ( <Translation passThrough={props.formattedAddress} /> ) : ( <Translation id="mmb.trip_services.transportation.map.marker_location_button" /> )} </Text> </View> </TouchableWithoutFeedback> </View> ); } const styles = StyleSheet.create({ container: { backgroundColor: defaultTokens.paletteWhite, padding: 10, }, locationButton: { flexDirection: 'row', backgroundColor: defaultTokens.backgroundInputDisabled, alignItems: 'center', android: { borderRadius: 2, elevation: 1, height: 48, }, ios: { height: 47, borderRadius: 6, }, }, placeholderText: { color: defaultTokens.paletteInkLight, flex: 1, }, locationText: { color: defaultTokens.paletteInkDark, flex: 1, }, icon: { marginHorizontal: 10, alignSelf: 'center', color: defaultTokens.paletteInkLight, fontSize: 16, }, });
// eslint-disable-next-line no-unused-vars import express from 'express'; import {APIResponse} from './APIResponse.js'; import {APIError} from './APIError.js'; const RESPONSE_TIMEOUT = 30 * 1000; // 30 sec /** */ export class APIMiddleware { /** * @param {express.Request} request * @param {express.Response} response */ constructor(request, response) { this._request = request; this._response = response; } /** * @param {Object} data * @param {number} status */ sendResponse(data, status) { // todo: parse errors const response = new APIResponse(this._response); response.send(data, status); } /** * @param {Object} result * @return {Promise<void>} */ async sendResponsePromise(result) { await Promise .race( [ result.then((data) => { console.log('Result data built'); return data; }), this._startApiTimeout(), ], ) .then((data) => { this._removeTimeout(); this.sendResponse(data); }); } /** * @return {Promise} * @private */ async _startApiTimeout() { return new Promise((resolve, reject) => { this._timeout = setTimeout(() => { reject(new APIError(APIError.ERRORS.RESPONSE_TIMEOUT)); }, RESPONSE_TIMEOUT); }); } /** * @private */ _removeTimeout() { clearTimeout(this._timeout); } }