text
stringlengths
7
3.69M
var things = [] var WorldBound = { init: function (x, y) { this.x = x || 0 this.y = y || 0 }, draw: function () { UFX.draw("t", this.x, this.y) }, } var Ticks = { init: function () { this.t = 0 }, think: function (dt) { this.t += dt }, } var Transitions = { init: function () { this.trans = null }, think: function (dt) { if (!this.trans) return this.trans.think(dt, this) if (this.trans.done) { if (this.trans.kills) this.done = true this.trans = null } }, draw: function () { if (this.trans) { this.trans.draw(this) } }, halts: function () { return this.trans && this.trans.halts }, } var Clickable = { init: function (r) { this.r = r || 0 }, hits: function (x, y) { var dx = x - this.x, dy = y - this.y return dx * dx + dy * dy < this.r * this.r }, draw: function () { if (settings.DEBUG) { UFX.draw("b o 0 0", this.r, "lw 0.03 ss red s") } }, } var Unclickable = { hits: function () { return false }, } var Collectible = { init: function () { this.collectible = true }, } var Disposible = { init: function () { this.disposible = true }, } var FreesSister = { think: function (dt) { if (this.active && !this.sister.free) { this.sister.free = true this.sister.trans = new GrowFadeHalt(this.sister) } }, } var WobbleOnActive = { init: function (omega, beta) { this.womega = omega || 2.6 this.wbeta = beta || 0.12 this.wf = 0 }, think: function (dt) { this.wf += (this.active ? 2 : -2) * dt this.wf = clip(this.wf, 0, 1) }, draw: function () { if (this.wf) { var s = Math.exp(this.wf * this.wbeta * Math.sin(this.t * this.womega)) UFX.draw("z", s, 1/s) } }, } var Rocks = { draw: function () { var A = 20 * Math.sin(this.t * 0.1) UFX.draw("r", A) }, } var FacesActive = { init: function () { this.A = 0 }, think: function (dt) { var as = things.filter(function (thing) { return thing.active }) if (!as.length) return var dx = as[0].x - this.x, dy = as[0].y - this.y var A = Math.atan2(dx, -dy), dA = zmod(A - this.A, tau) this.A += 5 * dt * dA }, draw: function () { UFX.draw("r", this.A) }, } var DrawPath = { init: function (path) { this.path = path || "b o 0 0 2" }, draw: function (menu, selected, a) { if (!menu) { selected = true a = 0 } if (a >= 1) { UFX.draw("lw 0.2", this.path, "fs #CCC ss black f s") } else if (selected) { var c0 = clip(Math.floor(192 * a), 0, 192) + 32 var c1 = clip(Math.floor(255 * (1-a)), 0, 255) var color0 = "rgb(" + c0 + "," + c0 + "," + c0 + ")" var color1 = "rgb(" + c1 + "," + c1 + "," + c1 + ")" UFX.draw("lw 0.2", this.path, "fs", color0, "ss", color1, "f s") } else { UFX.draw("lw 0.2", this.path, "alpha", a, "fs #CCC ss black f s") } }, } var DrawTcircle = { draw: function () { UFX.draw("b o 0 0 1 lw 0.3 s b o 0 0 0.5 f") }, } var DrawTtriangle = { draw: function () { UFX.draw("( m 1 0.6 l -1 0.6 l 0 -1.4 ) lw 0.3 s") UFX.draw("[ z 0.4 0.4 ( m 1 0.6 l -1 0.6 l 0 -1.4 ) ] f") }, } var DrawTsquare = { draw: function () { UFX.draw("lw 0.3 sr -1 -1 2 2 fr -0.5 -0.5 1 1") }, } var DrawStar = { draw: function () { UFX.draw("z 0.2 0.2 ( m 0 4 l 1 1 l 4 0 l 1 -1 l 0 -4 l -1 -1 l -4 0 l -1 1 ) f") }, } var DrawString = { draw: function () { if (this.active || this.trans || this.done) return if (this.sister.active || this.sister.trans || this.sister.done) return UFX.draw("[ b m", this.x, this.y, "l", this.sister.x, this.sister.y, "lw 0.1 s ]") }, } // Centerpiece of each level, also the level identifier shape function Piece(name, path, x, y, r) { this.name = name this.x = x || 0 this.y = y || 0 this.path = path || this.path this.r = r || 2 } Piece.prototype = UFX.Thing() .addcomp(WorldBound) .addcomp(Ticks) .addcomp(Transitions) .addcomp(WobbleOnActive, null, 0.05) .addcomp(DrawPath) .addcomp(Clickable, 2) // Just a normal target function Target(x, y) { this.x = x this.y = y } Target.prototype = UFX.Thing() .addcomp(WorldBound) .addcomp(Ticks) .addcomp(Transitions) .addcomp(WobbleOnActive) .addcomp(DrawTcircle) .addcomp(Clickable, 1.4) .addcomp(Disposible) function Dagger(x, y) { this.x = x this.y = y } Dagger.prototype = UFX.Thing() .addcomp(WorldBound) .addcomp(Ticks) .addcomp(Transitions) .addcomp(FacesActive) .addcomp(DrawTtriangle) .addcomp(Clickable, 1.4) .addcomp(Disposible) function Sister(x, y, sister) { this.x = x this.y = y this.sister = sister } Sister.prototype = UFX.Thing() .addcomp(DrawString) .addcomp(WorldBound) .addcomp(Ticks) .addcomp(Transitions) .addcomp(DrawTsquare) .addcomp(Clickable, 1.4) .addcomp(Disposible) .addcomp(FreesSister) // Star bits. These represent your possessions or whatever function Bit(x, y) { this.x = x this.y = y this.t = Math.random() * 1000 this.think(0) } Bit.prototype = UFX.Thing() .addcomp(WorldBound) .addcomp(Ticks) .addcomp(Transitions) .addcomp(Rocks) .addcomp(DrawStar) .addcomp(Unclickable) .addcomp(Collectible)
import React from 'react'; const Rating = (props) => { const {rating,numReviews}=props; return ( <div> <i className={(rating>=1?"fa fa-star colour":(rating>=0.5)?"fa fa-star-half-o colour":"fa fa-star-o colour")}></i> <i className={(rating>=2?"fa fa-star colour":(rating>=1.5)?"fa fa-star-half-o colour":"fa fa-star-o colour")}></i> <i className={(rating>=3?"fa fa-star colour":(rating>=2.5)?"fa fa-star-half-o colour":"fa fa-star-o colour")}></i> <i className={(rating>=4?"fa fa-star colour":(rating>=3.5)?"fa fa-star-half-o colour":"fa fa-star-o colour")}></i> <span style={{margin: '0.5em', color:"blue"}}>{numReviews} reviews</span> </div> ); } export default Rating;
import React from "react"; import CallApi from "../../../../api/api"; import Spinner from "../../../Spinner/Spinner"; class MovieVideo extends React.Component { state = { movieVideos: [], showSpinner: false, }; componentDidMount() { this.toggleSpinner(); CallApi.get(`movie/${this.props.match.params.id}/videos`, { params: { language: "ru-RU" }, }) .then((data) => this.updateMovieVideos(data.results)) .then(() => this.toggleSpinner()); } updateMovieVideos = (movieVideos) => { this.setState({ movieVideos: movieVideos, }); }; toggleSpinner = () => { this.setState((prevState) => ({ showSpinner: !prevState.showSpinner, })); }; render() { return ( <> {this.state.showSpinner ? ( <Spinner /> ) : ( <div className="container"> {this.state.movieVideos.map((el) => { return ( <div key={el.id} className="embed-responsive embed-responsive-16by9 mt-3 mb-3" > <iframe className="embed-responsive-item" title={el.key} src={`https://www.youtube.com/embed/${el.key}?rel=0`} allowFullScreen ></iframe> </div> ); })} </div> )} </> ); } } export default MovieVideo;
$(document).ready(function() { $('#filters').on('submit', filtersItem); $('#search-events').on('keyup', filtersItem); function filtersItem(e) { e.preventDefault(); const type = $('#selecttype').val(), level = $('#selectlevel').val(), month = $('#selectmonth').val(), items = $('#mytable tbody tr'), search = $('#search-events').val().toLowerCase(); const re = new RegExp(search); $(items).hide(); if (type === '0' && level === '0' && month === '0' && !search.length) { $(items).show(); } $('#mytable tbody .no-results').hide(); $(items).each(function() { let arr = []; if (type === '0') arr.push(true); else if (type !== '0' && $(this).attr('data-type') === type) arr.push(true); if (level === '0') arr.push(true); else if (level !== '0' && $(this).attr('data-level') === level) arr.push(true); if (month === '0') arr.push(true); else if (month !== '0' && ($(this).attr('data-from') === month || $(this).attr('data-to') === month)) arr.push(true); if (!search.length) arr.push(true); else if (re.test($(this).find('.event-name').text().toLowerCase())) arr.push(true); if (arr.length === 4) $(this).show(); }); if (!$('#mytable tbody tr:visible').length) { $('#mytable tbody .no-results').show(); } } });
/** * Created by dianwoba on 2015/7/31. */ 'use strict'; var Reflux = require('reflux'); var withdrawActions = require('../../actions/cashMgt/withdrawActions'); var WithdrawStore = Reflux.createStore({ citys: [], items: [], listenables: [withdrawActions], onGetCitys: function(model){ $.get("../../dummy/citys.json",function(data){ if(data.status === 1){ this.citys = this.citys.concat(data.data); this.trigger(this.citys); } }.bind(this)); } }); module.exports = WithdrawStore;
import {seq} from "src/base/Seq.js"; import {XY} from "src/sim/util/XY.js"; import {Axis} from "src/sim/util/Axis.js"; import {GeneralSet} from "src/base/GeneralSet.js" import {GeneralMap} from "src/base/GeneralMap.js" import {DetailedError} from "src/base/DetailedError.js"; import {setMembershipInOfTo, xorSetInto, makeArrayGrid} from "src/sim/util/Util.js"; import {PauliMap} from "src/sim/util/PauliMap.js"; import {indent} from "src/base/Util.js"; class ControlledPauliMaps { /** * @param {!GeneralMap.<!XYT, !PauliMap>} pauliMaps */ constructor(pauliMaps=new GeneralMap()) { /** * @type {!GeneralMap.<!XYT, !PauliMap>} * @private */ this._pauliMaps = pauliMaps; /** * An index that allows fast lookup of the controls operating on a given target. * @type {GeneralMap.<!XY, !GeneralSet.<!XYT>>} * @private */ this._targetToControls = this._regeneratedTargetToControlsMap(); } /** * @returns {!Iterator.<![!XYT, !PauliMap]>} */ entries() { return this._pauliMaps.entries(); } /** * @returns {!ControlledPauliMaps} */ clone() { return new ControlledPauliMaps(this._pauliMaps.mapValues(e => e.clone())); } /** * @param {!XY} control * @param {!XY} target */ cnot(control, target) { for (let k of this.controlsAffecting(control, target)) { this._pauliMaps.get(k).cnot(control, target); this.syncTargetToControlsFor(control, k); this.syncTargetToControlsFor(target, k); } } /** * @param {!XY} target */ hadamard(target) { for (let k of this.controlsAffecting(target)) { this._pauliMaps.get(k).hadamard(target); this.syncTargetToControlsFor(target, k); } } /** * @param {!XYT} control * @returns {!PauliMap} */ pauliMapForControl(control) { return this._pauliMaps.getOrInsert(control, () => new PauliMap()); } /** * @param {!XYT} control */ deleteControlPauliMapIfEmpty(control) { let map = this._pauliMaps.get(control); if (map !== undefined && map.operations.size === 0) { this._pauliMaps.delete(control); } } /** * @param {!XY} target */ deleteTargetIndexIfEmpty(target) { let map = this._targetToControls.get(target); if (map !== undefined && map.size === 0) { this._targetToControls.delete(target); } } /** * @param {!XYT} control * @param {!XY} target */ feedforward_x(control, target) { this._pauliMaps.getOrInsert(control, () => new PauliMap()).x(target); this.syncTargetToControlsFor(target, control); } /** * @param {!XYT} control * @param {!XY} target */ feedforward_z(control, target) { this._pauliMaps.getOrInsert(control, () => new PauliMap()).z(target); this.syncTargetToControlsFor(target, control); } /** * @param {!function(control: !XYT) : !XYT} controlFunc * @returns {!ControlledPauliMaps} */ mapControls(controlFunc) { return new ControlledPauliMaps(this._pauliMaps.mapKeys(controlFunc)); } /** * @param {!ControlledPauliMaps} other * @returns {!ControlledPauliMaps} */ union(other) { return this.clone().inline_union(other); } /** * @param {!ControlledPauliMaps} other * @returns {!ControlledPauliMaps} */ inline_union(other) { for (let [control, map] of other._pauliMaps.entries()) { this._pauliMaps.getOrInsert(control, () => new PauliMap()).inline_union(map); } return this; } /** * @returns {!GeneralMap.<!XY, !GeneralSet.<!XYT>>} * @private */ _regeneratedTargetToControlsMap() { let result = new GeneralMap(); for (let [xyt, pauliMap] of this._pauliMaps.entries()) { for (let xy of pauliMap.targets()) { result.getOrInsert(xy, () => new GeneralSet()).add(xyt); } } return result; } /** * Performs an incremental update of the target-to-control map, focused on the given pair. * @param {!XY} target * @param {!XYT} control */ syncTargetToControlsFor(target, control) { let controlsForTarget = this._targetToControls.getOrInsert(target, () => new GeneralSet()); let targetsForControl = this._pauliMaps.get(control); setMembershipInOfTo( controlsForTarget, control, targetsForControl !== undefined && targetsForControl.get(target) !== 0); this.deleteControlPauliMapIfEmpty(control); this.deleteTargetIndexIfEmpty(target); } /** * Looks up controls that operate on the given target. * @param {...!XY} xy * @returns {!Array.<!XYT>} */ controlsAffecting(...xy) { return seq(xy).flatMap(k => this._targetToControls.get(k, [])).distinct().toArray(); } /** * @param {*} other * @returns {!boolean} */ isEqualTo(other) { return other instanceof ControlledPauliMaps && this._pauliMaps.isEqualTo(other._pauliMaps); } /** * @returns {!string} */ toString() { let rows = []; for (let [k, v] of this._pauliMaps.entries()) { rows.push(`IF ${k} THEN ${v}`); } return `ControlledPauliMaps {\n${indent(rows.join('\n'))}\n}` } } export {ControlledPauliMaps}
'use strict'; var path = require('path'); var webpack = require('webpack'); var HtmlWebpackPlugin = require('html-webpack-plugin'); var ExtractTextPlugin = require('extract-text-webpack-plugin'); var ManifestPlugin = require('webpack-manifest-plugin'); var CopyWebpackPlugin = require('copy-webpack-plugin'); var InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin'); var paths = require('./paths'); var getClientEnvironment = require('./env'); var base = require('./baseConfig'); var HappyPack = require('happypack'); var ParallelUglifyPlugin = require('webpack-parallel-uglify-plugin'); process.env.NODE_ENV = 'production'; var publicPath = paths.servedPath; var publicUrl = publicPath.slice(0, -1); var env = getClientEnvironment(publicUrl); var cssFilename = 'static/css/[name].[contenthash:8].css'; process.noDeprecation = true; if (env.stringFiled['process.env'].NODE_ENV !== '"production"') { throw new Error('Production builds must have NODE_ENV=production.'); } var minify = { removeComments: true, collapseWhitespace: true, removeRedundantAttributes: true, useShortDoctype: true, removeEmptyAttributes: true, removeStyleLinkTypeAttributes: true, keepClosingSlash: true, minifyJS: true, minifyCSS: true, minifyURLs: true }; module.exports = { bail: true, devtool: 'hidden-source-map', cache: true, entry: { "vendor": ["react-router-dom", require.resolve('./polyfills')], "antd-main": [ "antd/lib/layout", "antd/lib/menu", "antd/lib/message", "antd/lib/button", "antd/lib/icon", "antd/lib/breadcrumb", "antd/lib/pagination" ], "app": [ paths.appIndexJS ], 'console': [ paths.consoleIndexJS ], 'search': [ paths.searchJS ], 'register': [ paths.registerJS ], 'resetPassword': [ paths.resetPasswordJS ] }, output: { path: paths.appBuild, filename: 'static/js/[name].[chunkhash:8].js', chunkFilename: 'static/js/[name].[chunkhash:8].chunk.js', publicPath: publicPath }, externals: base.externals, resolve: base.resolve, module: { noParse: [ /socket.io-client/ ], rules: [ { test: /\.(png|jpg|gif|jpeg)$/, exclude: /node_modules/, use: [ { loader: 'url-loader', options: { limit: 3000, name: 'static/media/[name].[hash:8].[ext]' } } ] }, { test: /\.(js|jsx)$/, include: paths.appSrc, exclude: /node_modules/, enforce: 'pre', use: ['happypack/loader?id=hpjsx'] }, { test: /\.css$/, use: ExtractTextPlugin.extract({ fallback: "style-loader", use: "css-loader?importLoader=1&sourceMap=false" }) }, { test: /\.svg$/, exclude: /node_modules/, use: [{ loader: 'file-loader', options: { name: 'static/media/[name].[hash:8].[ext]' } }] } ] }, plugins: [ new webpack.optimize.ModuleConcatenationPlugin(), new InterpolateHtmlPlugin(env.raw), new webpack.LoaderOptionsPlugin({ minimize: true, debug: false }), new HappyPack({ id: 'hpjsx', threads: 2, loaders: [ { loader: 'babel-loader', query: { cacheDirectory: true, plugins: [ ['import', [{libraryName: "antd", style: 'css'}]], ["syntax-dynamic-import"] ] } }, 'eslint-loader'] }), new ExtractTextPlugin({filename: cssFilename, allChunks: true }), new webpack.optimize.CommonsChunkPlugin({ name: 'common', chunks:['app', 'console'] }), new webpack.optimize.CommonsChunkPlugin({ name: 'antd-main', chunks:['antd-main', 'console'] }), new webpack.optimize.CommonsChunkPlugin('vendor'), new ParallelUglifyPlugin({ exclude: /node_modules/, cacheDir: path.resolve(__dirname, '.cache/'), uglifyJS: { output: { comments: false }, compress: { warnings: false } } }), new HtmlWebpackPlugin({ inject: true, filename: "app.ejs", template: paths.appHtml, chunks: ['vendor', 'common', 'app'], chunksSortMode: function (chunk1, chunk2) { var order = ['vendor','common', 'app']; var order1 = order.indexOf(chunk1.names[0]); var order2 = order.indexOf(chunk2.names[0]); return order1 - order2; }, minify: minify }), new HtmlWebpackPlugin({ inject: true, filename: 'console.ejs', template: paths.consoleHtml, chunks: ['vendor', 'common', 'antd-main', 'console'], chunksSortMode: function (chunk1, chunk2) { var order = [ 'vendor', 'common', 'antd-main', 'console']; var order1 = order.indexOf(chunk1.names[0]); var order2 = order.indexOf(chunk2.names[0]); return order1 - order2; }, minify: minify }), new HtmlWebpackPlugin({ inject: true, filename: 'search.ejs', template: paths.searchHtml, chunks: ['vendor', 'search'], chunksSortMode: function (chunk1, chunk2) { var order = ['vendor', 'search']; var order1 = order.indexOf(chunk1.names[0]); var order2 = order.indexOf(chunk2.names[0]); return order1 - order2; }, minify: minify }), new HtmlWebpackPlugin({ inject: true, filename: 'register.ejs', template: paths.registerHtml, chunks: ['vendor', 'register'], minify: minify }), new HtmlWebpackPlugin({ inject: true, filename: 'resetPassword.ejs', template: paths.registerHtml, chunks: ['vendor', 'resetPassword'], minify: minify }), new CopyWebpackPlugin(base.copyWebpackPlugin), new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': '"production"' } }), new ManifestPlugin({ fileName: 'asset-manifest.json' }) ], node: base.node };
const PdfDoc = require('pdfkit'); const path = require('path'); const fs = require('fs'); const { calculateEqTotal, calculateEqOfferedTotal, isOutsource, isBudgetOutdated } = require('../shared'); const { addHeader, getLongDate, toCurrency, getClientAddress } = require('./addHeader'); const sizeOf = require('image-size'); module.exports = function createPdfOrder(res, budget, dbx, user) { const doc = new PdfDoc({ info: { Title: `OFFERTA NUOVA ATTREZZATURA - ${budget.client.name || ''}`, Author: 'CGT EDILIZIA' } }); const db = isBudgetOutdated('equipmentbudgets', budget, dbx) ? dbx.getVersion(budget.created) : dbx; const retailer = db.retailers.find(r => r.id === user.organization) || {}; doc.pipe(res); const docWidth = 612; // doc.info = { // Title: '', // Author: '', // Subject: '', // CreationDate: '', // }; const marginLeft = 30; const bodyLineHeight = 14; const spettMarginLeft = 300; let pos = addHeader(user, doc, db); /** SPETT.LE */ doc.y = 110; doc .fillColor('black') .fontSize(10) .text('Spett.le', spettMarginLeft); doc.y += 5; doc.text(budget.client.name || '', spettMarginLeft) .text(getClientAddress(budget.client), spettMarginLeft); pos = 154; /** Date */ const date = new Date(budget.modified || budget.created); doc .text(`${getLongDate(date)}`, marginLeft, (pos += 50)) .text(`Alla Cortese Attenzione Sig. ${budget.client.pa}`, marginLeft, (pos += 30)); /** Subject */ doc .font('Helvetica-Bold') .text('Oggetto: OFFERTA NUOVA ATTREZZATURA', marginLeft, (pos += 30)) .font('Helvetica') .text('A seguito di Vs. gradita richiesta, Vi sottoponiamo nostra migliore offerta commerciale come di seguito descritto:', marginLeft, (pos += 30)) .font('Helvetica-Bold'); pos += 20; doc.font('Helvetica') .fontSize(6) .text('Foto puramente a scopo illustrativo', marginLeft, pos + 22) .fontSize(10); budget.equipment.forEach((eqId, index) => { const eq = db.equipements.find(e => e.id === eqId) || {}; pos += index === 0 ? 30 : 60; if (doc.y > 630) { doc.addPage(); pos = 40; } const imagePath = path.resolve(`${__dirname}/..${eq.src}`); if (fs.existsSync(imagePath)) { const dimensions = sizeOf(imagePath); const maxHeight = 50, maxWidth = 90; const ratio = maxWidth / maxHeight; if (ratio < (dimensions.width / dimensions.height)) { doc.image(imagePath, marginLeft, (pos), { width: maxWidth }); } else { doc.image(imagePath, marginLeft, (pos), { height: maxHeight }); } } doc .font('Helvetica-Bold') .text(`COSTRUTTORE: `, marginLeft + 100, pos) .text(`CODICE:`, marginLeft + 100, pos + 15) .text(`NOME:`, marginLeft + 100, pos + 30) .font('Helvetica') .text(`${eq.constructorId}`, marginLeft + 180, pos) .text(`${eq.code}`, marginLeft + 180, pos + 15) .text(`${eq.name}`, marginLeft + 180, pos + 30); }); pos += 70; if (doc.y > 500) { doc.addPage(); pos = 40; } doc.fontSize(9); const summary = { payment: 'Pagamento', availability: 'Disponibilità', validity: 'Validità' }; Object.keys(summary) .filter(key => budget.summary[key]) .forEach(function (key, index) { pos = index === 0 ? pos : doc.y + 4; doc .font('Helvetica') .text(`${summary[key]}:`, marginLeft, pos) .text(budget.summary[key] + (key === 'validity' ? 'gg' : ''), marginLeft + 100, pos); }); if (budget.client.showPriceReal) { pos += 20; doc .rect(marginLeft, pos, docWidth - (marginLeft * 2), 24) .stroke('black') .font('Helvetica-Bold') .text('PREZZO DI LISTINO', marginLeft + 20, (pos += 8)) .text(`${toCurrency(calculateEqTotal(budget, db))} + IVA`, marginLeft + 250, pos, { align: 'right', width: 200 }); } pos += 20; doc .rect(marginLeft, pos, docWidth - (marginLeft * 2), 24) .stroke('black') .font('Helvetica-Bold') .text('PREZZO NETTO A VOI RISERVATO', marginLeft + 20, (pos += 8)) .text(`${toCurrency(calculateEqOfferedTotal(budget, db))} + IVA`, marginLeft + 250, pos, { align: 'right', width: 200 }); if (budget.summary.notes) { pos += 40; doc .fontSize(9) .font('Helvetica') .text(`Note:`, marginLeft, pos) .text(budget.summary.notes.replace(/\t/g, ' '), marginLeft + 100, pos); pos = doc.y; } pos += 20; doc.text('Restiamo a disposizione per ogni chiarimento e con l’occasione Vi inviamo i ns più Cordiali Saluti.', marginLeft, (pos += 20)); doc.text(`${user.name} ${user.surname || ''}`, 200, (pos += 30), { align: 'center' }); doc.text(`${user.email} - ${user.tel}`, 200, (pos += 13), { align: 'center' }); if (user.type == 1) doc.font('Helvetica-Bold').text('CGT Edilizia Spa', 200, (pos += 13), { align: 'center' }); if (user.type == 2) doc.font('Helvetica-Bold').text('Compagnia Generale Trattori S.p.A.', 200, (pos += 13), { align: 'center' }); if (isOutsource(user.type)) doc.font('Helvetica-Bold').text(retailer.name || '', 200, (pos += 13), { align: 'center' }); doc.end(); };
'use strict'; var RM = require('./lib/rm.js'); var rm = new RM(); rm.init();
/// <reference types="Cypress" /> describe('Head Banner', () => { it('Capture the head banner', () => { cy.visit('http://automationpractice.com/index.php') cy.get('#header > div.banner > div > div > a > img').screenshot('headBanner_1') }) it('Verify redirection of head banner', () => { cy.visit('http://automationpractice.com/index.php') cy.get('#header > div.banner > div > div > a > img').click() cy.wait(5) cy.url().should('include', '/index.php') cy.screenshot('headBanner_2') }) })
import React, { Component, View, TouchableOpacity, Text, } from 'react-native'; import moment from 'moment'; import styles from './styles'; import Icon from 'react-native-vector-icons/FontAwesome'; import PostWebView from './PostWebView'; import PostComments from './PostComments'; export default class Post extends Component { handlePressComments = () => this.props.commentCount && this.props.navigator.push({ component: PostComments, passProps: this.props, }); handlePressLink = () => this.props.navigator.push({ component: PostWebView, passProps: this.props, }); hasComments() { return this.props.commentCount > 0; } render() { return ( <View style={styles.postStyle}> <TouchableOpacity> <View style={{width:40,marginRight:10,alignItems:'center',}}> <Icon name="chevron-up" color={'#1B0732'} size={20} /> <Text>{this.props.upvotes}</Text> </View> </TouchableOpacity> <View style={[styles.container]}> <TouchableOpacity onPress={this.handlePressLink}> <Text style={{color:'#1B0732'}}>{this.props.title}</Text> <View> <Text style={{fontSize:10}}>by {this.props.author} {moment(this.props.createdAt).fromNow()}</Text> </View> </TouchableOpacity> </View> <TouchableOpacity onPress={this.handlePressComments}> <View style={{ width: 40, marginLeft:10, alignItems:'center' }}> <Icon name={this.hasComments() ? 'commenting' : 'comment-o'} color={this.hasComments() ? '#1B0732' : '#cccccc'} size={20} /> {this.hasComments() ? ( <Text>{this.props.commentCount}</Text> ) : false} </View> </TouchableOpacity> </View> ); } }
/** * */ goog.provide('SB.Input'); goog.require('SB.Service'); goog.require('SB.Mouse'); goog.require('SB.Keyboard'); SB.Input = function() { // N.B.: freak out if somebody tries to make 2 // throw (...) this.mouse = new SB.Mouse(); this.keyboard = new SB.Keyboard(); SB.Input.instance = this; } goog.inherits(SB.Input, SB.Service); SB.Input.instance = null;
document.addEventListener('DOMContentLoaded', (pageLoadEvent) => { let allData const addBtn = document.querySelector('#new-toy-btn') const submitBtn = document.querySelector('.submit[name=submit]') const likeBtn = document.querySelector('.like-btn') const toyForm = document.querySelector('.container') const toyCollectionDiv = document.querySelector('#toy-collection') let addToy = false function renderSingleToy(toy) { addToy = !addToy toyForm.style.display = 'none' toyCollectionDiv.insertAdjacentHTML("beforeend",` <div class="card"> <h2>${toy.name}</h2> <img src=${toy.image} class="toy-avatar" /> <p><span data-toyid=${toy.id}>${toy.likes}</span> Likes </p> <button class="like-btn" data-toyid=${toy.id}>Like <3</button> </div> `) // Ends insert Adjacent HTML } function renderAllData(arr) { toyCollectionDiv.innerHTML="" arr.forEach( function(toy) { renderSingleToy(toy) }) // Ends forEach loop in renderData function } // Ends renderData() Function // YOUR CODE HERE document.addEventListener('click', function(event) { switch (true) { case(event.target === addBtn): // hide & seek with the form addToy = !addToy if (addToy) { toyForm.style.display = 'block' } else { toyForm.style.display = 'none' } break case(event.target === submitBtn): event.preventDefault() let nameFieldValue = document.querySelector('.input-text[name=name]').value let imageFieldValue = document.querySelector('.input-text[name=image]').value let data = {name: `${nameFieldValue}`, image: `${imageFieldValue}`, likes: 0}// ends data variable document.querySelector('.input-text[name=name]').value = "" document.querySelector('.input-text[name=image]').value = "" fetch("http://localhost:3000/toys", { headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, method: "POST", body: JSON.stringify(data) })//Ends FETCH POST .then( function(response) { return response.json() }) //ends first THEN statement .then ( function (response) { if (!response.errors) { allData.push(response) renderSingleToy(response) } else { return response.errors } }) // ends Second THEN statement .catch( function(err) { alert(err) }) // ends Catch break case(event.target.className === "like-btn"): event.preventDefault() let toyId = event.target.dataset.toyid let startingLikes = document.querySelector(`span[data-toyid='${toyId}']`).innerText let likeData = {likes: `${++startingLikes}`}// ends data variable fetch(`http://localhost:3000/toys/${toyId}`, { headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, method: "PATCH", body: JSON.stringify(likeData) })//Ends FETCH POST .then( function(response) { return response.json() }) //ends first THEN statement .then ( function (response) { if (!response.errors) { document.querySelector(`span[data-toyid='${toyId}']`).innerText++ } else { return response.errors } }) // ends Second THEN statement .catch( function(err) { alert(err) }) // ends Catch } //Ends SWITCH statement }) // Ends Event Listener fetch("http://localhost:3000/toys") .then( function(response) { return response.json() })// Ends the first THEN statement from original FETCH Statement .then( function(response) { console.dir(response) allData = response renderAllData(response) })// Ends the second THEN statement from original FETCH Statement }); // ends the DOM Content Loaded efvent
export { get as getImage } from './get';
import React from 'react'; import ShortDescription from './ShortDescription'; class Tag extends React.Component{ constructor(props) { super(props); this.state = { shortDescriptionVisibleOnPage: false }; this.showShortDescription = this.showShortDescription.bind(this); } showShortDescription() { this.setState({shortDescriptionVisibleOnPage: true}); } render(){ let shortDescriptionAreaContent = null; if(this.state.shortDescriptionVisibleOnPage){ shortDescriptionAreaContent = <ShortDescription/>; } else { shortDescriptionAreaContent = <p onMouseEnter={this.showShortDescription}>Web Developer</p>; } return ( <div> {shortDescriptionAreaContent} </div> ); } } export default Tag;
//generate seeds: function randomBinary(length, pblack){ var out = []; while(out.length<length){ if(Math.random()<pblack){ out.push(1); } else { out.push(0); } } return out; } var seenBefore = {} function freshRandomBinary(length, pblack){ //fresh means: not in seenBefore (add holdout test set to seenBefore before starting...) while(true){ var candidate = randomBinary(length,pblack); if(seenBefore[candidate.toString()]==null){ seenBefore[candidate.toString()]=true; return candidate; } } } function isFresh(arr){//fresh means: not in seenBefore. seenBefore is exposed, could be checked directly, just keeping similar tools in one place. if(seenBefore[arr.toString()]==null)return true; else return false; } function addToSeen(arr){ seenBefore[arr.toString()]=true; } //Transformation library: transformations need only return a single successor, randomly selected if many are possible with this transformation //These are (almost) the hahn03 transformations: delete is single not runs, and phasic shift wraps, does not fill-by-estimation function insertTransform(arr){ var toInsert; if(Math.random()<.5)toInsert=1; else toInsert = 0; var index = Math.floor(Math.random()*(arr.length+1)); var newarr = []; for(var i=0;i<=arr.length;i++){ if(i==index)newarr.push(toInsert); if(i<arr.length)newarr.push(arr[i]); } return newarr; } function deleteTransform(arr){ var toDelete = Math.floor(Math.random()*arr.length); var newarr = []; for(var i=0;i<arr.length;i++){ if(i!=toDelete)newarr.push(arr[i]); } return newarr; } function reverseTransform(arr){ //there is a javascript array.reverse(), but it manipulates the passed array, this creates a reversed clone. var newarr = []; for(var i = arr.length-1;i>=0;i--){ newarr.push(arr[i]); } return newarr; } function mirrorTransform(arr){ var newarr = []; for(var i=0;i<arr.length;i++){ newarr.push((arr[i]+1)%2) } return newarr; } function phasicTransform(arr){ var newarr = arr.slice(); //clones arr if(Math.random()<.5){ var temp = newarr[0]; newarr.splice(0,1); newarr.push(temp); } else{ var temp = newarr[newarr.length-1]; newarr.splice(newarr.length-1,1);//?? newarr.unshift(temp); } return newarr; } //Using transforms: code for applying transforms, and setting transform probabilities. var alltransforms = [insertTransform,deleteTransform,reverseTransform,mirrorTransform,phasicTransform]; var transformnames =["insert","delete","reverse","mirror","phasic"]; //saved to data object: make sure it matches 'alltransforms'... var transformprobs = []; //code as cumulative probability for easy pick-via-spinner, ie three equal options should be [.333,.666,1] var luckytransform = Math.floor(Math.random()*alltransforms.length); //Indexs into alltransforms: lucky because common, is target in critical test var foiltransform = luckytransform; while(foiltransform==luckytransform)foiltransform=Math.floor(Math.random()*alltransforms.length); //this will be competition transform in criticaltest. function initUniformTransforms(){ transformprobs[0]=1/alltransforms.length; for(var i=1;i<alltransforms.length;i++){ transformprobs[i]=transformprobs[i-1]+(1/alltransforms.length); } } function initSkewedTransforms(){ //params: how much spike do you want? var maxp = .7; var leftovers = 1-maxp; var peach = leftovers/(alltransforms.length-1) var cumulativeP = 0; for(var i=0;i<alltransforms.length;i++){ if(i==luckytransform)cumulativeP=cumulativeP+maxp; else cumulativeP=cumulativeP+peach; transformprobs[i]=cumulativeP; } transformprobs[transformprobs.length-1]=1; //probably unneccessary, but precision errors do tend to make the last entry .999999998 } function applyTransforms(target, hm_transforms){//Returns an object with two parts: the result array ('features') and the transformations used to get it ('transnames') var ops_done = 0; var transPath={}; //intermediate steps in the transform saved, may not be repeated, to avoid backtracking ie double mirror or delete-reinsert transPath[target.toString()]=true; var usedTransNames = []; while(ops_done<hm_transforms){ var spinner = Math.random(); var candidate; for(var i=0;i<transformprobs.length;i++){ if(spinner<transformprobs[i]){ candidate = alltransforms[i](target); // console.log("transform:"+i+alltransforms[i].toString().substring(0,15));//DIAG if(transPath[candidate.toString()]==null){ transPath[candidate.toString()]=true; ops_done++; usedTransNames.push(alltransforms[i].toString().substring(9,15));//haha hack, requires a function naming convention for transforms (id first up, must be 6 characters or more(but the more gets truncated...) target = candidate; } break; } } }//while opsdone<hm_transforms return {features:target,transnames:usedTransNames} }//applytransforms //TEST var test = [1,0,0] var bob = ""; //for(var i=0;i<20;i++){ // bob=bob+phasicTransform(test)+"\n"; //} //alert(applyTransforms(test,1));//diag //alert(bob);
const assert = require('assert'); const { promisify } = require('util'); const { order } = require('../test/helpers'); const glob = promisify(require('glob')); const fast = require('fast-glob'); const tiny = require('../'); let prev; module.exports = async function (str, opts) { let fn, tmp; for (fn of [glob, fast, tiny]) { tmp = await fn(str, opts).then(order); prev && assert.deepEqual(tmp, prev); prev = tmp; } }
exports = module.exports = require('./lib/require-middleware');
import React, { useEffect } from "react"; import Draggable from "react-draggable"; import "./Terminal.css"; const Terminal = ({ setExerciseTracker, setTerminalDisplay, onStart, terminalDisplay, }) => { const terminalDataArray = [ "Loading packages from RANDOM DATA://JOA/WEBDEV", "Downloading [05 / 20]...", "Downloading [10 / 20]...", "Downloading [15 / 20]...", "Downloading [19 / 20]...", "Downloading [20 / 20]...", "Finished Downloading packages", "Compiling...", "Compiled succesfully!", "Launching Exercise Tracker...", ]; useEffect(() => { setTimeout(() => { setExerciseTracker(true); setTerminalDisplay(false); }, 5500); }, [setTerminalDisplay, setExerciseTracker]); return ( <> {terminalDisplay ? ( <Draggable handle="#handle" onMouseDown={(e) => onStart(e)}> <div className="terminal"> <header className="terminal-header" id="handle"> <p className="header-p">MINGW64:/c/Users/Guest</p> <div className="flex"> <div className="close-terminal" onClick={() => setTerminalDisplay(false)} > X </div> </div> </header> <div className="input-field"> <p>Terminal [Version 10.16.12387.123]</p> <p className="quest-p"> guest@DESKTOP-WEBDEV6 MINGW64 ~ </p> <br></br> {terminalDataArray.map((data, index) => { return ( <p key={index}className={`delay-${index} loader`}> {data} </p> ); })} </div> </div> </Draggable> ) : null} </> ); }; export default Terminal;
import React from "react"; import { connect } from "react-redux"; import { Link } from "react-router-dom"; import { productAddedToBag, productAllRemovedFromBag, productRemovedFromBag, } from "../../actions"; import BagItem from "../bag-item"; import ContainedButton from "../contained-button"; import { withModnikkyService } from "../hoc"; import "./bag.css"; const Bag = ({ products, totalPrice, onDelete, totalItems, onDecrease, onIncrease, }) => { const button_text_checkout = "PROCEED TO CHECKOUT"; return ( <section className="bag"> <div className="bag-header"> BAG <span>{totalItems} items</span>{" "} </div> {products.map((product, idx) => { return ( <BagItem onDelete={() => onDelete(product.id)} onDecrease={() => onDecrease(product.id)} onIncrease={() => onIncrease(product.id)} product={product} key={product.id} /> ); })} <div className="payment"> {" "} <div className="bag-total">Total USD ${totalPrice}</div> <Link to="/payment"> <ContainedButton button_text={button_text_checkout} /> </Link> </div> </section> ); }; const mapStateToProps = ({ bagItems, orderTotal, orderTotalPrice }) => { return { products: bagItems, totalItems: orderTotal, totalPrice: orderTotalPrice, }; }; const mapDispatchToProps = { onDecrease: productRemovedFromBag, onDelete: productAllRemovedFromBag, onIncrease: productAddedToBag, }; export default withModnikkyService()( connect(mapStateToProps, mapDispatchToProps)(Bag) );
import config from './config'; let ContactAPI = (object) => { let url = config.API_URL + '/contact'; return fetch(url, { method: 'POST', headers: { "Content-Type": "application/json", }, body: JSON.stringify(object) }) .then((res) => { return res.json(); }) .catch((error) => { console.log('API ContactAPI.js: ', error); }); } export default ContactAPI;
$(function() { console.log('Loaded!'); Pace.on('done', function() { $('.site-border').addClass('show'); }); $('.blog-tease').matchHeight(); });
/** * Created with IntelliJ IDEA. * User: EricLiu * Date: 10/03/14 * Time: 9:57 AM * To change this template use File | Settings | File Templates. */ // /scripts/app/UserApp.js Ext.Loader.setConfig({ enabled: true, paths: { 'Ext.ux': jsFolder + '/ux' } }); Ext.require([ 'Ext.grid.*', 'Ext.data.*', 'Ext.util.*', 'Ext.toolbar.Paging', 'Ext.ModelManager', 'Ext.tip.QuickTipManager', 'Ext.ux.form.SearchField' ]); Ext.Ajax.on('requestexception', function (conn, response, options) { // if (response.status === 403) { // window.location = 'login'; // } console.log(response); Ext.Msg.alert('Error - ' + response.status, response.responseText); }); Ext.application({ name: 'App', appFolder: jsFolder + '/app', controllers: [ 'Users' ], launch: function () { Ext.tip.QuickTipManager.init(); Ext.create('Ext.container.Viewport', { // layout: 'fit', items: [ {xtype: 'userlist'} ] }); } });
import React, {Fragment} from 'react' import {connect} from 'react-redux' import {compose, lifecycle, withHandlers, onlyUpdateForKeys, withPropsOnChange} from 'recompose' import Typography from '@material-ui/core/Typography' // local libs import { withStylesProps, getRouterContext, immutableProvedGet as ig, plainProvedGet as g, PropTypes, setPropTypes, getPageRequestParams, doesItHaveToBeReloaded, } from 'src/App/helpers' import {routerContextModel} from 'src/App/models' import {model} from 'src/App/AllNiches/models' import routerGetters from 'src/App/routerGetters' import PageTextHelmet from 'src/generic/PageTextHelmet' import actions from 'src/App/AllNiches/actions' import sectionPortal from 'src/App/MainHeader/Navigation/sectionPortal' import orientationPortal from 'src/App/MainHeader/Niche/orientationPortal' import loadingWrapper from 'src/generic/loadingWrapper' import ListWithLabels from 'src/generic/ListWithLabels' import {PageWrapper} from 'src/App/AllNiches/assets' import {muiStyles} from 'src/App/AllNiches/assets/muiStyles' const AllNiches = props => <Fragment> <PageTextHelmet htmlLang={g(props, 'htmlLang')} pageText={ig(props.data, 'pageText')}/> <PageWrapper> <Typography variant="h4" paragraph> {g(props, 'i18nAllNichesHeader')} </Typography> <ListWithLabels list={ig(props.data, 'nichesList')} linkBuilder={g(props, 'listsNicheLinkBuilder')} /> </PageWrapper> </Fragment>, loadPageFlow = ({data, loadPage, routerContext, match}) => { const pageRequestParams = getPageRequestParams(routerContext, match) if (doesItHaveToBeReloaded(data, pageRequestParams)) loadPage(pageRequestParams) } export default compose( orientationPortal, sectionPortal, connect( state => ({ cb: ig(state, 'app', 'ui', 'currentBreakpoint'), data: ig(state, 'app', 'allNiches'), htmlLang: ig(state, 'app', 'locale', 'i18n', 'htmlLangAttribute'), i18nAllNichesHeader: ig(state, 'app', 'locale', 'i18n', 'headers', 'allNiches'), routerContext: getRouterContext(state), }), { loadPageRequest: g(actions, 'loadPageRequest'), } ), onlyUpdateForKeys(['data', 'cb']), withHandlers({ loadPage: props => pageRequestParams => props.loadPageRequest({pageRequestParams}), listsNicheLinkBuilder: props => child => routerGetters.niche.link(g(props, 'routerContext'), child, null), }), lifecycle({ componentDidMount() { loadPageFlow(this.props) }, componentWillReceiveProps(nextProps) { loadPageFlow(nextProps) }, }), withStylesProps(muiStyles), withPropsOnChange([], props => ({ classedBounds: Object.freeze({ listComponent: Object.freeze({root: g(props, 'classes', 'listComponentRoot')}), listItem: Object.freeze({gutters: g(props, 'classes', 'itemGutters')}), listItemText: Object.freeze({ root: g(props, 'classes', 'listItemTextRoot'), primary: g(props, 'classes', 'primaryTypography'), secondary: g(props, 'classes', 'secondaryTypography'), }), }), })), setPropTypes(process.env.NODE_ENV === 'production' ? null : { classes: PropTypes.exact({ listComponentRoot: PropTypes.string, itemGutters: PropTypes.string, listItemTextRoot: PropTypes.string, primaryTypography: PropTypes.string, secondaryTypography: PropTypes.string, }), classedBounds: PropTypes.exact({ listComponent: PropTypes.object, listItem: PropTypes.object, listItemText: PropTypes.object, }), cb: PropTypes.string, data: model, htmlLang: PropTypes.string, i18nAllNichesHeader: PropTypes.string, routerContext: routerContextModel, loadPageRequest: PropTypes.func, loadPage: PropTypes.func, listsNicheLinkBuilder: PropTypes.func, }), loadingWrapper({ isAllNiches: true, }) )(AllNiches)
/* eslint-disable camelcase */ export const server_url = 'http://192.168.100.90:8002/' export const ws_server_url = 'ws://192.168.100.90:8002/' // export const server_url = 'https://ecommero.ninjascode.com/' // export const ws_server_url = 'wss://ecommero.ninjascode.com/' export const cloudinary_upload_url = 'https://api.cloudinary.com/v1_1/ecommero/image/upload' export const cloudinary_sub_categories = 'd11htdsp' export const cloudinary_products = 'cb9rpz8r'
var faker = require('faker'); class User{ constructor(){ this._id=faker.random.uuid(); this.firstname=faker.name.firstName(); this.lastname=faker.name.lastName(); this.phone=faker.phone.phoneNumber(); this.email=faker.internet.email(); this.password=faker.internet.password(); } } module.exports = User
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _prosemirrorModel = require('prosemirror-model'); var _EditorMarks = require('./EditorMarks'); var _EditorMarks2 = _interopRequireDefault(_EditorMarks); var _EditorNodes = require('./EditorNodes'); var _EditorNodes2 = _interopRequireDefault(_EditorNodes); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var EditorSchema = new _prosemirrorModel.Schema({ nodes: _EditorNodes2.default, marks: _EditorMarks2.default }); exports.default = EditorSchema;
import { LIGHT, DARK } from "./types" import {themes} from '../../Context/ThemeContext' export function lightTheme(){ return function(dispatch, getState, extraArguments){ // Asynchronous code can go here dispatch({type: LIGHT, payload: themes.light}) } } export function darkTheme(){ return function(dispatch, getState, extraArguments){ dispatch({type: DARK, payload: themes.dark}) } }
import React from 'react'; import { Title, TextBlock, InvasivePotential, Resources, Resource, Summary, SexualReproduction, AsexualReproduction, EcologicalNiche, PopulationDensity, EnvironmentImpact, ManagementMethod, ManagementApplication, OriginalArea, SecondaryArea, Introduction, Breeding, CaseImage, } from '../components'; import image from '../../../assets/caseDetails/rak-mramorovany.png'; const RakMramorovany = (props) => ( <div> <Title name="Rak mramorovaný" nameSynonyms="" latinName="Procambarus virginalis" latinNameSynonyms="Procambarus fallax f. virginalis" /> <Summary> <OriginalArea text="neznámý, rak pravděpodobně pochází ze Severní Ameriky, ale k vzniku druhu jako takového mohlo dojít až v akváriích v Německu. Rodičovským druhem byl pravděpodobně rak klamavý." /> <SecondaryArea text="Ojediněle na různých místech v Evropě včetně ČR, místy tvoří početné populace (např. na Slovensku)." /> <Introduction text="Vypouštěn pravděpodobně záměrně akvaristy" /> <Breeding text="Velice populární akvarijní druh" /> </Summary> <CaseImage source={image} /> <TextBlock> <p> V akváriích dorůstá 80 až 100 mm v délce těla, jedinci v přírodě jsou větší (přibližně 120 mm). Krunýř je hladký, po stranách hlavy je jeden pár trnů. Typické je nepravidelné mramorování hlavohrudi i zadečku (béžové, hnědé až hnědočervené skvrny). Vzorec mramorování je pro každého jedince unikátní. Za očima se nachází jeden pár postorbitálních lišt. Po délce těla se přes hlavohruď a zadeček táhne na každém boku nepravidelný černý pruh doplněný na zadečku ještě jedním méně zřetelným. Klepeta jsou relativně krátká a úzká, dosahují přibližně poloviny délky hlavohrudi. Areola (prostor mezi žábrosrdečními švy) je poměrně široká, což raka mramorovaného odlišuje od příbuzného raka červeného (<i>P. clarkii</i>) a raka floridského ( <i>P. alleni</i>). </p> <h5>Ekologie a způsob šíření</h5> <p> Jedná se o adaptabilní druh, který je částečně tolerantní i k salinitě vody. Dožívá se 3 až 5 let věku. Osídluje střední a větší toky, případně i nádrže, rychlému proudění vody se ale vyhýbá. Pokud jsou samice z nějakého důvodu izolované od samců, mohou se začít množit partenogeneticky (ráčata se líhnou z neoplozených vajec). V jedné snůšce může být i více než 500 vajec. Jedná se o raka s neobvyklou denní aktivitou. Nejedná se o příliš hrabavý druh, hloubí si jen mělké nory. Stejně jako ostatní raci, je i rak pruhovaný všežravcem. Vzhledem k drobnějším klepetům není tak zdatným lovcem jako druhy s klepety většími. Je přenašečem infekčního račího moru a může se sympatricky vyskytovat na jedné lokalitě s dalšími invazními raky. </p> <p> Poprvé uváděný v 90. letech 20. století v Německu. Zdejší akvaristi jej popsali díky zřetelnému mramorování jako Marmorkrebs (angl. marbled crayfish). Je schopen osídlit ve stojaté i tekoucí vody, příliš velké proudění mu nevyhovuje. Dožívá se přibližně tří let věku. Má velice rychlou generační periodu a dospívá již ve věku čtyř až pěti měsíců a ve velikosti 3,5 až 4 cm délky těla. Jedná se o druh množící se výhradně partenogeneticky, kdy se z neoplozených vajec líhnou klony samice. To je u raků zcela unikátní strategie. Na založení nové populace tedy teoreticky stačí jedna samice. Samci u tohoto druhu nebyli nikdy nalezeni. V jedné snůšce může být více než 700 vajec. Na prudký pokles teploty reaguje svlečením krunýře. Ač je to rak s v poměru k tělu drobnými klepety, je vnitrodruhově značně agresivní. Je přenašečem infekčního račího moru. </p> </TextBlock> <InvasivePotential> <SexualReproduction score={0} /> <AsexualReproduction score={3} /> <EcologicalNiche score={3} /> <PopulationDensity score={3} /> <EnvironmentImpact score={2} /> <ManagementMethod text="odchyt" /> <ManagementApplication text="řídká, lokálně" /> </InvasivePotential> <Resources> <Resource> Hossain, M. S., Patoka, J., Kouba, A., & Buřič, M. (2018). Clonal crayfish as biological model: a review on marbled crayfish. Biologia, 73(9), 841-855. </Resource> <Resource> Kouba, A., Petrusek, A., & Kozák, P. (2014). Continental-wide distribution of crayfish species in Europe: update and maps. Knowledge and Management of Aquatic Ecosystems, 413, 05. </Resource> <Resource> Patoka, J., Buřič, M., Kolář, V., Bláha, M., Petrtýl, M., Franta, P., ... & Kouba, A. (2016). Predictions of marbled crayfish establishment in conurbations fulfilled: evidences from the Czech Republic, 71, 1380-1385. </Resource> <Resource> Patoka, J., Kalous, L., & Kopecký, O. (2014). Risk assessment of the crayfish pet trade based on data from the Czech Republic. Biological Invasions, 16(12), 2489-2494. </Resource> <Resource> Scholtz, G., Braband, A., Tolley, L., Reimann, A., Mittmann, B., Lukhaup, C., ... & Vogt, G. (2003). Ecology: Parthenogenesis in an outsider crayfish. Nature, 421(6925), 806. </Resource> </Resources> </div> ); export default RakMramorovany;
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g,""); } String.prototype.ltrim = function() { return this.replace(/^\s+/,""); } String.prototype.rtrim = function() { return this.replace(/\s+$/,""); } $(document).ready(function() { bg_store = {} var pageTracker = _gat._getTracker("UA-6961171-1"); var conversions = { 'adwords': function(){ var image = new Image(1,1); image.src = "http://www.googleadservices.com/pagead/conversion/1070629377/?value=3.5&amp;label=sGrlCNeHjAEQgYTC_gM&amp;guid=ON&amp;script=0"; return; }, '7search': function(){ var image = new Image(1,1); image.src = "http://conversion.7search.com/conversion/v1/?advid=155680&urlid=&type=purchase&value=1&noscript=1"; return; } } $.localScroll(); $('#hide_all').live('click', function() { $(this).text('Show All Features'); $('.hide').each(function() { $(this).fadeOut(1500); }); $(this).attr('id', 'show_all'); }); $('#show_all').live('click', function() { $(this).text('Hide All Features'); $('.hide').each(function() { $(this).fadeIn(1500); }); $(this).attr('id', 'hide_all'); }); $('[class=see_more] a').click(function() { $(this).fadeOut(500); $('.hidden').each(function() { $(this).fadeIn(1500); }); }); $('[class=visit]').each(function() { var url = $(this).attr('href'); var name = $(this).attr('name'); var session = $.cookie('sessionid'); $(this).attr('href', url+'?note='+name+'&sid='+session); $(this).click(function() { pageTracker._trackPageview(url); conversions['adwords'](); conversions['7search'](); }); }); $('#errors').fadeIn(1500); $('#success').fadeIn(1500); read_more = function(link) { $('.dotdots').fadeOut(400, function() { $(this).remove(); }); $('.read').fadeOut(400, function() { $(this).remove(); $('.more').fadeIn(500, function() { $(this).show(); }); }); } /* Add Tools to each Comment */ $('.comment .meta').each(function() { var comment_id = $(this).parent().attr('id').split('-')[1]; $(this).html($(this).html()+'\ <span class="tools">\ <a href="/comment/helpful/'+comment_id+'.html">This review was helpful</a> or\ <a href="/comment/report/'+comment_id+'.html">Report abuse</a>\ </span>\ <div class="clear"></div>'); }); /* Hover Effect for tools on comments. Brings up "I liked this" links */ $('.tools a').livequery(function() { $(this).ajaxify({ method: 'POST', onComplete: function(opt) { par.html('<strong>Thanks!</strong>'); par.fadeOut(5000, function() { $(this).remove(); }); if ($(this).attr('link').match('report')) { var grand = $(par).parent().parent() grand.fadeOut(1500, function() { $(this).remove(); }); } } }); }); $('.comment').hover( function(){ $(this).find(".tools").show() }, function(){ $(this).find(".tools").hide() }); /* Set default items for star ratings (comment error) */ var types = ['features', 'support', 'uptime'] for (key in types) { var name = 'id_rating_' + types[key]; var val_name = name+'_val' var curvalue = $('#'+val_name).val() if (curvalue < 0) { curvalue = 0; } $('#'+name).rating(val_name, {maxvalue: 5, curvalue: curvalue}); } });
import { SET_MEOWS, LOADING_DATA, LIKE_MEOW, UNLIKE_MEOW, DELETE_MEOW, SET_ERRORS, POST_MEOW, CLEAR_ERRORS, LOADING_UI, SET_MEOW, STOP_LOADING_UI, SUBMIT_COMMENT } from '../types'; import axios from 'axios'; // get all meows export const getMeows = () => (dispatch) => { dispatch({ type: LOADING_DATA }); axios .get('/meows') .then(res => { dispatch({ type: SET_MEOWS, payload: res.data }); }) .catch(err => { dispatch({ type: SET_MEOWS, payload: [] }); }); }; export const getMeow = (meowId) => (dispatch) => { dispatch({ type: LOADING_UI }); axios .get(`/meow/${meowId}`) .then((res) => { dispatch({ type: SET_MEOW, payload: res.data }); dispatch({ type: STOP_LOADING_UI }); }) .catch(err => console.log(err)); }; // post a meow export const postMeow = (newMeow) => (dispatch) => { dispatch({ type: LOADING_UI }); axios .post('/meow', newMeow) .then(res => { dispatch({ type: POST_MEOW, payload: res.data }); dispatch(clearErrors()); }) .catch(err => { dispatch({ type: SET_ERRORS, payload: err.response.data }) }); }; // like a meow export const likeMeow = (meowId) => dispatch => { axios .get(`/meow/${meowId}/like`) .then(res => { dispatch({ type: LIKE_MEOW, payload: res.data }); }) .catch(err => console.log(err)); }; // unlike a meow export const unlikeMeow = (meowId) => dispatch => { axios .get(`/meow/${meowId}/unlike`) .then(res => { dispatch({ type: UNLIKE_MEOW, payload: res.data }); }) .catch(err => console.log(err)); }; // submit a comment export const submitComment = (meowId, commentData) => (dispatch) => { axios .post(`/meow/${meowId}/comment`, commentData) .then(res => { dispatch({ type: SUBMIT_COMMENT, payload: res.data }); dispatch(clearErrors()); }) .catch(err => { dispatch({ type: SET_ERRORS, payload: err.response.data }); }); }; // delete a meow export const deleteMeow = (meowId) => (dispatch) => { axios .delete(`/meow/${meowId}`) .then(() => { dispatch({ type: DELETE_MEOW, payload: meowId }); }) .catch((err) => console.log(err)); }; export const getUserData = (userHandle) => dispatch => { dispatch({ type: LOADING_DATA }); axios .get(`/user/${userHandle}`) .then(res => { dispatch({ type: SET_MEOWS, payload: res.data.meows }); }) .catch(() => { dispatch({ type: SET_MEOWS, payload: null }); }); }; export const clearErrors = () => dispatch => { dispatch({ type: CLEAR_ERRORS }); };
'use strict' require('angular') require('angular-strap') require('angular-strap/dist/angular-strap.tpl') var cougar = angular.module('cougar', []) cougar.factory('Teams', function ($http) { var teams = { list: [] } $http.get('http://localhost:7777/api/teams/').success(function (data) { teams.list = data }) return teams }) cougar.controller('PlayersCtrl', function ($scope, $http, Teams) { $scope.teams = Teams $scope.addPlayer = function (player) { if (player) { $http.post('http://localhost:7777/api/players/', player, {headers: {'Content-Type': 'application/json'}}) .success(function playerCreated(data) { console.log(data) }) .error(function playerCreateError(data) { console.error(data) }) } } }) cougar.controller('TeamsCtrl', function ($scope, $http, Teams) { $scope.teams = Teams $scope.addTeam = function (team) { if (team) { $http.post('http://localhost:7777/api/teams/', team, {headers: {'Content-Type': 'application/json'}}) .success(function teamCreated(data) { console.log(data) $scope.team.name = '' Teams.list.push(data) }) .error(function teamCreateError(data) { console.error(data) }) } } $scope.deleteTeam = function (team) { if (team) { $http.delete('http://localhost:7777/api/teams/' + team.id) .success(function teamDeleted(data) { var index = Teams.list.indexOf(team) Teams.list.splice(index, 1) console.log('Team' ,team.id, 'was destroyed') }) .error(function teamDeleteError(data) { console.error(data) }) } } })
import React from 'react' import AddProductForm from "../component/AddProductForm"; const AddProduct = () => { return ( <> <main> <AddProductForm/> </main> </> ) } export default AddProduct
const express = require("express"); const app = express(); app.set("view engine", "pug"); app.get("/", (req, res) => { res.render("index"); }); app.get("/aidan", (req, res) => { res.render("aidan"); }); app.get("/ninam", (req, res) => { res.render("ninam"); }); app.get("/james", (req, res) => { res.render("james"); }); app.get("/*", (req, res) => { throw new Error("None Specified Route"); }); app.use((error, req, res, next) => { console.error(error.stack); res.status(404); res.render("error-page"); }); const port = process.env.PORT || 8000; app.listen(port, () => { console.log(`http://localhost:${port}`); });
export const navigation_icons = { Menu: {name: 'menu', type: 'feather', size: 25}, Map: {name: 'map-outline', active_name: 'map', type: 'ionicon', size: 22}, Events: { name: 'compass-outline', active_name: 'compass', type: 'ionicon', size: 25, }, Calendar: { name: 'calendar-outline', active_name: 'calendar', type: 'ionicon', size: 22, }, Profile: { name: 'user-circle-o', active_name: 'user-circle', type: 'font-awesome', size: 26, }, // Calendar: {name: 'calendar', type: 'feather', size: 22}, Another: { name: 'square-o', active_name: 'square', type: 'font-awesome', size: 26, }, CreateEvent: { name: 'plus-square-o', active_name: 'plus-square', type: 'font-awesome', size: 35, }, };
/** * Created by blood_000 on 16.01.2016. */ var EMAIL_REGEX = /^([a-z0-9_\.-])+@[a-z0-9-]+\.([a-z]{2,4}\.)?[a-z]{2,4}$/i; var DATE_REGEX = /^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/; var PHONE_REGEX = /^((8|\+7)[\- ]?)?(\(?\d{3,4}\)?[\- ]?)?[\d\- ]{5,10}$/; function validateExpression(variable, regexType) { switch (regexType) { case "EMAIL_REGEX" : return EMAIL_REGEX.test(variable); case "DATE_REGEX" : return DATE_REGEX.test(variable); case "PHONE_REGEX" : return PHONE_REGEX.test(variable); } }
"use strict"; // let $ = 'body'; // //... // //... // {//.. область видимости // $ = "foot"; // } // { // $ = "round"; // } // // alert($); // // let answer = prompt('hello', ['crew']) // let answer = confirm('hello'); // alert($); // let admin, username; // username = 'John'; // admin = username; // let user = 'Vasya'; // alert(admin + ' ' + user); // let username = prompt('What is your name?', ['Your name']); // // alert('Hi, ' + username); // console.log('Hi, ' + username); // const burger = document.querySelector('.burger'); // const menu = document.querySelector('.nav__list'); // const closeBtn = document.querySelector('.close-btn'); // const links = document.querySelectorAll('nav ul li a'); // burger.addEventListener('click', e => menu.classList.toggle('open')); // closeBtn.addEventListener('click', e => menu.classList.remove('open')); // [...links].forEach(link => link.addEventListener('click', e => menu.classList.remove('open'))); // let a = 4, // b = 9, // c = b % a; // console.log(c) // let a = 'hello', // b = 'world', // // c = a + ' ' + b; // c = `khg kjh kjh ${a} , ${b} asdasasd`; // console.log(c); // console.error(c); // document.write(c); // let price = 56; // let count = '4'; // let summ = price + +count; // console.log(summ); // let price = 56; // let count = '4'; // let summ = price + Number(count); // console.log(summ); // let price = 56; // let count = '4'; // let summ = price + Boolean(count); // console.log(summ); // let price = 56; // let count = '4'; // let summ = price * 0 || price * count; // console.log(summ); // let price = 56; // let count = '4'; // let summ = price * 0 && price * count; // console.log(summ); // let price = 56; // let count = '1'; // let summ = price * count; // if (summ > 100) { // console.log('Discount' + summ * 0.1) // } else { // console.log('Check' + summ) // } // let message = (summ > 100) ? console.log('Discount' + summ * 0.1) : console.log('Check' + summ); // let answer = +prompt('2+2=?') // if (answer === 4) { // alert('Ты красавчег') // } // else { // alert('Пшол вон отседа!') // } //....... // let answer = +prompt('Твій вік?') // if (answer <= 17) { // alert('Иди в школу') // } // else if (answer >= 18 && answer <= 45) { // alert('Добро пожаловать') // } // else if (answer >= 60) { // alert('Не') // } //....... // let a = prompt('???') // let b; // a == 'Director' ? b = 'Hello' : a == 'Manager' ? b = 'Hi' : b = 'Error'; // alert(b) //...... // let message; // let Login = prompt('Who are you?') // switch (Login) { // case 'Director': // message = 'Hello'; // break; // case 'Manager': // message = 'Hi'; // break; // case '': // message = 'empty'; // break; // default: // message = 'Error'; // break; // } // alert(message); //...... // let number = +prompt('Укажи трехзначное число', 324); // let number1 = (number - number % 100) / 100; // let number2 = (number - number % 10) / 10 - number1 * 10; // let number3 = number - number1 * 100 - number2 * 10; // if (number1 == number2 || number1 == number3 || number2 == number3) { // console.log('Есть повторы') // } // else { // console.log('Нет повторов') // } //...... // let price = 100; // price -= 10; // let count = '1'; // let summ = price * count; // console.log(summ) //...... let a = 2; ++a; console.log(a)
// const API_KEY = "d7af8e4b98131b441c22344c1d9d976d" const API_KEY = "b4543ad002224a398312e5820400c6e7" export default API_KEY
/* * 图表显示隐藏 * author : 陆议 */ KISSY.add("components/chart_toggle/index", function(S, Brick) { var $ = S.all; var ChartToggle = Brick.extend({ bindUI: function(){ var me = this; var el = me.get('el'); var chartToggle = el.one('.chart-toggle'); chartToggle.attr({title: '收起折线图'}); } },{ EVENTS: { '.chart-toggle': { click: function(e) { e.preventDefault(); var me = this; var curNode = $(e.currentTarget); var chartCnt = $('.chart-container'); if (!chartCnt.hasClass('chart-hidden')) { chartCnt.animate({height: 0}, {duration: 0.3, easing: 'easeOut', complete: function () { chartCnt.addClass('chart-hidden'); curNode.removeClass('btn-active'); curNode.attr({title: '展开折线图'}); }}); } else { chartCnt.animate({height: 377}, {duration: 0.3, easing: 'easeOut', complete: function () { chartCnt.removeClass('chart-hidden'); curNode.addClass('btn-active'); curNode.attr({title: '收起折线图'}); }}); } } } } }); return ChartToggle; }, { requires: ["brix/core/brick"] });
var modalOpen = document.querySelector(".modal-open"); var modalClose = document.querySelector(".modal-close") var modalPopup = document.querySelector(".modal"); var modalOverlay = document.querySelector(".modal-overlay"); var modalName = modalPopup.querySelector("[id=name]"); var modalForm = modalPopup.querySelector("form"); var modalUser = modalPopup.querySelector("#name"); var modalEmail = modalPopup.querySelector("#email"); var modalText = modalPopup.querySelector("#text"); modalOpen.addEventListener("click", function(event){ event.preventDefault(); modalPopup.classList.add("modal-show"); modalOverlay.classList.add("modal-overlay-show"); modalName.focus(); }); modalClose.addEventListener("click", function(event){ event.preventDefault(); modalPopup.classList.remove("modal-show"); modalOverlay.classList.remove("modal-overlay-show"); }); modalForm.addEventListener("submit", function(event){ if (!modalUser.value || !modalEmail.value || !modalText.value) { event.preventDefault(); modalPopup.classListAdd("modal-error"); console.log("Что то не заполнено"); } }); modalOverlay.addEventListener("click", function(event) { event.preventDefault(); modalPopup.classList.remove("modal-show"); modalOverlay.classList.remove("modal-overlay-show"); });
window.onload = function () { //导航栏 const header = document.querySelector('header'); const block = document.querySelector('header>.right').querySelectorAll('div'); const body = document.querySelector('body'); window.onscroll = function () { if (document.documentElement.scrollTop > 100) { header.classList.add("header"); block[1].style.backgroundColor = "white"; block[1].style.borderColor = "rgb(87, 19, 87)"; block[2].style.backgroundColor = "rgb(87, 19, 87)"; block[2].style.color = "white"; body.style.paddingTop = '70px'; } else { header.classList.remove("header"); block[1].style.backgroundColor = ""; block[1].style.borderColor = ""; block[2].style.backgroundColor = ""; block[2].style.color = ""; body.style.paddingTop = ''; } } const ad = document.querySelector('.ad'); const adc = ad.querySelector('.click'); adc.addEventListener('click',function(){ ad.style.display = "none"; }) //取消视频控制 // const video = document.querySelector("video"); // video.controls = false; //设置左边动态 const midleft = document.getElementsByClassName('middle_left')[0]; window.addEventListener('scroll',function(){ if(document.documentElement.scrollTop > 1000 &&document.documentElement.scrollTop < 2000){ midleft.classList.add('middle_left2'); body.style.backgroundColor = "rgb(248, 235, 215)" midleft.style.display = "block"; }else{ midleft.classList.remove('middle_left2'); body.style.backgroundColor = ""; midleft.style.display = ""; } }) }
exports.seed = function(knex, Promise) { // Deletes ALL existing entries return knex('sales').insert([ {month: 4 ,year: 2019, bookid: 1, totalsold: 32}, {month: 4 ,year: 2019, bookid: 2, totalsold: 113}, {month: 4 ,year: 2019, bookid: 3, totalsold: 102}, {month: 4 ,year: 2019, bookid: 4, totalsold: 39}, {month: 4 ,year: 2019, bookid: 5, totalsold: 66}, {month: 4 ,year: 2019, bookid: 6, totalsold: 19}, {month: 4 ,year: 2019, bookid: 7, totalsold: 59}, {month: 4 ,year: 2019, bookid: 8, totalsold: 79}, {month: 4 ,year: 2019, bookid: 9, totalsold: 26}, {month: 4 ,year: 2019, bookid: 10, totalsold: 71}, {month: 4 ,year: 2019, bookid: 11, totalsold: 87}, {month: 5 ,year: 2019, bookid: 1, totalsold: 34}, {month: 5 ,year: 2019, bookid: 2, totalsold: 93}, {month: 5 ,year: 2019, bookid: 3, totalsold: 112}, {month: 5 ,year: 2019, bookid: 4, totalsold: 91}, {month: 5 ,year: 2019, bookid: 5, totalsold: 88}, {month: 5 ,year: 2019, bookid: 6, totalsold: 32}, {month: 5 ,year: 2019, bookid: 7, totalsold: 70}, {month: 5 ,year: 2019, bookid: 8, totalsold: 60}, {month: 5 ,year: 2019, bookid: 9, totalsold: 77}, {month: 5 ,year: 2019, bookid: 10, totalsold: 13}, {month: 5 ,year: 2019, bookid: 11, totalsold: 98}, {month: 6 ,year: 2019, bookid: 1, totalsold: 119}, {month: 6 ,year: 2019, bookid: 2, totalsold: 54}, {month: 6 ,year: 2019, bookid: 3, totalsold: 70}, {month: 6 ,year: 2019, bookid: 4, totalsold: 84}, {month: 6 ,year: 2019, bookid: 5, totalsold: 91}, {month: 6 ,year: 2019, bookid: 6, totalsold: 10}, {month: 6 ,year: 2019, bookid: 7, totalsold: 111}, {month: 6 ,year: 2019, bookid: 8, totalsold: 7}, {month: 6 ,year: 2019, bookid: 9, totalsold: 54}, {month: 6 ,year: 2019, bookid: 10, totalsold: 19}, {month: 6 ,year: 2019, bookid: 11, totalsold: 117}, {month: 6 ,year: 2019, bookid: 12, totalsold: 201}, {month: 6 ,year: 2019, bookid: 13, totalsold: 18}, {month: 7 ,year: 2019, bookid: 1, totalsold: 57}, {month: 7 ,year: 2019, bookid: 2, totalsold: 33}, {month: 7 ,year: 2019, bookid: 3, totalsold: 109}, {month: 7 ,year: 2019, bookid: 4, totalsold: 83}, {month: 7 ,year: 2019, bookid: 5, totalsold: 37}, {month: 7 ,year: 2019, bookid: 6, totalsold: 28}, {month: 7 ,year: 2019, bookid: 7, totalsold: 56}, {month: 7 ,year: 2019, bookid: 8, totalsold: 116}, {month: 7 ,year: 2019, bookid: 9, totalsold: 15}, {month: 7 ,year: 2019, bookid: 10, totalsold: 88}, {month: 7 ,year: 2019, bookid: 11, totalsold: 88}, {month: 7 ,year: 2019, bookid: 12, totalsold: 20}, {month: 7 ,year: 2019, bookid: 13, totalsold: 18}, {month: 8 ,year: 2019, bookid: 1, totalsold: 95}, {month: 8 ,year: 2019, bookid: 2, totalsold: 91}, {month: 8 ,year: 2019, bookid: 3, totalsold: 24}, {month: 8 ,year: 2019, bookid: 4, totalsold: 22}, {month: 8 ,year: 2019, bookid: 5, totalsold: 83}, {month: 8 ,year: 2019, bookid: 6, totalsold: 11}, {month: 8 ,year: 2019, bookid: 7, totalsold: 110}, {month: 8 ,year: 2019, bookid: 8, totalsold: 42}, {month: 8 ,year: 2019, bookid: 9, totalsold: 117}, {month: 8 ,year: 2019, bookid: 10, totalsold: 62}, {month: 8 ,year: 2019, bookid: 11, totalsold: 22}, {month: 8 ,year: 2019, bookid: 12, totalsold: 21}, {month: 8 ,year: 2019, bookid: 13, totalsold: 20}, {month: 9 ,year: 2019, bookid: 1, totalsold: 32}, {month: 9 ,year: 2019, bookid: 2, totalsold: 113}, {month: 9 ,year: 2019, bookid: 3, totalsold: 102}, {month: 9 ,year: 2019, bookid: 4, totalsold: 39}, {month: 9 ,year: 2019, bookid: 5, totalsold: 66}, {month: 9 ,year: 2019, bookid: 6, totalsold: 19}, {month: 9 ,year: 2019, bookid: 7, totalsold: 59}, {month: 9 ,year: 2019, bookid: 8, totalsold: 79}, {month: 9 ,year: 2019, bookid: 9, totalsold: 26}, {month: 9 ,year: 2019, bookid: 10, totalsold: 71}, {month: 9 ,year: 2019, bookid: 11, totalsold: 87}, {month: 9 ,year: 2019, bookid: 12, totalsold: 24}, {month: 9 ,year: 2019, bookid: 13, totalsold: 21}, {month: 10 ,year: 2019, bookid: 1, totalsold: 510}, {month: 10 ,year: 2019, bookid: 2, totalsold: 33}, {month: 10 ,year: 2019, bookid: 3, totalsold: 109}, {month: 10 ,year: 2019, bookid: 4, totalsold: 83}, {month: 10 ,year: 2019, bookid: 5, totalsold: 310}, {month: 10 ,year: 2019, bookid: 6, totalsold: 28}, {month: 10 ,year: 2019, bookid: 7, totalsold: 56}, {month: 10 ,year: 2019, bookid: 8, totalsold: 116}, {month: 10 ,year: 2019, bookid: 9, totalsold: 15}, {month: 10 ,year: 2019, bookid: 10, totalsold: 88}, {month: 10 ,year: 2019, bookid: 11, totalsold: 88}, {month: 10 ,year: 2019, bookid: 12, totalsold: 20}, {month: 10 ,year: 2019, bookid: 13, totalsold: 18} ]); };
/// <reference types="cypress" /> describe("My third test suite", () => { before("", () => { }) it("My third testcase", () => { cy.visit("https://www.rahulshettyacademy.com/angularpractice/"); cy.get("input[name='name']") }); });
const acl = require('./../middlewares/auth'); const uploader = require('../middlewares/multer'); const UserController = require('./../controllers/users/user.controller'); const VendorController = require('./../controllers/vendors/vendor.controller'); const PostController = require('./../controllers/blogpost/post.controller'); const CategoryController = require('./../controllers/categories/category.controller'); const BlogCommentController = require('./../controllers/comments/blog.comment.controller'); const VendorCommentController = require('./../controllers/comments/vendor.comment.controller'); module.exports = app => { 'use strict'; /* User routes */ app.get('/users', acl.isAuthenticated, UserController.index); app.post('/user/register', UserController.save); app.post('/users/auth/login', UserController.authenticate); app.get('/users/:id', acl.isAuthenticated, UserController.find); app.put('/users/:id', acl.isAuthenticated, UserController.update); app.delete('/users/:id', acl.isAuthenticated, UserController.destroy); /* Vendor routes */ app.get('/vendors', VendorController.index); app.post('/vendors', acl.isAuthenticated,VendorController.save); app.post('/vendors/upload', uploader('vendors'), VendorController.upload); app.get('/vendors/:id', VendorController.find); app.put('/vendors/:id', acl.isAuthenticated, VendorController.update); app.delete('/vendors/:id', acl.isAuthenticated, VendorController.destroy); /* Blog post routes */ app.get('/blog/posts', PostController.index); app.post('/blog/posts', acl.isAuthenticated, PostController.save); app.post('/blog/posts/upload', uploader, PostController.upload); app.get('/blog/posts/:id', PostController.find); app.put('/blog/posts/:id', acl.isAuthenticated, PostController.update); app.delete('/blog/posts/:id', acl.isAuthenticated, PostController.destroy); /* Categories Routes */ app.get('/blog/categories', CategoryController.index); app.post('/blog/categories', acl.isAuthenticated, CategoryController.save); app.get('/blog/categories/:id', CategoryController.find); app.put('/blog/categories/:id', acl.isAuthenticated, CategoryController.update); app.delete('/blog/categories/:id', acl.isAuthenticated, CategoryController.destroy); /* Blog Comment routes */ app.get('/blog/comments', BlogCommentController.index); app.post('/blog/comments', acl.isAuthenticated, BlogCommentController.save); app.get('/blog/comments/:id', BlogCommentController.find); app.put('/blog/comments/:id', acl.isAuthenticated, BlogCommentController.update); app.delete('/blog/comments/:id', acl.isAuthenticated, BlogCommentController.destroy); /* Vendor Comment routes */ app.get('/vendor/comments', VendorCommentController.index); app.post('/vendor/comments', acl.isAuthenticated, VendorCommentController.save); app.get('/vendor/comments/:id', VendorCommentController.find); app.put('/vendor/comments/:id', acl.isAuthenticated, VendorCommentController.update); app.delete('/vendor/comments/:id', acl.isAuthenticated, VendorCommentController.destroy); };
const fs = require('fs'); const { app, BrowserWindow, dialog } = require('electron'); let mainWindow = null; const openFile = (file) => { const content = fs.readFileSync(file).toString(); mainWindow.webContents.send('file-opened', file, content) }; const getFileFromUser = exports.getFileFromUser = () => { const files = dialog.showOpenDialog(mainWindow, { properties: ['openFile'], filters: [ { name: 'Text Files', extensions: ['txt'] }, { name: 'Markdown Files', extensions: ['md', 'markdown'] } ] }); if (!files) return; // 'files' is Promise. // console.log(files); // files.then( files => console.log(files)); // const file = files[0]; // const content = fs.readFileSync(file).toString(); // console.log(content); files.then( files => { if (files.filePaths[0]) openFile(files.filePaths[0]); }) }; app.on('ready', () => { mainWindow = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); mainWindow.loadFile('./app/index.html'); mainWindow.once('ready-to-show', () => { mainWindow.show(); getFileFromUser(); }); mainWindow.on('closed', () => { mainWindow = null; }); });
const ResponseError = require('../../../Enterprise_business_rules/Manage_error/ResponseError'); const { TYPES_ERROR } = require('../../../Enterprise_business_rules/Manage_error/codeError'); module.exports = async (space, { spaceRepositoryMySQL }) => { const name = space.getName(); // Se comprueba que el aula o laboratorio no existe mediante el nombre const nameExist = await spaceRepositoryMySQL.getName(name); if (nameExist) { throw new ResponseError(TYPES_ERROR.ERROR, 'Ese aula o laboratorio ya está registrado', 'space_exist'); } const spaceData = space.toJSON(); return spaceRepositoryMySQL.createSpace({ spaceData }); };
import React, { Component } from "react"; import classNames from "classnames"; import "./notification.scss"; export default class Notification extends Component { constructor(props) { super(props); this.state = {}; } render() { const { message, level } = this.props; const containerClasses = classNames({ ["notification-container"]: true, [level]: level, show: message && level, }); return <div className={containerClasses}>{message}</div>; } }
var PropertiesReader = require('properties-reader'); var properties = PropertiesReader('./api.properties'); var moment = require("moment"); // Definición del log var fs = require('fs'); var log = require('tracer').console({ transport : function(data) { //console.log(data.output); fs.open(properties.get('main.log.file'), 'a', 0666, function(e, id) { fs.write(id, data.output+"\n", null, 'utf8', function() { fs.close(id, function() { }); }); }); } }); var dbConfig = { host: properties.get('bbdd.mysql.ip') , user: properties.get('bbdd.mysql.user') , password: properties.get('bbdd.mysql.passwd') , database: properties.get('bbdd.mysql.name'), connectionLimit: 50, queueLimit: 0, waitForConnection: true }; var mysql = require('mysql'); // Crear la conexion a la base de datos var connection = mysql.createPool(dbConfig); //crear un objeto para ir almacenando todo lo que necesitemos var vehicleModel = {}; //obtener todos vehicleModel.getVehicles = function(startRow, endRow, sortBy, callback) { if (connection) { var sqlCount = "SELECT count (*) as nrows FROM VEHICLE V, HAS H, FLEET F where V.DEVICE_ID=H.DEVICE_ID and H.FLEET_ID=F.FLEET_ID" ; log.debug ("Query: "+sqlCount); connection.query(sqlCount, function(err, row) { if(row) { var consulta = "SELECT V.DEVICE_ID as id, V.ALIAS as alias, V.VEHICLE_LICENSE as license FROM VEHICLE V, HAS H, FLEET F where V.DEVICE_ID=H.DEVICE_ID and H.FLEET_ID=F.FLEET_ID"; var totalRows = row[0].nrows; var sql = ''; var orderBy = ''; if (sortBy == null) { orderBy = 'id'; } else { vsortBy = sortBy.split(','); for (var i=0; i<vsortBy.length; i++ ) { if (vsortBy[i].charAt(0) == '-') { var element = vsortBy[i].substring(1, vsortBy[i].length); if (element == 'id' || element == 'license' || imo == 'alias' || email == 'fleetId') { if (orderBy == '') orderBy = element + ' desc'; else orderBy = orderBy + ',' + element + ' desc'; } } else { var element = vsortBy[i]; if (element == 'id' || element == 'license' || imo == 'alias' || email == 'fleetId') { if (orderBy == '') orderBy = element; else orderBy = orderBy + ',' + element; } } } } if (orderBy == '') { orderBy = 'id'; } if (startRow == null || endRow == null) { sql = consulta + " ORDER BY " + orderBy; } else { sql = consulta + " ORDER BY " + orderBy + " LIMIT " + (endRow - startRow + 1) + " OFFSET " + startRow; } log.debug ("Query: "+sql); connection.query(sql, function(error, rows) { if(error) { callback(error, null); } else { callback(null, rows, totalRows); } }); } else { callback(null,[]); } }); } else { callback(null, null); } } //obtenemos 1 vehicleModel.getVehicle = function(id,callback) { if (connection) { var sql = "SELECT V.DEVICE_ID as id, V.ALIAS as alias, V.VEHICLE_LICENSE as license FROM VEHICLE V, HAS H, FLEET F where V.DEVICE_ID=H.DEVICE_ID and V.DEVICE_ID = " + connection.escape(id); log.debug ("Query: "+sql); connection.query(sql, function(error, row) { if(error) { callback(error, null); } else { callback(null, row); } }); } else { callback(null, null); } } //añadir 1 nuevo vehicleModel.insertVehicle = function(vehicleData,callback) { if (connection) { var now = moment(new Date()); var sql = "INSERT INTO VEHICLE SET VEHICLE_LICENSE = " + connection.escape(vehicleData.license) + "," + "ALIAS = " + connection.escape(vehicleData.alias); log.debug ("Query: "+ sql); connection.query(sql, function(error, result) { if(error) { callback(error, null); } else { var deviceId = result.insertId; //insertar en tabla OBT var sqlObt = 'INSERT INTO OBT SET IMEI = ' + connection.escape(vehicleData.imei) + ',' + 'VERSION_ID = ' + '11' + ',' + 'DEVICE_ID = ' + deviceId + ',' + 'VEHICLE_LICENSE = ' + connection.escape(vehicleData.license) + ',' + 'GSM_OPERATOR_ID = ' + '0'+ ',' + 'ID_CARTOGRAPHY_LAYER = ' + '0'+ ',' + 'ID_TIME_ZONE = ' + '1'+ ',' + 'TYPE_SPECIAL_OBT = ' + '0'+ ',' + 'LOGGER = ' + '0'; log.debug ("Query: "+ sqlObt); connection.query(sqlObt, function(error, result) { if(error) { callback(error, null); } else{ //insertar en tabla HAS var sqlHas = "INSERT INTO HAS SET FLEET_ID = " + connection.escape(vehicleData.fleetId) + ',' + "DEVICE_ID = " + deviceId + "," + "VEHICLE_LICENSE = " + connection.escape(vehicleData.license); log.debug ("Query: "+ sqlHas); connection.query(sqlHas, function(error, result) { if(error) { callback(error, null); } else { //devolvemos la última id insertada callback(null,{"insertId" : deviceId}); } }); } }); } }); } else { callback(null, null); } } //actualizar vehicleModel.updateVehicle = function(vehicleData, callback) { if(connection) { var sql = "UPDATE VEHICLE SET ALIAS = " + connection.escape(vehicleData.alias) + " " + "WHERE DEVICE_ID = " + vehicleData.id; //console.log(sql); log.debug ("Query: "+sql); connection.query(sql, function(error, result) { if(error) { callback(error, null); } else { // Actualizar la tabla HAS var sqlHas = "UPDATE HAS SET FLEET_ID = " + connection.escape(vehicleData.fleetId) + " " + "WHERE DEVICE_ID = " + vehicleData.id; log.debug ("Query: "+ sqlHas); connection.query(sqlHas, function(error, result) { if(error) { callback(error, null); } else { //devolvemos la última id insertada callback(null,{"message":"success"}); } }); } }); } else { callback(null, null); } } //eliminar 1 vehicleModel.deleteVehicle = function(id, callback) { if(connection) { var sqlExists = "SELECT V.DEVICE_ID as id, V.ALIAS as alias, V.VEHICLE_LICENSE as license FROM VEHICLE V, HAS H, FLEET F where V.DEVICE_ID=H.DEVICE_ID and V.DEVICE_ID = " + connection.escape(id); log.debug ("Query: "+sqlExists); connection.query(sqlExists, function(err, row) { if(row) { var sql = 'DELETE FROM VEHICLE WHERE DEVICE_ID = ' + connection.escape(id); log.debug ("Query: "+sql); connection.query(sql, function(error, result) { if(error) { callback(error, null); } else { // Borrar de la tabla HAS var sqlHas = 'DELETE FROM HAS WHERE DEVICE_ID = ' + connection.escape(id); log.debug ("Query: "+sqlHas); connection.query(sqlHas, function(error, result) { if(error) { callback(error, null); } else { // se devuelven los datos del elemento eliminado callback(null,row); } }); } }); } else { callback(null,{"message":"notExist"}); } }); } else { callback(null, null); } } //exportamos el objeto para tenerlo disponible en la zona de rutas module.exports = vehicleModel;
const express = require("express"); const bodyParser = require("body-parser"); const methodOverride = require("method-override"); // const popup = require('popups'); require("dotenv").config(); // get funcs from mongoose const { upload } = require("./mongoose"); const { Check_If_File_And_Table_Is_Valid } = require("./mongoose"); const { findProjects } = require("./mongoose"); const { getCollections } = require("./mongoose"); const { resolvePromises } = require("./mongoose"); const { getDocumentsFromCollections } = require("./mongoose"); const { findImg } = require('./mongoose'); const { imageFileGetReq } = require('./mongoose'); // const app = express(); //middle ware // telling method override that we want to make a query string in order to make a delete req app.use(methodOverride("_method")); // app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(express.static(__dirname + "/../dist")); // const port = 5000; app.listen(port, () => { console.log(`Server started on port ${port}`); }); // app.post('/formValid' , upload.single("file") , ( req, res) => { // console.log('form passed') // res.status(200).send(req.body); // }) app.post("/validationForm", upload.single("file"), (req, res) => { console.log(req.body, "req bod"); let collectionName = req.body.text; let fileName = req.body.originalName; let formValidation = Check_If_File_And_Table_Is_Valid( collectionName, fileName ); console.log(collectionName, fileName); // if form validation is false if (formValidation === false) { // then we can pop up an err to the page, console.log("form validation did not pass"); res.status(200).send(req.body); } else { // else we have to make a pop up saying file save successful! res.status(200).send(req.body); } }); app.get("/GetAllProjectCollections", async (req, res) => { try { let getCollectionsResult = await getCollections(); let resolvedGetCollections = await resolvePromises(getCollectionsResult); res.send(resolvedGetCollections); } catch (err) { console.log(err); } }); app.put("/GetImagesFromCollections", async (req, res) => { try { let collectionsData = req.body.collections; /* Reading in parallel */ let collectionDataPromise = await Promise.all( collectionsData.map(async (collection) => { let result = await getDocumentsFromCollections(collection); return result; }) ); /* ----------- https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop ------------------ Reading in sequence let result = []; for (let i = 0; i < collectionsData.length; i++) { let data = await getDocumentsFromCollections(collectionsData[i]); result.push(data); } */ res.send(collectionDataPromise); } catch (err) { console.log(err); } }); app.get( '/image/:filename-:collection' , imageFileGetReq); /////////////////////
import React, { Component } from "react"; import Navbar from "../layout/Navbar"; import { Container, Col, Row } from "react-bootstrap"; import "./AboutUs2.css"; import Car from "../layout/Car"; import Digital from "../layout/Digital"; import Key from "../layout/Key"; import Clients from "../layout/Clients "; import StartToNow from "../layout/StartToNow"; import OurVal from "../layout/OurVal"; import Together from "../layout/Together"; import AboutCover from "../layout/AboutCover"; export default class AboutUs2 extends Component { componentDidMount() { window.scrollTo(0, 0); } render() { return ( <div className="AboutUs-page"> <Navbar color={"black"} /> <Container> <Row className=" align-items-center mt-5"> <Col lg={6} md={6} sm={12}> <Row> <h1> DIGITAL INNOVATION <span className="title"> <br /> SPECIALISTS </span> </h1> </Row> </Col> <Col lg={6} md={6} sm={12}> <Row className="justify-content-end"> <img src={require("../../images/rocket.PNG")} alt="rocket" className="img-fluid " /> </Row> </Col> </Row> <Row className="my-5"> <Col lg={2} md={6} sm={12}> <p>ABOUT US</p> </Col> <Col lg={7} md={6} sm={12}> <p> We’re a digital agency specializing in digital innovation. Our team of consultants, designers and developers builds and launches digital products and experiences for ambitious clients </p> </Col> </Row> </Container> <Car /> <Container className="my-5"> <h2 className="my-5 pt-5">The basics</h2> <Row> <Col lg={4} md={4} sm={12}> <img src="https://www.datocms-assets.com/7718/1545058582-what.svg" alt="our basics" /> <h6 className="my-3">What we do</h6> <p> Signifly creates brands, builds products and launches campaigns </p> </Col> <Col lg={4} md={4} sm={12}> <img src="https://www.datocms-assets.com/7718/1545058787-how.svg" alt="our basics" /> <h6 className="my-3">How we do it</h6> <p>Our tools are innovation, design and technology.</p> </Col> <Col lg={4} md={4} sm={12}> <img src="https://www.datocms-assets.com/7718/1545058780-why.svg" alt="our basics" /> <h6 className="my-3">What makes us different</h6> <p> We believe in close collaboration and a multidisciplinary culture. </p> </Col> </Row> </Container> <Digital /> <Key /> <div> <img src="https://www.datocms-assets.com/7718/1578908485-signifly-team.jpg?auto=compress&w=1519&dpr=1.25&q=70" className=" img-fluid" alt="pic" /> </div> <Clients /> <StartToNow /> <OurVal /> <Together /> <AboutCover /> </div> ); } }
//= require active_admin/base var iframe; function resizeFrame() { if (!iframe) { iframe = document.querySelector('iframe'); } if (!iframe) { return; } iframe.style.height = iframe.contentWindow.document.body.scrollHeight + 'px'; } setInterval(resizeFrame, 1000);
Package.describe({ name: 'brandonparee:metadisk', version: '0.3.0', summary: 'Meteor wrapper for metadisk-client API and Storj', git: 'https://github.com/brandonparee/meteor-metadisk.git', documentation: 'README.md' }); Npm.depends({ "metadisk-client": "0.3.0", "storj": "0.3.0" }); Package.onUse( function( api ) { api.addFiles( 'metadisk.js', [ 'server' ] ); api.export( 'metadisk', [ 'server' ] ); api.export( 'storj', [ 'server' ] ); });
import Icon from './Icon' import { windowContext } from '../context/windowContext' import { useContext } from 'react' import { userConext } from '../context/userContext' const Nav = () => { const windowCtx = useContext(windowContext) const userCtx = useContext(userConext) const createPortfolioHandler = () => userCtx.isOwner() ? windowCtx.openPorfolioForm() : windowCtx.showWarning( '관리자만 접근 할 수 있습니다. 관리자로 로그인 해주세요.' ) const handleTrashcan = () => { alert('공사중입니다') } return ( <ul className="window__container"> <li className="item" style={{ top: 10, left: 0 }} onDoubleClick={windowCtx.openAboutMe} > <Icon name="computer" title="내 컴퓨터" /> </li> <li className="item" style={{ top: 100, left: 0 }} onDoubleClick={handleTrashcan} > <Icon name="recyclebin" title="휴지통" /> </li> <li className="item" style={{ top: 190, left: 0 }} onDoubleClick={windowCtx.openInternet} > <Icon name="internet" title="인터넷" /> </li> <li className="item" style={{ top: 280, left: 0 }} onDoubleClick={windowCtx.openContact} > <Icon name="inbox" title="편지쓰기" /> </li> <li className="item" style={{ top: 370, left: 0 }} onDoubleClick={windowCtx.openPortfolioFoler.bind( this, '포트폴리오' )} > <Icon name="briefcase" title="포트폴리오" /> </li> <li className="item" style={{ top: 460, left: 0 }} onDoubleClick={createPortfolioHandler} > <Icon name="portfolio-form" title="문서작성" /> </li> </ul> ) } export default Nav
// React import React, { Component } from 'react'; // Components import Hand from './components/Hand'; import Deck from './components/Deck'; import Lobby from './components/Lobby'; // CSS import './App.css'; // Images import cardback from './images/cardbacks/southern-belle.JPG'; // Actions import Actions from './Actions'; class App extends Component { constructor(props) { super(props); this.actions = new Actions("ws://localhost:8001"); const initialHand = [ this.actions.pickUp(), this.actions.pickUp(), this.actions.pickUp(), ]; // _____ _ _ // / ____| | | | // | (___ | |_ __ _| |_ ___ // \___ \| __/ _` | __/ _ \ // ____) | || (_| | || __/ // |_____/ \__\__,_|\__\___| // // this.state = { //-----------LOGIN STATE-----------\\ // Whether you are logged in or not. loggedIn: false, // The name that identifies you to other players. username: "", // Login error loginError: false, //-----------GAME LOBBY-----------\\ // List of games available to join lobbyGamesList: [], // Whether we are creating a new game creatingGame: false, // The name of our new game newGameName: '', // The number of players for the new game newGameNumPlayers: 2, // The privacy level of the new game newGamePublic: true, //-----------CURRENT GAME-----------\\ // Whether you are in a game that has started. gameStarted: false, // The ID that links you to a game in progress. gameID: "", // Which player you are in an ongoing game. playerNumber: null, // The player who's turn it is. currentPlayer: null, // The cards in your hand. hand: initialHand, // The card in play cardInPlay: [], }; this.logIn = this.logIn.bind(this); this.getGamesList = this.getGamesList.bind(this); this.createGameButtonInputHandler = this.createGameButtonInputHandler.bind(this); this.usernameInputHandler = this.usernameInputHandler.bind(this); this.newGameNameInputHandler = this.newGameNameInputHandler.bind(this); this.newGameNumPlayersInputHandler = this.newGameNumPlayersInputHandler.bind(this); this.newGamePublicInputHandler = this.newGamePublicInputHandler.bind(this); this.createGame = this.createGame.bind(this); this.drawCard = this.drawCard.bind(this); this.quit = this.quit.bind(this); // Gracefully close websocket connection before unload. window.addEventListener("beforeunload", (ev) => { this.quit(); }); } // _ _ _ // | | | | | | // | | ___ | |__ | |__ _ _ // | | / _ \| '_ \| '_ \| | | | // | |___| (_) | |_) | |_) | |_| | // |______\___/|_.__/|_.__/ \__, | // __/ | // |___/ /** * Attempt to login to the server with the currently set username */ logIn() { // If the username field is blank. Don't allow login if (this.state.username === '') { this.setState({ loggedIn: false, loginError: true, }); } else { // Submit username to server for login. // Callback updates state depending on success. this.actions.submitUserName(this.state.username, (success) => { if (success) { this.setState({ loggedIn: true }); } else { this.setState({ loggedIn: false, loginError: true, }); } }); this.getGamesList(); } } /** * Asks the server for a list of open games then updates state. */ getGamesList() { this.actions.getGamesList((list) => { console.log(list); this.setState({lobbyGamesList: list }); }); } createGame() { this.createGameButtonInputHandler(false); console.log("create game"); } // _____ _ _ _ _ _ // |_ _| | | | | | | | | | // | | _ __ _ __ _ _| |_ | |__| | __ _ _ __ __| | | ___ _ __ ___ // | | | '_ \| '_ \| | | | __| | __ |/ _` | '_ \ / _` | |/ _ \ '__/ __| // _| |_| | | | |_) | |_| | |_ | | | | (_| | | | | (_| | | __/ | \__ \ // |_____|_| |_| .__/ \__,_|\__| |_| |_|\__,_|_| |_|\__,_|_|\___|_| |___/ // | | // |_| /** * Handle username input from the Lobby component. * @param {*} event */ usernameInputHandler(event) { this.setState({username: event.target.value }); } /** * Handle new game name input from the Lobby component. * @param {*} event */ newGameNameInputHandler(event) { this.setState({newGameName: event.target.value }); } /** * Handle new game name num players input from the Lobby component. * @param {*} event */ newGameNumPlayersInputHandler(event) { this.setState({newGameNumPlayers: event.target.value }); //console.log(event.target.value); } /** * Handle new game name num public checbox input from the Lobby component. * @param {*} event */ newGamePublicInputHandler(event) { this.setState({newGamePublic: event.target.checked }); console.log(event.target.checked); } /** * Changes the creating game state. */ createGameButtonInputHandler(value) { this.setState({creatingGame: value}); } // _____ // / ____| // | | __ __ _ _ __ ___ ___ // | | |_ |/ _` | '_ ` _ \ / _ \ // | |__| | (_| | | | | | | __/ // \_____|\__,_|_| |_| |_|\___| // // /** * Disconnect from the game server */ quit() { this.actions.disconnect(); } drawCard() { const newCard = Actions.pickUp(); console.log(`Randomly drew ${newCard.name} of ${newCard.suit}`); this.setState({ hand: [...this.state.hand, newCard] }); } // _____ _ // | __ \ | | // | |__) |___ _ __ __| | ___ _ __ // | _ // _ \ '_ \ / _` |/ _ \ '__| // | | \ \ __/ | | | (_| | __/ | // |_| \_\___|_| |_|\__,_|\___|_| // // render() { return ( <div className="App"> {/* That's a lotta props. Maybe I should look into a state management framework...?*/} <Lobby loggedIn={this.state.loggedIn} loginError={this.state.loginError} value={this.state.username} loginInput={this.usernameInputHandler} logInAction={this.logIn} greeting={this.state.username} gamesList={this.state.lobbyGamesList} createGame={this.createGame} creatingGame={this.state.creatingGame} creatingGameAction={this.createGameButtonInputHandler} newGameName={this.state.newGameName} newGameAction={this.newGameNameInputHandler} newGameNumPlayers={this.state.newGameNumPlayers} newGameNumPlayersAction={this.newGameNumPlayersInputHandler} newGamePublic={this.state.newGamePublic} newGamePublicAction={this.newGamePublicInputHandler} /> <Deck image={cardback} onClick={this.drawCard}/> <button onClick={this.drawCard}>Pick up</button> <Hand className="Hand" cards={this.state.hand}/> </div> ); } } export default App;
const express = require('express') const app = express() const configRoutes = require('./routes') const mongoose = require('mongoose') var cors = require("cors") app.use(express.json()); app.use(cors()); configRoutes(app) app.listen(3080, async () => { if (process.env.NODE_ENV === 'prod') { // This will be when NODE_ENV is prod. Needs AWS DB await mongoose.connect('mongodb://mongodb:27017/', { useNewUrlParser: true, useUnifiedTopology: true }, (err) => { if (err) console.error(err); }) } else { // This is dev await mongoose.connect('mongodb://localhost:27017/miraDB', { useNewUrlParser: true, useUnifiedTopology: true }, (err) => { if (err) console.error(err); }) } console.log("Listening on port 3000") })
import article, { initialState } from '../articles'; import { ADD_ARTICLES, ADD_ARTICLES_ERROR, } from '../../../constants'; const articleState = initialState; describe('Article reducers', () => { it('should provide the initial article state', () => { expect(article(undefined, {})).toEqual(articleState); }); it('should add article to the state', () => { expect(article(articleState, {})).toEqual(articleState); }); it('should set article success', () => { expect(article(articleState, { type: ADD_ARTICLES }).success).toEqual(true); }); it('should set article error', () => { expect(article(articleState, { type: ADD_ARTICLES_ERROR, payload: {} }).success).toEqual(false); }); });
module("GameObject.initialize"); test("Testing constructor correct initializations", function () { var objData = { "name": "Grass", "selector":$("div"), "left": 0, "top": 0, "align": "bottom", "parent": null, }; var testGameObj = new GameObject(objData); equal(testGameObj.name, objData.name, "Check in name"); equal(testGameObj.x, objData.left, "Check in direction"); equal(testGameObj.parent, objData.parent, "Check in parent"); equal(testGameObj.width, 0, "Check in width"); equal(testGameObj.height, 0, "Check in height"); }); module("GameObject.move"); test("Testing move() method of gameObject on X and Y", function () { var objData = { "name": "Grass", "selector": $("div"), "left": 0, "top": 0, "align": "bottom", "parent": null, }; var testGameObj = new GameObject(objData); testGameObj.move(-1, -2); var expectedNewCordinates = { x: 1, y: 2 }; equal(testGameObj.x, expectedNewCordinates.x, "Check in X"); equal(testGameObj.y, expectedNewCordinates.y, "Check in Y"); equal(testGameObj.div.css("left"), "auto", "Check CSS X"); equal(testGameObj.div.css("top"), "auto", "Check CSS Y"); }); module("GameObject.move"); test("Testing move() method of gameObject when there is no change", function () { var objData = { "name": "Grass", "selector": $("div"), "left": 0, "top": 0, "align": "bottom", "parent": null, }; var testGameObj = new GameObject(objData); testGameObj.move(0, 0); var expectedNewCordinates = { x: 0, y: 0 }; equal(testGameObj.x, expectedNewCordinates.x, "Check in X"); equal(testGameObj.y, expectedNewCordinates.y, "Check in Y"); equal(testGameObj.div.css("left"), "auto", "Check CSS X"); equal(testGameObj.div.css("top"), "auto", "Check CSS Y"); }); module("GameObject.intersects"); test("Testing intersects() method of two gameObject that intersec on X and Y", function () { var objData = { "name": "Grass", "selector": $("div"), "left": 0, "top": 0, "align": "bottom", "parent": null, }; var testGameObjFirst = new GameObject(objData); testGameObjFirst.width = 10; testGameObjFirst.height = 10; var testGameObjSecond = new GameObject(objData); testGameObjSecond.x = 5; testGameObjSecond.y = 5; testGameObjSecond.width = 10; testGameObjSecond.height = 10; var expected = true; equal(testGameObjFirst.intersects(testGameObjSecond), expected); }); module("GameObject.intersects"); test("Testing intersects() method of two gameObject when there is no intersection", function () { var objData = { "name": "Grass", "selector": $("div"), "left": 0, "top": 0, "align": "bottom", "parent": null, }; var testGameObjFirst = new GameObject(objData); testGameObjFirst.width = 10; testGameObjFirst.height = 10; var testGameObjSecond = new GameObject(objData); testGameObjSecond.x = 20; testGameObjSecond.y = 20; testGameObjSecond.width = 10; testGameObjSecond.height = 10; var expected = false; equal(testGameObjFirst.intersects(testGameObjSecond), expected); }); module("GameObject.intersects"); test("Testing intersects() method of two gameObject when there is intersection only on X", function () { var objData = { "name": "Grass", "selector": $("div"), "left": 0, "top": 0, "align": "bottom", "parent": null, }; var testGameObjFirst = new GameObject(objData); testGameObjFirst.width = 10; testGameObjFirst.height = 10; var testGameObjSecond = new GameObject(objData); testGameObjSecond.x = 10; testGameObjSecond.y = 20; testGameObjSecond.width = 10; testGameObjSecond.height = 10; var expected = false; equal(testGameObjFirst.intersects(testGameObjSecond), expected); }); module("GameObject.intersects"); test("Testing intersects() method of two gameObject when there is intersection only on Y", function () { var objData = { "name": "Grass", "selector": $("div"), "left": 0, "top": 0, "align": "bottom", "parent": null, }; var testGameObjFirst = new GameObject(objData); testGameObjFirst.width = 10; testGameObjFirst.height = 10; var testGameObjSecond = new GameObject(objData); testGameObjSecond.x = 20; testGameObjSecond.y = 10; testGameObjSecond.width = 10; testGameObjSecond.height = 10; var expected = false; equal(testGameObjFirst.intersects(testGameObjSecond), expected); });
import React from "react"; import { Link } from "react-router-dom"; import LoadingSpinner from "../reusableComponents/LoadingSpinner"; import CommentListContainer from "../../containers/comments/CommentListContainer"; const PostDetail = ({ post, err, loading, show_comments, params, handleShowCommentsChange }) => { if (loading) { return <LoadingSpinner />; } let updated_date, posted_date, category_upper_case; if (post) { updated_date = new Date(post.updated_on); posted_date = new Date(post.posted_on); category_upper_case = post.category && post.category.charAt(0).toUpperCase() + post.category.slice(1); } const createMarkup = content => ({ __html: content }); return ( <div className="container mt-4"> {err && err.message && ( <div className="alert alert-danger"> <b>err.message</b> </div> )} {post && post.category && ( <div> <h1 className="text-center">{post.title}</h1> <hr /> <div className="row justify-content-md-center"> <div className="col-12 col-md-10"> <span> <p> {updated_date > posted_date ? ( <span> {" "} Last Updated on{" "} <b>{new Date(updated_date).toDateString()} </b> </span> ) : ( <span style={{ fontSize: "16px" }}> {" "} Posted on <b>{new Date(posted_date).toDateString()} </b> </span> )} <span> {" "} in{" "} <Link to={{ pathname: "/", search: `?q=${post.category}` }} style={{ color: "#165395" }} > <b>{category_upper_case}</b> </Link>{" "} by <b>{post.author}</b> </span> </p> <hr /> {/* CONTENT HERE */} <span style={{ fontSize: "20px", textAlign: "left" }} dangerouslySetInnerHTML={createMarkup(post.content)} /> <hr /> </span> </div> <div className="className=col-12 col-md-10" style={{ marginTop: "4em" }} > <div className="text-center"> <button id="toggle-comments" onClick={handleShowCommentsChange} className="btn btn-secondary btn-lg" > <b>Toggle the comments</b> </button> </div> {show_comments && post.category && ( <CommentListContainer postId={post.id} postSlug={params.slug} /> )} </div> </div> </div> )} </div> ); }; export default PostDetail;
const express = require("express"); const router = express.Router(); const getProjectSummary = require("../library/getProjectSummary"); const updateSequence = require("../library/updateSequence"); /** * Express router for /updateSeq * * Handle request to update one proteoform in database by scan */ const updateSeq = router.post('/updateSeq', function (req, res) { console.log('Hello updateSeq!'); let uid; //console.log(req.session.passport.user.profile); if (!req.session.passport) { res.write('Unauthorized'); res.end(); return; } else { uid = req.session.passport.user.profile.id; } let projectCode = req.query.projectCode; let scanNum = req.query.scanNum; let proteoform = req.query.proteoform; getProjectSummary(projectCode, function (err, row) { let seqStatus = row.sequenceStatus; let projectDir = row.projectDir; let projectUid = row.uid; if (projectUid !== uid) { res.write('Unauthorized'); res.end(); return; } if(seqStatus === 1) { try { updateSequence(projectDir, proteoform, scanNum); res.write('1'); res.end(); } catch (e) { console.log(e); res.write('0'); res.end(); } } else { res.write('0'); res.end(); } }) }); module.exports = updateSeq;
import * as React from 'react' import { Linechart } from '@accurat/chart-library' import appearanceConfig from '../lib/appearanceConfig.json' import { dimensions } from '../lib/constants' import { dataJuggler } from '../lib/fixDJ' import { d1, d2 } from '../datasets/datasets' import d3 from '../datasets/data.csv' // call the method `dataJuggler` for each dataset // the first input is the dataset (d1, d2, ...) // the second input is the name of the date column const { data: data1, moments: moments1, types: types1 } = dataJuggler(d1, 'date') const { data: data2, moments: moments2, types: types2 } = dataJuggler(d2, 'birthday') const { data: data3, moments: moments3, types: types3 } = dataJuggler(d3, 'date') export class Linecharts extends React.Component { render() { const { className = '' } = this.props return ( <div className={`${className}`}> <Linechart data={data1} moments={moments1} structure={{ x: [{ variable: 'date' }], y: [{ variable: 'value' }], color: [{ variable: 'cat' }], }} appearanceConfig={appearanceConfig} dimensions={dimensions} types={types1} withLegend={true} /> <Linechart data={data2} moments={moments2} structure={{ x: [{ variable: 'birthday' }], y: [{ variable: 'height' }], color: [{ variable: 'category' }], }} appearanceConfig={appearanceConfig} dimensions={dimensions} types={types2} withLegend={true} /> <Linechart data={data3} moments={moments3} structure={{ x: [{ variable: 'date' }], y: [{ variable: 'value' }], color: [{ variable: 'cat' }], }} appearanceConfig={appearanceConfig} dimensions={dimensions} types={types3} withLegend={true} /> </div> ) } }
import React from "react"; import {Route, Switch} from "react-router-dom"; import Charts from "./charts/index"; import Calendar from "./calendar"; import Maps from "./map"; const Extensions = ({match}) => ( <Switch> <Route path={`${match.url}/map`} component={Maps}/> <Route path={`${match.url}/chart`} component={Charts}/> <Route path={`${match.url}/calendar`} component={Calendar}/> </Switch> ); export default Extensions;
module.exports = (sequelize, DataTypes) => sequelize.define('PassangersInRoom', { });
class Nav { constructor() { this.navBtn = document.querySelector(".nav__btn"); this.nav = document.querySelector("nav"); this.setEventListener(); } setEventListener = () => { // About nav toggle btn this.navBtn.addEventListener("click", () => { if (this.nav.classList.contains("open")) { this.nav.classList.remove("open"); this.nav.classList.add("close"); } else { this.nav.classList.add("open"); this.nav.classList.remove("close"); } }); }; } export default Nav;
import React from 'react'; import {Row, Col, Button} from 'react-bootstrap'; const SubCourseList = (props) => { return ( <div className="subcourselist"> <thead> <tr> <h4>{props.degreeArea}</h4> </tr> </thead> {props.courses.map(courseObject => ( courseObject.taken && <tbody> <tr> <h4>{courseObject.search_name} <a id='ex' onClick={(e) => {props.changeClass(courseObject);}} className="changeButton" bsStyle="danger"> X</a></h4> {/* <td class="col-xs-2"> <h4><a onClick={(e) => {props.changeClass(courseObject);}} className="changeButton" bsStyle="primary"> X</a></h4> </td> */} </tr> </tbody> ))} </div> ) } export default SubCourseList
/** * Creates a Phaser P2 vehicle which can have wheels * @param {Phaser.Sprite} frameSprite The sprite of the truck's main frame */ Vehicle = function(frameSprite) { this.frame = frameSprite; this.game = this.frame.game; this.wheels = this.game.add.group(); this.debug = false; this.game.physics.p2.enable(this.frame, this.debug); this.cursors = this.game.input.keyboard.createCursorKeys(); this.maxWheelForce = 1000; this.rotationSpeed = 400; } Vehicle.prototype = { /** * Constrains a wheel to the frame at a given offset position * @param {String} wheelSpriteKey Preloaded sprite key of the wheel * @param {Array} offsetFromVehicle Relative position on vehicle frame to * constrain the wheel in the form [x,y] * @return {Phaser.Sprite} The created wheel */ addWheel: function(wheelSpriteKey, offsetFromVehicle) { var vehicleX = this.frame.position.x; var vehicleY = this.frame.position.y; var wheel = this.game.add.sprite(vehicleX + offsetFromVehicle[0], vehicleY + offsetFromVehicle[1], wheelSpriteKey); this.game.physics.p2.enable(wheel, this.debug); wheel.body.clearShapes(); wheel.body.addCircle(wheel.width * 0.5); //constrain the wheels to the vehicle frame so that they can rotate //about a fixed point var rev = this.game.physics.p2.createRevoluteConstraint( this.frame.body, offsetFromVehicle, wheel.body, [0,0], this.maxWheelForce ); this.wheels.add(wheel); return wheel; }, /** * Update method for the vehicle's wheels to be controlled */ update: function() { var rotationSpeed = this.rotationSpeed; if (this.cursors.left.isDown) { this.wheels.children.forEach(function(wheel,index) { wheel.body.rotateLeft(rotationSpeed); }); } else if (this.cursors.right.isDown) { this.wheels.children.forEach(function(wheel,index) { wheel.body.rotateRight(rotationSpeed); }); } else { this.wheels.children.forEach(function(wheel,index) { wheel.body.setZeroRotation(); }); } } };
import ETable from './e-table.js' const install = function (Vue) { // if (install.installed) return; Vue.component(ETable.name, ETable) } if (typeof window !== 'undefined' && window.Vue) { install(window.Vue) } export { ETable } export default { install, ETable }
import React from "react"; import 'bootstrap/dist/css/bootstrap.min.css'; import { Container, Button, Badge } from "react-bootstrap"; import { Link } from "react-router-dom"; import { connect } from 'react-redux'; import { setIsLoggedIn, setEmail, setUsername, setPassword } from '../redux/actions/userActions'; import { setTweets } from '../redux/actions/noteActions'; import ProfileSearch from './ProfileSearch'; import axios from 'axios'; const ProfileSidebar = ({ dispatch, activeUsers, username }) => { const logout = ( ) => { // return to initial state: dispatch(setIsLoggedIn(false)); dispatch(setUsername('')); dispatch(setPassword('')); dispatch(setEmail('')); }; const profile = ( ) => { axios .get('/api/profileEmail', { params: { username: username, } }) .then(response => { if (response.data ) { dispatch(setEmail(response.data[0].email)); dispatch(setTweets([])); } }) .catch(err => { console.log("no user found", err); }); } return ( <Container> <br/> <br /> <ProfileSearch /> <br/> <h5> <Link to="/account"> <Button variant="primary" onClick={profile} > Profile </Button> </Link> </h5> <br/> <div> <h5> Active Users <Badge variant="secondary">{activeUsers}</Badge> </h5> </div> <br/> <div> <h5> Hello <Badge variant="secondary">{username}</Badge> </h5> </div> <br/> <Link to="/"> <Button variant="primary" onClick={logout} > Logout </Button> </Link> </Container> ); } const mapStateToProps = state => ({ activeUsers: state.userReducer.activeUsers, username: state.userReducer.username, password: state.userReducer.password, email: state.userReducer.email, tweets: state.notesReducer.tweets, }); export default connect(mapStateToProps, null)(ProfileSidebar);
import React from 'react' const CBME_Curriculum = () => { return ( <> <div className="news-updates"> <div className="container"> <div className="row"> <div className="col-lg-12"> <div className="section-heading"> <h3 >CBME Curriculum</h3> </div> </div> </div> </div> </div> <div class="container"> <div class="row"> <div class="col"> <ul> <li> - MBBS 1st Prof = subjects covered</li> <li> - MBBS 2nd prof = subjects covered</li> <li>- MBBS mini prof = subjects covered</li> <li>- Final Prof = subjects covered</li> </ul> </div> </div> </div> </> ) } export default CBME_Curriculum
import EmberRouter from '@ember/routing/router'; import config from './config/environment'; export default class Router extends EmberRouter { location = config.locationType; rootURL = config.rootURL; } Router.map(function() { this.route('dashboard', function() { this.route('contributors', function() { this.route('show', { path: ':id' }); }); this.route('contributions', function() { this.route('show', { path: ':id' }); }); }); this.route('contributions', function() { this.route('new', { queryParams: ['contributorId', 'kind', 'amount'] }); this.route('resubmit', { path: ':id/resubmit' }); }); this.route('contributors', function() { this.route('new'); this.route('edit', { path: ':id/edit' }); }); this.route('signup', function() { this.route('github'); this.route('account'); this.route('complete'); }); this.route('budget', function() { this.route('expenses'); this.route('reimbursements', function() {}); }); this.route('reimbursements', function() { this.route('new'); }); });
import Home from "./Home"; import ProductList from "./ProductList"; import Navbar from "./Navbar"; import OneItem from "./OneItem" export {Navbar, Home, ProductList, OneItem};
'use strict'; var dgram = require('dgram'); var host = '192.168.2.14', port = 1634; var client = dgram.createSocket( 'udp4' ); var deviceTypes = { zonwering: 'sun', tv: 'tv' } module.exports = { handleAction: function(deviceType, device, deviceState, callback){ var error; switch(deviceType){ case deviceTypes.zonwering: switch(deviceState) { case 'up': case 'down': case 'idle': var message = Buffer.from(device.data[deviceState], 'hex'); break; default: error = 'Zonwering actie niet ondersteund'; break; } break; case deviceTypes.tv: switch(deviceState) { case 'on': case 'off': var message = Buffer.from(device.data[deviceState], 'hex'); break; default: error = 'TV actie niet ondersteund'; break; } break; default: error = 'Apparaat niet ondersteund'; break; } if(error) return callback(error, false); if(message){ Homey.log(message); client.send(message, 0, message.length, port, host ); callback(deviceState, true); } else { return callback('Er is iets mis met het bericht', false); } }, deviceTypes: deviceTypes }
/****************************************************************************** * WEB222 - Assignment 01 * I declare that this assignment is my own work in accordance with Seneca Academic Policy. No part of * this assignment has been copied manually or electronically from any other source (including web sites) * or distributed to other students. * Name: Andrew Van Student ID: 141267179 Date: May 11, 2018 * ******************************************************************************/ /***************************** * Task 1 *****************************/ var studentName = "Andrew Van", numCourses = 4, program = "CPA", ptJob = false; if (ptJob == true) { var have = "have"; } else { var have = "don't have"; } console.log("My name is " + studentName + " and I'm in " + program + " program. I'm taking " + numCourses + " course in this semester and I " + have + " a part-time job now.") /***************************** * Task 2 *****************************/ var cYear = 2018; var age = prompt("Please enter your age: "); var bYear = cYear - age; console.log("You were born in the year of " + bYear); var sYear = prompt("Enter the number of years you expect to study in the college: "); var gYear = cYear + parseInt(sYear); console.log("You will graduate from Seneca college in the year of " + gYear); /***************************** * Task 3 *****************************/ function toC(f) { return (5/9) * (f-32); } function toF(c) { return (1.8 * c) + 32; } var c = 0; var f = toF(c); console.log(c.toFixed(1) + "°C is " + f.toFixed(1) + "°F"); f = 100; c = toC(f); console.log(f.toFixed(1) + "°F is " + c.toFixed(1) + "°C"); /***************************** * Task 4 *****************************/ for (var i = 0; i <= 10; i++) { if (i%2 != 0) { console.log(i + " is odd"); } else { console.log(i + " is even"); } } /***************************** * Task 5 *****************************/ function largerNum(n1, n2) { if (n1 > n2) { return n1; } else { return n2; } } var n1 = 5, n2 = 12; console.log("The larger number of " + n1 + " and " + n2 + " is " + largerNum(n1, n2)); n1 = 15; n2 = 12; console.log("The larger number of " + n1 + " and " + n2 + " is " + largerNum(n1, n2)); var greaterNum = function (n1, n2) { return Math.max(n1, n2); } console.log("The greater number of " + n1 + " and " + n2 + " is " + greaterNum(n1,n2)); n1 = 5 n2 = 12; console.log("The greaer number of " + n1 + " and " + n2 + " is " + greaterNum(n1,n2)); /***************************** * Task 6 *****************************/ function Evaluator() { var sum = 0; var avg = 0; for (var i=0; i < arguments.length; i++) { sum += arguments[i]; } avg = sum/arguments.length; if (avg >= 50) { return true; } return false; } console.log("Average greater than equal to 50: " + Evaluator(20,30,40)); console.log("Average greater than equal to 50: " + Evaluator(60,70,80)); console.log("Average greater than equal to 50: " + Evaluator(30,60,90)); /***************************** * Task 7 *****************************/ var grader = function(score) { if (score >= 80) { return "A"; } else if (score >= 70) { return "B"; } else if (score >= 60) { return "C"; } else if (score >= 50) { return "D"; } else { return "F"; } } var score = 82; console.log(score + " is a letter grade of " + grader(score)); score = 66; console.log(score + " is a letter grade of " + grader(score)); score = 41; console.log(score + " is a letter grade of " + grader(score)); /***************************** * Task 8 *****************************/ function showMultiples(num, numMultiples) { for (var i=1; i<= numMultiples; i++) { console.log(num + " x " + i + " = " + num*i); } } showMultiples(5,4); showMultiples(2,5); showMultiples(4,3);
import React, { Fragment, useState } from "react"; // componentes import Logo from "./subcomponents/Logo"; import AccionPortafolio from "./subcomponents/AccionPortafolio"; import MostrarProyectos from "./subcomponents/MostrarProyectos"; import Redes from "./subcomponents/Redes"; import Menu from "./subcomponents/Menu"; // imagenes de los proyectos import gym from "../img/imagenes-proyectos/gym.jpg"; import psicotest from "../img/imagenes-proyectos/psicotest.jpg"; import hamilton from "../img/imagenes-proyectos/hamilton.jpg"; import poke from "../img/imagenes-proyectos/poke.jpg"; import ricardo from "../img/imagenes-proyectos/ricardo.jpg"; // logos tecnologias import css from "../img/logos-tecnologias/css.png"; import html from "../img/logos-tecnologias/html.png"; import javascript from "../img/logos-tecnologias/javascript.png"; import php from "../img/logos-tecnologias/php.png"; import react from "../img/logos-tecnologias/react.png"; import mysql from "../img/logos-tecnologias/mysql.png"; // ojo en la propiedad de tecnologias pasar hasta un maximo de tres imagenes ya que se puede romper el diseño const Personales = () => { const [proyectos, setProyectos] = useState([ { id: 5, nombre: "Ricardo Cañas", url: "https://ricardocanas.net/", imagen: ricardo, descripcion: "Sitio web y portafolio", tecnologias: [react, javascript, css], }, { id: 4, nombre: "Poké cards", url: "https://jamesricardocr.github.io/pokemon/", imagen: poke, descripcion: "Consultando la PokeAPI para crear cartas de pokémon", tecnologias: [html, css, javascript], }, { id: 3, nombre: "Gym", url: "http://gym.smartcreaty.com/", imagen: gym, descripcion: "CRUD, registro de usuarios y panel de administración.", tecnologias: [javascript, php, mysql], }, { id: 2, nombre: "Psicotest v1.0", url: "https://dreamy-villani-5d65f8.netlify.app/", imagen: psicotest, descripcion: "plataforma de test psicologicos", tecnologias: [html, css, javascript], }, { id: 1, nombre: "Test de Hamilton", url: "https://boring-spence-29ef28.netlify.app/", imagen: hamilton, descripcion: "programacion del test de Hamilton", tecnologias: [html, css, javascript], }, ]); const mensaje = "En esta sección encuentras todos mis proyectos personales."; return ( <Fragment> <div className="header"> <Menu /> <Logo /> </div> <AccionPortafolio mensaje={mensaje} /> <div className="container-proyectos"> {proyectos.map((proyecto) => ( <MostrarProyectos key={proyecto.id} proyecto={proyecto} /> ))} </div> <br /> <Redes /> </Fragment> ); }; export default Personales;
'use strict'; const express = require('express'); const router = express.Router(); const nodemailer = require('nodemailer'); const User = require('../models/user'); const upload = require('../middlewares/upload'); router.get('/edit', (req, res, next) => { if (!req.session.currentUser) { return res.redirect('/'); } User.findById(req.session.currentUser._id) .then((user) => { let hasCategoryMedicine; let hasCategoryFood; let hasCategoryEducation; if (user.categories.includes('medicine')) { hasCategoryMedicine = true; } if (user.categories.includes('food')) { hasCategoryFood = true; } if (user.categories.includes('education')) { hasCategoryEducation = true; } const data = { messages: req.flash('edit-profile-error'), previousData: req.flash('edit-profile-data')[0], user: user, hasCategoryMedicine: hasCategoryMedicine, hasCategoryFood: hasCategoryFood, hasCategoryEducation: hasCategoryEducation }; res.render('profile-edit', data); }); }); router.post('/edit', upload.single('photo'), (req, res, next) => { const currentUser = req.session.currentUser; if (!currentUser) { return res.redirect('/'); } const categories = []; if (req.body.medicine) { categories.push('medicine'); } if (req.body.food) { categories.push('food'); } if (req.body.education) { categories.push('education'); } const previousData = req.body; const previousPicture = currentUser.imgUrl; previousData.categories = categories; if (!previousPicture && !req.file) { req.flash('edit-profile-data', previousPicture); req.flash('edit-profile-error', 'Please upload a picture'); return res.redirect('/profile/edit'); } if (!req.body.description) { req.flash('edit-profile-data', previousData); req.flash('edit-profile-error', 'Description is required'); return res.redirect('/profile/edit'); } if (!req.body.mail) { req.flash('edit-profile-data', previousData); req.flash('edit-profile-error', 'Email is required'); return res.redirect('/profile/edit'); } if (!req.body.medicine && !req.body.food && !req.body.education) { req.flash('edit-profile-data', previousData); req.flash('edit-profile-error', 'Please select at least one type of organisation'); return res.redirect('/profile/edit'); } const data = { username: req.body.username, description: req.body.description, isActive: false, phone: req.body.phone, mail: req.body.mail, website: req.body.website, facebook: req.body.facebook, instagram: req.body.instagram, twitter: req.body.twitter, categories: categories, imgUrl: req.file ? req.file.url : previousPicture }; const options = {new: true}; // --------- Mail part --------- // User.findByIdAndUpdate(currentUser._id, data, options) .then((user) => { req.session.currentUser = user; let transporter = nodemailer.createTransport({ service: 'Gmail', auth: { user: 'helpvzlaproject@gmail.com', pass: 'tripletsproject' } }); transporter.sendMail({ from: '"HelpVzla" <helpvzlaproject@gmail.com>', to: data.mail, subject: 'Thank you for signing up in HelpVzla', text: 'We will verify your account and activate it in 48 hours', html: `<b>We will verify your account and activate it in 48 hours</b>` }); transporter.sendMail({ from: data.mail, to: '"HelpVzla" <helpvzlaproject@gmail.com>', subject: 'A new organisation has signed up in HelpVzla', text: 'The account should be verified and activated in 48 hours', html: `<b>The account should be verified and activated in 48 hours</b>` }); res.redirect(`/org/${currentUser._id}`); }) .catch(next); }); module.exports = router;
import React from 'react'; import 'bootstrap/dist/css/bootstrap.min.css'; import { Card } from 'react-bootstrap'; import Button from 'react-bootstrap/Button'; import HotelModal from '../ModalComponents/HotalModal'; class HotelDataRendering extends React.Component { constructor(props) { super(props); this.state = { hotelData: {}, modalShow: false, }; } hotelModalFun = index => { let data = this.props.hotelsData[index]; this.setState({ hotelData: data, modalShow: true, }); console.log(index); console.log(this.state.modalShow); }; handleClose = () => { this.setState({ modalShow: false, }); }; render() { return ( <> <div className='bg-hotel' style={{ margin: '10px', backgroundColor: '#FEFDCA' }} > {/* {console.log('data[0] :', this.props.hotelsData[0])} */} {<h1 style={{ textAlign: 'center', color: 'black' }}>Hotels</h1>} <br /> {this.props.hotelsData.map((item, idx) => { return ( <> <Card key={idx} style={{ width: '20%', height: '27%', display: 'inline-block', marginLeft: '10%', marginBottom: '5%', backgroundImage: 'linear-gradient(#ffd298,#f5d976)', }} > <Card.Body style={{ width: '100%', height: '10%', textAlign: 'center', }} > <strong>{item.name}</strong> </Card.Body> <Card.Body> <img style={{ width: '100%', height: '8rem' }} src={item.cardImgUrl} alt={item.name} ></img> <p style={{ marginTop: '5px' }}> {' '} <strong>StarRating : {item.starRating}</strong> <br /> <strong>Price : {item.price}</strong> </p> </Card.Body> <Button style={{ width: '80%', height: '10%', margin: '0 0 10px 30px', }} variant='warning' onClick={() => { this.hotelModalFun(idx); }} > More... </Button> </Card> </> ); })} </div> <HotelModal hotelData={this.state.hotelData} modalShow={this.state.modalShow} handleClose={this.handleClose} /> </> ); } } export default HotelDataRendering;
import React from "react"; import { storiesOf } from "@storybook/react"; import { Story } from "storybook/assets/styles/common.styles"; import { getStoryName } from "storybook/storyTree"; import ListBoxBrowser from "../src"; import dataSingle from "../test/specs/fixtures/single.oneColumn"; const storyName = getStoryName("ListBoxBrowser"); storiesOf(`${storyName}/Examples/Single`, module).add("One column", () => ( <Story> <ListBoxBrowser data={dataSingle} isMulti={false} rootTitle="Universes" browserTitle="Heroes" hasLeftColumn={false} isParentSelectable onChange={selectedOptions => { console.log("selected options:", selectedOptions); }} /> </Story> ));
import React from 'react' import Missioncomponents from '../Components/Mission/Missioncomponents' const Mission = () => { return ( <Missioncomponents></Missioncomponents> ) } export default Mission
const Engine = Matter.Engine; const World = Matter.World; const Bodies = Matter.Bodies; const Body = Matter.Body; function preload() { dImage=loadImage("Dustbin.js"); } var ground; var dustbin,dObject,dImage; var ball; function setup() { createCanvas(1600, 700); engine = Engine.create(); world = engine.world; //Create the Bodies Here. ground= new Ground (width/2,670,width,20); dustbin= new Dustbin (1200,650); ball= new Paper (200,450,40); World.add(world,ball); Engine.run(engine); } function draw() { rectMode(CENTER); background(0); drawSprites(); ball.display(); dustbin.display(); ground.display(); } function keyPressed() { if (keyCode === UP_ARROW) { Matter.Body.applyForce(paper.body,paper.body.position,{x:85,y:-85}); } }
var searchData= [ ['labelfacecameraonyaxis_2ecs',['LabelFaceCameraOnYAxis.cs',['../_label_face_camera_on_y_axis_8cs.html',1,'']]] ];
var arr = [1, 2, 3]; function getFirstElement(arr) { return arr[0]; } console.log(getFirstElement(arr)); console.log(getFirstElement([1,2,3])); console.log(getFirstElement([8,5,100])); console.log(getFirstElement([3,5,12]));
describe('QuizController test', function() { var QUIZ_1 = 'test_quiz1'; var QUIZ_2 = 'test_quiz2'; var userResponse = {}; var questionsQuiz1 = {}; var questionsQuiz2 = {}; var quizPerformance = {}; var routeParams = {}; beforeEach(module('quizz')); beforeEach(inject(function ($injector) { initUserResponse(); questionsQuiz1 = initQuestions(QUIZ_1, 10); questionsQuiz2 = initQuestions(QUIZ_2, -1); initQuizPerformance(); $httpBackend = $injector.get('$httpBackend'); $httpBackend.expectPOST('/getUser').respond(userResponse); $httpBackend.expectPOST('/listNextQuestions').respond(questionsQuiz1); $httpBackend.expectPOST('/getQuizPerformance').respond(quizPerformance); $httpBackend.expectPOST('/recordQuestionShown').respond('ok'); })); afterEach(function() { $httpBackend.verifyNoOutstandingExpectation(); $httpBackend.verifyNoOutstandingRequest(); delete $.cookie['username']; }); it('test init', inject(['$rootScope', '$controller', 'userService', function($rootScope, $controller, userService) { // init scopes quizControllerScope = $rootScope.$new(); // quiz controller routeParams['quizId'] = QUIZ_1; $controller('QuizController', { $scope: quizControllerScope, $routeParams: routeParams }); // Just initialize quiz controller will call some init function to // create a new username, fetch question, and quiz performance. $httpBackend.flush(); expect(quizControllerScope.currentQuestionIndex).toEqual(1); expect(quizControllerScope.numQuestions).toEqual(10); expect(quizControllerScope.currentQuestion.text) .toEqual('Calibration question 1'); expect(quizControllerScope.currentQuestion.quizID).toEqual(QUIZ_1); expect(quizControllerScope.readyToShow).toEqual(true); expect(quizControllerScope.performance.score).toEqual(0.7891); expect(quizControllerScope.showPerformance).toEqual(true); }]) ); it('test reload diff quiz', inject([ '$rootScope', '$controller', 'userService', function($rootScope, $controller, userService) { // Mocks the storeCookie function to store a cookie that works without // https since karma test starts a http server. userService.storeCookie = function(userid) { $.cookie("username", userid); }; // init scopes quizControllerScope = $rootScope.$new(); // quiz controller routeParams['quizId'] = QUIZ_1; $controller('QuizController', { $scope: quizControllerScope, $routeParams: routeParams }); // Init with first quiz. $httpBackend.flush(); // Switch to second quiz. routeParams['quizId'] = QUIZ_2; $controller('QuizController', { $scope: quizControllerScope, $routeParams: routeParams }); // As the routeParams changes, we need to fetch new questions. $httpBackend.expectPOST('/listNextQuestions').respond(questionsQuiz2); $httpBackend.expectPOST('/getQuizPerformance').respond(quizPerformance); $httpBackend.expectPOST('/recordQuestionShown').respond('ok'); $httpBackend.flush(); expect(quizControllerScope.currentQuestion.quizID).toEqual(QUIZ_2); }]) ); it('test reload same quiz', inject([ '$rootScope', '$controller', 'userService', function($rootScope, $controller, userService) { // Mocks the storeCookie function to store a cookie that works without // https since karma test starts a http server. userService.storeCookie = function(userid) { $.cookie("username", userid); }; // init scopes quizControllerScope = $rootScope.$new(); // quiz controller routeParams['quizId'] = QUIZ_1; $controller('QuizController', { $scope: quizControllerScope, $routeParams: routeParams }); // Init with first quiz. $httpBackend.flush(); // Reload again with the same quiz. $controller('QuizController', { $scope: quizControllerScope, $routeParams: routeParams }); // Since this is the same quiz, we won't need to fetch questions again. $httpBackend.expectPOST('/recordQuestionShown').respond('ok'); $httpBackend.expectPOST('/getQuizPerformance').respond(quizPerformance); $httpBackend.flush(); expect(quizControllerScope.currentQuestion.quizID).toEqual(QUIZ_1); }]) ); it('test fetch unlimited question', inject([ '$rootScope', '$controller', 'userService', 'workflowService', function($rootScope, $controller, userService, workflowService) { // Mocks the storeCookie function to store a cookie that works without // https since karma test starts a http server. userService.storeCookie = function(userid) { $.cookie("username", userid); }; // Sets up listNextQuestions to only return 2 gold questions for the // "unlimited" quiz. questionsQuiz2.calibration = questionsQuiz2.calibration.slice(0, 2); questionsQuiz2.collection = []; $httpBackend.resetExpectations(); $httpBackend.expectPOST('/getUser').respond(userResponse); $httpBackend.expectPOST('/listNextQuestions').respond(questionsQuiz2); $httpBackend.expectPOST('/getQuizPerformance').respond(quizPerformance); $httpBackend.expectPOST('/recordQuestionShown').respond('ok'); quizControllerScope = $rootScope.$new(); routeParams['quizId'] = QUIZ_2; $controller('QuizController', { $scope: quizControllerScope, $routeParams: routeParams }); $httpBackend.flush(); expect(quizControllerScope.numQuestions).toEqual(-1); // Simulate answering the first question. workflowService.incCurrentQuestionIndex(); $controller('QuizController', { $scope: quizControllerScope, $routeParams: routeParams }); // No extra call to fetch additional question. $httpBackend.expectPOST('/recordQuestionShown').respond('ok'); $httpBackend.expectPOST('/getQuizPerformance').respond(quizPerformance); $httpBackend.flush(); // Simulate answering the second question. workflowService.incCurrentQuestionIndex(); $controller('QuizController', { $scope: quizControllerScope, $routeParams: routeParams }); // Since there is only two questions in this unlimited QUIZ_2, we need to // fetch questions again. $httpBackend.expectPOST('/listNextQuestions').respond(questionsQuiz2); $httpBackend.expectPOST('/getQuizPerformance').respond(quizPerformance); $httpBackend.expectPOST('/recordQuestionShown').respond('ok'); $httpBackend.flush(); }]) ); function initUserResponse() { userResponse = { userid: 'aff2', }; } function initQuestions(quizID, numQuestions) { var calibrationQuestions = []; for (var i = 1; i <= 10; i++) { var question = { 'quizID' : quizID, 'text' : 'Calibration question ' + i, 'answers': [] }; for (var j = 1; j < 4; j++) { question.answers.push({ 'internalID' : j, 'text' : 'Calibration question ' + i + ' answer ' + j, 'kind' : i % 4 == j ? 'GOLD' : 'INCORRECT', 'quizID' : quizID }); } calibrationQuestions.push(question); } var collectionQuestions = []; for (var i = 1; i <= 10; i++) { var question = { 'quizID' : quizID, 'text' : 'Collection question ' + i, 'answers': [] }; for (var j = 1; j < 4; j++) { question.answers.push({ 'internalID' : j, 'text' : 'Collection question ' + i + ' answer ' + j, 'kind' : 'SILVER', 'quizID' : quizID }); } collectionQuestions.push(question); } return { calibration: calibrationQuestions, collection: collectionQuestions, numQuestions: numQuestions }; } function initQuizPerformance() { quizPerformance = { score: 0.7891, rankScore: 3, totalUsers: 10, correctanswers: 4, totalanswers: 8, percentageCorrect: 0.5 }; } });
import axios from 'axios'; import debug from 'debug'; const log = debug('roadie'); export default class Roadie { constructor({ environment, token }) { this.request = axios.create({ baseURL: environment === 'production' ? 'https://connect.roadie.com' : 'https://connect-sandbox.roadie.com', // TODO: ensure production url is correct before go live headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', }, }); } // eslint-disable-next-line class-methods-use-this async handleError(err) { if (err.response) { // The request was made and the server responded with a status code // that falls out of the range of 2xx log('Error: response.data: %o', err.response.data); log('Error: response.status: %o', err.response.status); log('Error: response.headers: %o', err.response.headers); if (err.response.data && err.response.data.errors) { throw new Error( err.response.data.errors .map(error => { return `code: ${error.code} parameter: ${error.parameter} message: ${error.message}`; }) .reduce((a, b) => { return `${a}\n${b}`; }, 'Roadie Error: '), ); } } else if (err.request) { // The request was made but no response was received // `err.request` is an instance of XMLHttpRequest in the browser and an instance of // http.ClientRequest in node.js log('Error: err.request: %o', err.request); throw new Error(`Roadie Error: request: ${err.request.status}`); } else { // Something happened in setting up the request that triggered an err log('Error: %s', err.message); throw new Error(`Roadie Error: ${err.message}`); } } /** * * from https://docs.roadie.com/#create-a-shipment * * @param {Object} params reference_id (required) string The user supplied ID for the shipment. Max length 100 characters. items (required) array An array of one or more Item. pickup_location (required) Location A complete Location object. delivery_location (required) Location A complete Location object. pickup_after (required) timestamp The time when the shipment is ready for pickup. deliver_between (required) TimeWindow The window within which the shipment must be completed. options (required) DeliveryOptions Any delivery options for the shipment. * @param {function} cb */ createShipment(params) { return this.request .post('/v1/shipments', params) .then(response => response.data) .catch(err => this.handleError(err)); } /** * * @param {Number} id (required) string id of previously created shipment */ deleteShipment(id) { return this.request .delete(`/v1/shipments/${id}`) .then(response => response.data) .catch(err => this.handleError(err)); } /** * * from https://docs.roadie.com/#create-an-estimate * * @param {Object} params items (required) array An array of one or more Item. pickup_location (required) Location A Location object. delivery_location (required) Location A Location object. pickup_after (required) timestamp The time when the shipment is ready for pickup. deliver_between (required) TimeWindow The window within which the shipment must be completed. * @param {function} cb */ estimate(params) { return this.request .post('/v1/estimates', params) .then(response => response.data) .catch(err => this.handleError(err)); } /** * * @param {Number} id (required) string id of previously created shipment */ retrieveShipment(id) { return this.request .get(`/v1/shipments/${id}`) .then(response => response.data) .catch(err => this.handleError(err)); } /** * * @param {Number} id (required) string id of previously created shipment * @param {Object} params reference_id string The user supplied ID for the shipment. state string The current state of the shipment. See ShipmentState for all possible values. items array An array of one or more Item. pickup_location Location The address and contact info where the driver will pick up the shipment. delivery_location Location The address and contact info where the driver will deliver the shipment. pickup_after timestamp The time, in RFC 3339 format, after which the shipment is ready for pickup. deliver_between TimeWindow The window within which the shipment must be completed. options DeliveryOptions Any delivery options for the shipment. tracking_number string A unique number used to track the shipment. driver Driver The information about the assigned driver. created_at timestamp The time when the shipment was created in RFC 3339 format. updated_at timestamp The time when the shipment was last updated in RFC 3339 format. */ updateShipment(id, params) { return this.request .patch(`/v1/shipments/${id}`, params) .then(response => response.data) .catch(err => this.handleError(err)); } }
const express = require('express'); const router = express.Router(); const mongoose = require('mongoose'); const Book = require('../models/Book'); const Student = require('../models/Student'); mongoose.Promise = global.Promise; const passport = require('passport'); require('../config/passport')(passport); const protect = passport.authenticate('jwt', { session: false, }); router.get('/', (req, res) => { const book = { welcome_message: 'Book model', book: { _student: 'book owner id', title: 'title of book', summary: 'description >= 30 char', tags: [], active: 'status of book == true or false', chapters: [], }, }; res.json(book); }); // create new book to student login router.post('/:login', protect, (req, res) => { Student.findOne({ login: req.params.login, }) .then((student) => { //Token verification if ((req.user.login) == (student.login)) { req.body._students = student; Book.create(req.body).then((book) => { Student.findByIdAndUpdate(student._id, { $push: { books: [book], }, }) .catch((err) => { // todo-> error handling@can't update student res.status(400); res.json(err); }); res.json(book); }).catch((err) => { // todo-> error handling@can't create book res.status(400); res.json(err); }); } else { res.status(400); res.json({ error: 'This token does not refer to this person.', }); } }).catch(() => { // if not found student res.status(404); res.end(); }); }); // all books from login router.get('/:login', protect, (req, res) => { Student.findOne({ login: req.params.login, }) .then((student) => { Book.find({ _students: student._id, }).then((books) => { //Token verification if ((req.user.login) == (req.params.login)) { res.json(books); } else { res.status(400); res.json({ error: 'This token does not refer to this person.', }); } }).catch((err) => { res.status(400); res.json(err); }); }).catch((err) => { res.status(400); res.end(); }); }); // book by id router.get('/id/:book_id/', protect, (req, res) => { Book.findById(req.params.book_id).then((book) => { //Token verification if (book._students.indexOf(String(req.user._id)) == 0) { res.json(book); } else { res.status(400); res.json({ error: 'This token does not refer to this person.', }); res.end(); } }).catch((err) => { // todo-> error handling@can't find book id res.status(400); res.json({ error: 'book not found', }); }); }); // update book by id router.put('/id/:book_id', protect, (req, res) => { Book.findById(req.params.book_id).then((book) => { //find book_id in books of student(Token verification) if (req.user.books.indexOf(req.params.book_id) != -1) { Book.findByIdAndUpdate(req.params.book_id, req.body).then((updatedBook) => { res.status(200).send('Updated') }).catch((err) => { // todo-> error handling@can't update book id res.status(400); res.json(err); }); } else { res.status(400); res.json({ error: 'This token does not refer to this person.', }); } }).catch((err) => { // todo-> error handling@can't update book id res.status(400); res.json(err); }); }); // delete book by id router.delete('/id/:book_id', protect, (req, res) => { Book.findById(req.params.book_id).then((book) => { //find book_id in books of student(Token verification) if (req.user.books.indexOf(req.params.book_id) != -1) { Book.findByIdAndRemove(req.params.book_id).then((removedBook) => { Student.findByIdAndUpdate(req.user._id, { $pull: { books: [removedBook], }, }) .catch((err) => { // todo-> error handling@can't pull book in student array res.status(400); res.json(err); }); }).catch((err) => { // todo-> error handling@can't delete book res.status(400); res.json(err); }); } else { if (book != null) { res.status(400); res.json({ error: 'This token does not refer to this person.', }); } else { res.status(404).json({ error: 'Book not found' }) } } res.json({ status: 'Sucesso' }) }).catch((err) => { // todo-> error handling@can't find book res.status(404); res.json(err); }); }); module.exports = router;
import React, {Fragment} from 'react'; import PropTypes from 'prop-types'; import withStyles from "@material-ui/core/styles/withStyles"; import Drawer from '@material-ui/core/Drawer'; import HomeIcon from '@material-ui/icons/Menu'; import List from '@material-ui/core/List'; import Divider from '@material-ui/core/Divider'; import IconButton from "@material-ui/core/IconButton/IconButton"; import {Link} from 'react-router-dom'; import FaBook from 'react-icons/lib/fa/book'; import FaUserLock from 'react-icons/lib/fa/user-secret'; import FaHome from 'react-icons/lib/fa/home'; import FaStickyNote from 'react-icons/lib/fa/sticky-note'; import MdAddBox from 'react-icons/lib/md/add-box'; import MdPersonAdd from 'react-icons/lib/md/person-add'; import People from 'react-icons/lib/md/people'; import MdInfoOutline from 'react-icons/lib/md/info-outline'; import MdLockOutline from 'react-icons/lib/md/lock-outline'; import {connect} from 'react-redux'; const styles = { list: { width: 350, paddingTop: '15px' }, fullList: { width: 'auto', }, icon: { fontSize: '40px', marginRight: '15px', marginLeft: '10px', color: '#65446d' }, testIcon: { fontSize: '25px', color: '#65446d', marginLeft: '15px', }, text: { textDecoration: 'none', color: '#404040', cursor: 'pointer', display: 'block', '&:hover': { background: "#ebebeb" } }, textLine: { marginBottom: '20px', paddingTop: '20px', color: '#404040', }, nested: { paddingLeft: '15px', }, listItemText: { color: '#65446d', } }; class Sidebar extends React.Component { state = { left: false, openItem: true }; toggleDrawer = (side, open) => () => { this.setState({ [side]: open, }); }; render() { const {classes} = this.props; const sideList = ( <div className={classes.list}> <Link className={classes.text} to='/blocks'> <List> <FaHome className={classes.icon}/> <Link className={classes.textLine} to="/blocks">На главную</Link> </List> </Link> <Divider/> <Link className={classes.text} to='/changePassword'> <List> <FaUserLock className={classes.icon}/> <Link className={classes.textLine} to="/changePassword">Сменить пароль</Link> </List> </Link> {/*<Divider/>*/} {/*<Link className={classes.text} to='/reviews'>*/} {/* <List>*/} {/* <FaStickyNote className={classes.icon}/>*/} {/* <Link className={classes.textLine} to="/reviews">Мои рецензии</Link>*/} {/* </List>*/} {/*</Link>*/} <Divider/> <Link className={classes.text} to='/contacts'> <List className={classes.textLine} id='contacts'> <FaBook className={classes.icon}/> <Link className={classes.textLine} to="/contacts">Контакты</Link> </List> </Link> {this.props.user.role === 'admin' ? <Fragment> <Divider/> <Link className={classes.text} to='/admin'> <List> <MdAddBox className={classes.icon}/> <Link className={classes.textLine} to="/admin">Добавить секцию</Link> </List> </Link> </Fragment> : null} {/*{this.props.user.role === 'admin' ?*/} {/* <Fragment>*/} {/* <Divider/>*/} {/* <Link className={classes.text} to='/addPsychologist'>*/} {/* <List id='addNewPsycho'>*/} {/* <MdPersonAdd className={classes.icon}/>*/} {/* <Link className={classes.textLine} to="/addPsychologist">Добавить психолога</Link>*/} {/* </List>*/} {/* </Link>*/} {/* </Fragment>*/} {/* : null*/} {/*}*/} {this.props.user.role === 'admin' ? <Fragment> <Divider/> <Link className={classes.text} to='/users'> <List> <People className={classes.icon}/> <Link className={classes.textLine} to="/users">Все пользователи</Link> </List> </Link> </Fragment> : null } {/*<Divider/>*/} {/*<Link className={classes.text} to='/privacy'>*/} {/* <List>*/} {/* <MdLockOutline className={classes.icon}/>*/} {/* <Link className={classes.textLine} to="/privacy">Политика конфиденциальности</Link>*/} {/* </List>*/} {/*</Link>*/} <Divider/> <Link className={classes.text} to='/aboutUs'> <List> <MdInfoOutline className={classes.icon}/> <Link className={classes.textLine} to="/aboutUs">О нас</Link> </List> </Link> </div> ); return ( <Fragment> <IconButton onClick={this.toggleDrawer('left', true)} className={classes.menuButton} color="inherit" aria-label="Menu" id="hamburger" > <HomeIcon/> </IconButton> <Drawer open={this.state.left} onClose={this.toggleDrawer('left', false)}> <div tabIndex={0} role="button" onClick={this.toggleDrawer('left', false)} onKeyDown={this.toggleDrawer('left', false)} > {sideList} </div> </Drawer> </Fragment> ); } } Sidebar.propTypes = { classes: PropTypes.object.isRequired, }; const mapStateToProps = state => { return { user: state.users.user } }; export default connect(mapStateToProps, null)(withStyles(styles)(Sidebar));
import { workoutReducer } from '../workoutReducer'; import * as actions from '../../actions'; describe('workoutReducer reducer', () => { it('should return initial state', () => { expect(workoutReducer(undefined, {})).toEqual([]) }) })
export class Storage { constructor() { } static read(name) { try { return JSON.parse(window.localStorage.getItem(name)) } catch (e) { console.log(e) } return null } static write(name, value) { try { if (value == null) { localStorage.removeItem(name) } else { localStorage.setItem(name, JSON.stringify(value)) } } catch (e) { console.log(e) } } }
import BottomNav from './BottomNav' import CommunityDrawer from './CommunityDrawer' import CommunityStack from './CommunityStack' import EventLocation from './EventLocation' import RunTracker from './RunTracker' export { BottomNav, CommunityDrawer, CommunityStack, EventLocation, RunTracker }
const ajax = { /** * ajax封装 * url 发送请求的地址 * data 发送到服务器的数据,数组存储,如:{"date": new Date().getTime(), "state": 1} * async 默认值: true。默认设置下,所有请求均为异步请求。如果需要发送同步请求,请将此选项设置为 false。 * 注意,同步请求将锁住浏览器,用户其它操作必须等待请求完成才可以执行。 * type 请求方式("POST" 或 "GET"), 默认为 "GET" * dataType 预期服务器返回的数据类型,常用的如:xml、html、json、text * successfn 成功回调函数 * errorfn 失败回调函数 */ get: function (url, p1, p2, p3) { let param, func, errorFunc; const deferred = $.Deferred(); if (typeof(p1) === 'object' && p2 === undefined) { param = p1; } else if (typeof(p1) === 'function') { func = p1; errorFunc = p2; } else if (typeof(p1) === 'object' && typeof(p2) === 'function') { param = p1; func = p2; errorFunc = p3; } else if (p1 === undefined && p2 === undefined) { } else { util.hideLoading('*'); layer.alert('error parameter, please see'); deferred.reject(); return deferred.promise(); } $.ajax({ type: "GET", url: url, data: param, // headers: { // bukrs: $.cookie('bukrs') // }, success: function (rs) { if (rs.code === 'SUCCESS') { func && func(rs.data); deferred.resolve(rs.data); } else { if (errorFunc) { errorFunc(rs); } else { util.hideLoading('*'); layer.alert(rs.code + "<br>" + (rs.message && rs.message.replace(/\n/g,'<br>'))); } deferred.reject(); } }, error: function (err) { util.hideLoading('*'); layer.alert(JSON.stringify(err)); deferred.reject(); } }); return deferred.promise(); }, /** * ajax封装 * url 发送请求的地址 * data 发送到服务器的数据,数组存储,如:{"date": new Date().getTime(), "state": 1} * dataType 预期服务器返回的数据类型,常用的如:xml、html、json、text * successfn 成功回调函数 * errorfn 失败回调函数 */ post: function (url, p1, p2, p3) { var param, func, errorFunc; var deferred = $.Deferred(); if (typeof(p1) === 'object' && p2 === undefined) { param = p1; } else if (typeof(p1) === 'function') { func = p1; errorFunc = p2; } else if (typeof(p1) === 'object' && typeof(p2) === 'function') { param = p1; func = p2; errorFunc = p3; } else if (p1 === undefined && p2 === undefined) { } else { util.hideLoading('*'); layer.alert('error parameter, please see'); deferred.reject(); return deferred.promise(); } $.ajax({ type: "POST", url: url, data: param, // headers: { // bukrs: $.cookie('bukrs') // }, success: function (rs) { if (rs.code === 'SUCCESS') { func && func(rs.data); deferred.resolve(rs.data); } else { if (errorFunc) { errorFunc(rs); } else { util.hideLoading('*'); layer.alert(rs.code + "<br>" + (rs.message && rs.message.replace(/\n/g,'<br>'))); } deferred.reject(); } }, error: function (err) { util.hideLoading('*'); layer.alert(JSON.stringify(err)); deferred.reject(); } }); return deferred.promise(); }, postJson: function (url, p1, p2, p3) { let param, func, errorFunc; const deferred = $.Deferred(); if (typeof(p1) === 'object' && p2 === undefined) { param = p1; } else if (typeof(p1) === 'function') { func = p1; errorFunc = p2; } else if (typeof(p1) === 'object' && typeof(p2) === 'function') { param = p1; func = p2; errorFunc = p3; } else if (p1 === undefined && p2 === undefined) { } else { util.hideLoading('*'); layer.alert('error parameter, please see'); deferred.reject(); return deferred.promise(); } $.ajax({ contentType: 'application/json', type: "POST", url: url, data: JSON.stringify(param), // headers: { // bukrs: $.cookie('bukrs') // }, dataType: 'json', success: function (rs) { if (rs.code === 'SUCCESS') { func && func(rs.data); deferred.resolve(rs.data); } else { if (errorFunc) { errorFunc(rs); } else { util.hideLoading('*'); layer.alert(rs.code + "<br>" + (rs.message && rs.message.replace(/\n/g,'<br>'))); } deferred.reject(); } }, error: function (err) { util.hideLoading('*'); layer.alert(JSON.stringify(err)); deferred.reject(); } }); return deferred.promise(); } }; /** * 工具类 */ const util = { uuid: function () { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { const r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); }).replace(/-/g, '').toUpperCase(); }, /** * 在selector上增加loading层. 使用方法: util.showLoading('body'); util.showLoading('.container'); util.showLoading('#wrapper') * @param selector jQuery选择器 */ showLoading: function (selector) { $(selector).showLoading(); }, /** * 隐藏selector上的loading层. 使用方法同showLoading * @param selector jQuery选择器 */ hideLoading: function (selector) { $(selector).hideLoading(); } }
let helpers = { transformThreeD: function(e, x, xUnit, y, yUnit, z, zUnit) { e.style.webkitTransform = "translate3d(" + x + xUnit + ", " + y + yUnit + ", " + z + zUnit + ")"; e.style.MozTransform = "translate3d(" + x + xUnit + ", " + y + yUnit + ", " + z + zUnit + ")"; e.style.OTransform = "translate3d(" + x + xUnit + ", " + y + yUnit + ", " + z + zUnit + ")"; e.style.transform = "translate3d(" + x + xUnit + ", " + y + yUnit + ", " + z + zUnit + ")"; }, transformRotate: function(e, value) { e.style.webkitTransform = 'rotate(' + value + 'deg) translateZ(0)'; e.style.MozTransform = 'rotate(' + value + 'deg) translateZ(0)'; e.style.OTransform = 'rotate(' + value + 'deg) translateZ(0)'; e.style.transform = 'rotate(' + value + 'deg) translateZ(0)'; }, position: function(base, range, relativeY, offset) { let returnVal = base + helpers.limit(0, 1, relativeY - offset) * range; return returnVal; }, limit: function(min, max, value) { return Math.max(min, Math.min(max, value)); }, prefix(obj, prop, value) { let prefs = ['webkit', 'Moz', 'O', 'ms']; for (let pref in prefs) { if ({}.hasOwnProperty.call(prefs, pref)) { obj[prefs[pref] + prop] = value; } } } }; let { transformThreeD, transformRotate, position, prefix } = helpers; let { findDOMNode } = ReactDOM; let logo = "https://s3.amazonaws.com/underbelly/playground/rio/logo.png", cardbox = { lid : "https://s3.amazonaws.com/underbelly/playground/rio/lid-lip.png", lidBack : "https://s3.amazonaws.com/underbelly/playground/rio/lid-open.png", front : "https://s3.amazonaws.com/underbelly/playground/rio/box-front-01.png", card : "https://s3.amazonaws.com/underbelly/playground/rio/card.png" }, hero = "https://s3.amazonaws.com/underbelly/playground/rio/two-cards.jpg"; const images = { 'logo': 'https://s3.amazonaws.com/underbelly/website/work/run-it-once/hero/logo.svg', 'hero': 'https://s3.amazonaws.com/underbelly/website/work/run-it-once/hero/hero.jpg', 'cardbox': { 'lid': 'https://s3.amazonaws.com/underbelly/website/work/run-it-once/hero/lid-lip.png', 'lidBack': 'https://s3.amazonaws.com/underbelly/website/work/run-it-once/hero/lid-open.png', 'front': 'https://s3.amazonaws.com/underbelly/website/work/run-it-once/hero/box-front-01.png', 'card': 'https://s3.amazonaws.com/underbelly/website/work/run-it-once/hero/card.png' }, 'deck': { 'one': 'https://s3.amazonaws.com/underbelly/website/work/run-it-once/deck/01.png', 'two': 'https://s3.amazonaws.com/underbelly/website/work/run-it-once/deck/02.png', 'three': 'https://s3.amazonaws.com/underbelly/website/work/run-it-once/deck/03.png', 'four': 'https://s3.amazonaws.com/underbelly/website/work/run-it-once/deck/04.png', 'five': 'https://s3.amazonaws.com/underbelly/website/work/run-it-once/deck/05.png', 'six': 'https://s3.amazonaws.com/underbelly/website/work/run-it-once/deck/06.png' }, 'gallery': { 'one': 'https://s3.amazonaws.com/underbelly/website/work/run-it-once/gallery/01-no-border.jpg', 'two': 'https://s3.amazonaws.com/underbelly/website/work/run-it-once/gallery/02-no-border.jpg', 'three': 'https://s3.amazonaws.com/underbelly/website/work/run-it-once/gallery/03-no-border.jpg' }, 'cards': { 'one': 'https://s3.amazonaws.com/underbelly/website/work/run-it-once/cards/1.png', 'two': 'https://s3.amazonaws.com/underbelly/website/work/run-it-once/cards/2.png', 'three': 'https://s3.amazonaws.com/underbelly/website/work/run-it-once/cards/3.png' }, 'gallery2': { 'one': 'https://s3.amazonaws.com/underbelly/website/work/run-it-once/gallery2/01-no-border.jpg', 'two': 'https://s3.amazonaws.com/underbelly/website/work/run-it-once/gallery2/02-no-border.jpg', 'three': 'https://s3.amazonaws.com/underbelly/website/work/run-it-once/gallery2/03-no-border.jpg' }, 'lifestyle': 'https://s3.amazonaws.com/underbelly/website/work/fluid/lifestyle/01.jpg', 'seeMore': { 'one': 'https://s3.amazonaws.com/underbelly/website/work/see-more/hive.jpg', 'two': 'https://s3.amazonaws.com/underbelly/website/work/see-more/just-family.jpg', 'three': 'https://s3.amazonaws.com/underbelly/website/work/see-more/nsac.jpg', 'four': 'https://s3.amazonaws.com/underbelly/website/work/see-more/rent-tree.jpg' } }; class RioHero extends React.Component { constructor(props) { super(props); this.onScroll = this.onScroll.bind(this); this.onResize = this.onResize.bind(this); this.update = this.update.bind(this); this.onLoad = this.onLoad.bind(this); this.requestTick = this.requestTick.bind(this); this.state = { 'loaded': false }; } copmonentDidUpdate() { this.height = this.element.clientHeight; } componentDidMount() { this.lastKnownScroll = 0; this.ticking = false; this.dimensions = this.element.getBoundingClientRect(); this.cardboxNodes = document.querySelectorAll('.cardbox__item'); this.cardboxArray = [].slice.call(this.cardboxNodes); this.viewportHeight = window.innerHeight || document.documentElement.clientHeight; window.addEventListener('scroll', this.onScroll, false); window.addEventListener('resize', this.onResize, false); } componentWillUnmount() { window.removeEventListener('scroll', this.onScroll, false); window.removeEventListener('resize', this.onResize, false); } onScroll() { if (this.props.parallax) { this.requestTick(); } } onResize() { this.lastKnownScroll = window.pageYOffset; this.dimensions = this.element.getBoundingClientRect(); this.viewportHeight = window.innerHeight || document.documentElement.clientHeight; this.requestTick(); } requestTick() { if (!this.ticking) { this.ticking = true; window.requestAnimationFrame(this.update); this.dimensions = this.element.getBoundingClientRect(); this.lastKnownScroll = window.pageYOffset; } } onLoad() { this.setState({ 'loaded': true }); } update() { let scroll = this.lastKnownScroll; let cardboxBottom = this.dimensions.bottom; let context = (scroll - this.viewportHeight) * -1; let relativeY = scroll / this.dimensions.height; let movement1 = this.dimensions.height * 0.11; let movement2 = this.dimensions.height * -0.11; let movement3 = this.dimensions.height * -0.05; let movement4 = this.dimensions.height * 0.01; let movement5 = this.dimensions.height * 0.165; if (context >= 0 && cardboxBottom >= 0) { transformThreeD(this.cardboxArray[0], -50, '%', position(0, movement1, relativeY, 0), 'px', 0, 'px'); transformThreeD(this.cardboxArray[1], -50, '%', position(0, movement1, relativeY, 0), 'px', 0, 'px'); transformThreeD(this.cardboxArray[2], -50, '%', position(0, movement2, relativeY * 2, 0), 'px', 0, 'px'); transformThreeD(this.cardboxArray[3], -50, '%', position(0, movement3, relativeY * 2, 0), 'px', 0, 'px'); transformThreeD(this.cardboxArray[4], -50, '%', position(0, movement4, relativeY * 2, 0), 'px', 0, 'px'); transformThreeD(this.cardboxArray[5], -50, '%', position(0, movement5, relativeY * 1.35, 0), 'px', 0, 'px'); } this.ticking = false; } render() { let { logo, cardbox } = this.props; let loaded = this.state.loaded ? "loaded" : ""; return ( <div ref={(ref) => this.element = ref} className="parallax-container hero--rio"> <div id="cardBox" className={`cardbox-container cardbox-container--intro ${loaded}`}> <div className="rio-logo"> <div className="rio-logo__inner"> <img src={logo} /> </div> </div> <div className="cardbox"> <img src={cardbox.lid} className="cardbox__item cardbox__item--lid" /> <img src={cardbox.lidBack} className="cardbox__item cardbox__item--lidback" /> <img src={cardbox.card} className="cardbox__item cardbox__item--card" /> <img src={cardbox.card} className="cardbox__item cardbox__item--card" /> <img src={cardbox.card} className="cardbox__item cardbox__item--card" /> <img onLoad={this.onLoad} src={cardbox.front} className="cardbox__item cardbox__item--front" /> </div> </div> </div> ); } } class TwoCards extends React.Component { constructor(props) { super(props); this.onLoad = this.onLoad.bind(this); this.state = { loaded: false } } componentDidMount() { let img = document.createElement('img'); img.src = this.props.hero; img.onload = this.onLoad; this.src = img.src; } onLoad() { this.setState({ loaded: true }); } render() { let { hero } = this.props; let loaded = this.state.loaded ? "loaded" : ""; let style = { backgroundImage: `url(${this.src})` } return ( <section style={style} className={`two-cards ${loaded}`}></section> ) } } class Deck extends React.Component { constructor(props) { super(props); this.onScroll = this.onScroll.bind(this); this.onResize = this.onResize.bind(this); this.update = this.update.bind(this); this.requestTick = this.requestTick.bind(this); } componentDidMount() { this.ticking = false; this.element = findDOMNode(this.refs.deck); this.fade = findDOMNode(this.refs.fade); this.fadeDimensions = this.fade.getBoundingClientRect(); this.dimensions = this.element.getBoundingClientRect(); this.deckNodes = document.querySelectorAll('.deck-cards__item'); this.deckArray = [].slice.call(this.deckNodes); this.viewportHeight = window.innerHeight || document.documentElement.clientHeight; this.windowWidth = window.innerWidth || document.documentElement.clientWidth; window.addEventListener('scroll', this.onScroll, false); window.addEventListener('resize', this.onResize, false); } componentWillUnmount() { window.removeEventListener('scroll', this.onScroll, false); window.removeEventListener('resize', this.onResize, false); } onScroll() { if (this.props.parallax) { this.requestTick(); } } onResize() { this.dimensions = this.element.getBoundingClientRect(); this.fadeDimensions = this.fade.getBoundingClientRect(); this.viewportHeight = window.innerHeight || document.documentElement.clientHeight; this.windowWidth = window.innerWidth || document.documentElement.clientWidth; this.requestTick(); } requestTick() { if (!this.ticking) { this.ticking = true; window.requestAnimationFrame(this.update); this.dimensions = this.element.getBoundingClientRect(); this.fadeDimensions = this.fade.getBoundingClientRect(); } } update() { let { viewportHeight, dimensions, fadeDimensions, windowWidth } = this; let relativeYHelper = dimensions.height > viewportHeight ? dimensions.height : viewportHeight; let deckTop = dimensions.top; let deckBottom = dimensions.bottom; let context = (deckTop - viewportHeight) * -1; let fadeContext = (fadeDimensions.top - viewportHeight) * -1; let relativeY = context / (relativeYHelper * 2); let values = []; windowWidth <= 768 ? values = [[25], [-50, -145]] : values = [[100], [0, -320]]; if (context >= 0 && deckBottom >= 0) { transformThreeD(this.deckArray[0], values[1][0], '%', position(values[0][0], values[1][1], relativeY, 0), 'px', 0, 'px'); transformThreeD(this.deckArray[1], values[1][0], '%', position(values[0][0], values[1][1], relativeY * 0.8, 0), 'px', 0, 'px'); transformThreeD(this.deckArray[2], values[1][0], '%', position(values[0][0], values[1][1], relativeY * 0.6, 0), 'px', 0, 'px'); transformThreeD(this.deckArray[3], values[1][0], '%', position(values[0][0], values[1][1], relativeY * 0.4, 0), 'px', 0, 'px'); transformThreeD(this.deckArray[4], values[1][0], '%', position(values[0][0], values[1][1], relativeY * 0.2, 0), 'px', 0, 'px'); transformThreeD(this.deckArray[5], values[1][0], '%', position(values[0][0], values[1][1], relativeY * 0.1, 0), 'px', 0, 'px'); } if (fadeContext >= this.viewportHeight * 0.1) { this.fade.style.opacity = 1; this.fade.style.webkitTransform = 'translateY(0)'; this.fade.style.MozTransform = 'translateY(0)'; this.fade.style.transform = 'translateY(0)'; } else { this.fade.style.opacity = 0; this.fade.style.webkitTransform = 'translateY(50px)'; this.fade.style.MozTransform = 'translateY(50px)'; this.fade.style.transform = 'translateY(50px)'; } this.ticking = false; } render() { let { deck } = this.props; return ( <div className="parallax-container deck" ref="deck"> <div className="deck-container"> <div ref="fade" className="deck-container__item deck-copy"> <h1>Backstory</h1> <p>Run It Once, created by legendary poker player Phil Galfond, is a place for poker enthusiasts to gather and contribute professional-level strategy with others in the poker community. Besides the wealth of knowledge available at Run It Once, RIO’s brand is one classy act. With a clean, professional, and luxurious logo its no wonder their site is one of the best looking (and functioning) poker communities out there.</p> <p>At Underbelly, we’re suckers for playing card designs. That’s one of the many reasons we were stoked to partner with Phil and the Run It Once crew on designing the first official Run It Once card deck.</p> </div> <div className="deck-container__item deck-cards"> <img src={deck.one} className="deck-cards__item" /> <img src={deck.two} className="deck-cards__item" /> <img src={deck.three} className="deck-cards__item" /> <img src={deck.four} className="deck-cards__item" /> <img src={deck.five} className="deck-cards__item" /> <img src={deck.six} className="deck-cards__item" /> </div> </div> </div> ); } } class Cards extends React.Component { constructor(props) { super(props); this.onScroll = this.onScroll.bind(this); this.onResize = this.onResize.bind(this); this.update = this.update.bind(this); this.requestTick = this.requestTick.bind(this); } componentDidMount() { this.ticking = false; this.element = findDOMNode(this.refs.cards); this.dimensions = this.element.getBoundingClientRect(); this.cardsNodes = document.querySelectorAll('.cards-cards__item'); this.cardsArray = [].slice.call(this.cardsNodes); this.fade = findDOMNode(this.refs.fade); this.fadeDimensions = this.fade.getBoundingClientRect(); this.viewportHeight = window.innerHeight || document.documentElement.clientHeight; this.windowWidth = window.innerWidth || document.documentElement.clientWidth; window.addEventListener('scroll', this.onScroll, false); window.addEventListener('resize', this.onResize, false); } componentWillUnmount() { window.removeEventListener('scroll', this.onScroll, false); window.removeEventListener('resize', this.onResize, false); } onScroll() { if (this.props.parallax) { this.requestTick(); } } onResize() { this.dimensions = this.element.getBoundingClientRect(); this.fadeDimensions = this.fade.getBoundingClientRect(); this.viewportHeight = window.innerHeight || document.documentElement.clientHeight; this.windowWidth = window.innerWidth || document.documentElement.clientWidth; if (this.props.parallax) { this.requestTick(); } } requestTick() { if (!this.ticking) { this.ticking = true; window.requestAnimationFrame(this.update); this.dimensions = this.element.getBoundingClientRect(); this.fadeDimensions = this.fade.getBoundingClientRect(); } } update() { let relativeYHelper = this.dimensions.height > this.viewportHeight ? this.dimensions.height : this.viewportHeight; let cardsTop = this.dimensions.top; let cardsBottom = this.dimensions.bottom; let context = (cardsTop - this.viewportHeight) * -1; let relativeY = context / (relativeYHelper * 2); let fadeContext = (this.fadeDimensions.top - this.viewportHeight) * -1; if (context >= 0 && cardsBottom >= 0) { transformRotate(this.cardsArray[0], position(15, -15, relativeY, 0)); transformRotate(this.cardsArray[1], position(-15, 15, relativeY, 0)); transformRotate(this.cardsArray[2], position(15, -15, relativeY, 0)); } if (fadeContext >= this.viewportHeight * 0.1) { this.fade.style.opacity = 1; this.fade.style.webkitTransform = 'translateY(0)'; this.fade.style.MozTransform = 'translateY(0)'; this.fade.style.transform = 'translateY(0)'; } else { this.fade.style.opacity = 0; this.fade.style.webkitTransform = 'translateY(50px)'; this.fade.style.MozTransform = 'translateY(50px)'; this.fade.style.transform = 'translateY(50px)'; } this.ticking = false; } render() { let { cards } = this.props; return ( <div className="parallax-container cards" ref="cards"> <div className="cards-container"> <div ref="fade" className="cards-container__item cards-copy"> <p>Matching the palatial look and feel of Run It Once’s brand was no small feat. We took multiple approaches before finally landing on a style that was sleek, geometric, and modern. Each suit was designed with a unique personality to give the deck depth and variety while still remaining true to RIO’s brand. Diamonds crafted to be rugged and adventurous, spades strong and ruthless, clubs secretive and seductive, and hearts trustworthy and approachable.</p> <p>The finished product is a world-class, unique deck of cards worthy of the most talented professional poker hands. However, no need to worry; you don’t have to have a bracelet under your belt to enjoy these cards. Anyone can purchase these beauties directly from RIO’s site- even if you’re one of those casual, low-stakes, hold-em folks. If you’re anything like us, you can’t pass up a hot deck of cards.</p> </div> <div className="card-container__item cards-cards"> <img src={cards.one} className="cards-cards__item" /> <img src={cards.two} className="cards-cards__item" /> <img src={cards.three} className="cards-cards__item" /> </div> </div> </div> ); } } class RunItOnce extends React.Component { constructor(props) { super(props); this.state = { 'parallax0': false, 'parallax1': false, 'parallax2': false, 'parallax3': false }; this.scrollManager = this.scrollManager.bind(this); this.requestTick = this.requestTick.bind(this); this.update = this.update.bind(this); } componentDidMount() { this.ticking = false; this.parallaxNodeList = document.querySelectorAll('.parallax-container'); this.parallaxArray = [].slice.call(this.parallaxNodeList); this.dimensions0 = this.parallaxArray[0].getBoundingClientRect(); this.dimensions1 = this.parallaxArray[1].getBoundingClientRect(); this.dimensions2 = this.parallaxArray[2].getBoundingClientRect(); this.viewportHeight = window.innerHeight || document.documentElement.clientHeight; window.addEventListener('scroll', this.scrollManager); window.addEventListener('resize', this.scrollManager); } comonentWillUnmount() { window.removeEventListener('scroll', this.scrollManager); window.removeEventListener('resize', this.scrollManager); } scrollManager() { this.requestTick(); } requestTick() { if (!this.ticking) { this.ticking = true; window.requestAnimationFrame(this.update); this.dimensions0 = this.parallaxArray[0].getBoundingClientRect(); this.dimensions1 = this.parallaxArray[1].getBoundingClientRect(); this.dimensions2 = this.parallaxArray[2].getBoundingClientRect(); this.viewportHeight = window.innerHeight || document.documentElement.clientHeight; } } update() { this.context0 = (this.dimensions0.top - this.viewportHeight) * -1; this.context1 = (this.dimensions1.top - this.viewportHeight) * -1; this.context2 = (this.dimensions2.top - this.viewportHeight) * -1; if (this.context0 >= 0 && this.dimensions0.bottom >= 0 && !this.state.parallax0) { this.setState({ 'parallax0': true }); } else if (this.state.parallax0 && (this.dimensions0.bottom <= 0 || this.context0 <= 0)) { this.setState({ 'parallax0': false }); } if (this.context1 >= 0 && this.dimensions1.bottom >= 0 && !this.state.parallax1) { this.setState({ 'parallax1': true }); } else if (this.state.parallax1 && (this.dimensions1.bottom <= 0 || this.context1 <= 0)) { this.setState({ 'parallax1': false }); } if (this.context2 >= 0 && this.dimensions2.bottom >= 0 && !this.state.parallax2) { this.setState({ 'parallax2': true }); } else if (this.state.parallax2 && (this.dimensions2.bottom <= 0 && this.context2 <= 0)) { this.setState({ 'parallax2': false }); } this.ticking = false; } render() { return ( <div className="case-study run-it-once"> <RioHero logo={images.logo} cardbox={images.cardbox} parallax={this.state.parallax0} /> <TwoCards hero={images.hero} /> <Deck deck={images.deck} parallax={this.state.parallax1} /> <Cards cards={images.cards} parallax={this.state.parallax2} /> </div> ); } } ReactDOM.render(<RunItOnce images={images} helpers={helpers} />, document.getElementById("app"));
var searchData= [ ['groundplanestage_101',['groundPlaneStage',['../class_a_r_handler.html#a297c5c6c349ae85b67bc40739f40a6b2',1,'ARHandler']]] ];
//---------------------------------------------------------------------- // // This source file is part of the Effects project. // // Licensed under MIT. See LICENCE for full licence information. // See CONTRIBUTORS for the list of contributors to the project. // //---------------------------------------------------------------------- const { effect } = require("../effect"); const Random = effect( "@builtin:Random", { Random: [] }, { Random(_, k) { k(null, Math.random()); } } ); const random = { random() { return Random.Random(); }, *randomInt(start, stop) { return Math.floor(start + (stop - start) * (yield random.random())); } }; module.exports = { random, Random };
/* eslint-disable */ var webpack = require('webpack'); var path = require('path'); var ROOT_PATH = path.resolve(__dirname); module.exports = { entry: [ path.resolve(ROOT_PATH, 'src/app'), 'bootstrap-loader' ], module: { loaders: [{ test: /\.js?$/, exclude: /node_modules/, loader: 'babel', query: { presets: ["es2015", "stage-0", "react"] } }, { test: /\.scss$/, loaders: ['style','css','sass'] }, { test: /\.(woff2?|ttf|eot|svg)$/, loader: 'url?limit=10000' }, { test: /bootstrap-sass\/assets\/javascripts\//, loader: 'imports?jQuery=jquery' } ]}, resolve: { extensions: ['', '.js', '.jsx'] }, output: { path: path.resolve(ROOT_PATH, 'dist'), publicPath: '/', filename: 'bundle.js' }, externals: { 'cheerio': 'window', 'react/lib/ExecutionEnvironment': true, 'react/lib/ReactContext': true, }, devServer: { contentBase: path.resolve(ROOT_PATH, 'dist'), historyApiFallback: true, hot: true, inline: true, progress: true, proxy: { path: '/horizon/*', target: 'http://localhost:8181' }, }, plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.ProvidePlugin({ jQuery: "jquery" }) ] };
"use strict"; const express = require('express'); const app = express(); const bodyParser = require('body-parser'); app.use(bodyParser.json()); const USERS = [ { id: '01', userName: 'admin', chenji: '99' }, { id: '02', userName: 'aaa', chenji: '99' } ]; let index = 1; const admin = [ { userName: 'admin', password: 'admin' }, { userName: 'root', password: 'root' } ]; app.all('*', function (req, res, next) { res.header("Access-Control-Allow-Origin", '*'); res.header("Access-Control-Allow-Headers", 'Content-Type,Content-Length,Authorization,Accept,X-Requested-With'); res.header("Access-Control-Allow-Methods", 'PUT,POST,GET,DELETE,OPTIONS'); res.header("x-Powered-By", '3.2.1') if (req.method == "OPTIONS") res.send(200); else next(); }) app.get('/hello', function (req, resp) { resp.send('哈哈哈'); resp.end(); }); app.get('/users', function (req, resp) { resp.send(USERS); resp.end(); }); app.get('/users/:id', function (req, resp) { console.log(req.params); const id = req.params.id; for (let user of USERS) { if (user.id === id) { resp.send([user]); resp.end(); return; } } resp.send({succ:false}); resp.end(); }); //添加用户 app.post('/user', function (req, resp) { USERS.push(req.body); resp.send({ succ: true }); resp.end(); }); //修改用户 app.put('/user', function (req, resp) { let founded = false; for (let user of USERS) { if (user.id === req.body.id) { user.userName = req.body.userName; user.chenji = req.body.chenji; founded = true; break; } } if (founded) { resp.send({ succ: true }); } else { resp.send({ succ: false, msg: '没有找到用户!' }); } resp.end(); }); //删除用户 app.delete('/user/:id', function (req, resp) { let founded = false; let index = 0; for (let user of USERS) { if (user.id === req.params.id) { USERS.splice(index, 1) founded = true; break; } index++; } if (founded) { resp.send({ succ: true }); } else { resp.send({ succ: false, msg: '没有找到用户!' }); } resp.end(); }); app.listen(8080, function () { console.log('服务器在8080端口启动!'); }); app.get('/admin', function (req, resp) { resp.send(admin); resp.end(); }); app.get('/admin/:userName', function (req, resp) { console.log(req.params); const userName = req.params.userName; for (let i of admin) { if (i.userName === userName) { resp.send([i]); break; } } resp.end(); }); //添加用户 app.post('/admin', function (req, resp) { admin.push(req.body); resp.send({ succ: true }); resp.end(); }); app.post('/denglu', function (req, resp) { for (let i of admin) { if (i.userName === req.body.userName && i.password === req.body.password) { resp.send({ succ: true }); resp.end(); return; } } resp.send({ succ: false }); resp.end(); }); //修改用户 app.put('/admin', function (req, resp) { let founded = false; for (let i of admin) { if (i.userName === req.body.userName) { i.userName = req.body.userName; i.password = req.body.password; founded = true; break; } } if (founded) { resp.send({ succ: true }); } else { resp.send({ succ: false, msg: '没有找到用户!' }); } resp.end(); }); //删除用户 app.delete('/admin/:id', function (req, resp) { let founded = false; let index = 0; for (let i of admin) { if (i.userName === req.params.userName) { admin.splice(index, 1) founded = true; break; } index++; } if (founded) { resp.send({ succ: true }); } else { resp.send({ succ: false, msg: '没有找到用户!' }); } resp.end(); });
define(['apps/system/system.controller', 'apps/system/system.service.organization', 'apps/system/system.service.business', 'apps/system/system.service.permission', 'apps/system/system.service.user'], function (app) { app.controller("system.controller.department", function ($scope, $stateParams, system_organization_service, system_business_service) { $scope.setTreeApi = function (api) { $scope.treeApi = api; } $scope.loadDeptTree = function () { $scope.deptPanel.block(); system_organization_service.getDepartment().then(function (source) { $scope.deptPanel.unblock(); $scope.departments = paraseTreeData(source) }); } $scope.$watch('$viewContentLoaded', function () { $scope.loadDeptTree(); }); // 将服务端数据转换为界面tree识别的数据 var paraseTreeData = function (nodes) { var newNodes = []; angular.forEach(nodes, function (node) { var newNode = {}; newNode.text = node.Name; newNode.key = node.Key; newNode.permissionValue = node.Permission; newNode.unInheritPermissionValue = node.UnInheritPermission; newNode.inheritPermissionValue = node.InheritPermission; newNode.permissions = node.Permissions; newNode.users = node.Users; newNode.state = { 'opened': true }; newNode.children = paraseTreeData(node.SubDepartments); newNodes.push(newNode); }); return newNodes; } var deptKey = ""; $scope.changed = function (e, data) { deptKey = data.node.original.key; $scope.$broadcast("$DeptSelected", data.node.original); } // 部门右键菜单 $scope.treeContextmenu = function (node) { var remove = { "label": "删除部门", "icon": "fa fa-trash", "action": function (obj) { removeDepartment(node); }, }; var create = { "label": "新建部门", "icon": "fa fa-file", "action": function (obj) { createDepartment(node); }, }; var rename = { "label": "重命名", "icon": "fa fa-edit", "action": function (obj) { renameDepartment(node); }, } return { "remove": remove, "create": create, "rename": rename }; } // 保存权限 $scope.savePermission = function (permission, callback) { system_organization_service.changeDeptPermission(deptKey, permission).then(function () { $scope.loadDeptTree(); callback(); }); } // 保存用户 $scope.saveUser = function (users, callback) { system_organization_service.changeDeptUsers(deptKey, users).then(function () { $scope.loadDeptTree(); callback(); }); } // 删除部门 var removeDepartment = function (node) { system_organization_service.removeDept(node.original.key).then(function () { $scope.treeApi.delete_node(node); }); } // 新建部门 var createDepartment = function (parentNode) { var nodeID = $scope.treeApi.create_node(parentNode, { text: "新建部门", state: { opened: true } }); $scope.treeApi.edit(nodeID, '新建部门', function (node, isRename, isCancelled) { system_organization_service.createDept(node.text, parentNode.original.key).then(function (key) { node.original.key = key; }) }); } // 部门重命名 var renameDepartment = function (node) { $scope.treeApi.edit(node, null, function (editNode, isRename, isCancelled) { system_organization_service.renameDept(editNode.text, editNode.original.key).then(function () { }) }); } }); app.controller("system.controller.department.user", function ($scope, $stateParams, system_user_service, system_organization_service) { var waitToRole = undefined; var opRoleUser = function (role) { angular.forEach($scope.users, function (user) { user.isSelected = false; angular.forEach(role.Users, function (roleUser) { if (user.ID == roleUser.ID) { user.isSelected = true; } }); }); } $scope.$watch('$viewContentLoaded', function () { $scope.userPanel.block(); system_user_service.getUsers(true, true, true).then(function (result) { $scope.users = result; if (waitToRole) { opRoleUser(waitToRole); } $scope.userPanel.unblock(); }) }); $scope.$on("$DeptSelected", function (event, dept) { $scope.$safeApply(function () { angular.forEach($scope.users, function (user) { user.isSelected = false; angular.forEach(dept.users, function (deptUser) { if (user.ID == deptUser.ID) { user.isSelected = true; } }); }); }); }); $scope.$on("$RoleSelected", function (event, role) { if ($scope.users) { opRoleUser(role); } else { waitToRole = role; } }); $scope.save = function () { $scope.userPanel.block(); var checkedUsers = []; angular.forEach($scope.users, function (user) { if (user.isSelected) { checkedUsers.push(user); } }); $scope.saveUser(checkedUsers, function () { $scope.userPanel.unblock(); }) } }); app.controller("system.controller.department.permission", function ($scope, $rootScope, $stateParams, system_permission_service, system_organization_service) { var loadPermission = function (business) { $scope.permissionPanel.block(); system_permission_service.all(1, business.Key).then(function (source) { $scope.uiPermissions = paraseTreeData(source,0); $scope.permissionPanel.unblock(); }); system_permission_service.all(2, business.Key).then(function (source) { $scope.dataPermissions = paraseTreeData(source,0); }); system_permission_service.all(3, business.Key).then(function (source) { $scope.apiPermissions = paraseTreeData(source,0); }); } // 将服务端数据转换为界面tree识别的数据 var paraseTreeData = function (nodes,deep) { var newNodes = []; angular.forEach(nodes, function (node) { var newNode = {}; newNode.text = node.Name; newNode.state = { 'opened': deep == 0, selected: false }; newNode.Index = node.Index; newNode.Value = node.Value; newNode.StrValue = node.StrValue; newNode.ID = node.ID; newNode.CanInherit = node.CanInherit; newNode.OrgCanInherit = node.OrgCanInherit; newNode.children = paraseTreeData(node.Children, deep+1); newNodes.push(newNode); }); return newNodes; } var isInherit = function (permission, data) { if (permission && permission[data.Index] && new BigInt(permission[data.Index]).permissionCheck(new BigInt(data.StrValue))) { return true; } else { return false; } } var treeReady = false; var enableContextmenu = true; var waitToRole = undefined; var waitToDept = undefined; var opRole = function (role, treeApi) { enableContextmenu = false; treeApi.deselect_all(); for (var id in treeApi._model.data) { if (id == "#") { continue; } var node = treeApi._model.data[id]; var data = node.original; var v = role.PermissionValue[data.Index]; if (v && new BigInt(data.StrValue).permissionCheck(new BigInt(v))) { treeApi.select_node(node); } } } var opDept = function (dept, treeApi) { enableContextmenu = true; treeApi.deselect_all(); $scope.$safeApply(function () { for (var id in treeApi._model.data) { if (id == "#") { continue; } var node = treeApi._model.data[id]; var data = node.original; if (!data.CanInherit) { treeApi.rename_node(node, data.text + "<span class='inheritTag'>[禁止继承_权限]</span>"); } else { treeApi.rename_node(node, data.text); } treeApi.enable_node(node); if (dept.permissionValue && new BigInt(data.StrValue).permissionCheck(new BigInt(dept.permissionValue[data.Index]))) { treeApi.select_node(node); node.original.OrgCanInherit = !isInherit(dept.unInheritPermissionValue, data); node.original.IsInherit = isInherit(dept.inheritPermissionValue, data); if (node.original.IsInherit) { treeApi.rename_node(node, data.text + "<span class='inheritTag'>[继承]</span>"); treeApi.disable_node(node); } else if (!node.original.OrgCanInherit) { treeApi.rename_node(node, data.text + "<span class='inheritTag'>[禁止继承_部门]</span>"); } } } }) } $scope.$on('businessChanged', function (e, business) { if (business) { loadPermission(business); } else { $scope.uiPermissions = []; $scope.dataPermissions = []; $scope.apiPermissions = []; } }); $scope.$watch('$viewContentLoaded', function (e) { if ($scope.currentBusiness) { loadPermission($scope.currentBusiness); } }); $scope.$watch('currentIndex', function (newVal, oldVal) { if ($scope.permissionScroller) { $scope.permissionScroller.init(); } }); $scope.permissionChanged = function (e, data) { if (data.node && !data.node.state.selected && data.node.original.CanInherit) { $scope.uiTreeApi.rename_node(data.node, data.node.original.text); } } $scope.dataPermissionChanged = function (e, data) { if (data.node && !data.node.state.selected && data.node.original.CanInherit) { $scope.dataTreeApi.rename_node(data.node, data.node.original.text); } } $scope.apiPermissionChanged = function (e, data) { if (data.node && !data.node.state.selected && data.node.original.CanInherit) { $scope.apiTreeApi.rename_node(data.node, data.node.original.text); } } var treeReady1 = false, treeReady2 = false, treeReady3 = false; $scope.treeReady1 = function (e, data) { treeReady1 = true; if (waitToRole) { opRole(waitToRole, $scope.uiTreeApi); } if (waitToDept) { opDept(waitToDept, $scope.uiTreeApi); } if ($scope.uiTreeScroll) { $scope.uiTreeScroll.init(); } } $scope.treeReady2 = function (e, data) { treeReady2 = true; if (waitToRole) { opRole(waitToRole, $scope.dataTreeApi); } if (waitToDept) { opDept(waitToDept, $scope.dataTreeApi); } if ($scope.dataTreeScroll) { $scope.dataTreeScroll.init(); } } $scope.treeReady3 = function (e, data) { treeReady3 = true; if (waitToRole) { opRole(waitToRole, $scope.apiTreeApi); } if (waitToDept) { opDept(waitToDept, $scope.apiTreeApi); } if ($scope.apiTreeScroll) { $scope.apiTreeScroll.init(); } } $scope.$on("$RoleSelected", function (event, role) { waitToRole = role; if (treeReady1) { opRole(role, $scope.uiTreeApi); } if (treeReady2) { opRole(role, $scope.dataTreeApi); } if (treeReady3) { opRole(role, $scope.apiTreeApi); } }); $scope.$on("$DeptSelected", function (event, dept) { waitToDept = dept; if (treeReady1) { opDept(dept, $scope.uiTreeApi); } if (treeReady2) { opDept(dept, $scope.dataTreeApi); } if (treeReady3) { opDept(dept, $scope.apiTreeApi); } }); $scope.treeContextmenu = function (node) { if ((node.state && node.state.disabled) || node.original.CanInherit == false || !enableContextmenu) { return null; } var canInherit = { "label": "允许继承", "action": function (obj) { node.original.OrgCanInherit = true; $scope.uiTreeApi.rename_node(node, node.original.text); } } var disInherit = { "label": "不允许继承", "action": function (obj) { node.original.OrgCanInherit = false; $scope.uiTreeApi.rename_node(node, node.original.text + "<span class='inheritTag'>[禁止继承_部门]</span>"); }, } return { "canInherit": canInherit, "disInherit": disInherit }; } $scope.save = function () { $scope.permissionPanel.block(); var uiNodes = $scope.uiTreeApi.get_selected(true); var dataNodes = $scope.dataTreeApi.get_selected(true); var apiNodes = $scope.apiTreeApi.get_selected(true); var permissions = {}; var unInheritPermissions = {}; getPermission(uiNodes, permissions, unInheritPermissions); getPermission(dataNodes, permissions, unInheritPermissions); getPermission(apiNodes, permissions, unInheritPermissions); $scope.savePermission({ Permissions: permissions, UnInheritPermissions: unInheritPermissions }, function () { $rootScope.$broadcast("permissionChanged"); $scope.permissionPanel.unblock(); }); } var getPermission = function (nodes, permissions, unInheritPermissions) { angular.forEach(nodes, function (node) { var data = node.original; // 排除掉继承来的权限 if (!node.state.disabled) { if (permissions[data.Index]) { permissions[data.Index].push(data.StrValue); } else { permissions[data.Index] = [data.StrValue]; } if (!data.OrgCanInherit) { if (unInheritPermissions[data.Index]) { unInheritPermissions[data.Index].push(data.StrValue); } else { unInheritPermissions[data.Index] = [data.StrValue]; } } } }); } }); });
export const SET_SORTED = 'SET_SORTED'
/* eslint-disable no-console */ const mongoose = require('mongoose'); const { db } = require('../../configs'); class MongoDB { constructor() { this.uris = db.mongo.uris; this.db = null; } connect() { if (this.db) { return this.db; } mongoose.connect(this.uris, { useNewUrlParser: true }); this.db = mongoose.connection; this.db.on('error', err => console.log(`FAIL: connection error: ${err}`)); this.db.once('open', () => console.log(`SUCCESS: DB connected to ${this.db.client.s.url}`)); return this.db; } } module.exports = new MongoDB();
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _variables = require("./variables"); var _variables2 = _interopRequireDefault(_variables); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var styleVariables = { boxShadow: { sm: { boxShadow: "0 1px 4px rgba(0, 0, 0, .5)" }, md: { boxShadow: "0 1px 10px rgba(0, 0, 0, .5)" }, lg: { boxShadow: "0 5px 15px rgba(0,0,0,.5)" }, li: { boxShadow: "0 -1px 0 #e5e5e5,0 0 2px rgba(0,0,0,.12),0 2px 4px rgba(0,0,0,.24)" } }, t: { caption: { fontSize: "12px", fontWeight: "400", color: _variables2.default.grey.dark }, display4: { fontSize: "112px", fontWeight: "300" }, display3: { fontSize: "56px", fontWeight: "400px" }, display2: { fontSize: "45px", fontWeight: "400" }, display1: { fontSize: "34px", fontWeight: "400" }, headline: { fontSize: "24px", fontWeight: "500", margin: "0 0 10px" }, title: { fontSize: "20px", fontWeight: "50px", margin: "0 0 10px" }, subheading: { fontSize: "16px", fontWeight: "400", margin: "0 0 10px" }, body2: { fontSize: "14px", fontWeight: "500" }, body1: { fontSize: "14px", fontWeight: "400" } }, BgColors: { greyXxDark: { background: _variables2.default.grey.xXDark }, greyXDark: { background: _variables2.default.grey.xDark }, greyDark: { background: _variables2.default.grey.dark }, greyDarkMid: { background: _variables2.default.grey.darkMid }, greyMid: { background: _variables2.default.grey.mid }, greyLightMid: { background: _variables2.default.grey.lightMid }, greyLight: { background: _variables2.default.grey.light }, greyXLight: { background: _variables2.default.grey.xLight }, greyXxlight: { background: _variables2.default.grey.xXLight } } }; exports.default = styleVariables;
//==================================================================== // Node4Max - p5.js communication // with socket.io // // by Timo Hoogland (c) 2020, www.timohoogland.com // MIT License //==================================================================== // variables for user interface objects var inPort, outPort, ipHost, inSubmit; let color = [255, 255, 255, 255]; function setup(){ createCanvas(windowWidth, windowHeight-50); menu(); setupOsc('127.0.0.1', 12000, 8000); } function draw(){ background(0, 20); fill(color); noStroke(); ellipse(mouseX, mouseY, 50, 50); // send x and y position of mouse sendOsc('/pointer/x', mouseX/width); sendOsc('/pointer/y', (height-mouseY)/height); } // create some user interface objects to set ip and port numbers function menu(){ ipHost = createInput('127.0.0.1'); inPort = createInput('12000'); outPort = createInput('8000'); inSubmit = createButton("MAKE CONNECTION"); inSubmit.mousePressed(() => { setupOsc(ipHost.value(), inPort.value(), outPort.value()); }); } // send an osc message over specified port function sendOsc(address, value){ socket.emit('message', [address, value]); } // setup the osc message send and receive ports // set isConnected to true when connection established // specify number for incoming port and outgoing port function setupOsc(hostIn, oscPortIn, oscPortOut){ socket = io.connect("http://" + hostIn + ":" + oscPortOut); socket.on('connect', function() { socket.emit('config', { server: { port: oscPortIn, host: hostIn}, client: { port: oscPortOut, host: hostIn} }); }); socket.on('connect', function(){ console.log('connected:', hostIn, oscPortIn, oscPortOut); }); socket.on('message', function(msg){ console.log('received:', ...msg); if (msg[0] == '/color'){ color = msg.slice(1, 4); } }); }
import path from 'path' import git from '..' describe('findRoot', () => { test('__dirname', async () => { let root = await git().findRoot(__dirname) expect(path.basename(root)).toBe('isomorphic-git') }) test('.', async () => { let root = await git().findRoot(path.resolve('.')) expect(path.basename(root)).toBe('isomorphic-git') }) test('..', async () => { let root = git().findRoot(path.resolve('..')) expect(root).rejects.toBeDefined }) })
// Copyright 2013 William Malone (www.williammalone.com) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. (function() { // http://paulirish.com/2011/requestanimationframe-for-smart-animating/ // http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating // requestAnimationFrame polyfill by Erik Möller. fixes from Paul Irish and Tino Zijdel // MIT license let lastTime = 0; const vendors = ['ms', 'moz', 'webkit', 'o']; for (let x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { window.requestAnimationFrame = window[`${vendors[x]}RequestAnimationFrame`]; window.cancelAnimationFrame = window[`${vendors[x]}CancelAnimationFrame`] || window[`${vendors[x]}CancelRequestAnimationFrame`]; } if (!window.requestAnimationFrame) window.requestAnimationFrame = function(callback, element) { const currTime = new Date().getTime(); const timeToCall = Math.max(0, 16 - (currTime - lastTime)); const id = window.setTimeout(() => { callback(currTime + timeToCall); }, timeToCall); lastTime = currTime + timeToCall; return id; }; if (!window.cancelAnimationFrame) window.cancelAnimationFrame = function(id) { clearTimeout(id); }; }()); /** * Create sprite animation loop * @param options = {canvas , image, width , height , frames , tick} */ const makeSpriteLoop = options => { let spriteLoop = {}; const gameLoop = () => { const isPaused = window[`${options.canvas}_RAF_Paused`] || false; window.requestAnimationFrame(gameLoop); if (!isPaused) { spriteLoop.update(); spriteLoop.render(); } }; const sprite = options => { let that = {}, frameIndex = 0, tickCount = 0; const ticksPerFrame = options.ticksPerFrame || 0, numberOfFrames = options.numberOfFrames || 1; that.context = options.context; that.width = options.width; that.height = options.height; that.image = options.image; that.update = () => { tickCount += 1; if (tickCount > ticksPerFrame) { tickCount = 0; // If the current frame index is in range if (frameIndex < numberOfFrames - 1) { // Go to the next frame frameIndex += 1; } else { frameIndex = 0; } } }; that.render = function(frameIndexPassed = '') { if (frameIndexPassed !== '') { frameIndex = frameIndexPassed; } // Clear the canvas that.context.clearRect(0, 0, that.width, that.height); // Draw the animation that.context.drawImage( that.image, frameIndex * that.width / numberOfFrames, 0, that.width / numberOfFrames, that.height, 0, 0, that.width / numberOfFrames, that.height ); }; return that; }; // Get canvas const canvas = document.getElementById(options.canvas); canvas.width = options.width; canvas.height = options.height; // Create sprite sheet const spriteImage = new Image(); // Create sprite spriteLoop = sprite({ context : canvas.getContext('2d'), width : (options.frames * options.width), height : options.height, image : spriteImage, numberOfFrames: options.frames, ticksPerFrame : options.tick }); // Load sprite sheet spriteImage.addEventListener('load', gameLoop); spriteImage.src = options.image; }; export default makeSpriteLoop;