text
stringlengths
7
3.69M
'use strict'; // Create an instance var slimsurfer; // Init & load audio file document.addEventListener('DOMContentLoaded', function() { // Init slimsurfer = SlimSurfer.create({ container: document.querySelector('#waveform'), waveColor: '#A8DBA8', progressColor: '#3B8686', backend: 'MediaElement', plugins: [ SlimSurfer.regions.create({ regions: [ { start: 0, end: 5, color: 'hsla(400, 100%, 30%, 0.1)' }, { start: 10, end: 100, color: 'hsla(200, 50%, 70%, 0.1)' } ] }), SlimSurfer.timeline.create({ container: '#timeline' }) ] }); // Load audio from URL slimsurfer.load('../media/demo.wav'); // Zoom slider var slider = document.querySelector('[data-action="zoom"]'); slider.value = slimsurfer.params.minPxPerSec; slider.min = slimsurfer.params.minPxPerSec; slider.addEventListener('input', function() { slimsurfer.zoom(Number(this.value)); }); // Play button var button = document.querySelector('[data-action="play"]'); button.addEventListener('click', slimsurfer.playPause.bind(slimsurfer)); });
const React = require('react'); const ReactDOM = require('react-dom'); const ReactRouter = require('react-router'); const GetSmart = require('GetSmart'); const { Route, HashLocation } = ReactRouter; let router; exports.start = function(context, onError) { const params = context.params || {}; const emberRouter = GetSmart.__container__.lookup("router:main"); if (typeof params.path !== 'string') { onError("You must specify the route path for this handler!"); return; } else if (!context.subject) { onError("No subject? No play!"); return; } const routes = ( <Route path="/"> <Route path={params.path} handler={context.subject} /> </Route> ); router = ReactRouter.create({ routes, location: HashLocation, onError: function(error) { console.error(error && error.stack || error); throw error; } }); ignoreUnknownDestinations(router); ignoreUnknownEmberDestinations(emberRouter); router.run((Handler, state) => { ReactDOM.render(<Handler {...state} />, context.rootElement); }); }; exports.stop = function(context) { const emberRouter = GetSmart.__container__.lookup("router:main"); if (router) { restoreEmberRouterIfNeeded(emberRouter); ReactDOM.unmountComponentAtNode(context.rootElement); router.stop(); router = null; } }; function ignoreUnknownDestinations(router) { const { makePath } = router; router.makePath = function() { try { return makePath.apply(router, arguments); } catch(e) { return ''; } }; } function ignoreUnknownEmberDestinations(emberRouter) { [ 'generate' ].forEach(function(method) { const original = emberRouter[method]; emberRouter[method] = function() { try { return original.apply(emberRouter, arguments); } catch(e) { return ''; } }; emberRouter[method].restore = function() { emberRouter[method] = original; }; }); } function restoreEmberRouterIfNeeded(emberRouter) { [ 'generate' ].forEach(function(method) { if (emberRouter[method].restore instanceof Function) { emberRouter[method].restore(); } }); }
import Link from "next/link"; import { PreviewHero } from "../atoms/PreviewHero"; import { Date } from "../atoms/Date"; export function PostPreview({ title, date, slug, category, coverImage, description, }) { return ( <> <article className="mx-auto w-88 bg-white group hover:text-blue-800"> <Link as={`/post/${slug}`} href="/post/[slug]"> <a> <div className="flex flex-wrap content-start h-full border border-gray-200 rounded-md relative"> <PreviewHero title={title} src={coverImage} width={360} height={220} /> <div className="p-6"> <h3 className="text-sm opacity-50 mb-2">{category ?? ""}</h3> <h2 className="text-lg font-medium mb-2">{title}</h2> <p className="mb-10">{description}</p> <p className="text-xs opacity-70 absolute bottom-6"> <Date dateString={date} /> </p> </div> </div> </a> </Link> </article> </> ); }
import React from "react"; import { render, fireEvent, screen } from "@testing-library/react"; import "@testing-library/jest-dom/extend-expect"; import "jest-localstorage-mock"; import Cart from "../Cart"; // eslint-disable-next-line jest/no-mocks-import import MockBooks from "../../book/__mocks__/mockBooks"; describe("Cart", () => { afterEach(() => localStorage.clear()); test("add and delete book on the cart", async () => { const KEY = "cart"; localStorage.setItem(KEY, JSON.stringify([MockBooks[0]])); render(<Cart />); expect(JSON.parse(localStorage.getItem(KEY))).toHaveLength(1); expect(screen.getAllByText("Remove Item")).toBeTruthy(); // delete item fireEvent.click(await screen.findByRole("button")); expect(JSON.parse(localStorage.getItem(KEY))).toHaveLength(0); }); });
module.exports = { configureWebpack: { resolve: { alias: require("./aliases.config").webpack } }, runtimeCompiler: true, css: { // Enable CSS source maps. sourceMap: true, loaderOptions: { sass: { data: `@import "~@/style/app.scss";` } } } };
'use strict'; import Async from 'async'; import Cache from 'memory-cache'; import Navigation from '../../database/models/cms/navigation'; class User { constructor (Website) { Website.use(User.apply); } static apply (request, result, next) { if (request.user) { User.user = request.user; Async.parallel([User.navi], ((errors, results) => { if (errors) { result.render('errors/500'); } else { result.locals.navi = results[0]; result.locals.user = request.user; next(); } })); } else { if (request.path == '/login') { next(); } else { result.redirect('/login'); } } } static navi (callback) { if (!Cache.get('cms_navi')) { Navigation.fetchAll() .then ((navi) => { let parents = []; let children = []; navi = navi.toJSON(); navi.forEach((n) => { if (n.text == 'USER') { n.text = User.user.username; } if (n.href == 'profile') { n.href = 'profile/' + User.user.username; } if (n.parent == 1) { parents.push(n); } else { children.push(n); } }); navi = { parents : parents, children : children }; Cache.put('cms_navi', navi); return callback(null, navi); }) .catch ((err) => { callback(err); }); } else { callback(null, Cache.get('cms_navi')); } } } module.exports = User;
import React, {Component} from 'react' import $ from 'jquery' class Edit extends Component{ constructor(props){ super(props) this.editTask = this.editTask.bind(this) this.state = { taskData: {} } } componentDidMount(){ var taskId = this.props.match.params.taskId $.getJSON(`http://localhost:3000/getTask/${taskId}`, (taskData)=>{ this.setState({taskData}) }) } editTask(e){ e.preventDefault() var taskId = this.props.match.params.taskId var taskNameToEdit = document.getElementById('edit-task').value var taskDateToEdit = document.getElementById('edit-task-date').value $.ajax({ method: 'POST', url: 'http://localhost:3000/editTask', data: {taskId: taskId, taskName: taskNameToEdit, taskDate: taskDateToEdit} }).done((tasksArray)=>{ this.props.history.push('/') }) } render(){ var taskId = this.props.match.params.taskId console.log(taskId) return( <div className="container"> <div className="row"> <form className="col s12 center-align" className="add-box"> <input className="col s4" type="text" id="edit-task" placeholder={this.state.taskData.taskName} /> <input className=" col s4" type="date" id="edit-task-date" placeholder={this.state.taskData.taskDate}/> <div className="col s4 center-align"> <button onClick={this.editTask} className="waves-effect waves-light btn-flat green darken-2" id="add-btn"><i className="material-icons left">save</i>Save Changes</button> </div> </form> </div> </div> ) } } export default Edit
let selectedColor = 'red'; function changeColor (oldColor, color){ if(oldColor) document.getElementById(oldColor).classList.remove('active') if(color) document.getElementById(color).classList.add('active') } console.log('started'); document.addEventListener("DOMContentLoaded", (event) => { let interval; const startTimer = () => { interval = setInterval(() => { if(selectedColor === 'red') { changeColor('red', 'yellow') selectedColor = 'yellow' console.log(selectedColor); } else if(selectedColor === 'yellow') { selectedColor = 'green' changeColor('yellow', 'green') console.log(selectedColor); } else if(selectedColor === 'green') { changeColor('green', 'red') selectedColor = 'red' console.log(selectedColor); } }, 1000); } const stopTimer = () => { clearInterval(interval) interval = null } document.getElementById("btn").onclick = function () { console.log('ready'); if(interval){ stopTimer() changeColor(selectedColor) } else { startTimer() changeColor(null, 'red') } } });
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Link } from 'react-router-dom'; import { signin, clearSigninError } from '../actions/authActions'; import validateAuth from '../lib/validation'; import AuthInput from '../components/shared/AuthInput'; import Button from '../components/shared/Button'; const initialState = { email: '', password: '', touched: { email: false, password: false, }, }; const fieldNames = ['email', 'password']; class SigninForm extends Component { state = initialState; componentDidMount = () => { const { clearSigninError: clearError } = this.props; clearError(); } handleSubmit = async (event) => { event.preventDefault(); const { signin: signinUser, history } = this.props; const { email, password } = this.state; const validationError = validateAuth({ email, password }, fieldNames); const changedTouchState = this.changeTouchState(fieldNames, true); this.setState({ touched: changedTouchState }); if (!validationError.status) { signinUser({ email, password }, () => history.push('/main/entries')); this.setState(initialState); } } handleChange = (event) => { this.setState({ [event.target.id]: event.target.value }); } handleBlur = (field) => () => { const { touched } = this.state; this.setState({ touched: { ...touched, [field]: true }, }); } changeTouchState = (fields, state) => { const touchState = {}; fields.forEach((field) => { touchState[field] = state; }); return touchState; } render() { const { email, password, touched } = this.state; const { errorMessage } = this.props; const validationError = validateAuth({ email, password }, fieldNames); return ( <div> <div className="authContent signin"> <main> <div className="authLogo">MyDiary</div> <div className="title">Welcome back!</div> <hr/> <form className="signinForm" onSubmit={this.handleSubmit}> <div className="authError">{errorMessage}</div> <AuthInput value={email} touched={touched} error={validationError} handleChange={this.handleChange} handleBlur={this.handleBlur('email')} name="email" placeholder="Email" /> <AuthInput value={password} touched={touched} error={validationError} handleChange={this.handleChange} handleBlur={this.handleBlur('password')} name="password" type="password" placeholder="Password" /> <Button title="Sign In" type="submit" /> </form> </main> </div> <div className="authAlt"> Don't have an account? <Link to="/auth/signup">Sign Up</Link> </div> </div> ); } }; function mapStateToProps(state) { return { errorMessage: state.auth.errorMessage }; } export default connect(mapStateToProps, { signin, clearSigninError })(SigninForm);
module.exports = 3.1416;
// renderer.js import fs from "fs"; import path from "path"; import React from "react"; import ReactDOMServer from "react-dom/server"; import { StaticRouter } from "react-router" // import main App component import App from "../PairBNB/src/App"; export default (req, res, next) => { // point build index.html const filePath = path.resolve("PairBNB", "./build", "index.html"); // read in html file fs.readFile(filePath, "utf8", (err, htmlData) => { if (err) { return res.send(err).end(); } // render the app as a string const context = {} const html = ReactDOMServer.renderToString( <StaticRouter location={req.url} context={context}> <App /> </StaticRouter>); // inject the rendered app into our html and send it return res.send( // replace default html with rendered html htmlData.replace('<div id="root"></div>', `<div id="root">${html}</div>`) ); }); };
import React from 'react' import {Redirect, Route} from "react-router-dom"; import {connect} from 'react-redux' const PrivateRoute = ({component: Component, rest, is_auth})=>( <Route {...rest} render={(props)=>{ return is_auth ? ( <Component {...props}/> ) : <Redirect to="/notfound" /> } } /> ) const mapStateToProps = state=> ({ is_auth: state.users.is_auth }) export default connect(mapStateToProps,{})(PrivateRoute)
import {StyleSheet, Text, View} from 'react-native'; export const SharedStyles = StyleSheet.create({ container: { marginTop: 50, }, bigBlue: { color: 'blue', fontWeight: 'bold', fontSize: 30, }, red: { color: 'red', }, whiteText: { color: 'white', fontSize: 20, fontFamily: 'Noto+Sans+KR' }, whiteTextSmall: { color: 'white', fontSize: 14, fontFamily: 'Noto+Sans+KR' }, textArea001: { backgroundColor: 'black', height: 100, color: 'white', borderColor: 'white', borderStyle: "solid", borderWidth: 1, marginTop: 1, marginLeft: 0, paddingLeft: 10, paddingBottom: 2, width: '100%', padding: 8, }, });
import GoodDataHelper from '../lib/GoodDataHelper'; import SSO from '../lib/SSO'; const fs = require('fs'); const moment = require('moment'); export default class KbcAccess { constructor(db, storage, services) { this.db = db; this.storage = storage; this.services = services; } getLogin(kbcId) { return `${kbcId}@${this.services.getEnv('KBC_ACCESS_DOMAIN')}`; } create(event) { const gd = this.services.getGoodData(); return this.storage.verifyTokenAdmin() .then(auth => this.db.getProject(event.pathParameters.pid, auth.owner.id) .then(() => this.db.checkKbcProjectUserNonExistence(auth.admin.id, event.pathParameters.pid) .then(() => gd.getUserUid(this.getLogin(auth.admin.id)) .catch(() => { const gdHelper = new GoodDataHelper(this.db, this.services); return gd.createUser(this.getLogin(auth.admin.id), gdHelper.generatePassword(), auth.admin.name, '(KBC)'); })) .then(uid => gd.addUserToProject(event.pathParameters.pid, uid, 'admin') .then(() => this.services.sendNotification({ event: 'create-user-kbc', uid, login: this.getLogin(auth.admin.id), user: auth.admin.name, }))) .then(() => this.db.addKbcUserToProject(auth.admin.id, event.pathParameters.pid)))); } sso(event) { const encryptKey = fs.readFileSync('./gooddata-pub.key').toString('ascii'); const signKey = Buffer.from(this.services.getEnv('GD_SSO_SIGN_KEY'), 'base64').toString('ascii'); const sso = new SSO( this.services.getEnv('GD_SSO_PROVIDER'), encryptKey, signKey, this.services.getEnv('GD_SSO_SIGN_KEY_PASS') ); return this.storage.verifyTokenAdmin() .then(auth => this.db.getProject(event.pathParameters.pid, auth.owner.id) .then(() => this.db.checkKbcProjectUserExistence(auth.admin.id, event.pathParameters.pid)) .then(() => sso.getClaims(this.getLogin(auth.admin.id), moment().add(1, 'day').unix()))); } remove(event) { const gd = this.services.getGoodData(); return this.storage.verifyTokenAdmin() .then(auth => this.db.getProject(event.pathParameters.pid, auth.owner.id) .then(() => this.db.checkKbcProjectUserExistence(auth.admin.id, event.pathParameters.pid) .then(() => gd.getUserUid(this.getLogin(auth.admin.id))) .then(uid => gd.removeUserFromProject(event.pathParameters.pid, uid)) .then(() => this.db.removeKbcUserFromProject(auth.admin.id, event.pathParameters.pid)))); } }
import React, { Component } from "react"; import "./FavoriteRestaurant.css"; import Avatar from "@material-ui/core/Avatar"; import { Link } from "react-router-dom"; import IconButton from "@material-ui/core/IconButton"; import DeleteForeverSharpIcon from "@material-ui/icons/DeleteForeverSharp"; import RestaurantApiService from "../services/restaurant-api-service"; import Context from "../Context/Context"; class FavoriteRestaurant extends Component { static contextType = Context; handleDeleteClick = () => { const fav_id = this.props.fav_id; RestaurantApiService.deleteItemInFavorites(fav_id) .then((item) => { //console.log("item need to delete:", item[0].fav_id) this.context.removeItemFromFavorites(item[0].fav_id); }) .catch((error) => { this.context.setError(error); }); }; render() { const { restaurant_id } = this.props; return ( <> <div className="chat"> <Avatar variant="square" className="chat__image" style={{ height: "100px", width: "100px" }} src={this.props.image_url} /> <div className="chat__details"> <Link to={`/favorites/${restaurant_id}`}> <h2>{this.props.name}</h2> <p>Price: {this.props.price}</p> <p>Cusine: {this.props.categories}</p> <p>{this.props.location}</p> </Link> </div> <div className="chat__timestamp"> <IconButton onClick={this.handleDeleteClick}> <DeleteForeverSharpIcon fontSize="large" /> </IconButton> </div> </div> </> ); } } export default FavoriteRestaurant;
// header search bar const searchBtn = document.querySelector('.header-search-btn'); const searchBar = document.querySelector('.header-search-bar'); // cart content const cartBtn = document.querySelector('.cart-content'); const siteHeaderCart = document.querySelector('.site-header-cart-side'); const closeHeaderCart = document.querySelector('.close-cart-side'); // navbar const hamburger = document.querySelector('#menu-bar'); const navbar = document.querySelector('.navbar'); // search bar toggle searchBtn.addEventListener('click', headerSearchBar); function headerSearchBar(){ searchBar.classList.toggle('active'); } // cart content visible & close cartBtn.addEventListener('click', headerCartlistOpen); closeHeaderCart.addEventListener('click', headerCartlistClose); function headerCartlistOpen(){ siteHeaderCart.classList.add('active'); } function headerCartlistClose(){ siteHeaderCart.classList.remove('active'); } // Mobile menu toggle hamburger.addEventListener('click', toggleMenu); function toggleMenu(){ navbar.classList.toggle('nav-toggle'); } // footer search bar toggle const footerSearchBtn = document.querySelector('.handheld-footer-bar .search a'); const footerSearchBar = document.querySelector('.footer-search-bar'); footerSearchBtn.addEventListener('click', footerSearchBarToggle); function footerSearchBarToggle(){ let searchBarNone = footerSearchBar.getAttribute('data-toggle', 'toggle'); if(searchBarNone){ footerSearchBar.style.display = 'block'; searchBarNone = footerSearchBar.removeAttribute('data-toggle', 'toggle'); }else{ searchBarNone = footerSearchBar.setAttribute('data-toggle', 'toggle'); footerSearchBar.style.display = 'none'; } } // parallax const sectionHome = document.querySelector('#home'); sectionHome.addEventListener('mousemove', parallax); function parallax(e){ this.querySelectorAll('.layer').forEach(layer =>{ const speed = layer.getAttribute('data-speed'); const x = (window.innerWidth - e.pageX * speed)/100 const y = (window.innerHeight - e.pageY * speed)/100 layer.style.transform = `translateX(${x}px) translateY(${y}px)` }) } $(document).ready(function(){ $('.responsive').slick({ dots: true, speed: 300, slidesToShow: 3, slidesToScroll: 1, autoplay: true, autoplaySpeed: 3000, responsive: [ { breakpoint: 1024, settings: { slidesToShow: 2, slidesToScroll: 1, infinite: true, dots: true } }, { breakpoint: 600, settings: { slidesToShow: 1, slidesToScroll: 1 } }, { breakpoint: 480, settings: { slidesToShow: 1, slidesToScroll: 1 } } // You can unslick at a given breakpoint now by adding: // settings: "unslick" // instead of a settings object ] }); // autoplay // $('.autoplay').slick({ // slidesToShow: 3, // slidesToScroll: 1, // autoplay: true, // autoplaySpeed: 2000, // }); }); // $('.autoplay').slick({ // slidesToShow: 3, // slidesToScroll: 1, // autoplay: true, // autoplaySpeed: 2000, // }); // http://kenwheeler.github.io/slick/
import React from 'react' import ReactDOM from 'react-dom' import { createStore, createLogger } from 'relite' import * as actions from './actions' import Counter from './Counter' const initialState = { count: 0, input: '1', } const store = createStore(actions, initialState) const logger = createLogger({ name: 'counter' }) store.subscribe(logger) store.subscribe(render) render() function render() { ReactDOM.render( <Counter {...store.getState()} {...store.actions} />, document.getElementById('container') ) }
'use strict'; let config = require('./config'); require('./api/server');
function LoadMaterial() { var Material = { Bronze: [ { Name: { EN: 'Metal Plate', DE: 'Metal Plate', FR: 'Metal Plate', ES: 'Metal Plate' }, Offset: 0 }, { Name: { EN: 'Monster Tooth', DE: 'Monster Tooth', FR: 'Monster Tooth', ES: 'Monster Tooth' }, Offset: 1 }, { Name: { EN: 'Old Rag', DE: 'Old Rag', FR: 'Old Rag', ES: 'Old Rag' }, Offset: 2 }, { Name: { EN: 'Soldier\'s Uniform', DE: 'Soldier\'s Uniform', FR: 'Soldier\'s Uniform', ES: 'Soldier\'s Uniform' }, Offset: 3 }, { Name: { EN: 'Rock', DE: 'Rock', FR: 'Rock', ES: 'Rock' }, Offset: 4 }, { Name: { EN: 'Aeralfos Leather', DE: 'Aeralfos Leather', FR: 'Aeralfos Leather', ES: 'Aeralfos Leather' }, Offset: 5 }, { Name: { EN: 'Fiery Aeralfos Leather', DE: 'Fiery Aeralfos Leather', FR: 'Fiery Aeralfos Leather', ES: 'Fiery Aeralfos Leather' }, Offset: 6 }, { Name: { EN: 'Gibdo Bandage', DE: 'Gibdo Bandage', FR: 'Gibdo Bandage', ES: 'Gibdo Bandage' }, Offset: 7 }, { Name: { EN: 'ReDead Bandage', DE: 'ReDead Bandage', FR: 'ReDead Bandage', ES: 'ReDead Bandage' }, Offset: 8 }, { Name: { EN: 'Lizalfos Scale', DE: 'Lizalfos Scale', FR: 'Lizalfos Scale', ES: 'Lizalfos Scale' }, Offset: 9 }, { Name: { EN: 'Dinolfos Fang', DE: 'Dinolfos Fang', FR: 'Dinolfos Fang', ES: 'Dinolfos Fang' }, Offset: 10 }, { Name: { EN: 'Moblin Flank', DE: 'Moblin Flank', FR: 'Moblin Flank', ES: 'Moblin Flank' }, Offset: 11 }, { Name: { EN: 'Shield-Moblin Helmet', DE: 'Shield-Moblin Helmet', FR: 'Shield-Moblin Helmet', ES: 'Shield-Moblin Helmet' }, Offset: 12 }, { Name: { EN: 'Piece of Darknut Armor', DE: 'Piece of Darknut Armor', FR: 'Piece of Darknut Armor', ES: 'Piece of Darknut Armor' }, Offset: 13 }, { Name: { EN: 'Stalmaster Wrist Bone', DE: 'Stalmaster Wrist Bone', FR: 'Stalmaster Wrist Bone', ES: 'Stalmaster Wrist Bone' }, Offset: 14 }, { Name: { EN: 'Big Poe Necklace', DE: 'Big Poe Necklace', FR: 'Big Poe Necklace', ES: 'Big Poe Necklace' }, Offset: 15 }, { Name: { EN: 'Essence of Icy Big Poe', DE: 'Essence of Icy Big Poe', FR: 'Essence of Icy Big Poe', ES: 'Essence of Icy Big Poe' }, Offset: 16 }, { Name: { EN: 'Hylian Captain Gauntlet', DE: 'Hylian Captain Gauntlet', FR: 'Hylian Captain Gauntlet', ES: 'Hylian Captain Gauntlet' }, Offset: 17 }, { Name: { EN: 'Goron Armor Breastplate', DE: 'Goron Armor Breastplate', FR: 'Goron Armor Breastplate', ES: 'Goron Armor Breastplate' }, Offset: 18 }, { Name: { EN: 'Big Blin Hide', DE: 'Big Blin Hide', FR: 'Big Blin Hide', ES: 'Big Blin Hide' }, Offset: 77 }, { Name: { EN: 'Stone Blin Buckler', DE: 'Stone Blin Buckler', FR: 'Stone Blin Buckler', ES: 'Stone Blin Buckler' }, Offset: 78 }, { Name: { EN: 'Monster Horn', DE: 'Monster Horn', FR: 'Monster Horn', ES: 'Monster Horn' }, Offset: 79 }, ], Silver: [ { Name: { EN: 'Ganon\'s Mane', DE: 'Ganon\'s Mane', FR: 'Ganon\'s Mane', ES: 'Ganon\'s Mane' }, Offset: 19 }, { Name: { EN: 'King Dodongo\'s Claws', DE: 'King Dodongo\'s Claws', FR: 'King Dodongo\'s Claws', ES: 'King Dodongo\'s Claws' }, Offset: 20 }, { Name: { EN: 'Gohma\'s Acid', DE: 'Gohma\'s Acid', FR: 'Gohma\'s Acid', ES: 'Gohma\'s Acid' }, Offset: 21 }, { Name: { EN: 'Manhandla\'s Toxic Dust', DE: 'Manhandla\'s Toxic Dust', FR: 'Manhandla\'s Toxic Dust', ES: 'Manhandla\'s Toxic Dust' }, Offset: 22 }, { Name: { EN: 'Argorok\'s Embers', DE: 'Argorok\'s Embers', FR: 'Argorok\'s Embers', ES: 'Argorok\'s Embers' }, Offset: 23 }, { Name: { EN: 'The Imprisoned\'s Scales', DE: 'The Imprisoned\'s Scales', FR: 'The Imprisoned\'s Scales', ES: 'The Imprisoned\'s Scales' }, Offset: 24 }, { Name: { EN: 'Cia\'s Bracelet', DE: 'Cia\'s Bracelet', FR: 'Cia\'s Bracelet', ES: 'Cia\'s Bracelet' }, Offset: 25 }, { Name: { EN: 'Volga\'s Helmet', DE: 'Volga\'s Helmet', FR: 'Volga\'s Helmet', ES: 'Volga\'s Helmet' }, Offset: 26 }, { Name: { EN: 'Wizzro\'s Robe', DE: 'Wizzro\'s Robe', FR: 'Wizzro\'s Robe', ES: 'Wizzro\'s Robe' }, Offset: 27 }, { Name: { EN: 'Link\'s Boots', DE: 'Link\'s Boots', FR: 'Link\'s Boots', ES: 'Link\'s Boots' }, Offset: 28 }, { Name: { EN: 'Lana\'s Hair Clip', DE: 'Lana\'s Hair Clip', FR: 'Lana\'s Hair Clip', ES: 'Lana\'s Hair Clip' }, Offset: 29 }, { Name: { EN: 'Zelda\'s Brooch', DE: 'Zelda\'s Brooch', FR: 'Zelda\'s Brooch', ES: 'Zelda\'s Brooch' }, Offset: 30 }, { Name: { EN: 'Impa\'s Hair Band', DE: 'Impa\'s Hair Band', FR: 'Impa\'s Hair Band', ES: 'Impa\'s Hair Band' }, Offset: 31 }, { Name: { EN: 'Ganondorf\'s Gauntlet', DE: 'Ganondorf\'s Gauntlet', FR: 'Ganondorf\'s Gauntlet', ES: 'Ganondorf\'s Gauntlet' }, Offset: 32 }, { Name: { EN: 'Sheik\'s Kunai', DE: 'Sheik\'s Kunai', FR: 'Sheik\'s Kunai', ES: 'Sheik\'s Kunai' }, Offset: 33 }, { Name: { EN: 'Darunia\'s Spikes', DE: 'Darunia\'s Spikes', FR: 'Darunia\'s Spikes', ES: 'Darunia\'s Spikes' }, Offset: 34 }, { Name: { EN: 'Ruto\'s Earrings', DE: 'Ruto\'s Earrings', FR: 'Ruto\'s Earrings', ES: 'Ruto\'s Earrings' }, Offset: 35 }, { Name: { EN: 'Agitha\'s Basket', DE: 'Agitha\'s Basket', FR: 'Agitha\'s Basket', ES: 'Agitha\'s Basket' }, Offset: 36 }, { Name: { EN: 'Midna\'s Hair', DE: 'Midna\'s Hair', FR: 'Midna\'s Hair', ES: 'Midna\'s Hair' }, Offset: 37 }, { Name: { EN: 'Fi\'s Heels', DE: 'Fi\'s Heels', FR: 'Fi\'s Heels', ES: 'Fi\'s Heels' }, Offset: 38 }, { Name: { EN: 'Ghirahim\'s Sash', DE: 'Ghirahim\'s Sash', FR: 'Ghirahim\'s Sash', ES: 'Ghirahim\'s Sash' }, Offset: 39 }, { Name: { EN: 'Zant\'s Magic Gem', DE: 'Zant\'s Magic Gem', FR: 'Zant\'s Magic Gem', ES: 'Zant\'s Magic Gem' }, Offset: 40 }, { Name: { EN: 'Round Aeralfos Shield', DE: 'Round Aeralfos Shield', FR: 'Round Aeralfos Shield', ES: 'Round Aeralfos Shield' }, Offset: 41 }, { Name: { EN: 'Fiery Aeralfos Wing', DE: 'Fiery Aeralfos Wing', FR: 'Fiery Aeralfos Wing', ES: 'Fiery Aeralfos Wing' }, Offset: 42 }, { Name: { EN: 'Heavy Gibdo Sword', DE: 'Heavy Gibdo Sword', FR: 'Heavy Gibdo Sword', ES: 'Heavy Gibdo Sword' }, Offset: 43 }, { Name: { EN: 'ReDead Knight Ashes', DE: 'ReDead Knight Ashes', FR: 'ReDead Knight Ashes', ES: 'ReDead Knight Ashes' }, Offset: 44 }, { Name: { EN: 'Lizalfos Gauntlet', DE: 'Lizalfos Gauntlet', FR: 'Lizalfos Gauntlet', ES: 'Lizalfos Gauntlet' }, Offset: 45 }, { Name: { EN: 'Dinolfos Arm Guard', DE: 'Dinolfos Arm Guard', FR: 'Dinolfos Arm Guard', ES: 'Dinolfos Arm Guard' }, Offset: 46 }, { Name: { EN: 'Moblin Spear', DE: 'Moblin Spear', FR: 'Moblin Spear', ES: 'Moblin Spear' }, Offset: 47 }, { Name: { EN: 'Metal Moblin Shield', DE: 'Metal Moblin Shield', FR: 'Metal Moblin Shield', ES: 'Metal Moblin Shield' }, Offset: 48 }, { Name: { EN: 'Large Darknut Sword', DE: 'Large Darknut Sword', FR: 'Large Darknut Sword', ES: 'Large Darknut Sword' }, Offset: 49 }, { Name: { EN: 'Stalmaster\'s Skull', DE: 'Stalmaster\'s Skull', FR: 'Stalmaster\'s Skull', ES: 'Stalmaster\'s Skull' }, Offset: 50 }, { Name: { EN: 'Big Poe\'s Lantern', DE: 'Big Poe\'s Lantern', FR: 'Big Poe\'s Lantern', ES: 'Big Poe\'s Lantern' }, Offset: 51 }, { Name: { EN: 'Icy Big Poe\'s Talisman', DE: 'Icy Big Poe\'s Talisman', FR: 'Icy Big Poe\'s Talisman', ES: 'Icy Big Poe\'s Talisman' }, Offset: 52 }, { Name: { EN: 'Holy Hylian Shield', DE: 'Holy Hylian Shield', FR: 'Holy Hylian Shield', ES: 'Holy Hylian Shield' }, Offset: 53 }, { Name: { EN: 'Thick Goron Helmet', DE: 'Thick Goron Helmet', FR: 'Thick Goron Helmet', ES: 'Thick Goron Helmet' }, Offset: 54 }, { Name: { EN: 'Big Blin Club', DE: 'Big Blin Club', FR: 'Big Blin Club', ES: 'Big Blin Club' }, Offset: 80 }, { Name: { EN: 'Stone Blin Helmet', DE: 'Stone Blin Helmet', FR: 'Stone Blin Helmet', ES: 'Stone Blin Helmet' }, Offset: 81 }, { Name: { EN: 'Helmarcc Plume', DE: 'Helmarcc Plume', FR: 'Helmarcc Plume', ES: 'Helmarcc Plume' }, Offset: 82 }, { Name: { EN: 'Panthom Ganon\'s Cape', DE: 'Panthom Ganon\'s Cape', FR: 'Panthom Ganon\'s Cape', ES: 'Panthom Ganon\'s Cape' }, Offset: 83 }, { Name: { EN: 'Twili Midna\'s Hairpin', DE: 'Twili Midna\'s Hairpin', FR: 'Twili Midna\'s Hairpin', ES: 'Twili Midna\'s Hairpin' }, Offset: 84 }, { Name: { EN: 'Young Links Belzz', DE: 'Young Links Belzz', FR: 'Young Links Belzz', ES: 'Young Links Belzz' }, Offset: 85 }, { Name: { EN: 'Tingles Map', DE: 'Tingles Map', FR: 'Tingles Map', ES: 'Tingles Map' }, Offset: 86 }, { Name: { EN: 'Linkes Boots', DE: 'Linkes Boots', FR: 'Linkes Boots', ES: 'Linkes Boots' }, Offset: 87 }, { Name: { EN: 'Skull Kid\'s Hat', DE: 'Skull Kid\'s Hat', FR: 'Skull Kid\'s Hat', ES: 'Skull Kid\'s Hat' }, Offset: 88 }, { Name: { EN: 'Pirate\'s Charm', DE: 'Pirate\'s Charm', FR: 'Pirate\'s Charm', ES: 'Pirate\'s Charm' }, Offset: 89 }, { Name: { EN: 'Tetra\'s Sandals', DE: 'Tetra\'s Sandals', FR: 'Tetra\'s Sandals', ES: 'Tetra\'s Sandals' }, Offset: 90 }, { Name: { EN: 'King Daphnes\'s Robe', DE: 'King Daphnes\'s Robe', FR: 'King Daphnes\'s Robe', ES: 'King Daphnes\'s Robe' }, Offset: 91 }, ], Gold: [ { Name: { EN: 'Ganon\'s Fang', DE: 'Ganon\'s Fang', FR: 'Ganon\'s Fang', ES: 'Ganon\'s Fang' }, Offset: 55 }, { Name: { EN: 'King Dodongo\'s Crystal', DE: 'King Dodongo\'s Crystal', FR: 'King Dodongo\'s Crystal', ES: 'King Dodongo\'s Crystal' }, Offset: 56 }, { Name: { EN: 'Gohma\'s Lens', DE: 'Gohma\'s Lens', FR: 'Gohma\'s Lens', ES: 'Gohma\'s Lens' }, Offset: 57 }, { Name: { EN: 'Manhandla\'s Sapling', DE: 'Manhandla\'s Sapling', FR: 'Manhandla\'s Sapling', ES: 'Manhandla\'s Sapling' }, Offset: 58 }, { Name: { EN: 'Argorok\'s Stone', DE: 'Argorok\'s Stone', FR: 'Argorok\'s Stone', ES: 'Argorok\'s Stone' }, Offset: 59 }, { Name: { EN: 'The Imprisoned\'s Pillar', DE: 'The Imprisoned\'s Pillar', FR: 'The Imprisoned\'s Pillar', ES: 'The Imprisoned\'s Pillar' }, Offset: 60 }, { Name: { EN: 'Cia\'s Staff', DE: 'Cia\'s Staff', FR: 'Cia\'s Staff', ES: 'Cia\'s Staff' }, Offset: 61 }, { Name: { EN: 'Volga\'s Dragon Spear', DE: 'Volga\'s Dragon Spear', FR: 'Volga\'s Dragon Spear', ES: 'Volga\'s Dragon Spear' }, Offset: 62 }, { Name: { EN: 'Wizzro\'s Ring', DE: 'Wizzro\'s Ring', FR: 'Wizzro\'s Ring', ES: 'Wizzro\'s Ring' }, Offset: 63 }, { Name: { EN: 'Link\'s Scarf', DE: 'Link\'s Scarf', FR: 'Link\'s Scarf', ES: 'Link\'s Scarf' }, Offset: 64 }, { Name: { EN: 'Lana\'s Cloak', DE: 'Lana\'s Cloak', FR: 'Lana\'s Cloak', ES: 'Lana\'s Cloak' }, Offset: 65 }, { Name: { EN: 'Zelda\'s Tiara', DE: 'Zelda\'s Tiara', FR: 'Zelda\'s Tiara', ES: 'Zelda\'s Tiara' }, Offset: 66 }, { Name: { EN: 'Impa\'s Breastplate', DE: 'Impa\'s Breastplate', FR: 'Impa\'s Breastplate', ES: 'Impa\'s Breastplate' }, Offset: 67 }, { Name: { EN: 'Ganondorf\'s Jewel', DE: 'Ganondorf\'s Jewel', FR: 'Ganondorf\'s Jewel', ES: 'Ganondorf\'s Jewel' }, Offset: 68 }, { Name: { EN: 'Sheik\'s Turban', DE: 'Sheik\'s Turban', FR: 'Sheik\'s Turban', ES: 'Sheik\'s Turban' }, Offset: 69 }, { Name: { EN: 'Darunia\'s Bracelet', DE: 'Darunia\'s Bracelet', FR: 'Darunia\'s Bracelet', ES: 'Darunia\'s Bracelet' }, Offset: 70 }, { Name: { EN: 'Ruto\'s Scale', DE: 'Ruto\'s Scale', FR: 'Ruto\'s Scale', ES: 'Ruto\'s Scale' }, Offset: 71 }, { Name: { EN: 'Agitha\'s Pendant', DE: 'Agitha\'s Pendant', FR: 'Agitha\'s Pendant', ES: 'Agitha\'s Pendant' }, Offset: 72 }, { Name: { EN: 'Midna\'s Fused Shadow', DE: 'Midna\'s Fused Shadow', FR: 'Midna\'s Fused Shadow', ES: 'Midna\'s Fused Shadow' }, Offset: 73 }, { Name: { EN: 'Fi\'s Crystal', DE: 'Fi\'s Crystal', FR: 'Fi\'s Crystal', ES: 'Fi\'s Crystal' }, Offset: 74 }, { Name: { EN: 'Ghirahim\'s Cape', DE: 'Ghirahim\'s Cape', FR: 'Ghirahim\'s Cape', ES: 'Ghirahim\'s Cape' }, Offset: 75 }, { Name: { EN: 'Zant\'s Helmet', DE: 'Zant\'s Helmet', FR: 'Zant\'s Helmet', ES: 'Zant\'s Helmet' }, Offset: 76 }, { Name: { EN: 'Helmaroc King\'s Mask', DE: 'Helmaroc King\'s Mask', FR: 'Helmaroc King\'s Mask', ES: 'Helmaroc King\'s Mask' }, Offset: 92 }, { Name: { EN: 'Phantom Ganon\'s Sword', DE: 'Phantom Ganon\'s Sword', FR: 'Phantom Ganon\'s Sword', ES: 'Phantom Ganon\'s Sword' }, Offset: 93 }, { Name: { EN: 'Twili Midna\'s Robe', DE: 'Twili Midna\'s Robe', FR: 'Twili Midna\'s Robe', ES: 'Twili Midna\'s Robe' }, Offset: 94 }, { Name: { EN: 'Keaton Mask', DE: 'Keaton Mask', FR: 'Keaton Mask', ES: 'Keaton Mask' }, Offset: 95 }, { Name: { EN: 'Tingle\'s Watch', DE: 'Tingle\'s Watch', FR: 'Tingle\'s Watch', ES: 'Tingle\'s Watch' }, Offset: 96 }, { Name: { EN: 'Linkle\'s Compass', DE: 'Linkle\'s Compass', FR: 'Linkle\'s Compass', ES: 'Linkle\'s Compass' }, Offset: 97 }, { Name: { EN: 'Majora\'s Mask', DE: 'Majora\'s Mask', FR: 'Majora\'s Mask', ES: 'Majora\'s Mask' }, Offset: 98 }, { Name: { EN: 'Island Outfit', DE: 'Island Outfit', FR: 'Island Outfit', ES: 'Island Outfit' }, Offset: 99 }, { Name: { EN: 'Tetra\'s Bandana', DE: 'Tetra\'s Bandana', FR: 'Tetra\'s Bandana', ES: 'Tetra\'s Bandana' }, Offset: 100 }, { Name: { EN: 'King Daphnes\'s Crown', DE: 'King Daphnes\'s Crown', FR: 'King Daphnes\'s Crown', ES: 'King Daphnes\'s Crown' }, Offset: 101 }, ] } return Material; }
import { applyMiddleware, createStore, combineReducers } from "redux"; import { createLogger } from "redux-logger"; import thunk from "redux-thunk"; import location from "./location"; import strava from "./strava"; import reports from "./reports"; const reducers = combineReducers({ location, strava, reports }); const logger = createLogger({ collapsed: true }); const store = createStore( reducers, applyMiddleware(thunk, logger), ); export default store;
/** * @file Card.jsx * @description This file exports a Card react component. * @author Manyi Cheng */ import React from 'react'; /** * @description This react arrow function represents a Card component in a BigTwo game. * @param {*} props Props from parent component. * @returns React div HTML element displaying the card. */ const Card = (props) => { const path = props.card.imagePath; const images = importAll(require.context('../res/Asset', false, /\.png$/)); /** * Imports all images from the parameter path r * @function importAll * @param {*} r Indicates the required path to the card image folder. * @returns List of json objects containing the images. */ function importAll(r) { let images = {}; r.keys().forEach((item) => { images[item.replace('./', '')] = r(item); }); return images; } if (props.user === 'opponent') { return ( <div> <img className={props.class} alt="opponent-card" src={images['Back.png']} /> </div> ); } else if (props.user === 'player') { const classname = props.selected ? 'selectedcard' : ''; return ( <div> <img onClick={() => props.selectCard(props.card)} className={'card ' + classname} alt="player-card" src={images[path]} /> </div> ); } else { return <img className={props.class + ' flip-in-ver-left'} alt="field-card" src={images[path]} />; } }; Card.defaultProps = { props: { user: '', }, }; export default Card;
document.addEventListener('DOMContentLoaded', VkInit); function VkInit(){ VK.init({ apiId: 6069953 }, false, false); setTimeout(function() { VK.Auth.getLoginStatus(VkLoginStatus, true) }, 0); } const authBtn = document.querySelector('.js-auth'); authBtn.addEventListener('click', function(event){ VK.Auth.login(VkLogin); }) function VkLogin(data){ VkLoginStatus(data) } function VkLoginStatus(data){ if (data.status === 'connected') { const userName = document.querySelector('.js-user-name'); const authBtn = document.querySelector('.js-auth'); userName.innerText = data.session.user.first_name + ' ' + data.session.user.last_name; VK.api('friends.get', { user_id: data.session.user.id, fields: 'first_name, last_name, user_id', }, showFriends) showLogoutButton(); authBtn.style.display='none'; } else { cleanInfo(); } } function showFriends(data) { const friends = data.response .sort(compareRandom) .slice(0, 5); const friendsList = document.querySelector('.js-user-friends'); let HTML = ''; friends.forEach(function(friend){ HTML += `<li> <a href="https://vk.com/id${friend.user_id}" target="_blank" class="user-friend"> ${friend.first_name} ${friend.last_name} </a> </li>` }) friendsList.innerHTML = HTML; } function compareRandom(a, b) { return Math.random() - 0.5; } function showLogoutButton(){ const logoutBtn = document.querySelector('.js-logout'); logoutBtn.style.display='block'; logoutBtn.addEventListener('click', function(){ VK.Auth.logout(); setTimeout(function() { VK.Auth.getLoginStatus(VkLoginStatus, true) }, 1000) }) } function cleanInfo(){ const userName = document.querySelector('.js-user-name'); const friendsList = document.querySelector('.js-user-friends'); userName.innerText=''; friendsList.innerText=''; const logoutBtn = document.querySelector('.js-logout'); logoutBtn.style.display='none'; const authBtn = document.querySelector('.js-auth'); authBtn.style.display='block'; }
angular.module('app') .constant('SEARCH_DETAILS_ENDPOINT', '/search-result/details/:hotelId') .constant('BOOK_TRIP_ENDPOINT', '/search-result/details/:hotelId/bookTrip') .factory('SearchDetails', function ($resource, SEARCH_DETAILS_ENDPOINT, BOOK_TRIP_ENDPOINT) { return $resource(SEARCH_DETAILS_ENDPOINT, { hotelId: '@_hotelId' }, { getSearchDetails: { method: 'GET', params: { hotelId: '@_hotelId' }, transformRequest: angular.identity, headers: {'Content-type': undefined} }, bookTripOffer: { method: 'POST', url: BOOK_TRIP_ENDPOINT, transformRequest: angular.identity, headers: {'Content-type': undefined} } }); }) .factory('ChosenRoom', function() { var room; var hotelId; var setRoomAndHotelId = (newRoom, hotId) => { room = newRoom; hotelId = hotId; }; var getRoom = function(){ return room; }; var getHotelIdByChosenRoom = function(){ return hotelId; }; return { setRoomAndHotelId: setRoomAndHotelId, getRoom: getRoom, getHotelIdByChosenRoom: getHotelIdByChosenRoom }; }) .factory('ChosenAirlineOffer', function() { var airlineOffer; var hotelId; var setAirlineOfferAndHotelId = (newObj, hotId) => { airlineOffer = newObj; hotelId = hotId; }; var getAirlineOffer = function(){ return airlineOffer; }; var getHotelIdByChosenAirlineOffer = function(){ return hotelId; }; return { setAirlineOfferAndHotelId: setAirlineOfferAndHotelId, getAirlineOffer: getAirlineOffer, getHotelIdByChosenAirlineOffer: getHotelIdByChosenAirlineOffer }; }) .service('SearchDetailsService', function (SearchDetails, ChosenRoom, ChosenAirlineOffer) { this.getSearchDetails = hotelId => SearchDetails.getSearchDetails({hotelId: hotelId}); this.setRoomAndHotelId = (room, hotId) => ChosenRoom.setRoomAndHotelId(room, hotId); this.setAirlineOfferAndHotelId = (airlineOffer, hotId) => ChosenAirlineOffer.setAirlineOfferAndHotelId(airlineOffer, hotId); this.getRoom = () => ChosenRoom.getRoom(); this.getAirlineOffer = () => ChosenAirlineOffer.getAirlineOffer(); this.getHotelIdByChosenRoom = () => ChosenRoom.getHotelIdByChosenRoom(); this.getHotelIdByChosenAirlineOffer = () => ChosenAirlineOffer.getHotelIdByChosenAirlineOffer(); this.bookTripOffer = (hotelId, formData) => SearchDetails.bookTripOffer({hotelId: hotelId}, formData); });
var widgetConfig = { // title: 'Diamond Story', // widget_brief_code: 'w15', // color_scheme: 'color-scheme-1', pages: [ { title: 'Loupe', code: 'loupe', enableStoryline: false } ] };
const config = require('./config.js') const axios = require('axios') const mqtt = require('mqtt') const moment = require('moment') const client = mqtt.connect(config.mqtt) client.on('connect', function () { client.subscribe(config.topic["sub"]) }) client.on('message', function (topic, message) { console.log(message.toString()) axios({ method: 'post', url: config.backend, data: { air: message.toString(), date: moment().unix() } }) .then(function(res){ console.log(res.data); }) .catch(function(e){ console.log(e); }); })
var fs = require('fs-extra'); var moment = require('moment'); var path = require('path'); function _require(module){ delete require.cache[require.resolve(module)]; return require(module); } function Logger(granularity, filepath, interval, winston_opts) { if (typeof granularity !== 'string') { throw new Error('Invalid granularity provided!'); } this.granularity = granularity; switch (this.granularity) { case 'y': this.granularity = 'year'; break; case 'M': this.granularity = 'month'; break; case 'w': this.granularity = 'week'; break; case 'd': this.granularity = 'day'; break; case 'h': this.granularity = 'hour'; break; case 'm': this.granularity = 'minute'; break; case 's': this.granularity = 'second'; break; } if (this.granularity.slice(-1) !== 's') { this.granularity += 's'; } switch (this.granularity) { case 'years': case 'months': case 'weeks': case 'days': case 'hours': case 'minutes': case 'seconds': break; default: throw new Error('Invalid granularity provided!'); } if (typeof filepath !== 'string') { throw new Error('Invalid path provided!'); } this.filepath = filepath; this.interval = typeof interval !== 'number' ? 1 : interval; this.logger = _require('winston'); this.winston_opts = typeof winston_opts === 'object' ? winston_opts : typeof interval === 'object' ? interval : { json: false, showLevel: false, timestamp: false }; this.logger.loggers.get('default').on('error', function (err) { throw err; }); this.logger.remove(this.logger.transports.Console); this.init(moment.utc()); } Logger.prototype = { createWriteStreamForDate: function createWriteStreamForDate(d){ var file = this.generateFilePath(d); return fs.createOutputStream(file.dir + '/' + file.base, { flags: 'a' }); }, generateFilePath: function generateFilePath(d){ var p = this.filepath.replace(/{(.*?)}/g, function replacer(m1) { return d.format(m1).slice(1, -1); }); return { base: path.basename(p), dir: path.dirname(p) }; }, init: function init(date){ this.date = date; this.stream = this.createWriteStreamForDate(date); this.winston_opts.stream = this.stream; try { this.logger.add(this.logger.transports.File, this.winston_opts); } catch(err) { this.logger.remove(this.logger.transports.File); this.logger.add(this.logger.transports.File, this.winston_opts); } }, isExpired: function isExpired(){ return (~this.date.diff(Date.now(), this.granularity) + this.interval) > 0; }, log: function log(){ if (this.isExpired()) { this.init(moment.utc()); } var args = ['info']; for(var i = 0, j = arguments.length; i < j; i++){ args.push(arguments[i]); } this.logger.log.apply(this.logger, args); } }; Logger.prototype.write = Logger.prototype.log; module.exports = Logger;
import config from './config' import { Actions } from './actions' import {filter, indexOf, without, concat} from 'lodash' const initialState = { isFetching: false, links: [], selectedClient: null, selectedItemIds: [] } const linkReducer = (state = initialState, action) => { switch (action.type) { case Actions.SET_LINKS: return {...state, links: action.links} case Actions.SET_FETCHING: return {...state, isFetching: action.isFetching} case Actions.ADD_LOCAL_LINK: return {...state, links: [...state.links, action.link]} case Actions.REMOVE_LOCAL_LINKS: return {...state, links: filter(state.links, link => action.ids.indexOf(link.id) < 0)} case Actions.SET_SELECTED_CLIENT: return {...state, selectedClient: action.client} case Actions.TOGGLE_SELECTED_ITEM: let selectedItemIds const idx = indexOf(state.selectedItemIds, action.id) if (idx >= 0) { selectedItemIds = without(state.selectedItemIds, action.id) } else { selectedItemIds = concat(state.selectedItemIds, action.id) } return {...state, selectedItemIds} case Actions.CLEAR_SELECTED_ITEMS: return {...state, selectedItemIds: []} } return state } export default { [config.entityName]: linkReducer }
import React, {Component} from 'react'; import {StackNavigator, TabNavigator,DrawerNavigator} from 'react-navigation'; import Ionicons from 'react-native-vector-icons/Ionicons'; // 4.4.2 import CardStackStyleInterpolator from 'react-navigation/src/views/CardStack/CardStackStyleInterpolator'; import Home from './pages/Home' import Find from './pages/Find' import Message from './pages/Message' import Me from './pages/Me' import Detail from './pages/Detail' import VideoView from './pages/VideoView' import { StyleSheet, Image, View, Text } from 'react-native'; /** * 界面组件 */ const TabRouteConfigMap = { Home: { screen: Home, navigationOptions: { tabBarLabel: '首页', tabBarIcon: ({tintColor}) => <Image style={[styles.tabBarImage, /*{tintColor: tintColor}*/]} source={require('../images/mode.png')} />, } }, Find: { screen: Find, navigationOptions: { tabBarLabel: '发现', tabBarIcon: ({tintColor}) => <Image style={[styles.tabBarImage,]} source={require('../images/mode.png')} />, } }, Message: { screen: Message, navigationOptions: { tabBarLabel: '消息', tabBarIcon: ({tintColor}) => <Image style={[styles.tabBarImage,]} source={require('../images/mode.png')} />, } }, Me: { screen: Me, navigationOptions: { title: "hello", tabBarVisible: true, tabBarLabel: '我的', tabBarIcon: ({tintColor}) => <Image style={[styles.tabBarImage,]} source={require('../images/mode.png')} />, } } }; const TabNavigatorConfig = { initialRouteName: 'Home', animationEnabled: true, tabBarPosition: 'bottom', swipeEnabled: true, backBehavior: 'none', tabBarOptions: { activeTintColor: 'orange', inactiveTintColor: 'gray', inactiveBackgroundColor: '#9eff5b', activeBackgroundColor: '#ffaeb5', showIcon: true, showLabel: true, upperCaseLabel: false, style: { backgroundColor: 'white', }, tabStyle: { height: 56, }, labelStyle: { fontSize: 12, marginBottom: 8, marginTop: 6, }, iconStyle: { height: 32, }, indicatorStyle: { height: 0, }, pressColor: 'gray', pressOpacity: 0.8, }, }; const Tabs = TabNavigator(TabRouteConfigMap, TabNavigatorConfig); const HomeScreen = () => ( <View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}> <Text>Home Screen</Text> </View> ); const ProfileScreen = () => ( <View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}> <Text>Profile Screen</Text> </View> ); //抽屉 const Drawer = DrawerNavigator( //NavigationRouteConfigMap { Main: { // screen: Tabs, screen: HomeScreen, navigationOptions: { drawerLabel: 'Main', drawerIcon: ({tintColor, focused}) => ( <Ionicons name={focused ? 'ios-home' : 'ios-home-outline'} size={26} style={{color: tintColor}} /> ), }, }, Profile: { screen: ProfileScreen, navigationOptions: { drawerLabel: 'Profile', drawerIcon: ({tintColor, focused}) => ( <Ionicons name={focused ? 'ios-person' : 'ios-person-outline'} size={26} style={{color: tintColor}} /> ), }, }, }, //DrawerNavigatorConfig { initialRouteName: "Main", drawerWidth: 200, contentOptions: { activeTintColor: "#7dd2ff", activeBackgroundColor: "#ffc31b", style: {backgroundColor: "#6d1025"} } }); /** * 路由导航 */ const NavigationRouteConfigMap = { Tabs: { screen: Tabs, // screen: Drawer, path: '', navigationOptions: { title: "导航", header: null, cardStack: { gesturesEnabled: false, } } }, Detail: { screen: Detail, }, VideoView: {screen: VideoView}, }; const StackNavigatorConfig = { navigationOptions: { headerTitle: "全局配置", headerBackTitle: null, headerTintColor: '', showIcon: true }, modal: 'card', headerMode: 'screen', transitionConfig: () => ({ screenInterpolator: CardStackStyleInterpolator.forHorizontal, }) }; const AppNavigator = StackNavigator(NavigationRouteConfigMap, StackNavigatorConfig); const styles = StyleSheet.create({ tabBarImage: { width: 24, height: 24, marginTop: 8, }, tabBar: { backgroundColor: 'white', }, tabBarLabel: { fontSize: 12, marginBottom: 8, marginTop: 6, }, tabBarItem: { height: 56, }, tabBarIcon: { height: 32, }, }); export default AppNavigator;
import React from "react"; import Layout from "components/mainLayout"; import notFound from "assets/image/404.svg"; import "./styles.scss"; export default function NotFoundPage() { return ( <Layout> <div className="container"> <div className="helper-page"> <img src={notFound} alt="Not Found" /> <div className="heading-2">Oops!</div> <div className="heading-4">Page not found.</div> </div> </div> </Layout> ); }
console.log('index.js加载了~'); // import { plus} from './test'; // console.log(plus(3,4)); document.getElementById('btn').onclick = function () { // lazy loading 可以正常使用 预加载有兼容性问题,慎用 // webpackPrefetch:true,会在使用之前,提前加载js文件 // 正常情况下加载是可以并行的,(同一时刻加载多个文件) // 预加载:prefetch 是等其他资源加载完毕,浏览器空闲了,在偷偷加载资源。 import(/* webpackChunkName:'test',webpackPrefetch:true */'./test').then(({ plus }) => { console.log(plus(2, 3)); }) }
var debug = true; function SearchRadioButtonSelect() { if (debug) console.log("SearchRadioButtonSelect() ... Called !"); var rates = document.getElementsByName('Person'); var rate_value; for (var i = 0; i < rates.length; i++) { if (rates[i].checked) { rate_value = rates[i].value; console.log("... Selected : ", rate_value); //document.getElementById('DocID').value = rate_value; window.location.href = "FamilyTree.xqy?q=" + rate_value; } } } function PersonAdd() { if (debug) console.log("PersonAdd() ... Called !"); window.location.href = "/AddPerson/AddPerson.xqy"; } function PersonSearch() { if (debug) console.log("Search() ... Called !"); var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { xmlDoc = xhttp.responseXML; if (debug) console.log("Response Text : [" + xhttp.responseText + "], Response XML : [" + xhttp.responseXML + "]"); ParseXML(this); } }; // Post Method Used xhttp.open("POST", "/AddPerson/Query/GetWildCardSearch.xqy", true); xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhttp.send("q=" + encodeURIComponent(document.getElementById("FirstName").getValue())); } function ParseXML(xmlhttp) { if (debug) console.log("ParseXML called"); var xmlDoc = xmlhttp.responseXML.documentElement; var xmlNodes = xmlDoc.getElementsByTagName("input"); var container = document.getElementById("PersonSearchResult"); // Clear previous contents of the container while (container.hasChildNodes()) container.removeChild(container.lastChild); // Extract All Serach Result & Create Radio Button For Each Entry to Select if (xmlNodes.length > 0) { console.log ("Number of nodes: " + xmlNodes.length); for (i = 0; i < xmlNodes.length; i++) { console.log ("Number of Child nodes: " + xmlNodes[i].childNodes.length); console.log ("Number of Child nodes Name : " + xmlNodes[i].nodeName); console.log ("Number of Child nodes Type : " + xmlNodes[i].nodeType); console.log ("Number of Child nodes Value : " + xmlNodes[i].getAttribute("value")); console.log ("Number of Child nodes Text : " + xmlNodes[i].getAttribute("text")); //for (j = 0; j < xmlNodes[i].childNodes.length; j++) //console.log ("Number of Child nodes Value : " + xmlNodes[i].childNodes[j].firstChild.nodeValue); var radioInput = document.createElement('input'); radioInput.setAttribute('type', 'radio'); radioInput.setAttribute('name', "Person"); radioInput.setAttribute('value', xmlNodes[i].getAttribute("value")); container.appendChild(radioInput); var t = document.createTextNode(xmlNodes[i].getAttribute("text")); container.appendChild(t); container.appendChild(document.createElement("br")); } } else { var t = document.createTextNode("No Existing Person Found.... ENTER Data as New Person !"); container.appendChild(t); // Append a line break container.appendChild(document.createElement("br")); document.getElementById("PersonAdd").style.display = "block"; } }
/** * contentscript * 真正能够操作页面DOM的脚本程序。 * 该脚本监听background的指示。负责往页面插入、移除相应js/css文件。 * 因为代码片段不利管理,采用整个文件的方式。 * @author fedeoo <tragedymi[at]163.com> * @version 1.0 */ // console.log('why???'); /* contentscript 在每个页面的独立环境执行 */ // debugger; var CONFIG = { CSSMap:{ 'globalStyle': 'css/qindeoo.css', 'foolsStyle': 'css/april-fools.css', 'nightSkyStyle': 'css/nightsky.css' }, JSMap: { 'nightSkyStyle': 'modulejs/nightsky.js' } }; /** * [接收消息并执行对应操作] * @param {[type]} request [消息请求正文] * @param {[type]} sender [description] * @param {[type]} sendResponse [description] */ chrome.extension.onMessage.addListener(function (request, sender, sendResponse) { //━ ━.━\r..\r━. console.debug("━ ━.━\r\t..\r\t━."); if (request.type === 'system') { var cmd = request.cmd; for (var prop in cmd) { if (cmd.hasOwnProperty(prop)) { if (cmd[prop] === 'enable') { CONFIG.CSSMap[prop] && addStyleFile(chrome.extension.getURL(CONFIG.CSSMap[prop])); CONFIG.JSMap[prop] && addJsFile(chrome.extension.getURL(CONFIG.JSMap[prop])); } else if (cmd[prop] === 'disable') { CONFIG.CSSMap[prop] && removeStyleFile(chrome.extension.getURL(CONFIG.CSSMap[prop])); CONFIG.JSMap[prop] && removeJsFile(chrome.extension.getURL(CONFIG.JSMap[prop])); } } } } else if (request.type === 'user') { var cmd = request.cmd; cmd.styleURL && addStyleFile(cmd.styleURL); cmd.jsURL && addJsFile(cmd.jsURL); } }); /** * [addStyleFile 在页面插入css文件,当然也可以是网络资源,如果是扩展资源需要在清单中配置] * @param {[String]} fileName [文件名称,包括全部路径] */ function addStyleFile (fileName) { if (document.head.querySelector('link[href="' + fileName + '"]')) { return ; } var style = document.createElement('link'); style.rel = 'stylesheet'; style.type = 'text/css'; style.href = fileName; (document.head || document.documentElement).appendChild(style); } /** * [removeStyleFile 在页面移除之前添加的css文件] * @param {[String]} fileName [文件名称,包括全部路径] */ function removeStyleFile (fileName) { var style = document.head.querySelector('link[href="' + fileName + '"]'); if (style) { style.remove(); } } /** * [addJsFile 在页面插入JS文件] * @param {[String]} fileName [文件名称,包括全部路径] */ function addJsFile (fileName) { if (document.head.querySelector('script[src="' + fileName + '"]')) { return ; } var script = document.createElement("script"); script.type = "text/javascript"; script.charset = "utf-8"; script.src = fileName; (document.head || document.documentElement).appendChild(script); } /** * [removeJsFile 在页面移除已插入的JS文件] * @param {[type]} fileName [文件名称,包括全部路径] */ function removeJsFile (fileName) { var script = document.head.querySelector('script[src="' + fileName + '"]'); if (script) { script.remove(); } }
import { LOAD_TEST } from '../actions'; export default (state = null, action) => { switch(action.type) { case LOAD_TEST: { return action.payload; } default: ; } return state; }
/** A grid of Escher maps powered by tinier.js. Zachary King 2016 */ import { createMiddleware, run } from 'tinier' import { Grid } from './Grid' import { applyMiddleware, createStore } from 'redux' import createLogger from 'redux-logger' const createStoreWithMiddleware = applyMiddleware( createMiddleware(Grid), createLogger() )(createStore) const api = run(Grid, document.body, null, createStoreWithMiddleware) api.addCell()
/* * @lc app=leetcode id=861 lang=javascript * * [861] Score After Flipping Matrix */ // @lc code=start /** * @param {number[][]} A * @return {number} */ var matrixScore = function(A) { const moveRow = y => { for(let i = 0; i < A[y].length; i++) { A[y][i] = +!A[y][i]; } } const moveColumn = x => { for (let y = 0; y < A.length; y++) { A[y][x] = +!A[y][x]; } } for (let y = 0; y < A.length; y++) { if (!A[y][0]) { moveRow(y); } } const countColumn = x => { return A.reduce((count, i) => { return count + i[x]; }, 0); } for (let x = 1; x < A[0].length; x++) { if (countColumn(x) * 2 < A.length) { moveColumn(x); } } return A.reduce((count, i) => { const n = +`0b${i.join('')}`; return count + n; }, 0); }; matrixScore([[0,0,1,1],[1,0,1,0],[1,1,0,0]]); // @lc code=end
//EXPLANATION ON WEEK 5/ DAY 23/ SLIDE 9 // HOW TO ON WEEK 5/ DAY 23/ SLIDE 10 var db = require('../config/db'); exports.all = function() { return db.rows("GetAllPosts", []); } exports.read = function(id){ return db.row("GetSinglePost", [id]); } exports.write = function(title, categoryId, userId, content) { return db.row("InsertPost", [title, categoryId, userId, content]); } exports.update = function(id, title, categoryId, content) { return db.empty("UpdatePost", [id, title, categoryId, content]); } exports.delete = function(id) { return db.empty("DeletePost", [id]); }
import React from 'react'; import { BrowserRouter as Router, Switch, Route } from 'react-router-dom'; import postDetail from './container/postDetail'; import postList from './container/postList'; import {createBrowserHistory} from 'history' const history=createBrowserHistory(); class App extends React.Component { render() { return ( <Router history={history}> <div> <Switch> <Route exact component={postList} path="/" /> <Route exact component={postDetail} path="/post/:id" /> </Switch> </div> </Router> ) } } export default App;
define(function(require, exports, module) { $("#codeConfirm").click(function(){ var code = $.trim($("#code").val()); Code[code](); }) $("#codeReset").click(function(){ foucusInput("#code"); }) $("#code").keyup(function(event){ if(event.keyCode == 13){ $("#codeConfirm").click(); } }) $(".img-circle").click(function(){ $("#myModal").modal('show'); setTimeout("foucusInput('#code')",300) }) var Code = { phone: function(){ $("#phone").html("13909842001"); $("#myModal").modal('hide') }, code : function(){ window.open("https://github.com/E-HERO-ZZ/resume/tree/gh-pages"); } } }) function foucusInput(id){ $(id).focus(); $(id).val(""); }
const DataTypes = require("sequelize"); const sequelize = require("../config/sequelize"); const User = sequelize.define('User', { email: { type: DataTypes.STRING, allowNull: false }, name: { type: DataTypes.STRING, allowNull: false }, hash: { type: DataTypes.STRING }, salt: { type: DataTypes.STRING }, CPF: { type: DataTypes.STRING, //allowNull: false }, gender: { type: DataTypes.STRING, //allowNull: false }, birthdate: { type: DataTypes.DATEONLY, //allowNull: false }, address: { type: DataTypes.STRING, //allowNull: false }, profilePicture: { type: DataTypes.STRING, allowNull: true }, type_user: { type: DataTypes.BOOLEAN, allowNull: true }, }); User.associate = function(models){ User.hasMany(models.Product, { }); User.hasMany(models.Comment, { }); User.belongsToMany(models.Product, {through: 'favoriteList', as: 'inList', foreignKey: 'userId'}); User.belongsToMany(models.Product, {through: 'cart', as: 'inCart', foreignKey: 'userId'}); } module.exports = User;
// import "babel-polyfill"; import "../styles/styles.sass"; import Main from "../components/main/index.js"; import Router from "../lib/router.js"; let main = new Main(); document.body.append(main.elem); let router = Router.instance(); router .addRoute(/^$/, "dashboard") .addRoute(/^products$/, "products") .listen();
var gulp = require("gulp"), uglify = require("gulp-uglify"), preprocess = require('gulp-preprocess'), babel = require('gulp-babel'), plumber = require('gulp-plumber'); gulp.task('scripts', function() { return gulp.src('./_src/js/index.js') .pipe(preprocess()) .pipe(plumber(function(error){ console.log("Styles Task Error"); console.log(error); this.emit('end'); })) .pipe(babel({ presets: ['es2015'] })) // .pipe(uglify()) .pipe(gulp.dest('./build/js')); });
import { LIGHT_THEME, DARK_THEME } from '../constants/themeConstants' export const themeReducer = (state = { theme: true }, action) => { switch (action.type) { case LIGHT_THEME: return { theme: true } case DARK_THEME: return { theme: false } default: return state } }
'use strict' var ngApp = require('./main.js') ngApp.controller('ctrlShare', [ '$scope', '$sce', '$q', 'tmsLocation', 'tmsSnsShare', 'http2', 'enlService', function ($scope, $sce, $q, LS, tmsSnsShare, http2, enlService) { function fnSetSnsShare(oApp, message, anchor) { function fnReadySnsShare() { if (window.__wxjs_environment === 'miniprogram') { return } var sharelink, shareid, shareby, target_type, target_title /* 设置活动的当前链接 */ shareid = _oUser.uid + '_' + new Date() * 1 shareby = location.search.match(/shareby=([^&]*)/) ? location.search.match(/shareby=([^&]*)/)[1] : '' sharelink = location.protocol + '//' + location.host if (LS.s().topic) { target_type = 'topic' target_title = oApp.record.title sharelink += LS.j('', 'site', 'app', 'topic') + '&page=topic&shareby=' + shareid } else { target_type = 'cowork' target_title = oApp.title sharelink += LS.j('', 'site', 'app', 'ek') + '&page=cowork&shareby=' + shareid if (anchor) { sharelink += '#' + anchor } } /* 分享次数计数器 */ tmsSnsShare.config({ siteId: oApp.siteid, logger: function (shareto) { var url url = '/rest/site/fe/matter/logShare' url += '?shareid=' + shareid url += '&site=' + oApp.siteid url += '&id=' + oApp.id url += '&title=' + target_title url += '&type=enroll' url += '&target_type=' + target_type url += '&target_id=' + oApp.record.id url += '&shareby=' + shareby url += '&shareto=' + shareto http2.get(url) }, jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage'], }) tmsSnsShare.set(oApp.title, sharelink, message, oApp.pic2 || oApp.pic) } if (/MicroMessenger/i.test(navigator.userAgent)) { if (!window.WeixinJSBridge || !WeixinJSBridge.invoke) { document.addEventListener( 'WeixinJSBridgeReady', fnReadySnsShare, false ) } else { fnReadySnsShare() } } } if (/MicroMessenger/i.test(navigator.userAgent)) { $scope.userAgent = 'wx' } var _oApp, _oUser, _oOptions, _oMessage, _oDeferred $scope.options = _oOptions = { canEditorAsAuthor: false, // 被分享内容的作者是否为编辑 canEditorAsInviter: false, shareByEditor: false, } _oMessage = { toString: function () { var msg msg = this.inviter + '邀请你查看' + this.author + (this.relevent || '') + this.object if (!/(\.|,|;|\?|!|。|,|;|?|!)$/.test(this.object)) { msg += '。' } return msg }, } _oDeferred = $q.defer() _oDeferred.promise.then(function (oMsg) { var message $scope.message = message = oMsg.toString() fnSetSnsShare(_oApp, message, oMsg.anchor) }) $scope.gotoHome = function () { location.href = '/rest/site/fe/matter/enroll?site=' + _oApp.siteid + '&app=' + _oApp.id + '&page=repos' } $scope.shiftAuthor = function () { if (_oOptions.editorAsAuthor) { _oMessage.defaultAuthor === undefined && (_oMessage.defaultAuthor = _oMessage.author) _oMessage.author = _oApp.actionRule.role.editor.nickname } else { _oMessage.author = _oMessage.defaultAuthor } $scope.message = _oMessage.toString() fnSetSnsShare(_oApp, $scope.message, _oMessage.anchor) } $scope.shiftInviter = function () { if (_oOptions.editorAsInviter) { _oMessage.defaultInviter === undefined && (_oMessage.defaultInviter = _oMessage.inviter) _oMessage.inviter = _oApp.actionRule.role.editor.nickname } else { _oMessage.inviter = _oMessage.defaultInviter } $scope.message = _oMessage.toString() fnSetSnsShare(_oApp, $scope.message, _oMessage.anchor) } /*不是用微信打开时,提供二维码*/ if (!$scope.userAgent) { $scope.qrcode = LS.j('topic/qrcode', 'site') + '&url=' + encodeURIComponent(location.href) } $scope.$on('xxt.app.enroll.ready', function (event, params) { var oEditor _oApp = params.app /* _oUser = params.user;*/ /* 用户信息 */ enlService.user().then(function (data) { _oUser = data if (oEditor && _oUser.is_editor === 'Y') { _oOptions.canEditorAsInviter = true } }) if ( _oApp.actionRule && _oApp.actionRule.role && _oApp.actionRule.role.editor ) { if ( _oApp.actionRule.role.editor.group && _oApp.actionRule.role.editor.nickname ) { oEditor = _oApp.actionRule.role.editor } } if (LS.s().data) { http2.get(LS.j('data/get', 'site', 'ek', 'data')).then(function (rsp) { var oRecord, oRecData oRecord = rsp.data oRecData = oRecord.verbose[oRecord.schema_id] _oApp.record = rsp.data _oMessage.inviter = _oUser.nickname _oMessage.author = _oUser.uid === oRecData.userid ? 'ta' : oRecData.nickname _oMessage.relevent = '给' if (oRecord.userid !== oRecData.userid) { _oMessage.relevent += oRecord.nickname } else { _oMessage.relevent += '自己' } _oMessage.object = '的回答:' + oRecData.value _oMessage.anchor = 'item-' + LS.s().data if ( _oUser.is_editor === 'Y' && oEditor && oRecData.is_editor === 'Y' && _oUser.uid !== oRecData.userid ) { _oOptions.canEditorAsAuthor = true } _oDeferred.resolve(_oMessage) }) } else if (LS.s().remark) { http2 .get(LS.j('remark/get', 'site', 'remark') + '&cascaded=Y') .then(function (rsp) { var oRemark oRemark = rsp.data _oApp.record = rsp.data.record _oMessage.inviter = _oUser.nickname _oMessage.author = _oUser.uid === oRemark.userid ? 'ta' : oRemark.nickname if (oRemark.record) { _oMessage.relevent = '给' if (oRemark.record.userid !== oRemark.userid) { _oMessage.relevent += oRemark.record.nickname } else { _oMessage.relevent += '自己' } if ( oRemark.data && oRemark.data.userid !== oRemark.record.userid ) { _oMessage.relevent += '和' if (oRemark.data.userid !== oRemark.userid) { _oMessage.relevent += oRemark.data.nickname } else { _oMessage.relevent += '自己' } } } _oMessage.object = '的留言:' + oRemark.content _oMessage.anchor = 'remark-' + oRemark.id if ( _oUser.is_editor === 'Y' && oEditor && oRemark.is_editor === 'Y' && _oUser.uid !== oRemark.userid ) { _oOptions.canEditorAsAuthor = true } _oDeferred.resolve(_oMessage) }) } else if (LS.s().ek) { http2 .get(LS.j('repos/recordGet', 'site', 'app', 'ek')) .then(function (rsp) { var oRecord oRecord = rsp.data _oApp.record = rsp.data _oMessage.inviter = _oUser.nickname _oMessage.author = _oUser.uid === oRecord.userid ? 'ta' : oRecord.nickname _oMessage.object = '的记录。' if ( _oUser.is_editor === 'Y' && oEditor && oRecord.is_editor === 'Y' && _oUser.uid !== oRecord.userid ) { _oOptions.canEditorAsAuthor = true } _oDeferred.resolve(_oMessage) }) } else if (LS.s().topic) { http2 .get(LS.j('topic/get', 'site', 'app', 'topic')) .then(function (rsp) { var oTopic oTopic = rsp.data _oApp.record = rsp.data _oMessage.inviter = _oUser.nickname _oMessage.author = _oUser.unionid === oTopic.unionid ? 'ta' : oTopic.nickname _oMessage.object = '的专题。' if ( _oUser.is_editor === 'Y' && oEditor && oTopic.is_editor === 'Y' && _oUser.unionid !== oTopic.unionid ) { _oOptions.canEditorAsAuthor = true } _oDeferred.resolve(_oMessage) }) } }) }, ])
import axios from "axios"; export function getUserConversations(userId, setConversations) { var config = { method: "get", url: "https://cors-anywhere.herokuapp.com/http://" + "95.71.15.60" + ":8000/getConversations?userID=" + userId, headers: { Origin: "http://localhost:10888", "Access-Control-Allow-Origin": "*", }, }; axios(config) .then(function (response) { if (response.data.data !== undefined) { setConversations(response.data.data); } }) .catch(function (error) {}); } export function getPubConversations(location, setPubConversations) { var config = { method: "get", url: "https://cors-anywhere.herokuapp.com/http://" + "95.71.15.60" + ":8000/getConversations?location=" + location, headers: { Origin: "http://localhost:10888", "Access-Control-Allow-Origin": "*", }, }; axios(config) .then(function (response) { if (response.data.data !== undefined) { setPubConversations(response.data.data); } }) .catch(function (error) {}); } export function search(query, setViewAddresses) { var config = { method: "get", url: "https://cors-anywhere.herokuapp.com/http://kladr-api.ru/api.php?query=" + query + "&oneString=1&limit=10&withParent=1", headers: { Origin: "http://localhost:10888", "Access-Control-Allow-Origin": "*", }, }; axios(config) .then(function (response) { if (response.data.result !== undefined) { setViewAddresses(response.data.result); } }) .catch(function (error) {}); } export function createConversation(name, userId, location, setPopout) { var config = { method: "get", url: "https://cors-anywhere.herokuapp.com/http://" + "95.71.15.60" + ":8000/createConversation?name=" + name + "&creator_id=" + userId + "&location=" + location, headers: { Origin: "http://localhost:10888", "Access-Control-Allow-Origin": "*", }, }; axios(config) .then(function (response) { if (response.data.status === "Error") { return("Error"); } }) .catch(function (error) { console.log(error); }); }
class ChangeGenerator { constructor() { this.changeOwed = 0; this.denominations = [2, 1]; this.collectedCoins = {}; } change() { return '1 x 1p'; } turnToNumber(stringValue) { let number = parseInt(stringValue.slice(0, -1)); return number; } setChangeOwed(valueReceived, valueReturned) { this.changeOwed = valueReceived - valueReturned; } highestPossibleReturn(changeOwed) { for ( let i = 0; i < this.denominations.length; i++ ) { if ( this.denominations[i] <= changeOwed ) { return this.denominations[i]; } } } coinIsInReturnedCoinChecker(coinToBeAdded) { return coinToBeAdded in this.collectedCoins; } addCoin(coin) { if ( this.coinIsInReturnedCoinChecker(coin) ) { this.collectedCoins[coin] += 1; this.changeOwed -= coin; } else { this.collectedCoins[coin] = 1; this.changeOwed -= coin; } } returnChange() { return '1 x 2p'; } }
var searchData= [ ['db4omanagercreationexception_2ejava',['DB4oManagerCreationException.java',['../DB4oManagerCreationException_8java.html',1,'']]] ];
/* - Connects Redux Store to Main Component - Acts as container component, does not have any DOM markup - Only job is to provide data to presentational component - Data injected into Main, then passed down via props in simple apps */ import Main from './Main' import {connect} from 'react-redux' import {bindActionCreators} from 'redux' import * as actions from '../redux/actions' import {withRouter} from 'react-router' // Installed with react-router-dom /* Map current state inside store to props The props can then be injected inside a component at any level as posts */ function mapStateToProps(state) { return{ posts: state.posts, comments: state.comments } } function mapDispatchToProps(dispatch) { // dispatch: Emits action return bindActionCreators(actions, dispatch) } /* - Connects Main component to redux store - Inject Main() with current state of props and dispatch actions - From Main(), pass props down to sub-components because its a smaller app */ const App = withRouter(connect(mapStateToProps, mapDispatchToProps)(Main)) export default App
'use strict' var apigClient = apigClientFactory.newClient(); // Http.onreadystatechange = (e) => { // selectElement.innerHTML = Http.responseText // } var objective = []; var subjective = []; function updateTable() { var subjcheck = document.getElementById('subjcheckbox').checked; var objcheck = document.getElementById('objcheckbox').checked; if(objective.length == 0 && subjective.length == 0) { return; } var arr = []; if(subjcheck && objcheck) { arr = objective.concat(subjective); } else if (!subjcheck && objcheck) { arr = objective; } else if (subjcheck && !objcheck) { arr = subjective; } var selectElement = document.getElementById('date'); var html = "<table><tr>"; // Loop through array and add table cells for (var i=0; i<arr.length; i++) { var factors = arr[i].split("&&&") var link = factors[0] var title = factors[1] var rating = factors[2] var blank = "target=\"_blank\""; var addition = "<td height=\"25\"><a href=\"" + link + "\" " + blank + ">" + title + " — Bias Level: " + Math.round(rating * 100) + "/100</a></td>"; if(addition.includes("NaN")) { continue; } html += addition; // Break into next row var next = i+1; if (next!=arr.length) { html += "</tr><tr>"; } } html += "</tr></table>"; document.getElementById("container").innerHTML = html; } function search() { var selectElement = document.getElementById('date'); selectElement.innerHTML = "Loading..."; var query = document.getElementById('textfield').value.toLowerCase(); var params = { // This is where any modeled request parameters should be added. // The key is the parameter name, as it is defined in the API in API Gateway. 'query': query, 'cap': 30 }; var additionalParams = { // If there are any unmodeled query parameters or headers that must be // sent with the request, add them here. headers: { 'content-type': 'application/json' }, queryParams: { 'query': query, 'cap': 30 } }; var body = { // This is where you define the body of the request, }; apigClient.classifyGet(params, body, additionalParams) .then(function(result){ selectElement.innerHTML = "" var data = JSON.stringify(result['data']) data = data.replace("\"", "").split(";;;") objective = data[0].split("!") subjective = data[1].split("!") if (objective.length <= 1 && subjective.length > 1) { document.getElementById("container").innerHTML = "<p>No unbiased results found.</p>"; return; } else if (objective.length <= 1) { document.getElementById("container").innerHTML = "<p>No results found.</p>"; return; } console.log(data) updateTable() }).catch( function(result){ console.log(result) selectElement.innerHTML = "Failed to search query. Please try a different one." }); } function submitMe() { var selectElement = document.getElementById('date'); selectElement.innerHTML = ""; var sentence1 = document.getElementById('sentence1'); var sentence2 = document.getElementById('sentence2'); var sentence3 = document.getElementById('sentence3'); var sentence4 = document.getElementById('sentence4'); selectElement.innerHTML = "Checking for Bias..."; let link = document.getElementById('textfield').value; var params = { // This is where any modeled request parameters should be added. // The key is the parameter name, as it is defined in the API in API Gateway. 'link': link }; var additionalParams = { // If there are any unmodeled query parameters or headers that must be // sent with the request, add them here. headers: { 'content-type': 'application/json' }, queryParams: { 'link': link} }; var body = { // This is where you define the body of the request, }; apigClient.classifyGet(params, body, additionalParams) .then(function(result){ console.log(result['data']) var data = JSON.stringify(result['data']) console.log(data.split("$$$")[0].substring(1)) console.log(parseFloat(data.split("$$$")[0])) var raw = parseFloat(data.split("$$$")[0].substring(1)) raw = 25.62050323 * raw - 13.67818969 raw = 1/(1+Math.pow(Math.E, 0-raw)) * 100 raw = Math.round(raw) selectElement.innerHTML = "Article Subjectivity: " + raw.toString() + "/100" // sentence1.innerHTML = data.split("$$$")[1].split(".")[0] // sentence2.innerHTML = data.split("$$$")[1].split(".")[1] // sentence3.innerHTML = data.split("$$$")[1].split(".")[2] // sentence4.innerHTML = data.split("$$$")[1].split(".")[3] }).catch( function(result){ console.log(result) selectElement.innerHTML = "Failed to retrieve article, please try a different one." }); }
/*************************************************************** * This script set to run_at document load. See manifest.json. ***************************************************************/ var userKanjiRegexp; var includeLinkText = false; var insertedNodesToCheck = []; var insertedNodeCheckTimer = null; chrome.extension.sendMessage({message: "config_values_request"}, function(response) { userKanjiRegexp = new RegExp("[" + response.userKanjiList + "]"); includeLinkText = JSON.parse(response.includeLinkText); persistentMode = JSON.parse(response.persistentMode); //Having received the config data, start searching for relevant kanji //If none find, do nothing for now except start a listener for node insertions if (document.body.innerText.match(/[\u3400-\u9FBF]/) || persistentMode) chrome.extension.sendMessage({message: "init_tab_for_fi"}); else document.addEventListener("DOMNodeInserted", DOMNodeInsertedHandler); }); function DOMNodeInsertedHandler(e) { if ((e.target.nodeType == Node.TEXT_NODE || e.target.nodeType == Node.CDATA_SECTION_NODE) && e.target.parentNode) insertedNodesToCheck.push(e.target.parentNode) else if (e.target.nodeType == Node.ELEMENT_NODE && e.target.tagName != "IMG" && e.target.tagName != "OBJECT" && e.target.tagName != "EMBED") insertedNodesToCheck.push(e.target); else return; if (!insertedNodeCheckTimer) insertedNodeCheckTimer = setTimeout(checkInsertedNodes, 1000); } function checkInsertedNodes() { var a = []; for (x = 0; x < insertedNodesToCheck.length; x++) a.push(insertedNodesToCheck[x].innerText); insertedNodesToCheck = []; insertedNodeCheckTimer = null; //Doing a join-concatenation then one RegExp.match() because I assume it will be quicker // than running RegExp.match() N times. var s = a.join(""); if (s.match(/[\u3400-\u9FBF]/)) { document.removeEventListener("DOMNodeInserted", DOMNodeInsertedHandler); chrome.extension.sendMessage({message: "init_tab_for_fi"}); return; } } function hasOnlySimpleKanji(rubySubstr) { var foundKanji = rubySubstr.match(/[\u3400-\u9FBF]/g); if (foundKanji) { for (var x = 0; x < foundKanji.length; x++) { if (!userKanjiRegexp.exec(foundKanji[x])) return false; } } else { return null; } return true; }
import React, { useRef } from "react"; import { makeStyles } from "@material-ui/styles"; import { Grid, Card, CardContent, Button } from "@material-ui/core"; import Tooltip from "@material-ui/core/Tooltip"; import Main from "./Main"; import MainTest from "./MainTest"; import PropTypes from "prop-types"; import { connect } from "react-redux"; import ReactToPrint, { useReactToPrint } from "react-to-print"; import PictureAsPdfRoundedIcon from "@material-ui/icons/PictureAsPdfRounded"; const useStyles = makeStyles((theme) => ({ root: { padding: theme.spacing(4), }, differenceIcon: { color: theme.palette.text.secondary, }, })); const ReportTemplate = (props) => { const classes = useStyles(); const componentRef = useRef(); const handlePrint = useReactToPrint({ content: () => componentRef.current, }); const { user } = props.auth; //console.log(user._id); return ( <div className={classes.root}> <Grid container spacing={0}> <Grid item lg={12} sm={12} xl={12} xs={12}> <Card> <CardContent> <Tooltip title="Print OR Save As Pdf" placement="right" arrow> <Button color="primary" variant="contained" endIcon={<PictureAsPdfRoundedIcon />} onClick={handlePrint} alt="Generate Pdf" > {/* Generate Pdf */} </Button> </Tooltip> <Main ref={componentRef} user_id={user._id} /> {/* <MainTest ref={componentRef} /> */} </CardContent> </Card> </Grid> </Grid> </div> ); }; ReportTemplate.propTypes = { className: PropTypes.string, auth: PropTypes.object.isRequired, }; const mapStateToProps = (state) => ({ auth: state.auth, }); export default connect(mapStateToProps)(ReportTemplate); //export default ReportTemplate;
// Photoshop variables var docRef = app.activeDocument; var newWidth, newHeight; var docNameNoExt = filenameNoExt(docRef.name); var scaleFactors = { '@3x': 1, '@2x': 1.5, '@1x': 3, }; // Run main function init(); function init() { rulerUnits = preferences.rulerUnits; // Backing up current document ruler units preferences.rulerUnits = Units.PIXELS; // Setting document units to pixels. if(!isDocumentNew()) { for(var dpi in scaleFactors) { saveFunc(dpi); } } else { alert("Please save your document before running this script."); } preferences.rulerUnits = rulerUnits; } function filenameNoExt(filename) { //Locate the final position of the final . before the extension. var dotPos = filename.lastIndexOf( "." ) ; if ( dotPos > -1 ) { return filename.substr( 0 , dotPos ); } //if dotPos is more than -1 then filename does not contain extension return filename; } // Test if the document is new (unsaved) // http://2.adobe-photoshop-scripting.overzone.net/determine-if-file-has-never-been-saved-in-javascript-t264.html function isDocumentNew(doc){ // assumes doc is the activeDocument cTID = function(s) { return app.charIDToTypeID(s); } var ref = new ActionReference(); ref.putEnumerated( cTID("Dcmn"), cTID("Ordn"), cTID("Trgt") ); //activeDoc var desc = executeActionGet(ref); var rc = true; if (desc.hasKey(cTID("FilR"))) { //FileReference var path = desc.getPath(cTID("FilR")); if (path) { rc = (path.absoluteURI.length == 0); } } return rc; } function saveFunc(dpi) { app.activeDocument = docRef; var originHeight = app.activeDocument.height; var originWidth = app.activeDocument.width; duplicateImage(false); //Some layers may have different effects such as "Outer Glow", "Bevel and Emboss", etc. //Those effect will not be scaled when image resized //So it's better to merge all layers before resizing: flattenLayers(app.activeDocument); resizeActiveDoc(dpi, originWidth, originHeight); var path = docRef.path; var folder = Folder(path + '/' + docNameNoExt + '-assets/'); if(!folder.exists) { folder.create(); } // Name the new asset var saveFile = File(folder + "/" + docNameNoExt + (dpi === '@1x' ? '' : dpi) + ".png"); var sfwOptions = new ExportOptionsSaveForWeb(); sfwOptions.format = SaveDocumentType.PNG; sfwOptions.includeProfile = false; sfwOptions.interlaced = 0; sfwOptions.optimized = true; sfwOptions.quality = 100; sfwOptions.PNG8 = false; // Export the layer as a PNG activeDocument.exportDocument(saveFile, ExportType.SAVEFORWEB, sfwOptions); // Close the document without saving activeDocument.close(SaveOptions.DONOTSAVECHANGES); } function flattenLayers(doc) { try{ doc.mergeVisibleLayers(); }catch(e){ //It may cause error to merge layers if there is only one visible layer in the document // Create a new art layer at the top of the current document doc.artLayers.add(); try { doc.mergeVisibleLayers(); } catch(e) { //do nothing } } } // Duplicate image. Merged shows if layers groups should be merged function duplicateImage(merged) { var desc1 = new ActionDescriptor(); var ref1 = new ActionReference(); ref1.putEnumerated(cTID('Dcmn'), cTID('Ordn'), cTID('Frst')); desc1.putReference(cTID('null'), ref1); if (merged) {desc1.putBoolean(cTID('Mrgd'), true);} executeAction(cTID('Dplc'), desc1, DialogModes.NO); } function resizeActiveDoc(scale, originWidth, originHeight) { // get a reference to the current (active) document and store it in a variable named "doc" doc = app.activeDocument; // change the color mode to RGB. Important for resizing GIFs with indexed colors, to get better results doc.changeMode(ChangeMode.RGB); // these are our values for the end result width and height (in pixels) of our image var newHeight = Math.round(originHeight / scaleFactors[scale]); var newWidth = Math.round(originWidth / scaleFactors[scale]); // do the resizing. if height > width (portrait-mode) resize based on height. otherwise, resize based on width if (doc.height > doc.width) { doc.resizeImage(null,UnitValue(newHeight,"px"),null,ResampleMethod.BICUBIC); } else { doc.resizeImage(UnitValue(newWidth,"px"),null,null,ResampleMethod.BICUBIC); } }
Vue.component('dlg-paragraph', { template: `<modal title="段落區塊" v-model="v" id="paragraph" :width="310" @on-visible-change="onVisibleChange" > <div v-for="(item, index) in paragraph2" :key="index" @click.stop='onClick(index)' :style="{ display: 'inline-block', 'text-align': 'center', width: '50px', padding: '10px 0px', margin: '2px', border: '1px solid #c5c5c5', 'border-radius': '5px', color: item == true ? 'white' : 'black', background: item == true ? '#c01921' : 'white' }"> <div >{{index + 1}}</div> </div> <div slot="footer" style="display: flex; flex-direction: row; justify-content: flex-start; align-items: center;"> <div style="flex: 1; text-align: left;"> <Icon type="ios-arrow-back" size="28" :color="iconColor1" style="cursor: pointer; padding: 3px 5px; border-radius: 5px; border: 1px solid #e6e6e6;" @click.native="moveTo(-1)" /> <Icon type="ios-arrow-forward" size="28" :color="iconColor2" style="cursor: pointer; padding: 3px 5px; border-radius: 5px; border: 1px solid #e6e6e6;" @click.native="moveTo(1)" /> </div> <i-button v-if="block2.length == 2" @click="onClickAll">{{"取消"}}</i-button> <i-button @click="onCancel">關閉</i-button> <i-button type="primary" @click="onOK">確定</i-button> </div> </modal>`, props: { visible: Boolean, paragraph: Array, block: Array }, data() { return { v: false, paragraph2: [], block2: [] }; }, created(){ }, async mounted () { }, destroyed() { }, methods: { onClickAll(){ if(this.block2.length == 0) { this.block2[0] = 0; this.block2[1] = this.paragraph2.length - 1; } else { this.block2 = []; } this.change(); }, moveTo(index){ if(index == -1 && this.iconEable(0)) { this.block2 = [ this.block2[0] + index, this.block2[1] + index ]; this.change(); } else if(index == 1 && this.iconEable(1)) { this.block2 = [ this.block2[0] + index, this.block2[1] + index ]; this.change(); } }, onOK(){ this.v = false; let b = this.block2.length != this.block.lengt || (this.block2.length == this.block.length && this.block2.length == 2 && (this.block2[0] != this.block[0] || this.block2[1] != this.block[1])) ? this.block2 : null; this.$emit("close", b); }, onCancel(){ this.v = false; this.$emit("close"); }, onClick(index) { if(this.block2.length == 0) { this.block2 = [index, index]; } else if(this.block2[0] != this.block2[1] && this.block2[0] == index) { this.block2[0]++; } else if(this.block2[0] != this.block2[1] && this.block2[1] == index) { this.block2[1]--; } else if(this.block2[0] <= index && this.block2[1] >= index) { this.block2 = []; } else { let start = this.block2[0] > index ? index : this.block2[0]; let end = this.block2[1] < index ? index : this.block2[1]; this.block2 = [start, end]; } this.change(); }, onVisibleChange(v){ if(v == true) { this.change(); } }, change(){ this.paragraph2.forEach((el, index) => { this.$set(this.paragraph2, index, (this.block2.length == 2 && index >= this.block2[0] && index <= this.block2[1]) ? true : false) }); }, iconEable(index){ if(index == 0) return this.block2.length == 2 && this.block2[0] > 0 ? true : false; else return this.block2.length == 2 && this.block2[1] < this.paragraph2.length - 1 ? true : false; } }, computed: { iconColor1() { return this.iconEable(0) ? 'black' : '#e6e6e6'; }, iconColor2() { return this.iconEable(1) ? 'black' : '#e6e6e6'; } }, watch: { visible(value) { if(value) this.v = true; }, paragraph(value) { this.paragraph2 = []; value.forEach((el, index) => { this.paragraph2.push(false) this.$set(this.paragraph2, index, false); }); if(this.v)this.change(); }, block(value) { this.block2 = []; value.forEach((el, index) => { this.block2.push(el); this.$set(this.block2, index, el); }); if(this.v) this.change(); }, } });
/** * Created by Liuwei on 2016/11/21. */ // init $(document).ready(function () { console.log('Author: 刘伟,'); console.log('Email: 116402157@qq.com,'); console.log('Phone: 15895891210,'); console.log('Age: 26,'); console.log('Education: college,'); console.log('Position desired: Front-End Engineer,'); console.log('Target city: ["Suzhou", "Shanghai"],'); console.log('[' + (Date()) + ']'); }); // fullpage $(document).ready(function () { $(function () { $("#out-wrapper").fullpage( { continuousVertical: false, //循环演示 //绑定菜单 anchors: ['1', '2', '3', '4', '5', '6'], // 导航 'navigation': true, }); $.fn.fullpage.setAllowScrolling(false); }); }); //hover $(document).ready(function () { var logo = $("#logo"); logo.hover(function(){ logo.find("#header_p1").html("刘伟"); logo.find("#header_p2").html("个人简历"); },function(){ logo.find("#header_p1").html("Liuwei"); logo.find("#header_p2").html("<small>JS on the front, JS on that back, JS at supper time.</small>"); }); });
/** * Created by Khang @Author on 15/01/17. */ import React, { Component } from 'react' import PropTypes from 'prop-types' export default class ResponsiveImage extends Component { static propTypes = { src: PropTypes.string.isRequired, width: PropTypes.number, height: PropTypes.number } render() { var width = this.props.width; var height = this.props.height; var src = this.props.src; return ( <div style={{ width, }} className="responsive-image"> <div style={{ paddingBottom: (height / width * 100) + '%' }} /> <img src={src} className="responsive-image__image" alt={"data"} /> </div> ); } }
import React, { useEffect, useRef } from "react"; import * as d3 from 'd3'; const BallsLegend = ({ height = 100, width, margin = { left: 0, right: 0, top: 20, bottom: 0 }, }) => { const anchor = useRef(); const didMount = useRef(false); const maxR = height / 2 - 10; const circleX = margin.left + maxR; var circleData = [ { "cy": height / 2 - 20, "radius": maxR }, { "cy": height / 2 - 10, "radius": maxR - 10 }, { "cy": height / 2 - 0, "radius": maxR - 20 }]; useEffect(() => { setupContainersOnMount(); didMount.current = true; //----- FUNCTION DEFINITIONS ------------------------------------------------------// function setupContainersOnMount() { const anchorNode = d3.select(anchor.current); if (!didMount.current) { let canvas = anchorNode .append("svg") .attr("width", width - margin.left - margin.right) .attr("height", height - margin.top - margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); var circles = canvas.selectAll("g") .data(circleData) .enter() .append("g"); circles.append("circle") .attr("cx", circleX) .attr("cy", function (d) { return d.cy / 1.3; }) .attr("r", function (d) { return d.radius / 1.3; }) .style("fill", "transparent") .attr("stroke", "black") .attr("stroke-width", 1.5) .style("stroke-dasharray", ("4,2")); canvas .append('text') .attr('class', 'details') .attr('x', (maxR * 2)) .attr('y', height / 2 / 1.3 - 8) .style("font-size", 24) .attr('text-anchor', 'start'); d3.selectAll('.details') .text("Company revenue"); } } }, [height, margin.bottom, margin.left, margin.right, margin.top, width]); // useEffect return <React.Fragment><svg height={maxR * 2} width={width} ref={anchor} /> </React.Fragment>; }; export default BallsLegend;
import { OfflineSerializer as ComputerSerializer } from '../mixins/regenerated/serializers/i-i-s-my-test-application-ember-computer-offline'; import __ApplicationSerializer from './application-offline'; export default __ApplicationSerializer.extend(ComputerSerializer, { });
const express = require("express"); const app = express(); const server = require("http").Server(app); const path = require("path"); const cors = require("cors"); const io = require("socket.io")(server, { cors: { origin: "*", credentials: true, methods: ["GET", "POST"], }, }); app.use(cors()); app.use(express.static(path.join(__dirname, "front/build"))); app.get("*", (req, res) => { res.sendFile(path.join(__dirname, "/front/build/index.html")); }); server.listen(4000, () => { console.log("run server 4000!"); }); let roomId = null; app.use(express.json()); app.post("/api/:roomId", (req, res) => { roomId = req.params.roomId; console.log("post api", roomId); }); io.on("connection", (socket) => { socket.on("join-room", (roomId, userId) => { console.log("user", userId); socket.join(roomId); socket.broadcast.emit("user-connected", userId); }); });
var sum = function(a, b){ return `Sum of ${a} & ${b} is: ${a+b}`; }; var difference = function(a, b){ return `Difference of ${a} & ${b} is: ${a-b}`; }; var multiply = function(a, b){ return `Product of ${a} & ${b} is: ${a*b}`; }; var divide = function(a, b){ return `${a} / ${b} is: ${a/b}`; }; module.exports.sum = sum; module.exports.difference = difference; module.exports.multiply = multiply; module.exports.divide = divide;
console.log("Operações Aritméticas"); console.log( 10 + (2*8) );
import React, { useState, useContext, useEffect } from 'react'; import { Link } from 'react-router-dom'; import AlertContext from '../../context/alerts/alertContext'; import AuthContext from '../../context/auth/authContext'; const NewAccount = (props) => { // Extract values from context const alertContext = useContext(AlertContext); const { alert, showAlert } = alertContext; // Extract values from Auth context const authContext = useContext(AuthContext); const { registerUser, message, authenticated } = authContext; // In case of user is authenticated or registered or is a duplicate registration, reload component useEffect(() => { if (authenticated) { props.history.push('/projects'); } if (message) { showAlert(message.msg, message.category); } // eslint-disable-next-line }, [message, authenticated, props.history]); // Stae for Login const [user, setUser] = useState({ name: '', email: '', password: '', confirm: '', }); // Extract data from user const { name, email, password, confirm } = user; const onChangeLogin = (e) => { setUser({ ...user, [e.target.name]: e.target.value, }); }; // User Login const onSubmitForm = (e) => { e.preventDefault(); // Validate empty fields if (name.trim() === '' || email.trim() === '' || password.trim() === '' || confirm.trim() === '') { showAlert('Todos los campos son obligatorios', 'alerta-error'); return; } // Pass min 6 chars if (password.length < 6) { showAlert('El password debe ser de almenos 6 caracteres', 'alerta-error'); return; } // Verify two password equals if (password !== confirm) { showAlert('Las contraseñas no coinciden', 'alert-error'); return; } // Pass to action registerUser({ name, email, password, }); }; return ( <div className="form-usuario"> {alert ? <div className={`alerta ${alert.category}`}>{alert.msg}</div> : null} <div className="contenedor-form sombra-dark"> <h1>Crear una cuenta</h1> <form onSubmit={onSubmitForm}> <div className="campo-form"> <label htmlFor="name">Nombre</label> <input type="text" id="name" name="name" placeholder="Tu Nombre" value={name} onChange={onChangeLogin} autoComplete="off" ></input> </div> <div className="campo-form"> <label htmlFor="email">Email</label> <input type="email" id="email" name="email" placeholder="Tu Email" autoComplete="off" value={email} onChange={onChangeLogin} ></input> </div> <div className="campo-form"> <label htmlFor="email">Password</label> <input type="password" id="password" name="password" autoComplete="new-password" placeholder="Tu Password" onChange={onChangeLogin} value={password} ></input> </div> <div className="campo-form"> <label htmlFor="confirm">Confirmar Password</label> <input type="password" id="confirm" name="confirm" autoComplete="new-password" value={confirm} placeholder="Repite tu password" onChange={onChangeLogin} ></input> </div> <div className="campo-form"> <input type="submit" className="btn btn-primario btn-block" value="Registrarme"></input> </div> </form> <Link className="enlace-cuenta" to={'/'}> Volver a Iniciar Sesión </Link> </div> </div> ); }; export default NewAccount;
/** * Created by winston on 18/03/16. */ //(function(){var s=document.createElement("script");s.onload=function() //{bootlint.showLintReportForCurrentDocument([]);};s.src="https://maxcdn.bootstrapcdn.com/bootlint/latest/bootlint.min.js";document.body.appendChild(s)})(); //set height of containers to 90% window height var h = $(window).height(); var w = $(window).width(); $("#mainwin").css("height",h *.65); $("#main_container").css("height", h * 0.9); //get width of jumbotron, set displaytable to 90% var wJumbo = $("#main_container").width(); //$("#displayTable").css("width", wJumbo); $(".badges").hover(function(){($(this).attr("src", "/badgeSampleHover.png"))},function(){($(this).attr("src", "/badgeSample.png"))}); $(".badges").click(function(){$("#dummybutton").trigger('click'); console.log("click")}); if(window.innerWidth <= 800 && window.innerHeight <= 600) { $("body").css("padding-top", 0); $("body").css("padding-bottom", 0); $("#logo").css("display","block"); $("#logo").css("margin-left","auto"); $("#logo").css("margin-right","auto"); $('#nav').removeClass('pull-right').addClass('nav-justified'); $("#nav").css("display","block"); $("#nav").css("margin-left","auto"); $("#nav").css("margin-right","auto"); $("#main_container").css("height", h*1.15); } $('body').show();
import * as firebase from 'firebase/app'; import "firebase/auth" import "firebase/storage" import "firebase/database" var firebaseConfig = { apiKey: "AIzaSyDCiqd0GNR4Mhs7xOooyjQ6Rg95AYNRYJM", authDomain: "react-slack-clone-18154.firebaseapp.com", databaseURL: "https://react-slack-clone-18154.firebaseio.com", projectId: "react-slack-clone-18154", storageBucket: "react-slack-clone-18154.appspot.com", messagingSenderId: "420445690002", appId: "1:420445690002:web:17cf9ce7a379e774912e4b" }; // Initialize Firebase firebase.initializeApp(firebaseConfig); export default firebase;
var express = require('express'); var router = express.Router(); var Joi = require('joi'); // database var emails = require('./database.js'); // api routes // get all emails router.get('/emails', function(req, res) { // responce with all emails res.send(emails); }); // get specific email router.get('/emails/:id', function(req, res) { // find the requests email var email = emails.find(function(email) { return email.id === parseInt(req.params.id); }); if (!email) { return res.status(404).send("The email with the given ID not found"); } // responce with the email res.send(email); }); // get inbox messages router.get('/inbox', function(req, res) { var emailsArray = []; // filter trought database and return emails of type inbox emails.forEach(function(email) { filterEmails(email, 'inbox', emailsArray); }); // responce with all inbox emails res.send(emailsArray); }); // get send messages router.get('/send', function(req, res) { var emailsArray = []; // filter trought database and return emails of type inbox emails.forEach(function(email) { filterEmails(email, 'send', emailsArray); }); // responce with all inbox emails res.send(emailsArray); }); // get draft messages router.get('/drafts', function(req, res) { var emailsArray = []; // filter trought database and return emails of type inbox emails.forEach(function(email) { filterEmails(email, 'draft', emailsArray); }); // responce with all inbox emails res.send(emailsArray); }); // create an email router.post('/emails', function(req, res) { // validate the requests email var result = validateEmail(req.body); if (result.error) { return res.status(400).send(result.error.details[0].message); } //create the email var email = { "id": emails.length + 1, "type": req.body.type, "to": req.body.to, "fromName": req.body.fromName, "fromEmail": req.body.fromEmail, "date": req.body.date, "subject": req.body.subject, "message": req.body.message }; // add to database (emails array) emails.push(email); // responce with all emails res.json(emails); }); // updare an email router.put('/emails/:id', function(req, res) { // find the requests email var email = emails.find(function(email) { return email.id === parseInt(req.params.id); }); if (!email) { return res.status(404).send("The email with the given ID not found"); } // validate the request var result = validateEmail(req.body); if (result.error) { return res.status(400).send(result.error.details[0].message); } // update the email email.to = req.body.to; email.fromName = req.body.fromName; email.fromEmail = req.body.fromEmail; email.date = req.body.date; email.subject = req.body.subject; email.message = req.body.message; // responce with the updated email res.send(email); }); // delete an email router.delete('/emails/:id', function(req, res) { // find the requests email var email = emails.find(function(email) { return email.id === parseInt(req.params.id); }); if (!email) { return res.status(404).send("The email with the given ID not found"); } // remove email from database (emails array) var index = emails.indexOf(email); emails.splice(index, 1); // responce with the deleted email res.send(email); }); // validating function function validateEmail(email) { var schema = { "type": Joi.string(), "to": Joi.string().email().allow(''), "from": Joi.string().email(), "fromName": Joi.string(), "fromEmail": Joi.string().email(), "date": Joi.string(), "subject": Joi.string().trim().allow(''), "message": Joi.string().trim().allow('') }; var result = Joi.validate(email, schema); return result; } // filtering function function filterEmails(item, type, array) { if (item.type === type) { array.push(item); } } module.exports = router;
import React from "react" export default class MineBoxGrids extends React.Component { render() { return ( <div style={{ display: "grid", gridTemplateColumns: "auto auto auto auto auto auto auto auto", width: "200px" }} > {this.props.children} </div> ) } }
const isString = v => typeof v === 'string'; const isFunction = v => typeof v === 'function'; const isObject = v => v != null && typeof v === 'object'; const hasProperties = (obj, props) => !!(props.filter(prop => prop in obj).length); const Sanitizers = { remove: (value, regex) => isString(value) ? value.replace(regex, '') : value, transform: (value, config) => isString(value) && isObject(config) && hasProperties(config, ['from', 'to']) ? value.replace(config.from, config.to) : value, convert: (value, func) => isFunction(func) ? func(value) : value }; export default Sanitizers;
import React from 'react' const ChangePayment = ({setSection}) => { return ( <div> <h4>Cambia aquí tu CLABE o Tarjeta de Débito</h4> <div className='change-payment-options'> <div onClick={() => setSection('payment-bank')} className='payment-type'> <div> <img src="/icons/uEA27-disbursement_bank.svg" alt="bank"/> <p>Cuenta bancaria</p> </div> <img src="/icons/uE020-chevron_right.svg" alt="chev right"/> </div> <hr style={{width: '100%', margin: '1rem'}}/> <div onClick={() => setSection('payment-debit')} className='payment-type'> <div> <img src="/icons/uEA28-disbursement_card.svg" alt="bank"/> <p>Tarjeta de débito</p> </div> <img src="/icons/uE020-chevron_right.svg" alt="chev right"/> </div> </div> </div> ) } export default ChangePayment
import React from 'react'; const Score = ({ score, colors }) => { let icons = []; if (score) { for (let i = 0; i < score; i++) { icons.push(<span className="icon icon-beer" key={i} style={{ color: `${colors}`, fontSize: '30px' }} />) } return <div className="score-container">{icons}</div>; } else { return ( <div> <h3 style={{fontSize: '30px', marginBlockEnd: '0', marginBlockStart: '0'}}>Click the Head</h3> </div> ) } } export default Score;
<?xml version="1.0" encoding="UTF-8"?> <Values version="2.0"> <value name="name">extractResourceFromServiceName</value> <value name="encodeutf8">true</value> <value name="body">SURhdGFDdXJzb3IgcGlwZWxpbmVDID0gcGlwZWxpbmUuZ2V0Q3Vyc29yKCk7DQpTdHJpbmcgcmVz b3VyY2VOYW1lID0gInVuZGVmaW5lZCI7DQp0cnkgew0KCVN0cmluZyBzZXJ2aWNlRnFuID0gSURh dGFVdGlsLmdldFN0cmluZyhwaXBlbGluZUMsICJzZXJ2aWNlRnFuIik7DQoJU3RyaW5nIGZvbGRl ckZxbiA9IHNlcnZpY2VGcW4uc3Vic3RyaW5nKDAsIHNlcnZpY2VGcW4uaW5kZXhPZigiOiIpKTsN CglyZXNvdXJjZU5hbWUgPSBmb2xkZXJGcW4uc3Vic3RyaW5nKGZvbGRlckZxbi5sYXN0SW5kZXhP ZigiLiIpKzEsIGZvbGRlckZxbi5sZW5ndGgoKSk7DQp9IGNhdGNoKEV4Y2VwdGlvbiBlKSB7DQoJ Ly8gZG8gbm90aGluZw0KfQ0KSURhdGFVdGlsLnB1dChwaXBlbGluZUMsICJyZXNvdXJjZU5hbWUi LCByZXNvdXJjZU5hbWUpOw0KcGlwZWxpbmVDLmRlc3Ryb3koKTsNCgk=</value> </Values>
export async function rollDice(rollData, dialogOptions) { let rolled = false; const speaker = rollData.speaker || ChatMessage.getSpeaker({actor: this}); const _roll = async function (rollData, bonusDie, bonusMod) { let result = 0; let norm = []; let wild = []; var count = rollData.value - 1 + bonusDie; let die = new Die({faces: 6, number: count}).evaluate(); //die.roll(count); die.results.forEach(n => { norm.push(n.result); }); let wildDie = new Die({faces:6, number: 1}).evaluate(); //wildDie.roll(1); wildDie.explode('X'); wildDie.results.forEach(n =>{ wild.push(n.result); }); if (wild[0] === 1) { if (norm.length === 1) { result = rollData.mod + bonusMod; } else { var idx = 0; var highest = 0; for (let i = 0; i < norm.length; i++) { if (norm[i] > highest) { idx = i; highest = norm[i] } } var temp = norm.slice(); temp.splice(idx, 1); result = temp.reduce((a,b) => a + b, 0); result = result + rollData.mod + bonusMod; } } else { result = norm.reduce((a,b) => a + b, 0) + wild.reduce((a,b) => a + b, 0) + rollData.mod + bonusMod; } let resultColor = ""; if (wild[0] === 1){ resultColor = "fumble"; } else if (wild[0] === 6){ resultColor = "critical"; } let bonusText = ""; if (bonusDie > 0 || bonusMod > 0){ bonusText = bonusText + ` + (${bonusDie}D + ${bonusMod})` } let resultDialogData = { skill: rollData.skill, diceRoll: `${rollData.value}D + ${rollData.mod}${bonusText}`, resultColor: resultColor, result: result, normalRolls: `${norm.join(",")}`, wildRolls: `${wild.join(",")}`, mod: rollData.mod + bonusMod } let template = "systems/swd6/templates/chat/roll-result-dialog.html"; const html = await renderTemplate(template, resultDialogData) await ChatMessage.create({content: html, speaker: speaker}); //return { norm, wild, result }; } // Render modal dialog let template = "systems/swd6/templates/chat/roll-dialog.html"; let dialogData = { skill: rollData.skill, value: `${rollData.value}D + ${rollData.mod}`, bonusDie: 0, bonusMod: 0, data: rollData }; const html = await renderTemplate(template, dialogData); // Create the Dialog window let roll; return new Promise(resolve => { new Dialog({ title: dialogData.skill, content: html, buttons: { normal: { label: game.i18n.localize("Roll!"), callback: html => { let bonusDie = html.find('.bonus-die-field')[0]; let bonusMod = html.find('.bonus-mod-field')[0]; if (isNaN(bonusDie.value)){ bonusDie.value = "0"; } if (isNaN(bonusMod.value)){ bonusMod.value = "0"; } roll = _roll(dialogData.data, parseInt(bonusDie.value), parseInt(bonusMod.value)) } } }, default: "normal", close: html => { resolve(rolled ? roll : false); } }, dialogOptions).render(true); }); }
import React from "react"; import s from "./Initialize.module.css"; import Preloader from "../common/Preloader/Preloader"; export const Initialize = () => { return ( <div className={s.container}> <div className={s.wrapper}> <Preloader /> </div> </div> ); }; export default Initialize;
'use strict'; angular.module('mean.mypackage').config(['$stateProvider', function($stateProvider) { $stateProvider.state('mypackage example page', { url: '/mypackage/example', templateUrl: 'mypackage/views/index.html' }); } ]);
var mongoose = require('mongoose'), path = require('path'), fs = require('fs'), model_path = path.join(__dirname,'./../models'); console.log("future mongoose connection and model loading"); mongoose.connect('mongodb://localhost/friends'); mongoose.connection.on('connected',function(){ console.log("mongoose connection successful"); }); mongoose.connection.on('error',function(err){ console.log("ERROR : "+err); }); mongoose.connection.on('disconnected',function() { console.log("Mongoose disconnected"); }) process.on('SIGINT',function(){ mongoose.connection.close(function functionName() { console.log("mongoose disconnected through app termination"); process.exit(0);}) }) fs.readdirSync(model_path).forEach(function(file) { if(file.indexOf('.js')>=0){ require(path.join(model_path,file)); } })
/** * Created by zhoucaiguang on 16/8/11. */ exports.mysqlConfig={ server:'localhost', user:"root", password:"root", database:"NodeJs", port:"3306", maxSockets : 10,//pool使用 timeout : 1//pool使用 };
import models from "../database"; import UserError from "../errors/user-error"; import * as Sequelize from "sequelize"; import ServerError from "../errors/server-error"; import {setPassword} from "../database/dto/user"; export default class UserRepository { constructor({db}) { this.db = db; } async all(offset, limit) { return this.db.Users.findAll({ offset, limit }) .then(result => { return result.map(data => data.dataValues); }).catch(err => { throw new ServerError(err) }); } async findByEmail(userModel) { return this.db.Users.findOne({where: {email: userModel.email}}) .then(result => { return result.dataValues; }) .catch(err => { throw new ServerError(err); }) } async findById(userModel) { return this.db.Users.findByPk(userModel.id) .then(result => { return result.dataValues; }) .catch(err => { throw new ServerError(err); }) } async create(userModel) { setPassword(userModel, userModel.password); return this.db.Users.create(userModel).then((query) => { return query.dataValues; }).catch((err) => { if (err instanceof Sequelize.ValidationError || err instanceof Sequelize.UniqueConstraintError) { let errorMessage = err.errors.map(e => e.message).join('\n'); throw new UserError(errorMessage); } if(err instanceof Sequelize.DatabaseError) { if(err.message === "invalid input value for enum enum_users_type: \"t\"") throw new UserError("invalid user type"); } throw new ServerError(err) }); } async update(userModel) { let result = undefined; return this.db.Users.findByPk(userModel.id).then((user) => { if(user){ if(userModel.password !== undefined) setPassword(userModel, userModel.password); return user.update(userModel).then(query => { return query.dataValues; }).catch(err => { if (err instanceof Sequelize.ValidationError) throw new UserError("User with same email already exists"); }); } }).catch(err => { throw new ServerError(err); }); } async delete(userModel) { let deletedUser = undefined; return this.db.Users.findByPk(userModel.id).then(user =>{ if(user) { deletedUser = user.dataValues; return user.destroy(); } return 0; }).then(() => { return deletedUser; }).catch(err => { throw new ServerError(err.message) }); } }
/*jshint mootools:true,browser:true,devel:false*/ /*global escape */ define("dr-media-abstract-player", ["dr-media-hash-implementation"], function (HashTimeCodeImplementation) { "use strict"; var AbstractPlayer = new Class({ Implements: [Events, Options], options: { appData: { gemius: { drIdentifier: '019_drdk-', identifier: 'p9AwR.N.S86s_NjaJKdww7b.fdp8ky90ZnrKpgLHOUn.s7', hitcollector: window.location.protocol + '//sdk.hit.gemius.pl', channelName: 'drdk' }, linkType: 'Streaming', fileType: 'mp3' }, videoData: { materialIdentifier: 'unknown' }, enableHashTimeCode: false }, /** @private raw result from getresource handler */ resourceResult: null, /** @private raw programcard */ programcardResult: null, /** bool is true when player has recieved the duration of the content */ hasDuration: false, /** * Instance of HashTimeCodeImplementation. Is set upon initialization if options.enableHashTimeCode is true. * @type {HashTimeCodeImplementation} */ hashTimeCodeInstance: null, /** @constructor */ initialize: function (options) { this.setOptions(options); if (this.options.element) { this.options.element.store("instance", this); /** * @name instance * @event * Dispatched when the class has been created. After this, the player object can be fetched by retrieving 'instance' from the containing element */ this.options.element.fireEvent('instance', this); } this.mediaPlayerId = ++AbstractPlayer.$mediaPlayerId; this.buildPreview(); if (this.options.enableHashTimeCode) { this.hashTimeCodeInstance = new HashTimeCodeImplementation(this); } }, updateOptions: function (options) { this.options.appData.autoPlay = true; this.setOptions(options); // reset resourceResult this.forgetModel(); }, /** * Loads the resource if it is not allready loaded and calls a closure * when the resource is ready * @param resourceReady Closure to call when resource is ready */ ensureResource: function (resourceReady) { if (this.hasResource()) { resourceReady(); } else { var url = this.options.videoData.resource; this.fireEvent('resourceLoading'); if (this.options.platform) { if (url.indexOf('?') !== -1) { url = url + '&type=' + this.options.platform; } else { url = url + '?type=' + this.options.platform; } } //debug replace: if (document.location.host != 'www.dr.dk') { url = url.replace('www.dr.dk', document.location.host); } new Request.JSON({ 'onSuccess': function (result) { if (result.Data) { this.programcardResult = result.Data[0]; } else { this.resourceResult = result; } this.onDurationChange(); resourceReady(); this.fireEvent('resourceReady'); } .bind(this), 'onFailure': function (x) { this.displayError('defaultMsg', 'State: ' + x.readyState + ' ' + x.statusText.toString() + ' ' + url); } .bind(this), 'onError': function (msg, e) { this.displayError('defaultMsg', 'Error: ' + msg + ' ' + url); } .bind(this), 'url': url }).get(); } }, /** * Loads the live stream resources if they are not allready loaded and calls a closure * @param {Function} liveStreamsReady Closure to call when the resources are loaded */ ensureLiveStreams: function (liveStreamsReady) { if (this.options.videoData.channels) { liveStreamsReady(); } else { var url = this.options.appData.urls.liveStreams, channel, server, quality, stream; this.fireEvent('resourceLoading'); new Request.JSON({ 'onSuccess': function (result) { this.options.videoData.channels = []; result.Data.each(function (c) { if (c.StreamingServers) { var logo = ""; if (c.SourceUrl && this.options.appData.urls.channelLogoUrl) { var m = c.SourceUrl.match(/\/(\w{3})\/?$/i); if (m) { logo = m[1].toLowerCase(); logo = logo === 'tvu' ? 'drn' : logo; logo = this.options.appData.urls.channelLogoUrl.replace("{id}", logo); } } channel = { 'name': c.Title, 'slug': c.Slug, 'url': c.Url, 'logo': logo, 'servers': [] }; c.StreamingServers.each(function (s) { server = { 'server': s.Server, 'qualities': [], 'linkType': s.LinkType, 'dynamicUserQualityChange': s.DynamicUserQualityChange || false }; s.Qualities.each(function (q) { quality = { 'kbps': q.Kbps, 'streams': [] }; q.Streams.each(function (st) { quality.streams.push(st.Stream); }); server.qualities.push(quality); }); channel.servers.push(server); }); this.options.videoData.channels.push(channel); } } .bind(this)); liveStreamsReady(); this.fireEvent('resourceReady'); } .bind(this), 'url': url }).get(); } }, /** * Returns the stream with kbps closest to the kbps param * @param {Array} streams [Array of streams] * @param {Number} kbps [Target kbps] * @param {String} linkType [Optional! Defaults to options.appData.linkType] * @return {Sring} [stream object] */ findClosestQuality: function (streams, kbps, linkType) { var i, stream, selecedStream, type, HLSStream, HDSStream; type = linkType || this.options.appData.linkType; for (i = 0; i < streams.length; i = i + 1) { stream = streams[i]; if ( stream.linkType && stream.linkType.toLowerCase() === "hls") { HLSStream = stream; } if ( stream.linkType && stream.linkType.toLowerCase() === "hds") { HDSStream = stream; } } selecedStream = this.selectStream(streams, kbps, type); if ( (type.toLowerCase() === "ios" || type.toLowerCase() === "android") && HLSStream ) { selecedStream = HLSStream; } else if ( (type.toLowerCase() === "streaming" ) && HDSStream ) { selecedStream = HDSStream; } if (!selecedStream) { selecedStream = this.selectStream(streams, kbps, 'download'); } if (!selecedStream) { console.log("Unable to find stream " + type + " " + this.options.appData.fileType); throw new Error("Unable to find stream " + type + " " + this.options.appData.fileType); } return selecedStream; }, selectStream: function(streams, kbps, type) { var stream, currentKbps, currentDist, returnStream; var dist = -1; for (var i = 0; i < streams.length; i = i + 1) { stream = streams[i]; if ((!stream.linkType || stream.linkType.toLowerCase() === type.toLowerCase()) && (!stream.fileType || stream.fileType == this.options.appData.fileType)) { currentKbps = (stream.kbps ? stream.kbps : stream.bitrateKbps); currentDist = Math.abs(currentKbps - kbps); if (dist === -1 || currentDist < dist) { dist = currentDist; returnStream = stream; } } } return returnStream; }, getQuerystring: function (key, default_) { if (default_==null) default_=""; key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]"); var regex = new RegExp("[\\?&]"+key+"=([^&#]*)"); var qs = regex.exec(window.location.href); if(qs == null) return default_; else return qs[1]; }, /** starts playing the content */ play: function () { }, /** pauses the content */ pause: function () { }, /** stops playback and returns to the first frame */ stop: function () { }, /** @return current position in timeline in percent (Number between 0 and 1) */ progress: function () { return this.position() / this.duration(); }, /** @return current position in timeline in seconds */ position: function () { return 0; }, currentTimeCode: function () { return this.timeCodeConverter.secondsToTimeCode(this.position()); }, /** @return total length of content in seconds */ duration: function () { if (this.resourceResult) { return this.resourceResult.durationInMilliseconds / 1000; } else if (this.programcardResult) { var resource = this.programcardResult.Assets.filter(function (item) { return item.Kind === "VideoResource" || item.Kind === "AudioResource"; })[0]; if (!resource) { return 0; } return resource.DurationInMilliseconds / 1000; } else { return 0; } }, productionNumber: function () { if (this.resourceResult) { return this.resourceResult.productionNumber; } else if (this.programcardResult && this.programcardResult.ProductionNumber) { return this.programcardResult.ProductionNumber; } else if (this.options.videoData.productionNumber) { return this.options.videoData.productionNumber; } else { return '00000000000'; } }, hasResource: function () { return (this.resourceResult != null || this.programcardResult != null); }, resourceSlug: function () { // create slug for old getResource handler if (this.programcardResult) { return this.programcardResult.Slug; } else if (this.resourceResult && this.resourceResult.name) { var slug = this.resourceResult.name.toLowerCase(); slug = slug.replace(/[^\-a-zA-Z0-9,&\s]+/ig, ''); slug = slug.replace(/[\s|\-|\_]+/gi, "-"); return slug.substr(0, 40); } else if (this.options.videoData.episodeSlug) { return this.options.videoData.episodeSlug; } else if (this.productionNumber() !== '00000000000') { return this.productionNumber(); } else if (this.resourceResult && this.resourceResult.resourceId) { return 'resourceId:' + this.resourceResult.resourceId; } else { return ''; } }, links: function () { if (this.resourceResult) { return this.resourceResult.links; } else if (this.programcardResult) { var resource = this.programcardResult.Assets.filter(function (item) { return item.Kind === "VideoResource" || item.Kind === "AudioResource"; })[0]; return resource.Links.map(function (item) { return { "uri": item.Uri, "linkType": item.Target, "fileType": item.FileFormat, "bitrateKbps": item.Bitrate, "width": item.Width, "height": item.Height } }); } return []; }, getPosterImage: function () { // use custom image, if defined if (this.options.videoData.image) { return this.options.videoData.image; } // use image from resource and resize var w, h, resourceImage; if (this.resourceResult && this.resourceResult.images && this.resourceResult.images.length > 0) { resourceImage = this.resourceResult.images[0].src; // w = this.options.element.offsetWidth; // h = Math.floor(this.options.element.offsetWidth / 16 * 9); return resourceImage; } else if (this.programcardResult) { var image = this.programcardResult.Assets.filter(function (item) { return item.Kind === "Image"; })[0]; if (image) { return image.Uri; } } // use original image, if defined if (this.originalPosterImage !== null) { return this.originalPosterImage; } else { return this.options.appData.urls.defaultImage || ""; } }, /** * forgets all properties loaded from ensureResource */ forgetModel: function () { this.resourceResult = null; this.programcardResult = null; }, resourceName: function () { if (this.resourceResult) { return this.resourceResult.name; } else if (this.programcardResult) { return this.programcardResult.Title; } return ""; }, resourceId: function () { if (this.resourceResult) { return this.resourceResult.resourceId; } else if (this.programcardResult) { return this.programcardResult._ResourceId; } return 0; }, onDurationChange: function () { var dur = this.duration(); if (dur && dur > 0 && dur !== Infinity) { this.hasDuration = true; this.fireEvent('durationChange'); } }, onPlay: function () { this.fireEvent('play'); }, onPause: function () { if (!this._forceSeekIntervalId) { this.fireEvent('pause'); } }, onProgressChange: function () { this.fireEvent('progressChange'); }, /** * @name buffering * @event * Dispatched when the player starts to buffer content */ onBuffering: function (position) { this.fireEvent('buffering', position); }, /** * @name bufferingComplete * @event * Dispatched when the player is finished buffering */ onBufferingComplete: function (position) { this.fireEvent('bufferingComplete', position); }, /** * @name beforeSeek * @event * Dispatched when the player starts to seek to another position */ onBeforeSeek: function (position) { //console.log('AbstractPlayer:onBeforeSeek'); this.fireEvent('beforeSeek', position); }, /** * @name afterSeek * @event * Dispatched when the player is finished seeking */ onAfterSeek: function (position) { //console.log('AbstractPlayer:onAfterSeek'); this.fireEvent('afterSeek', position); }, /** * @name complete * @event * Dispatched when the player has played the entire content */ onComplete: function () { //console.log('AbstractPlayer:onComplete'); this.fireEvent('complete'); }, /** * @name changeChannel * @event * Fired when the player changes live channel from an internal menu. IE. flash fullscreen. */ changeChannel: function (channelId) { this.fireEvent('changeChannel', channelId); this.channelHasChanged = true; }, /** * @name changeContent * @event * Fired when the player changes on demand content from an internal menu. IE. flash fullscreen. */ changeContent: function (programSLUG, programSerieSlug) { this.fireEvent('changeContent', programSLUG, programSerieSlug); this.contentHasChanged = true; }, /** * Removes all html from element */ clearContent: function () { this.fireEvent('clearContent'); try { if (this.options.element.getChildren().length() > 0) { this.options.element.getChildren().destroy(); } } catch (e) { this.options.element.innerHTML = ''; //IE friendly disposing of flash player } }, /** * Sends a logging entry if options.logging.errorLogUrl is defined * with the following GET parameters: * url - document.location of the containing page * error - "access_denied", "connection_failed", "defaultMsg", "notFound", "timeout" */ logError: function (errorCode) { if (this.options.logging && this.options.logging.errorLogUrl !== null) { new Request({ 'url': this.options.logging.errorLogUrl, 'method': 'get' }).send('error=' + errorCode + '&url=' + escape(document.location)); } }, /** * Displays error * @param {[type]} errorCode [description] * @private */ displayError: function (errorCode) { /*jshint devel:true */ if (window.console && console.log) { console.log("Error: " + errorCode); } }, /** * Seeks the player to a specific position in the timeline * @param {string} timeCode formatted HH:MM:SS, MM:SS, HH:MM:SS.MS or MM:SS.MS * @deprecated Use seek instead * @see seek */ seekToTimeCode: function (timeCode) { /*jshint devel:true*/ if (window.console && console.log) { console.log("seekToTimeCode is deprecated, use seek() instead"); } this.seek(timeCode); }, /** * Seeks the player to a specific position in the timeline * @param {object} time code or number between 0 and 1 */ seek: function (value) { if (this._forceSeekIntervalId) { this._forceSeekComplete(); } this._forceSeekIntervalId = this._forceSeek.periodical(100, this, value); this._forceSeek(value); }, /** @private */ _forceSeekIntervalId: null, /** @private */ _forceSeek: function (value) { var seconds, distance, pos, seekResult; seekResult = this._seek(value); if (typeof(value) === 'string') { seconds = this.timeCodeConverter.timeCodeToSeconds(value); } else { seconds = value * this.duration(); } pos = this.position(); distance = Math.abs(seconds - pos); if (distance < 0.1 || seekResult || !value) { this._forceSeekComplete(); } }, /** @private */ _forceSeekComplete: function () { clearTimeout(this._forceSeekIntervalId); this._forceSeekIntervalId = null; }, timeCodeConverter: { /** * @function * Converts timecode to seconds as a floating point number * @param {String} timeCode The timecode as a string. IE: HH:MM:SS or MM:SS or MM:SS.MS * @return {Number} */ timeCodeToSeconds: function (timeCode) { var values = timeCode.split(":"); values = values.reverse(); return Number(values[0]) + (Number(values[1]) * 60) + (values.length > 2 ? (Number(values[2]) * 3600) : 0); }, /** * @function * Converts timecode to a progress factor, where 0 is the beginning of the content and 1 is the end. * @param {String} timeCode The timecode as a string. IE: HH:MM:SS or MM:SS or MM:SS.MS * @param {Number} length The duration of the content in seconds as a floating point number */ timeCodeToProgress: function (timeCode, length) { return this.timeCodeToSeconds(timeCode) / length; }, /** * @function * Converts progress factor to timecode as a string. IE: HH:MM:SS or MM:SS * @param {Number} progress Progress as a number, where 0 is the beginning of the content and 1 is the end. * @param {Number} length The duration of the content in seconds as a floating point number * @param {bool} forceHours If true the time code will allways contain hours */ progressToTimeCode: function (progress, length, forceHours) { return this.secondsToTimeCode(this.progressToSeconds(progress, length), forceHours); }, /** * @function * Converts progress factor to seconds as a floating point number * @param {Number} progress Progress as a number, where 0 is the beginning of the content and 1 is the end. * @param {Number} length The duration of the content in seconds as a floating point number */ progressToSeconds: function (progress, length) { return progress * length; }, /** * @function * Converts from seconds as a floating point number to timecode as a string. IE: HH:MM:SS or MM:SS * @param {Number} seconds Seconds as a floating point number * @param {bool} forceHours If true the time code will allways contain hours */ secondsToTimeCode: function (seconds, forceHours) { var min = Math.floor(seconds / 60); var sec = parseInt(seconds, 10) % 60; var hours = 0; if (min >= 60) { hours = Math.floor(min / 60); min = min % 60; } return (hours > 0 || forceHours ? (hours < 10 ? "0" + hours : hours) + ":" : "") + (min < 10 ? "0" + min : min) + ":" + (sec < 10 ? "0" + sec : sec); }, /** * @function */ unixTimeStampToTimeCode: function (timestamp) { var date = new Date(timestamp); var seconds = 0; if (date.hours > 0) seconds += date.hoursUTC * 60 * 60; if (date.minutes > 0) seconds += date.minutesUTC * 60; if (date.seconds > 0) seconds += date.secondsUTC; return this.secondsToTimeCode(seconds); }, /** * @function * Converts from seconds as a floating point number to progress factor, where 0 is the beginning of the content and 1 is the end. * @param {Numver} seconds Seconds as a floating point number * @param {Number} length The duration of the content in seconds as a decimal number. */ secondsToProgress: function (seconds, length) { return seconds / length; } }, queryGeofilter: function() { var xmlhttp = new XMLHttpRequest(); xmlhttp.open("GET", window.location.protocol + "//geo.dr.dk/DR/DR.CheckIP.IsDanish/", true); xmlhttp.setRequestHeader("Cache-Control", "no-cache"); xmlhttp.setRequestHeader("Accept", "*/*"); xmlhttp.setRequestHeader("Server", "geo.dr.dk"); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4) { this.handleGeoResponse(xmlhttp.responseText); } }.bind(this); xmlhttp.send(); }, handleGeoResponse: function(isInDenmark) { console.log('handleGeoResponse() not implemented. Must be overridden in sub class'); } }); AbstractPlayer.$mediaPlayerId = 0; return AbstractPlayer; });
function calc_packyear() { "use strict"; var cigdie = document.anam.cigdie.value, cigyear = document.anam.cigyear.value, packyear = (cigdie * cigyear) / 20; document.anam.packyear.value = packyear; } function calc_bmi() { "use strict"; var altezza = document.anam.altezza.value, peso = document.anam.peso.value, bmi = peso / ((altezza / 100) * (altezza / 100)); document.anam.bmi.value = bmi.toFixed(1); } function calc_fio2_1() { "use strict"; var lmin = document.add4.oxther2lm.value, fio2 = (lmin * 3) + 21; if (lmin <= 6) { document.add4.fio2_1.value = (lmin * 3) + 21; } else { document.add4.fio2_1.value = (6 * 3) + 21; } } function calc_fio2_2() { "use strict"; var lmin = document.add4.oxther3lm.value, fio2 = (lmin * 3) + 21; if (lmin <= 6) { document.add4.fio2_2.value = (lmin * 3) + 21; } else { document.add4.fio2_2.value = (6 * 3) + 21; } }
/*jshint mootools:true,browser:true,devel:true */ define("dr-media-flash-audio-player", ['dr-media-audio-player'], function (AudioPlayer) { "use strict"; var FlashAudioPlayer = new Class({ Extends: AudioPlayer, eventCatcherId: null, swiff: null, flashStreamInitalized: false, lastProgressEvent: null, isPlaying: false, options: { 'appData': { 'errorMessages': { 'obsolete_flash_player': 'Du skal have <a href="http://get.adobe.com/flashplayer/">Adobe Flash Player 10 eller nyere</a> installeret for at høre dette.' } } }, initialize: function (options) { this.parent(options); //register global eventCatcher for flash callbacks: if (!window.DR) { window.DR = {}; } if (!window.DR.NetRadio) { window.DR.NetRadio = {}; } this.eventCatcherId = "eventCatcher_" + this.mediaPlayerId.toString(); window.DR.NetRadio[this.eventCatcherId] = this.eventCatcher.bind(this); }, build: function () { if (Browser.Plugins.Flash.version < 10) { this.displayError('obsolete_flash_player'); return; } this._ensureStream = this.options.videoData.videoType === 'ondemand' ? this.ensureResource : this.ensureLiveStreams; this._ensureStream(this.postBuild.bind(this)); this.parent(); }, getQuerystring: function (key, default_) { if (default_==null) default_=""; key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]"); var regex = new RegExp("[\\?&]"+key+"=([^&#]*)"); var qs = regex.exec(window.location.href); if(qs == null) return default_; else return qs[1]; }, postBuild: function () { var swiffContainer = new Element('div', { 'class':'DRInvisibleAudioPlayer', styles: { position: 'absolute' } }); this.options.element.adopt(swiffContainer); var swfUrl = ''; /*if (this.getQuerystring('akamai-test', '') == 'true') { swfUrl = '/assets/swf/DRInvisibleAudioPlayer-test.swf'; } else { swfUrl = '/assets/swf/DRInvisibleAudioPlayer.swf'; } */ swfUrl = '/assets/swf/DRInvisibleAudioPlayer.swf'; this.swiff = new Swiff(swfUrl, { container: swiffContainer, params: { allowscriptaccess: 'sameDomain', wmode: 'transparent', bgcolor: '#ffffff' }, vars: { eventCatcherFunction: "window.DR.NetRadio." + this.eventCatcherId, autoPlay: this.options.appData.autoPlay } }); // this.swiff.object.set('tabindex', '-1'); }, eventCatcher: function (event) { switch (event.type) { case "versionEvent": //flash player is ready this.setVolume(this.currentVolume || 0.7); this.setBroadcastData(); this.ready(); break; case "progressEvent": this.lastProgressEvent = event; this.onProgressChange(); break; case "complete": this.onComplete(); break; case "playStateChange": if (event.playState === "playing") { this.isPlaying = true; this.onPlay(); } else if (event.playState === "paused") { this.isPlaying = false; this.onPause(); } else if (event.playState === "stopped") { this.flashStreamInitalized = false; this.isPlaying = false; this.onStop(); } break; case "bufferProgressEvent": // console.log("buffer: " + event.progress); break; case "bufferingChange": if (event.buffering) { this.options.element.addClass('buffering'); this.onBuffering(this.position()); } else { this.options.element.removeClass('buffering'); this.onBufferingComplete(this.position()); } break; case "seekingChange": if (event.seeking) { this.onBeforeSeek(this.lastProgressEvent.currentTime); } else { this.lastProgressEvent = { 'currentTime': event.time}; this.onAfterSeek(event.time); this.onProgressChange(); this.onPlay(); } break; case "mediaError": if (event.error && event.error.detail) console.log(event.error.detail); this.displayError('defaultMsg'); break; default: if (window.console && console.log) { console.log("unknown event: ", event.type); } break; } }, setBroadcastData: function() { if (this.options.videoData.videoType === 'live') { try { Swiff.remote(this.swiff.object, 'flash_setVideoData', this.options.videoData); } catch (err) { console.log("Error calling 'flash_setVideoData'"); } } else if (this.programcardResult !== null) { var pc = this.programcardResult; pc.videoType = this.options.videoData.videoType; try { Swiff.remote(this.swiff.object, 'flash_setProgramCard', this.programcardResult); } catch (err) { console.log("Error calling 'flash_setProgramCard'"); } } }, setNewBitrate: function(bitrate) { this.parent(bitrate); this.flashStreamInitalized = false; this.play(); if (this.targetTimeCode) this.seek(this.targetTimeCode); }, updateOptions: function (options) { //this.pause(); // stop current stream this.setOptions(options); // set new options this.setOptions({ 'appData': { 'autoPlay': true} }); // enable autoplay this.forgetModel(); // reset resource this.flashStreamInitalized = false; // tell flash to load new file this.play(); }, play: function () { if (!this.flashStreamInitalized) { this._ensureStream(function () { var stream = this.getStream(this.options.appData.defaultQuality); if (!stream) { console.log('invalid stream: ' + stream + ' ::: ABORTING!'); } Swiff.remote(this.swiff.object, 'flash_play', stream); this.flashStreamInitalized = true; } .bind(this)); } else { if (!this.isPlaying) { Swiff.remote(this.swiff.object, 'flash_pause'); //toggle pause } } }, pause: function () { Swiff.remote(this.swiff.object, 'flash_pause'); }, stop: function () { Swiff.remote(this.swiff.object, 'flash_stop'); }, position: function () { // if (this.seekWhenReady) { // var fakePosition = 0; // if (typeof (this.seekWhenReady) === 'string') { // fakePosition = this.timeCodeConverter.timeCodeToSeconds(this.seekWhenReady); // } else { // fakePosition = this.seekWhenReady; // } // return fakePosition; // } if (this.lastProgressEvent) { return this.lastProgressEvent.currentTime; } else { return 0; } }, volume: function () { return this.currentVolume; }, setVolume: function (vol) { this.currentVolume = vol; if (this.swiff) Swiff.remote(this.swiff.object, 'flash_setVolume', vol); this.fireEvent('volumechange'); }, /** * @private */ _seek: function (value) { var seconds; if (typeof(value) === 'string') { seconds = this.timeCodeConverter.timeCodeToSeconds(value); } else { seconds = value * this.duration(); } if (this.isPlaying) { try { Swiff.remote(this.swiff.object, 'flash_seekTo', seconds); return true; } catch (error) { return false; } } return false; } }); return FlashAudioPlayer; });
/* globals __DEV__ */ import { currentReverse, iterationsComplete, position as getPosition } from './timeline' /** * An event. * * @typedef {Object} Event * * @property {number} at - The time the event occured. * @property {string} name - The event name. * @property {Object} options - Any additional event data. */ /** * A Timeline event subscription. * * @typedef {Object} EventSubscription * * @property {function} callback * @property {string} name * @property {number} token */ /** * An object to hold Timeline EventSubscriptions, and subscribe/unsubscribe functions. * * @typedef {Object} EventObject * * @property {Object} previousPlaybackOptions * @property {Object} previousState * @property {function} subscribe - A function to subscribe to Timeline events. * @property {EventSubscription[]} subscriptions * @property {function} unsubscribe - A function to unsubscribe to Timeline events. */ /** * Token incrementor. */ let t = 0 /** * Accepted event names. */ const acceptedEventNames = [ 'timeline.start', 'timeline.finish', 'shape.start', 'shape.finish', 'keyframe', 'frame' ] /** * An EventObject creator. * * @param {Timeline} timeline * * @returns {EventObject} * * @example * event(timeline) */ const event = timeline => ({ previousPlaybackOptions: {}, previousState: {}, subscribe: subscribe(timeline), subscriptions: [], unsubscribe: unsubscribe(timeline) }) /** * Is a Timeline active? * * @param {Timeline} timeline * * @returns {boolean} * * @example * active(timeline) */ const active = ({ event, state }) => ( state.started && (!state.finished || typeof event.previousState === 'undefined' || !event.previousState.finished) ) /** * A unique list of Timeline EventSubscription names. * * @param {Timeline} timeline * * @returns {string[]} * * @example * activeEventNames(timeline) */ const activeEventNames = ({ event: { subscriptions } }) => { const s = [] for (let i = 0, l = subscriptions.length; i < l; i++) { const name = subscriptions[ i ].name if (s.indexOf(name) === -1) { s.push(name) } } return s } /** * Run EventSubscription callbacks for every event that has occured since last check. * * @param {Timeline} timeline * * @example * events(timeline) */ const events = timeline => { if (playbackOptionsChanged(timeline)) { timeline.event.previousPlaybackOptions = {} timeline.event.previousState = {} } const subscriptions = timeline.event.subscriptions if (subscriptions.length && active(timeline)) { const eventNames = activeEventNames(timeline) const queue = eventQueue(timeline, eventNames) for (let i = 0, l = queue.length; i < l; i++) { const event = queue[ i ] const eventName = event.name const options = event.options || {} for (let _i = 0, _l = subscriptions.length; _i < _l; _i++) { const subscription = subscriptions[ _i ] if (eventName === subscription.name) { subscription.callback(options) } } } } timeline.event.previousPlaybackOptions = { ...timeline.playbackOptions } timeline.event.previousState = { ...timeline.state } } /** * An array of Events that have occured since last checked. * * @param {Timeline} timeline * @param {string[]} eventNames * * @returns {Event[]} * * @example * eventQueue(timeline, eventNames) */ const eventQueue = ({ event: { previousState }, playbackOptions, state, timelineShapes }, eventNames) => { const queue = [] const { alternate, duration, initialIterations, iterations, reverse, started } = playbackOptions const max = started + (duration * state.iterationsComplete) const min = typeof previousState.iterationsComplete !== 'undefined' ? started + (duration * previousState.iterationsComplete) + 1 : 0 const getTimestamps = pos => positionTimestamps({ alternate, duration, initialIterations, iterations, max, min, position: pos, reverse, started }) if (eventNames.indexOf('timeline.start') !== -1) { const timestamps = getTimestamps(0) for (let i = 0, l = timestamps.length; i < l; i++) { queue.push({ name: 'timeline.start', at: timestamps[ i ] }) } } if (eventNames.indexOf('timeline.finish') !== -1) { const timestamps = getTimestamps(1) for (let i = 0, l = timestamps.length; i < l; i++) { queue.push({ name: 'timeline.finish', at: timestamps[ i ] }) } } if (eventNames.indexOf('shape.start') !== -1) { for (let i = 0, l = timelineShapes.length; i < l; i++) { const { shape: { name: shapeName }, timelinePosition: { start } } = timelineShapes[ i ] const timestamps = getTimestamps(start) for (let _i = 0, _l = timestamps.length; _i < _l; _i++) { queue.push({ name: 'shape.start', at: timestamps[ _i ], options: { shapeName } }) } } } if (eventNames.indexOf('shape.finish') !== -1) { for (let i = 0, l = timelineShapes.length; i < l; i++) { const { shape: { name: shapeName }, timelinePosition: { finish } } = timelineShapes[ i ] const timestamps = getTimestamps(finish) for (let _i = 0, _l = timestamps.length; _i < _l; _i++) { queue.push({ name: 'shape.finish', at: timestamps[ _i ], options: { shapeName } }) } } } if (eventNames.indexOf('keyframe') !== -1) { for (let i = 0, l = timelineShapes.length; i < l; i++) { const { shape: { name: shapeName, keyframes }, timelinePosition: { start, finish } } = timelineShapes[ i ] for (let _i = 0, _l = keyframes.length; _i < _l; _i++) { const { name: keyframeName, position } = keyframes[ _i ] const keyframePosition = start + (finish - start) * position const timestamps = getTimestamps(keyframePosition) for (let __i = 0, __l = timestamps.length; __i < __l; __i++) { queue.push({name: 'keyframe', at: timestamps[ __i ], options: { keyframeName, shapeName }}) } } } } if (eventNames.indexOf('frame') !== -1) { queue.push({ name: 'frame', at: max }) } return queue.sort(oldest) } /** * A sort function for Events. * * @param {Event} a * @param {Event} b * * @returns {number} * * @example * oldest(event1, event2) */ const oldest = (a, b) => a.at === b.at ? 0 : (a.at < b.at ? -1 : 1) /** * Have playbackOptions changed since last check? * * @param {Timeline} timeline * * @return {boolean} * * @example * playbackOptionsChanged(timeline) */ const playbackOptionsChanged = timeline => ( JSON.stringify(timeline.playbackOptions) !== JSON.stringify(timeline.event.previousPlaybackOptions) ) /** * Timestamps at which a Timeline was at a Position. * * @param {Object} opts * @param {boolean} opts.alternate * @param {number} opts.duration * @param {number} initialIterations * @param {number} iterations * @param {number} opts.max - The maximum bound within which to look for timestamps. * @param {number} opts.min - The minimum bound within which to look for timestamps. * @param {Position} opts.position - The Position in question. * @param {boolean} opts.reverse * @param {number} opts.started * * @returns {number[]} * * @example * positionTimestamps(opts) */ const positionTimestamps = ({ alternate, duration, initialIterations, iterations, max, min, position, reverse, started }) => { const startedPosition = getPosition(initialIterations, reverse) const finishedTimestamp = started + duration * iterations const timestamps = timestamp => { if (timestamp <= max) { const timestampReverse = currentReverse({ alternate, initialIterations, iterations, reverse }, iterationsComplete({ duration, iterations, started }, timestamp)) const positionAtEnd = position === 0 || position === 1 const timelineFinished = timestamp === finishedTimestamp const finishedAtPosition = (position === 0 && timestampReverse) || (position === 1 && !timestampReverse) if ( timestamp <= finishedTimestamp && (!positionAtEnd || !timelineFinished || finishedAtPosition) ) { const t = timestamp >= min ? [ timestamp ] : [] return t.concat( timestamps(timestamp + timeToSamePosition({ alternate, duration, position, reverse: timestampReverse })) ) } } return [] } return timestamps(started + timeToPosition({ alternate, duration, from: startedPosition, reverse, to: position })) } /** * The number of milliseconds between two Positions during Timeline playback. * * @param {Object} opts * @param {boolean} opts.alternate * @param {number} opts.duration * @param {Position} opts.from - The from Position. * @param {boolean} opts.reverse - Is Timeline in reverse at the from Position? * @param {Position} opts.to - The to Position. * * @returns {number} * * @example * timeToPosition(opts) */ const timeToPosition = ({ alternate, duration, from, reverse, to }) => ( duration * (alternate ? reverse ? from < to ? to + from : from - to : from > to ? 2 - (to + from) : to - from : reverse ? from === 1 && to === 0 ? 1 : (1 - to + from) % 1 : from === 0 && to === 1 ? 1 : (1 - from + to) % 1 ) ) /** * The number of milliseconds between the same Position during Timeline playback. * * @param {Object} opts * @param {boolean} opts.alternate * @param {number} opts.duration * @param {Position} opts.position * @param {boolean} opts.reverse - Is Timeline in reverse at the Position? * * @returns {number} * * @example * timeToSamePosition(opts) */ const timeToSamePosition = ({ alternate, duration, position, reverse }) => ( duration * (alternate ? reverse ? (position === 0 ? 1 : position) * 2 : 2 - (position === 1 ? 0 : position) * 2 : 1 ) ) /** * Creates a subscribe function. * The created function adds an EventSubscription to the subscriptions * property of an EventObject. * * @param {Timeline} timeline * * @returns {function} * * @example * subscribe(timeline)('timeline.start', () => console.log('timeline.start')) */ const subscribe = timeline => (name, callback) => { if (validEventName(name)) { if (__DEV__ && typeof callback !== 'function') { throw new TypeError(`The subscribe functions second argument must be of type function`) } const token = ++t timeline.event.subscriptions.push({ name, callback, token }) return token } } /** * Is an event name valid? * * @param {string} name * * @throws {TypeError} Throws if not valid * * @returns {true} * * @example * validEventName('timeline.start') */ const validEventName = name => { if (__DEV__) { if (typeof name !== 'string') { throw new TypeError(`The subscribe functions first argument must be of type string`) } if (acceptedEventNames.indexOf(name) === -1) { throw new TypeError(`The subscribe functions first argument was not a valid event name`) } } return true } /** * Creates an unsubscribe function. * Created function removes an EventSubscription from the subscriptions * property of an EventObject, given the Event token. * * @param {Timeline} timeline * * @returns {function} * * @example * unsubscribe(timeline)(token) */ const unsubscribe = timeline => token => { const subscriptions = timeline.event.subscriptions let matchIndex for (let i = 0, l = subscriptions.length; i < l; i++) { if (subscriptions[ i ].token === token) { matchIndex = i } } if (typeof matchIndex !== 'undefined') { timeline.event.subscriptions.splice(matchIndex, 1) return true } return false } export { activeEventNames, event, eventQueue, oldest, playbackOptionsChanged, positionTimestamps, subscribe, timeToPosition, timeToSamePosition, unsubscribe, validEventName } export default events
/* * Copyright (C) 2021 Radix IoT LLC. All rights reserved. */ import publisherListTemplate from './publisherList.html'; /** * @ngdoc directive * @name ngMango.directive:maPublisherList * @restrict E * @description Displays a list of publishers */ const DEFAULT_SORT = ['name']; class PublisherListController { static get $$ngIsClass() { return true; } static get $inject() { return ['maPublisher', '$scope', '$filter']; } constructor(maPublisher, $scope, $filter) { this.maPublisher = maPublisher; this.$scope = $scope; this.$filter = $filter; } $onInit() { this.ngModelCtrl.$render = () => this.render(); this.doQuery(); this.maPublisher.subscribe({ scope: this.$scope, handler: (event, item, attributes) => { if (Array.isArray(this.preFilterItems)) { attributes.updateArray(this.preFilterItems); this.filterList(); } } }); } $onChanges(changes) { if (changes.filter && !changes.filter.isFirstChange() || changes.sort && !changes.sort.isFirstChange()) { this.filterList(); } } doQuery() { const queryPromise = this.maPublisher.buildQuery() // TODO this is a unbounded query .query() .then(items => { this.preFilterItems = items; return this.filterList(); }).finally(() => { if (this.queryPromise === queryPromise) { delete this.queryPromise; } }); return (this.queryPromise = queryPromise); } setViewValue() { this.ngModelCtrl.$setViewValue(this.selected); } render() { this.selected = this.ngModelCtrl.$viewValue; } selectPublisher(publisher) { if (this.selected === publisher) { // create a shallow copy if this publisher is already selected // causes the model to update this.selected = Object.assign(Object.create(this.maPublisher.prototype), publisher); } else { this.selected = publisher; } this.setViewValue(); } newPublisher(event) { this.selected = new this.maPublisher(); this.setViewValue(); } filterList() { if (!Array.isArray(this.preFilterItems)) { return; } let items = this.preFilterItems.filter(this.createFilter()); items = this.$filter('orderBy')(items, this.sort || DEFAULT_SORT); return (this.items = items); } createFilter() { if (!this.filter) return (item) => true; let filter = this.filter.toLowerCase(); if (!filter.startsWith('*')) { filter = '*' + filter; } if (!filter.endsWith('*')) { filter = filter + '*'; } filter = filter.replace(/\*/g, '.*'); const regex = new RegExp(filter, 'i'); return (item) => { return regex.test(item.name) || regex.test(item.description) || regex.test(item.connectionDescription); }; } } export default { template: publisherListTemplate, controller: PublisherListController, bindings: { showNew: '<?', showEnableSwitch: '<?', hideSwitchOnSelected: '<?', sort: '<?', filter: '<?' }, require: { ngModelCtrl: 'ngModel' }, designerInfo: { translation: 'ui.components.publisherList', icon: 'assignment_turned_in' } };
const mongoose = require('../connections/mongoose/instance'); const schema = require('../schema/story'); module.exports = mongoose.model('story', schema);
import React from "react"; import VRViz from "vr-viz"; import markdown from "../ReadMe/Charts/RectangleChart.md"; const Title = { title: "Graphs or Charts/Rectangle Chart", }; export default Title; export const RectangleChart = () => ( <VRViz scene={{ sky: { style: { color: "#333", texture: false, }, }, lights: [ { type: "directional", color: "#fff", position: "0 1 1", intensity: 1, decay: 1, }, { type: "ambient", color: "#fff", intensity: 1, decay: 1, }, ], camera: { position: "5 5 12", rotation: "0 0 0", }, reloadPageOnExitVR: true, }} graph={[ { type: "RectangleChart", data: { dataFile: "data/data3.csv", fileType: "csv", fieldDesc: [ ["Year", "text"], ["miles", "number"], ["gas", "number"], ["emission", "number"], ], }, style: { dimensions: { width: 25, height: 10, depth: 10, }, }, rotationOnDrag: { rotateAroundXaxis: false, }, mark: { position: { x: { field: "Year", }, }, type: "box", style: { depth: { field: "miles", startFromZero: true, }, height: { field: "gas", startFromZero: true, }, fill: { opacity: 0.9, scaleType: "linear", field: "emission", color: ["#b71c1c", "#2196f3"], }, }, mouseOver: { focusedObject: { opacity: 1, }, nonFocusedObject: { opacity: 0.2, }, label: { value: (d) => `Year: ${d.Year}\nMiles: ${d.miles}\nGas: ${d.gas}\nEmmision: ${d.emission}`, align: "center", width: 0.5, height: 0.35, wrapCount: 100, lineHeight: 75, backgroundColor: "#fff", backgroundOpacity: 0.9, fontColor: "#333", }, }, }, axis: { "x-axis": { orient: "front-bottom", ticks: { noOfTicks: 10, size: 0.01, color: "white", opacity: 0.7, fontSize: 3, }, grid: { color: "white", opacity: 0.7, }, }, "y-axis": { orient: "front-left", ticks: { noOfTicks: 10, size: 0.01, color: "white", opacity: 0.7, fontSize: 3, }, grid: { color: "white", opacity: 0.7, }, }, "z-axis": { ticks: { noOfTicks: 10, size: 0.01, color: "white", opacity: 0.7, fontSize: 3, }, grid: { color: "white", opacity: 0.7, }, }, }, }, ]} /> ); RectangleChart.story = { parameters: { notes: { markdown }, }, };
export default (value) => { return value ? 'True' : 'False' }
$(document).ready(function () { $('#Sheet').hide(); $('#TablesButton').hide(); populateDatabaseLists(); $('#lastSubmit').hide(); $('#vr').hide(); var sourcefile=''; var destDB=''; var sourceSheet=''; var destTable = '' var mode=''; $(document).on('click', '#list li', function(event) { sourcefile = $(this).text(); makeAjaxCallSDB(sourcefile); $('#selectdb').prop('disabled','true'); $('#selectdb').css("background-color","green"); $('#selectdb').text(sourcefile); }); $(document).on('click','#Sheet li', function(){ sourceSheet = $(this).text(); $('#SheetsButton').prop('disabled','true'); $('#SheetsButton').css("background-color","green"); $('#SheetsButton').text(sourceSheet); }); $(document).on('click','#Table li', function(){ destTable = $(this).text(); $('#TablesButton').prop('disabled','true'); $('#TablesButton').css("background-color","green"); $('#TablesButton').text(destTable); }); $(document).on('change','#myForm input', function() { mode = $(this).parent().text(); $('#myForm input:radio').prop('disabled','true'); }); $(document).on('click','#list2 li', function(){ destDB = $(this).text(); makeAjaxDest(destDB); $('#destDB').prop('disabled','true'); $('#destDB').css("background-color","green"); $('#destDB').text(destDB); }); $(document).on('click','#SubButton',function(){ //if(!(sourcefile.length==0 || sourceSheet.length==0 || mode.length==0 || destDB.length==0)) // makeCompleteAjax(sourcefile,sourceSheet,mode,destDB); //else //alert('The following fields are empty :\n\n'+(sourcefile=='' ? 'Source Database\n': '')+(sourceSheet=='' ? 'Source Database\'s Table\n':'')+(mode=='' ? 'Mode of Insertion\n':'')+(destDB=='' ? 'Destination Database\n':'')+''); $.post("getColumns.php",{sheet : sourceSheet, file : sourcefile},function(data){ alert(data); var start_li = '<li><a>' var end_li = '</a></li>'; data = JSON.parse(data); var start = "<option>" var end = "</option>"; $.post("getDBColumns.php",{DB : destDB, Tb : destTable},function(data2){ data2 = JSON.parse(data2); str = ""; for(var j = 0;j<data.length;j++) { str += start +data[j]+end; } var stringo = ""; for(var k = 0;k<data2.length; k++) { stringo +=""+data2[k] + " : <select id =\""+k+"\">"+ str+ "</select>"; } $("#afterSub").append(stringo); alert(stringo); }) //$("#afterSub").append(stringo); }); }); }); $(document).on("click","#afterSub > select > option",function(){ alert($(this).html()); alert($(this).parent().prop("id")); //alert('you clicked on button #' + clickedBtnID); }) function makeAjaxDest(dest) { $.post("HandleInputs.php",{source : dest},function(data){ var start_li = '<li><a>' var end_li = '</a></li>'; var opts = data.split(' '); var stringo = ""; for(var i= 0;i<opts.length;i++) { stringo += start_li + opts[i] + end_li; } $("#Table ul").append(stringo); }); $('#TablesButton').show(); } function populateDatabaseLists() { var start_li = '<li><a>'; var end_li = '</a></li>'; var output = ""; $.ajax({ url:'Databases.php', type: 'POST', }).done(function(data) {console.log(data)}) .fail(function(data) {alert("error");}) .success(function(data){ var recievedData = JSON.parse(data); for(var i =0;i<recievedData.length;i++){ if (recievedData[i] != "cdcol" && recievedData[i] != "information_schema" && recievedData[i] != "mysql" && recievedData[i] != "performance_schema" && recievedData[i] != "phpmyadmin" && recievedData[i] != "test" && recievedData[i] != "test" && recievedData[i] != "webauth") output += start_li+recievedData[i]+end_li; } $("#list2 ul").append(output); }) output = ""; $.ajax({ url:'Excels.php', type: 'POST', }).done(function(data) {console.log(data)}) .fail(function(data) {alert("error");}) .success(function(data){ var recievedData = JSON.parse(data); var outp = ""; for(var i =0;i<recievedData.length;i++){ outp += start_li+recievedData[i]+end_li; } $("#list ul").append(outp); }) } function makeCompleteAjax(sDB,sTable,md,dDB) { //Establish connection to php script $.ajax({ url: 'FILE1.php', type: 'POST', data: { sourcefile : sDB, sourceSheet : sTable, mode : md, destDB : dDB } }).done(function(data) { console.log(data); }) .fail(function() { alert("error");}) .always(function(data) { var span = $('#resultpic'); if (data.toString().toLowerCase() == "success") { span.addClass('glyphicon-ok') $('#vr').show(); $('#ICON').html("<h2 style='color: #3498db;'><strong><u>MESSAGE</u></strong><h2> <br> The Data was successfully " + (md == "Overwrite" ? "overwritten" : "appended") +" with any additional columns filled with 0."); } else { span.addClass('glyphicon-remove'); $('#vr').show(); $('#ICON').html("<h2 style='color: #3498db;'><strong><u>MESSAGE</u></strong><h2> <br> There was no tables whose schema matched that of the destination db."); } $('#lastSubmit').show(); $('html, body').animate({ scrollTop: $("#lastContainer").offset().top }, 1000); } ); } function makeAjaxCallSDB(sourcefile) { $.post("GetSheet.php",{file : sourcefile},function(data){ var start_li = '<li><a>' var end_li = '</a></li>'; var opts = data.split(' '); var stringout = ""; var recievedData = JSON.parse(data); var out=""; for(var i =0;i<recievedData.length;i++){ out += start_li+recievedData[i]+end_li; } $("#Sheet ul").append(out); }); $('#Sheet').show(); }
const callback = require('./build/Release/callback'); callback((msg) => { console.log(msg); });
define("elements/wb-grant-stream-help.js", [], function() { "use strict"; function e(e, t) { if (!(e instanceof t)) throw new TypeError("Cannot call a class as a function") } var t = function() { function e(e, t) { for (var n = 0; n < t.length; n++) { var i = t[n]; i.enumerable = i.enumerable || !1, i.configurable = !0, "value" in i && (i.writable = !0), Object.defineProperty(e, i.key, i) } } return function(t, n, i) { return n && e(t.prototype, n), i && e(t, i), t } }(), n = function() { function n() { e(this, n) } return t(n, [{ key: "beforeRegister", value: function() { this.is = "wb-grant-stream-help" } }, { key: "ready", value: function() { navigator.userAgent.includes("Chrome") ? this._videoId = "n9X-ereqeKU" : this._videoId = "OT99igvII58" } }, { key: "attached", value: function() { this.listen(window, "wb-got-cam-stream", "_gotStream") } }, { key: "detached", value: function() { this.listen(window, "wb-got-cam-stream", "_gotStream") } }, { key: "_gotStream", value: function() { this.$.dialog.close() } }, { key: "show", value: function() { this.$.dialog.open() } }]), n }(); Polymer(n) });
var searchData= [ ['dog',['Dog',['../class_dog.html#a48cb6f3ba25700f30dc96797c4764cf6',1,'Dog']]], ['dogfight',['dogFight',['../class_dog.html#afa0b680a20272e619d6f2cfd891db5a1',1,'Dog']]] ];
var divisor = 2; var input = 600851475143; while (input != divisor) { if (input % divisor === 0) input = input/divisor; else divisor++; } console.log(divisor);
if (self.CavalryLogger) { CavalryLogger.start_js(["O0qyl"]); } __d("XMercuryChatTabPagesNullStateConfigController",["XController"],(function a(b,c,d,e,f,g){f.exports=c("XController").create("/pages/messaging/mercury/greeting/",{})}),null);
$(()=>{ $('[name=disco-button-etudiant]').on('click', function(){ $.ajax({ url: "/", type: 'POST', data:{ action: 'logout' }, success: function(response){ whoami = ""; $('h3#bienvenue > span').append(whoami); loadPage('authentification'); $('[name=etudiant-navbar]').hide(); $("[name=prof-navbar]").hide(); }, error: function(err){ } }); }); $('[name=disco-button-prof]').on('click', function(){ $.ajax({ url: "/", type: 'POST', data:{ action: 'logout' }, success: function(response){ if(!msg_alerte(response)){ loadPage('authentification'); $('[name=etudiant-navbar]').hide(); $("[name=prof-navbar]").hide(); whoami = ""; } }, error: function(err){ } }); }); });
//用户交易明细 $(function() { //账户明细 充值记录 购买彩票等的tabswtich $('#account_detail .tab li').click(function(){ $(this).addClass('active').siblings().removeClass('active'); $('#type').val($(this).index()); $('#account_detail .tab_swtich').children().eq($(this).index()).show().siblings().hide(); getAccountDetail(1); }); getAccountDetail(1); $('#search').click(function(){ getAccountDetail(1); }) }); function getAccountDetail(pageNum) { var pageRow = 10; var startTime = $('#startTime').val(); var endTime = $('#endTime').val(); var type = $('#type').val(); var re = /^\d{4}-\d{1,2}-\d{1,2}$/; var objExp = new RegExp(re); var parm = "type="+type+"&pageRow="+pageRow+"&pageNum="+pageNum; if (startTime != ""||endTime != "") { if (objExp.test(startTime) == true) { parm += "&startTime=" + startTime; } else { alert('请输入正确的起始日期(yyyy-MM-dd)!'); return; } if (objExp.test(endTime) == true) { parm += "&endTime=" + endTime; } else { alert('请输入正确的结束日期(yyyy-MM-dd)!'); return; } } $('.tab_swtich').css({"background":"url(../../img/icon12.gif) no-repeat center center"}); $.ajax({ type: "POST", url: "/member/getAccountTradeList.htm", data:parm, dataType: "json", success: function(msg){ var content =""; var list = msg.result; if(type=='0'){//账户明细 for(var i in list){ content+="<div class=\"list\"><ul><li class=\"li1\">"+list[i].tradeTime+"</li>"; if(list[i].theirFlow=='0'){ content+="<li class=\"li2\">¥0.0</li>"+ "<li class=\"li3\">¥"+list[i].tradeTotal+"</li>"; }else if(list[i].theirFlow=='1'){ content+="<li class=\"li2\">¥"+list[i].tradeTotal+"</li>"+ "<li class=\"li3\">¥0.0</li>"; } content+="<li class=\"li4\">¥"+list[i].remainMoney+"</li>"+ "<li class=\"li5\">"+list[i].tradeType+"</li>"+ "<li class=\"li6\">"+list[i].tradeCode+"</li>"+ "<li class=\"li7\">"+list[i].tradeDesc+"</li></ul></div>"; } }else if(type=='1'||type=='2'||type=='3'){//充值记录,购买记录,奖金派送 for(var i in list){ content+="<div class=\"list\"><ul><li class=\"li1\">"+list[i].tradeTime+"</li>"+ "<li class=\"li2\">¥"+list[i].tradeTotal+"</li>"+ "<li class=\"li3\">¥"+list[i].charges+"</li>"+ "<li class=\"li4\">¥"+list[i].remainMoney+"</li>"+ "<li class=\"li5\">"+list[i].tradeType+"</li>"+ "<li class=\"li6\">"+list[i].tradeCode+"</li>"+ "<li class=\"li7\">"+list[i].tradeDesc+"</li></ul></div>"; } }else if(type=='4'){//提款记录 for(var i in list){ content+= "<div class=\"list\"><ul><li class=\"li1\">"+list[i].tradeTime+"</li>"+ "<li class=\"li2\">¥"+list[i].tradeTotal+"</li>"+ "<li class=\"li3\">¥"+list[i].charges+"</li>"+ "<li class=\"li4\">"; content+="</li><li class=\"li5\">"+list[i].tradeCode+"</li>"+ "<li class=\"li6\">"; if(list[i].tradeStatus=='0'){ content+="待审核"; }else if(list[i].tradeStatus=='1'){ content+="交易成功"; }else if(list[i].tradeStatus=='2'){ content+="交易失败"; } content+="</li><li class=\"li7\">"+list[i].tradeDesc+"</li></ul></div>"; } } if(msg.allPage==0){//没有记录存在 $('#content_'+type).html("<script>alert('无交易记录!')</script>"); $('#index').html(''); $('.tab_swtich').css({"background":"none"}); return; } //主要内容 $('#content_'+type).html(content); //分页 var index ="<ul> <li class=\"li1\" onclick=\"getAccountDetail(1)\">第一页</li> <li class=\"li2\" onclick=\"getAccountDetail("+msg.upPage+")\">←</li>"; if(msg.pageNum-3>0){index+="<li class=\"li3\">...</li>"} for(var i=msg.pageNum-2;i<=msg.allPage;i++){ if(i>0&&i<=msg.pageNum+2){ if(i==msg.pageNum){ index+="<li class=\"li2 active\">"+i+"</li>"; }else{ index+="<li class=\"li2\" onclick=\"getAccountDetail("+i+")\">"+i+"</li>"; } } } if(msg.pageNum+2<msg.allPage){index+="<li class=\"li3\">...</li>"} index+="<li class=\"li2\" onclick=\"getAccountDetail("+msg.nextPage+")\">→</li> " + "<li class=\"li1\" onclick=\"getAccountDetail("+msg.allPage+")\" >尾页</li></ul> "; $('#index').html(index); $('.tab_swtich').css({"background":"none"}); } }); }
import React from 'react'; import {Link} from 'react-router-dom'; export default function NavBar() { return ( <div className="navDiv p-3"> <nav className="navbar navbar-default"> <div className="navbar-header"> <a className="navbar-brand"><h3 className="headText logo">AEsKay.React</h3></a> </div> <ul className="nav navbar-navs"> <li> <Link to="/"> <button className="menuBtn">Home</button> </Link> </li> <li> <Link to="/services"> <button className="menuBtn">Services</button> </Link> </li> <li> <Link to="/about"> <button className="menuBtn">About</button> </Link> </li> </ul> </nav> </div> ) }
import React from "react"; import { Link } from "gatsby"; import Layout from "../components/layout"; const AboutPage = () => { return( <> <Layout> <h1>Title</h1> <p>lorem ipsum</p> <p><Link to="/contact">Contact Me!</Link></p> </Layout> </> ); } export default AboutPage;
import React from 'react' import { View, Text } from 'react-native' import Icon from 'react-native-vector-icons/MaterialIcons' import styles from './styles' const Message = ({ message: { fisrt, name, message, color, type, date } }) => ( <View style={styles.container}> <View style={[styles.image, { backgroundColor: color }]}> <Text style={styles.imageText}>{fisrt}</Text> </View> <View style={styles.message}> <Text style={styles.name}>{name}</Text> <Text style={styles.messageText}>{message}</Text> </View> <View style={styles.info}> <Text style={styles.hour}>{date}</Text> <View style={{ flexDirection: 'row', justifyContent: 'flex-end', marginTop: 10, }}> {type && <Text style={{ marginRight: 10, backgroundColor: type === 'Work' ? '#FB4C2F' : type === 'Family' ? '#98D7E4' : '#B6CFF5', color: '#FFFFFF', fontSize: 12, height: 20, paddingHorizontal: 5, }}>{type}</Text>} <Icon name='star-border' size={22} /> </View> </View> </View> ) export default Message
export default require( `${__dirname}/../../../.firebase.json` )
import { connect } from 'react-redux'; import App from './component'; import { setUser } from './actions'; const mapDispatchToProps = dispatch => ({ onUserRegister: username => dispatch(setUser({ username })) }); const AppContainer = connect( null, mapDispatchToProps )(App); export default AppContainer;
/** * Created by LinYichen on 12/2/14. */ var inspect = require('util').inspect; var Client = require('mariasql'); // The function to input data exports.inputData = function(req, res) { var c = new Client(); console.log(req.body); c.connect({ host:'localhost', user:'ykarita', password:'ykarita_pw', db:'ykarita_db' }); c.query('INSERT INTO USA VALUES (?, ?, ?)',[req.body.state,req.body.population,req.body.electricity],function (err,result) { console.log("hi0"); if (err) throw err; console.log("hi1"); res.send("Created "+JSON.stringify(result)); console.log("hi2"); }); };
const Joi = require('joi') module.exports = { createValidation: request => { const createSchema = { title:Joi.string().required().min(2).max(50), duration:Joi.string().required(), price:Joi.number().required(), description:Joi.string().required(), location:Joi.string().required(), Eduorganization:Joi.string().required(), courseIDs :Joi.array().items(), workshopsIDs :Joi.array().items(), applicants :Joi.array().items() } return Joi.validate(request, createSchema) }, updateValidation: request => { const updateSchema = { title:Joi.string(), duration:Joi.string(), price:Joi.number(), description:Joi.string(), location:Joi.string(), Eduorganization:Joi.string(), courseIDs :Joi.array().items(), workshopsIDs :Joi.array().items(), applicants :Joi.array().items() } return Joi.validate(request, updateSchema) }, applyValidation : request => { const applySchema = { applicantId : Joi.string() } return Joi.validate(request,applySchema) } }
module.exports = { extends: ['emperor/react', 'emperor/react/style'], plugins: ['simple-import-sort', 'unused-imports'], rules: { 'simple-import-sort/imports': 'warn', 'simple-import-sort/exports': 'warn', 'unused-imports/no-unused-imports': 'error', 'import/no-extraneous-dependencies': 'off', }, parserOptions: { project: './tsconfig.json', }, env: { node: true, }, };
export const load = '@@bypass/check/list/LOAD' export const select = '@@bypass/check/list/SELECT' export const selectAll = '@@bypass/check/list/SELECT_ALL'
//TEXTURES var TEXTURE_GRASS = 0; //textureType var GRASS_TOP; var GRASS_TOP_LEFT; var GRASS_TOP_RIGHT; var GRASS_TOP_MID; var GRASS_MID; var TEXTURE_BOX = 1; var BOX_BROWN_1; var BOX_BROWN_2; var BOX_YELLOW; function initTextures(){ GRASS_TOP = PIXI.loader.resources.GRASS_TOP.texture; GRASS_TOP_LEFT = PIXI.loader.resources.GRASS_TOP_LEFT.texture; GRASS_TOP_RIGHT = PIXI.loader.resources.GRASS_TOP_RIGHT.texture; GRASS_TOP_MID = PIXI.loader.resources.GRASS_TOP_MID.texture; GRASS_MID = PIXI.loader.resources.GRASS_MID.texture; BOX_BROWN_1 = PIXI.loader.resources.BOX_BROWN_1.texture; BOX_BROWN_2 = PIXI.loader.resources.BOX_BROWN_2.texture; BOX_YELLOW = PIXI.loader.resources.BOX_YELLOW.texture; } var loader; loader = PIXI.loader .add('GRASS_TOP','assets/grass_top.png') .add('GRASS_TOP_LEFT','assets/grass_top_left.png') .add('GRASS_TOP_RIGHT','assets/grass_top_right.png') .add('GRASS_TOP_MID','assets/grass_top_mid.png') .add('GRASS_MID','assets/grass_mid.png') .add('BOX_BROWN_1','assets/box.png') .add('BOX_BROWN_2','assets/boxAlt.png') .add('BOX_YELLOW','assets/boxYellow.png') .load(function(loader, resources) { initTextures(); initGame(); animate(); });