text
stringlengths
7
3.69M
require('virtual-dom')
/* * `merge` agreegates any number of sources as if they were one. It doesn't * change values in any way. * * It's usage is slightly different than other processors. Here's the general * syntax: * * ``` * const mergedSource = merge(sourceA, sourceB) * const subscriber = process(mergedSource) * ``` * * ``` * merge(sourceA, sourceB) * ``` * sourceA o---o---o--o----o * sourceB --x----x-x---x--- * emits o-x-o--xox-o-x--o * */ import forEach from 'ramda/src/forEach' export default (...eventSources) => (next) => { forEach((source) => source(next), eventSources) }
module.exports = { plugins: [ ['module-resolver', { root: ['./'], alias: { '@': './', actions: './src/store/actions', components: './src/components/', reducers: './src/store/reducers/', }, }], ], };
describe('Test Module Context', function () { var moduleContext = require('../../../lib/util/module-context'); var should = require('should'); it('should fail with no specified module', function () { (function () { moduleContext(); }).should.throw('No module specified'); }); it('should fail with invalid module', function () { [ undefined, null, false, true, void 0, -1, 0, 1, '', '-1', '0', '1', function () {}, /./i, [] ].forEach(function (invalidModule) { (function () { moduleContext(invalidModule); }).should.throw('Invalid module argument'); }); }); it('should fail when no name is provided for the specified module', function () { (function () { moduleContext({}); }).should.throw('Module has no name'); }); it('should create valid isntance', function () { var module = { name: 'test' }; var config = { foo: { bar: { buz: { meh: 'Hello World!' } } } }; var ctx = moduleContext(module, config); ctx.constructor.name.should.equal('ModuleContext'); ctx.should.have.ownProperty('_module').equal(module); ctx.should.have.ownProperty('_config').equal(config); ctx.should.have.ownProperty('config').be.a.Function; ctx.config('foo.bar.buz.meh').should.equal('Hello World!'); }); it('should ignore invalid config argument', function () { var module = { name: 'test' }; var ctx = moduleContext(module); ctx.constructor.name.should.equal('ModuleContext'); ctx.should.have.ownProperty('_module').equal(module); ctx.should.have.ownProperty('_config').and.be.an.Object.eql({}); ctx.should.have.ownProperty('config').be.a.Function; should(ctx.config('foo.bar.buz.meh')).be.undefined; }); });
'use strict'; const mongoose = require("mongoose"); //const validator = require("mongoose-validate"); const Schema = mongoose.Schema; const adminSchema = new Schema({ fname: String, lname: String, phone: { type: String, lowercase: true, required: true, validate: { isAsync: true, validator: function(value, isValid) { const self = this; return self.constructor.findOne({ email: value }) .exec(function(err, admin){ if(err){ throw err; } else if(admin) { if(self.id === admin.id) { // if finding and saving then it's valid even for existing email return isValid(true); } return isValid(false); } else{ return isValid(true); } }) }, message: 'The phone number is already taken!' }, }, email: { type: String, lowercase: true, required: true, validate: { isAsync: true, validator: function(value, isValid) { const self = this; return self.constructor.findOne({ email: value }) .exec(function(err, admin){ if(err){ throw err; } else if(admin) { if(self.id === admin.id) { // if finding and saving then it's valid even for existing email return isValid(true); } return isValid(false); } else{ return isValid(true); } }) }, message: 'The email address is already taken!' }, }, password: String, created_at: {type: Date, default: Date.now}, updated_at: {type: Date, default: Date.now} }); //companySchema.index({industry: 1, employee.staff_id: 1}, {unique: true, sparse: true}); module.exports = mongoose.model("Admin", adminSchema);
import React, {Component} from 'react'; import DeckGL from '@deck.gl/react'; import {GridLayer, HeatmapLayer} from '@deck.gl/aggregation-layers'; import {LineLayer, PolygonLayer, ScatterplotLayer} from '@deck.gl/layers'; import {WebMercatorViewport} from '@deck.gl/core'; import {Map} from 'react-map-gl'; import STORMS from './data/storms_with_ir.json'; import FilterPanel from "./filter-panel"; import CREDENTIALS from "../credentials.json" import StormInfo from "./storm-info"; import SettingsPanel from "./settings-panel"; /* /Settings Layers Trackpoint /Scatterplot /Heatmap //GridLayer/HexagonLayer /Number of points (heatmap) /Max Wind /Min Pressure /Storms /Storm display /Graph of storm winds/pressure Link to storm /LineLayer /Wind Radii Filters /Basin /Year /Month /Wind /Pressure - when enabled filter out all points wihtout pressure /6 hour points //Record Type (for storms make this a list) According to HURDAT only the landfall identifier is really useful, all others are only included after 1989 and at the discretion of whoever did the analysis /Landfall Latitude For storms max/min start/end Longitude /Status (for storms make this a list of all statuses achieved by the storm) Search in polygon Search in distance from point Wind Radii */ export const PLOT_TYPES = { STORM: "Storm", SCATTER_PLOT: "Scatter Plot", HEATMAP: "Heatmap", GRID: "Grid", MAX_WIND_GRID: "Max Wind Grid" }; export const BASINS = { ALL: "All", AL: "North Atlantic", EP: "East Pacific", CP: "Central Pacific" }; const SYSTEM_STATUSES = { "None": "", "Tropical Depression": "TD", "Tropical Storm": "TS", "Hurricane": "HU", "Extra-Tropical": "EX", "Sub-Tropical Depression": "SD", "Sub-Tropical Storm": "SS", "Low": "LO", "Disturbance": "DB" }; export const getColorFromWindSpeed = (windspeed) => { if (windspeed >= 137) { return [196, 100, 217]; } if (windspeed >= 113) { return [255, 96, 96]; } if (windspeed >= 96) { return [255, 143, 32]; } if (windspeed >= 83) { return [255, 216, 33]; } if (windspeed >= 64) { return [255, 247, 149]; } if (windspeed >= 34) { return [0, 250, 244]; } return [94, 186, 255]; }; const getLineDataFromStormTrackPoints = (storms) => { const line_list = [] storms.forEach(storm => { const trackpoints = storm["track_points"] for (let i = 0; i < trackpoints.length - 1; i++) { const line = { color: [...getColorFromWindSpeed(trackpoints[i].wind), 200], id: trackpoints["id"], from: [trackpoints[i]["longitude"], trackpoints[i]["latitude"]], to: [trackpoints[i + 1]["longitude"], trackpoints[i + 1]["latitude"]] } line_list.push(line); } }); return line_list }; const getStormLineLayer = (storms, settings) => new LineLayer({ id: 'line-layer', data: getLineDataFromStormTrackPoints(Object.values(storms)), pickable: false, getSourcePosition: d => d.from, getTargetPosition: d => d.to, getColor: d => d.color, // wrapLongitude: true, ...settings }); const getMaxWindAreaLayer = (track_points) => new PolygonLayer({ id: 'polygon-layer', data: track_points, lineWidthMinPixels: 1, getPolygon: point => point.max_wind_poly, getFillColor: d => { const color = [...getColorFromWindSpeed(d.wind)]; color[3] = 60; return color; }, getLineColor: [0, 0, 0, 0] }); const wind_area_keys = ["34_ne_poly", "34_se_poly", "34_sw_poly", "34_nw_poly", "50_ne_poly", "50_se_poly", "50_sw_poly", "50_nw_poly", "64_ne_poly", "64_se_poly", "64_sw_poly", "64_nw_poly"]; const getWindAreaLayers = (track_points, selectedPoint) => { return wind_area_keys.map(key => getWindAreaLayer(track_points.filter(point => point[key]), key, selectedPoint)); } const getWindAreaLayer = (track_points, key, selectedPoint) => new PolygonLayer({ id: 'polygon-layer', data: track_points, lineWidthMinPixels: 1, getPolygon: point => point[key], getFillColor: d => { let color = [0,0,0,0]; if (key.startsWith("64")) { color = [255, 247, 149, 40]; } else if (key.startsWith("50")) { color = [0, 250, 244, 30]; } else { color = [94, 186, 255, 20]; } if (selectedPoint && d.date_time === selectedPoint.date_time) { color[3] = color[3]*4; } return color; }, getLineColor: [0, 0, 0, 0] }); const getScatterplotLayer = (track_points, setHoverInfo, onChange, selectedPoint, settings) => new ScatterplotLayer({ id: 'scatterplot-layer', getPosition: d => [d.longitude, d.latitude], getFillColor: d => { let color = getColorFromWindSpeed(d.wind); if (selectedPoint) { d.date_time === selectedPoint.date_time ? color = [255,255,255] : color[3] = 128; } return color }, getLineColor: d => { let color = [0,0,0,0]; if (selectedPoint && d.date_time === selectedPoint.date_time) { color = getColorFromWindSpeed(d.wind); } return color }, radiusUnits: 'pixels', lineWidthUnits: 'pixels', data: track_points, pickable: true, onHover: info => setHoverInfo(info), onClick: info => onChange({ target: { name: "selectStorm", value: info.object }}), ...settings }); const getHeatmapLayer = (track_points, settings) => new HeatmapLayer({ id: 'heatmapLayer', data: track_points, getPosition: d => [d.longitude, d.latitude], getWeight: d => 1, // MAYBE ACE/WIND/PRESSURE in the future? aggregation: 'SUM', ...settings }); const getGridLayer = (track_points, settings) => new GridLayer({ id: 'new-grid-layer', data: track_points, pickable: true, extruded: true, colorRange: [[255,255,204,128],[255,237,160,128],[254,217,118,128],[254,178,76,128],[253,141,60,128],[252,78,42,128] ,[227,26,28,128],[189,0,38,128],[128,0,38,128]], getPosition: d => [d.longitude, d.latitude], ...settings }); const getGridLayerMaxWind = (track_points, settings) => new GridLayer({ id: 'new-grid-layer', data: track_points, pickable: true, extruded: true, colorRange: [[255,255,204,128],[255,237,160,128],[254,217,118,128],[254,178,76,128],[253,141,60,128],[252,78,42,128] ,[227,26,28,128],[189,0,38,128],[128,0,38,128]], getPosition: d => [d.longitude, d.latitude], getElevationWeight: p => p.wind, getColorWeight: p => p.wind, colorAggregation: 'MAX', elevationAggregation: 'MAX', ...settings }); const getStormLayers = (storms, setHoverInfo, onChange, showMaxWindPoly, showWindPoly, stormInfo, selectedPoint, scatterplotSettings, lineSettings) => { const track_points = Object.values(storms).flatMap(storm => storm["track_points"]); const selectedPointActual = stormInfo ? stormInfo.track_points[selectedPoint] : null; const layers = [ getScatterplotLayer(track_points, setHoverInfo, onChange, selectedPointActual, scatterplotSettings), getStormLineLayer(storms, lineSettings) ]; if (showMaxWindPoly) { layers.push( getMaxWindAreaLayer(track_points.filter(track_point => track_point.max_wind_poly)) ) } if (showWindPoly) { layers.push( getWindAreaLayers(track_points, selectedPointActual) ) } return layers; }; const getNewViewPort = (track_points) => { let minLat = 1000; let maxLat = -1000; let minLon = 1000; let maxLon = -1000; track_points.forEach(point => { if (point.latitude > maxLat) { maxLat = point.latitude; } if (point.latitude < minLat) { minLat = point.latitude; } if (point.longitude > maxLon) { maxLon = point.longitude; } if (point.longitude < minLon) { minLon = point.longitude; } }) return {minLat, maxLat, minLon, maxLon} } let doit; class Hurricane extends Component { state = { height: 0, width: 0, viewState: new WebMercatorViewport({ longitude: -64, latitude: 26, zoom: 3, pitch: 0, bearing: 0 }), scatterplotSettings: { name: "scatterplotSettings", radiusScale: 3, lineWidthScale: 2, stroked: true, filled: true, radiusMinPixels: 4, radiusMaxPixels: Number.MAX_SAFE_INTEGER, lineWidthMinPixels: 2, lineWidthMaxPixels: Number.MAX_SAFE_INTEGER }, lineSettings: { name: "lineSettings", widthScale: 1, widthMinPixels: 0, widthMaxPixels: Number.MAX_SAFE_INTEGER }, gridSettings: { name: "gridSettings", cellSize: 100000, elevationScale: 300 }, heatmapSettings: { name: "heatmapSettings", radiusPixels: 50, intensity: 1, threshold: 0.1 }, plotType: PLOT_TYPES.STORM, basin: "ALL", dataSource: STORMS, data: STORMS, name: "", minYear: 1851, maxYear: 2021, minMonth: 1, maxMonth: 12, minWind: 0, maxWind: 190, filterByPressure: false, minPressure: 870, // Only out 22,558 points of 53,501 points have pressure maxPressure: 1024, // Only 1,186 storms out of 1,936 storms have at leasy one pressure reading systemStatus: SYSTEM_STATUSES.None, landfall: false, showMaxWindPoly: false, showWindPoly: false, only6Hour: false, hoverInfo: {}, stormInfo: null, selectedPoint: 0, filterPanelOpen: true, settingsOpen: false, layers: [] }; onChange = async (evt) => { if (evt.target.name === "name") { await this.setState({ name: evt.target.value }); } if (evt.target.name === "minYear") { await this.setState({ minYear: evt.target.value }); } else if (evt.target.name === "maxYear") { await this.setState({ maxYear: evt.target.value }); } else if (evt.target.name === "minMonth") { await this.setState({ minMonth: evt.target.value }); } else if (evt.target.name === "maxMonth") { await this.setState({ maxMonth: evt.target.value }); } else if (evt.target.name === "minWind") { await this.setState({ minWind: evt.target.value }); } else if (evt.target.name === "maxWind") { await this.setState({ maxWind: evt.target.value }); } else if (evt.target.name === "filterByPressure") { await this.setState({ filterByPressure: evt.target.checked }); } else if (evt.target.name === "minPressure") { await this.setState({ minPressure: evt.target.value }); } else if (evt.target.name === "maxPressure") { await this.setState({ maxPressure: evt.target.value }); } else if (evt.target.name === "systemStatus") { await this.setState({ systemStatus: evt.target.value }); } else if (evt.target.name === "landfall") { await this.setState({ landfall: evt.target.checked }); } else if (evt.target.name === "showMaxWindPoly") { await this.setState({ showMaxWindPoly: evt.target.checked }); } else if (evt.target.name === "showWindPoly") { await this.setState({ showWindPoly: evt.target.checked }); } else if (evt.target.name === "only6Hour") { await this.setState({ only6Hour: evt.target.checked }); } else if (evt.target.name === "plotType") { await this.setState({ plotType: evt.target.value }); } else if (evt.target.name === "basin") { await this.setState({ basin: evt.target.value }); } else if (evt.target.name === "selectStorm") { await this.setState({ stormInfo: STORMS[evt.target.value.id] }); const {minLat, maxLat, minLon, maxLon} = getNewViewPort(this.state.stormInfo.track_points); await this.setState(prevState => ({ viewState: prevState.viewState.fitBounds([[minLon, minLat],[maxLon, maxLat]], {padding: 80})})) } else if (evt.target.name === "selectedPoint") { await this.setState({ selectedPoint: parseInt(evt.target.value) }); } else if (evt.target.name === "backwardSelectedPoint" && this.state.selectedPoint > 0) { await this.setState(prevState => ({ selectedPoint: (prevState.selectedPoint - 1)})) } else if (evt.target.name === "forwardSelectedPoint" && this.state.selectedPoint < this.state.stormInfo.track_points.length - 1) { await this.setState(prevState => ({ selectedPoint: (prevState.selectedPoint + 1)})) } let dataSource; if (this.state.plotType === PLOT_TYPES.STORM) { dataSource = STORMS; } else { dataSource = Object.values(STORMS).flatMap(storm => storm["track_points"]); // For aggregation layers we need to remove none 6 hours points so its unbiased if (this.state.plotType === PLOT_TYPES.HEATMAP || this.state.plotType === PLOT_TYPES.GRID) { await this.setState({ only6Hour: true }); } if (this.state.landfall) { await this.setState({ only6Hour: false }); } } let data; if (Array.isArray(dataSource)) { // Track points data = dataSource .filter(point => (this.state.basin === "ALL" ? true : STORMS[point.id].basin === this.state.basin) && point.year >= this.state.minYear && point.year <= this.state.maxYear && point.month >= this.state.minMonth && point.month <= this.state.maxMonth && point.wind >= this.state.minWind && point.wind <= this.state.maxWind && (this.state.filterByPressure ? point.pressure && point.pressure >= this.state.minPressure : true) && (this.state.filterByPressure ? point.pressure && point.pressure <= this.state.maxPressure : true) && (SYSTEM_STATUSES[this.state.systemStatus] ? point.status === SYSTEM_STATUSES[this.state.systemStatus] : true) && (this.state.landfall ? point.record_type === "L" : true) && (this.state.only6Hour ? point.minutes === 0 && point.hours % 6 === 0 : true)); } else { // Storm data = Object.fromEntries(Object.entries(dataSource) .filter(([k,storm]) => (this.state.stormInfo ? this.state.stormInfo["id"] === storm["id"] : true) && (this.state.basin === "ALL" ? true : storm.basin === this.state.basin) && (this.state.name ? storm.name.startsWith(this.state.name.toUpperCase()): true) && storm.season >= this.state.minYear && storm.season <= this.state.maxYear && storm.track_points[0].month >= this.state.minMonth && storm.track_points[storm.track_points.length - 1].month <= this.state.maxMonth && storm.max_wind >= this.state.minWind && storm.max_wind <= this.state.maxWind && (this.state.filterByPressure ? storm.min_pressure && storm.min_pressure >= this.state.minPressure : true) && (this.state.filterByPressure ? storm.min_pressure && storm.min_pressure <= this.state.maxPressure : true) && (SYSTEM_STATUSES[this.state.systemStatus] ? storm.status_list.includes(SYSTEM_STATUSES[this.state.systemStatus]) : true) && (this.state.landfall ? storm.record_type_list.includes("L") : true))) } let layers; if (this.state.plotType === PLOT_TYPES.STORM) { layers = getStormLayers(data, hoverInfo => this.setState({hoverInfo}), this.onChange, this.state.showMaxWindPoly, this.state.showWindPoly, this.state.stormInfo, this.state.selectedPoint, this.state.scatterplotSettings, this.state.lineSettings); } else if (this.state.plotType === PLOT_TYPES.HEATMAP) { layers = getHeatmapLayer(data, this.state.heatmapSettings); } else if (this.state.plotType === PLOT_TYPES.GRID) { layers = getGridLayer(data, this.state.gridSettings); } else if (this.state.plotType === PLOT_TYPES.MAX_WIND_GRID) { layers = getGridLayerMaxWind(data, this.state.gridSettings); } else { // Don't pass anything to stormInfo layers = getScatterplotLayer(data, hoverInfo => this.setState({hoverInfo}), stormInfo => {}, null, this.state.scatterplotSettings); } this.setState({ dataSource, data, layers }) }; onSettingsChange = async (evt, settings) => { await this.setState(prevState => ({ [settings.name]: { ...prevState[settings.name], [evt.target.name]: parseFloat(evt.target.value) } })); await this.onChange({target: {name: this.state.plotType}}) } updateDimensions = () => { const height = this.divElement.clientHeight; const width = this.divElement.clientWidth; this.setState({ height, width, viewState: new WebMercatorViewport({ height, width, longitude: -64, latitude: 26, zoom: 3, pitch: 0, bearing: 0 }), }); }; componentDidMount() { let minW = 999; let maxW = 0; let minP = 9999; let maxP = 0; Object.values(STORMS).flatMap(storm => storm["track_points"]).forEach(point => { if (point.wind < minW) { minW = point.wind } if (point.wind > maxW) { maxW = point.wind } if (point.pressure) { if (point.pressure < minP) { minP = point.pressure } if (point.pressure > maxP) { maxP = point.pressure } } }); console.log(minW, maxW, minP, maxP); window.addEventListener('resize', () => { clearTimeout(doit); doit = setTimeout(this.updateDimensions, 100); }); this.updateDimensions(); this.onChange({target: {name: PLOT_TYPES.STORM}}) } componentWillUnmount() { window.removeEventListener('resize', this.updateDimensions); } getToolTip = (object) => { if (!object) { return; } if (this.state.plotType === "Max Wind Grid") { return `Max Wind: ${object.colorValue}` } if (this.state.plotType === "Grid") { return `# of track points: ${object.colorValue}` } } render() { return ( <div style={{width: "100vw", height: "100vh"}} ref={ (divElement) => { this.divElement = divElement } }> <DeckGL initialViewState={this.state.viewState} controller={true} layers={this.state.layers} getTooltip={({object}) => this.getToolTip(object)} > <Map reuseMaps mapboxAccessToken={CREDENTIALS["MAP_TOKEN"]} mapStyle="mapbox://styles/mapbox/dark-v9" /> {this.state.hoverInfo && this.state.hoverInfo.object && ( <div className="tool-tip row" style={{position: 'absolute', zIndex: 1, pointerEvents: 'none', left: this.state.hoverInfo.x, top: this.state.hoverInfo.y}} > <div className="column"> <p>Name: {STORMS[this.state.hoverInfo.object["id"]]["name"]}</p> <p>Date: {this.state.hoverInfo.object["date_time"].split(" ")[0]}</p> <p>Longitude: {this.state.hoverInfo.object["longitude"]}</p> <p>Wind: {this.state.hoverInfo.object["wind"]}</p> {this.state.hoverInfo.object["max_wind_radius"] && <p>Max Wind Radius: {this.state.hoverInfo.object["max_wind_radius"]}</p>} </div> <div className="column" style={{paddingLeft: 10}}> <p>Season: {STORMS[this.state.hoverInfo.object["id"]]["season"]}</p> <p>Time: {this.state.hoverInfo.object["date_time"].split(" ")[1]}</p> <p>Latitude: {this.state.hoverInfo.object["latitude"]}</p> <p>Status: {this.state.hoverInfo.object["status"]}</p> {this.state.hoverInfo.object["pressure"] && <p>Pressure: {this.state.hoverInfo.object["pressure"]}</p>} </div> </div> )} </DeckGL> {this.state.stormInfo && ( <StormInfo stormInfo={this.state.stormInfo} selectedPoint={this.state.selectedPoint} onChange={this.onChange} exitStormInfo={async (evt) => { await this.setState({stormInfo: null, selectedPoint: 0}); this.onChange(evt) }} />) } <FilterPanel filterPanelOpen={this.state.filterPanelOpen} plotType={this.state.plotType} plotTypeOptions={PLOT_TYPES} basin={this.state.basin} basinOptions={BASINS} name={this.state.name} systemStatus={this.state.systemStatus} systemStatusOptions={SYSTEM_STATUSES} minYear={this.state.minYear} maxYear={this.state.maxYear} minMonth={this.state.minMonth} maxMonth={this.state.maxMonth} minWind={this.state.minWind} maxWind={this.state.maxWind} filterByPressure={this.state.filterByPressure} minPressure={this.state.minPressure} maxPressure={this.state.maxPressure} landfall={this.state.landfall} showMaxWindPoly={this.state.showMaxWindPoly} showWindPoly={this.state.showWindPoly} only6Hour={this.state.only6Hour} onChange={evt => this.onChange(evt)} toggleFilterPanel={evt => {this.setState(prevState => ({ filterPanelOpen: !prevState.filterPanelOpen}))}} /> <SettingsPanel settingsOpen={this.state.settingsOpen} onSettingsChange={this.onSettingsChange} toggleSettingsPanel={evt => {this.setState(prevState => ({ settingsOpen: !prevState.settingsOpen}))}} scatterplotSettings={this.state.scatterplotSettings} lineSettings={this.state.lineSettings} gridSettings={this.state.gridSettings} heatmapSettings={this.state.heatmapSettings} plotType={this.state.plotType} /> </div> ); } } export default Hurricane;
import produce from "immer" import * as types from "./constants" const initialState = { loading: false, list: [], meta: {} } export const reducer = (state = initialState, action) => produce(state, draft => { switch (action.type) { case types.GET_LIST_REQUESTED: draft.loading = true draft.meta = {} break case types.GET_LIST_SUCCESS: draft.loading = false draft.list = action.payload.data.data draft.meta = action.payload.data.meta break case types.GET_LIST_FAILED: draft.loading = false draft.list = [] draft.meta = {} break default: return state } })
require("../common/vendor.js"), (global.webpackJsonp = global.webpackJsonp || []).push([ [ "pages/building/_components/_top_guide" ], { "05e4": function(n, e, o) { Object.defineProperty(e, "__esModule", { value: !0 }), e.default = void 0; var t = { props: { banners: { type: Array, default: [] } }, methods: { goLink: function(n) { var e = this.banners[n], o = e.href, t = e.log; this.$sendCtmEvtLog(t), wx.navigateTo({ url: o }); } } }; e.default = t; }, 1398: function(n, e, o) {}, "303a": function(n, e, o) { o.r(e); var t = o("f2fe"), a = o("36f6"); for (var u in a) [ "default" ].indexOf(u) < 0 && function(n) { o.d(e, n, function() { return a[n]; }); }(u); o("dd68"); var i = o("f0c5"), c = Object(i.a)(a.default, t.b, t.c, !1, null, "098ca65b", null, !1, t.a, void 0); e.default = c.exports; }, "36f6": function(n, e, o) { o.r(e); var t = o("05e4"), a = o.n(t); for (var u in t) [ "default" ].indexOf(u) < 0 && function(n) { o.d(e, n, function() { return t[n]; }); }(u); e.default = a.a; }, dd68: function(n, e, o) { var t = o("1398"); o.n(t).a; }, f2fe: function(n, e, o) { o.d(e, "b", function() { return t; }), o.d(e, "c", function() { return a; }), o.d(e, "a", function() {}); var t = function() { var n = this; n.$createElement; n._self._c; }, a = []; } } ]), (global.webpackJsonp = global.webpackJsonp || []).push([ "pages/building/_components/_top_guide-create-component", { "pages/building/_components/_top_guide-create-component": function(n, e, o) { o("543d").createComponent(o("303a")); } }, [ [ "pages/building/_components/_top_guide-create-component" ] ] ]);
locbean.controller('resultCtrl', function($scope, $rootScope, $ionicPlatform, $cordovaBeacon){ console.log('resultCtrl'); var brIdentifier = 'ibeacon'; var brUuid = '01122334-4556-6778-899a-abbccddeeff0'; var brMajor = null; var brMinor = null; var brNotifyEntryStateOnDisplay = true; $scope.beacons = {}; $ionicPlatform.ready(function() { $cordovaBeacon.requestWhenInUseAuthorization(); $rootScope.$on("$cordovaBeacon:didRangeBeaconsInRegion", function(event, pluginResult) { var uniqueBeaconKey; for(var i = 0; i < pluginResult.beacons.length; i++) { uniqueBeaconKey = pluginResult.beacons[i].uuid + ":" + pluginResult.beacons[i].major + ":" + pluginResult.beacons[i].minor; $scope.beacons[uniqueBeaconKey] = pluginResult.beacons[i]; } $scope.$apply(); }); $cordovaBeacon.startRangingBeaconsInRegion($cordovaBeacon.createBeaconRegion("ibeacon", "01122334-4556-6778-899a-abbccddeeff0")); }); });
$(() => { /* * Denne er ikke i bruk men har tatt den med fra forelesning notat for kommer sikkert til å trenge den kanskje i dunno hahaha * * * */ const id = window.location.search.substring(1); const url = "Kunde/hentEn?" + id; $.get(url, (kunde) => { $("#id").val(kunde.id); $("#navn").val(kunde.navn); $("#adresse").val(kunde.adresse); }); }); function endreKunde(id) { const kunde = { id: $("#id").val(), navn: $("#navn").val(), adresse: $("#adresse").val() } $.post("Kunde/endre", kunde, (OK) => { if (OK) { window.location.href = "index.html"; } else { $("#feil").html("Feil hos server"); } }); }
const fs = require('fs') const request = require('superagent') const cheerio = require('cheerio') const dir = require('../config/savedir') const authorId = require('../config/authorid') const childurl = require('../config/childurl') const cookie = require('../config/cookie') const repeat = require('../api/repeat') const getPageNum = require('../api/getpagenum') const child = require('../childdata') const tips = require('../api/showtips') //页面所有图片链接地址 async function linkList() { return new Promise(async (resolve) => { var link = await child var imgId = [] console.log(tips.get('[','获取图片id',']')) //获取图片id link.forEach((v, i) => { imgId.push(v.split('id=')[1]) }) console.log(tips.get('[','所有图片id获取完成',']')) resolve(imgId) }) } module.exports = linkList()
import React from 'react'; import { Container } from 'semantic-ui-react'; const Footer = () => { return ( <Container className="Footer"> <h3>Thanks for taking a look around. <a href="mailto:tylerhueter08@gmail.com">Contact</a> me & let me know what you think.</h3> </Container> ); }; export default Footer;
const links = document.querySelectorAll('a[href^="#"]'); links.forEach((link) => { link.addEventListener("click", (e) => { e.preventDefault(); let href = link.getAttribute("href").replace("#", ""); let target = document.getElementById(href); const rect = target.getBoundingClientRect().top; const offset = window.pageYOffset const distance = rect + offset; window.scrollTo({ top: distance, behavior: "smooth", }); }); })
var sqlite3 = require('sqlite3').verbose(); var db = new sqlite3.Database('./SSNocDB.db'); var helper = require('./Helper'); // Sometimes only by check the db can we know if input is correct //whether the callback is suitable for the controller is judged in controller //Identifier is user or id ? maybe I will achieve both.In this module version,I used id except searchUserMessage exports.saveMessage =function(contents,authors,messageTypes,targets,postedAts, callback){ contents = helper.sqlite_escape(contents); sql_cmd = "INSERT INTO 'messageinfo' (content, author, messageType, target, postedAt)"; sql_cmd += " VALUES ("; sql_cmd += "'" + contents + "', "; sql_cmd += "'" + authors + "', "; sql_cmd += "'" + messageTypes + "', "; sql_cmd += "'" + targets + "', "; sql_cmd += "'" + postedAts + "')"; db.run(sql_cmd, function(err){ if (err) return callback({status: false, desc: err}); callback({status: true}); }); }; exports.searchPrivateMessageByAuthor = function(author, callback){ db.all("SELECT * FROM messageinfo WHERE author = '" + author + "' AND messageType = 'Private'", function(err, rows){ if(err){ console.log(err); callback({status: false, desc: "search private message by author failed"}); } else callback({status: true, msgs: rows, desc: "search private message by author success"}); }); }; exports.searchPrivateMessageByTarget = function(target, callback){ db.all("SELECT * FROM messageinfo WHERE target = '" + target + "' AND messageType = 'Private'", function(err, rows){ if(err) callback({status: false, desc: "search private message by target failed"}); else callback({status: true, msgs: rows, desc: "search private message by target success"}); }); }; exports.searchAuthorMessage=function (authors, callback){ db.all("SELECT * FROM messageinfo WHERE author='" + authors + "'",function(err,row) { if (err) { callback({status:false, desc:"searchAuthorMessage failed"}); }else{ callback({status:true,messageCB:row,desc:"searchAuthorMessage succeed"}); } } ); }; exports.getPublicMessages=function(callback){ var messageType = "Public"; db.all("SELECT * FROM messageinfo WHERE messageType='" + messageType + "'ORDER BY messageinfo.postedAt ASC", function(err, row) { if(err) { callback({status: false, desc: err}); } else { callback({status: true, msgs: row}); } }); }; exports.getPrivateMessages=function(usernames1,usernames2,callback){ var private="Private"; db.all("SELECT * FROM messageinfo WHERE messageType='" + private + "'AND ((author='"+usernames1+"'AND target='"+usernames2+"')OR(author='"+usernames2+"'AND target='"+usernames1+"'))ORDER BY messageinfo.postedAt ASC", function(err, rows) { if(err){ callback({status:false,desc:"getPrivateMessages failed"}); } else { callback({status: true, msgs: rows, desc: "getPrivateMessages succeed"}); } }); }; exports.getAnnouncements=function(callback){ var messageType = "Announcement"; db.all("SELECT * FROM messageinfo WHERE messageType='" + messageType + "'ORDER BY messageinfo.postedAt ASC", function(err, row) { if (err) { callback({status: false, desc: err}); } else { callback({status: true, msgs: row}); } }); }; //exports.deleteMessagebyid=function(messageIDs, callback){ // db.get("SELECT content FROM messageinfo WHERE messageID='" + messageIDs + "'",function(err,row){ // if(err !== null) { // // callback({status:false,desc:messageIDs+"pinpoint Message failed"}); // }else // { // // if(row===undefined){ // // callback({status:false,desc:messageIDs+"has No such message in db"}); // }else{ // // db.run("DELETE FROM messageinfo WHERE messageID='" + messageIDs + "'", // function(err) { // if(err !== null) { // // callback({status:false,desc:messageIDs+"delete Message by id failed"}); // }else // { // // callback({status:true,desc:messageIDs+"delete Message by id succeed"}); // } // }); // } // // } // // }); //}; //exports.updateOneMessagebyid=function(contents,authors,messageTypes,targets,postedAts,messageIDs, callback){ // db.get("SELECT content FROM messageinfo WHERE messageID='" + messageIDs + "'",function(err,row) { // if (err !== null) { // callback({status: false, desc: messageIDs + "pinpoint Message failed"}); // } else { // if (row === undefined) { // // callback({status: false, desc: messageIDs + " has No such message in db"}); // } else { // contents = helper.sqlite_escape(contents); // db.run("UPDATE messageinfo SET content = '" + contents + "',author='" + authors + "',messageType='" + messageTypes + // "',target='" + targets + // "',postedAt='" + postedAts + "' WHERE messageID='" + messageIDs + "'", // function (err) { // if (err !== null) { // // callback({status: false, desc: messageIDs + "update One Message by id failed"}); // } else { // // callback({status: true, desc: messageIDs + "update One Message by id succeed"}); // } // }); // } // } // //} exports.deleteMessagebyid=function(messageIDs, callback){ db.get("SELECT content FROM messageinfo WHERE messageID='" + messageIDs + "'", function(err, row){ if (err) return callback({ status: false, desc: err }); if (!row) return callback({ status: false, desc: "No message with ID " + messageIDs }); db.run("DELETE FROM messageinfo WHERE messageID='" + messageIDs + "'", function(err) { if (err) return callback({status:false,desc:messageIDs+"delete Message by id failed"}); callback({status:true,desc:messageIDs+"delete Message by id succeed"}); }); }); }; exports.updateAuthor = function(username, newUsername, callback){ var sql = "UPDATE messageinfo SET author = '" + newUsername + "' WHERE author = '" + username + "'"; db.run(sql, function(err){ if(err){ callback({status: false, desc: err}); return; }else{ callback({status: true, desc: "update author succeed"}); return; } }); }; exports.updateTarget = function(username, newUsername, callback){ var sql = "UPDATE messageinfo SET target = '" + newUsername + "' WHERE target = '" + username + "'"; db.run(sql, function(err){ if(err){ callback({status: false, desc: err}); return; }else{ callback({status: true, desc: "update target succeed"}); return; } }); }; exports.deleteAllMessages = function(callback){ var sql = "DELETE FROM messageinfo"; db.run(sql, function(err){ if (err){ return callback({status: false, desc: err}); } callback({status: true, desc: "all messages deleted"}); }); };
function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(getUserLoc); } else { console.log("Could not find your location"); } } // var User = function(userloc, userLat, activity) { // this.userloc = userloc; // this.userLat = userLat; // this.activity = activity; // } var userloc; var userLat; var userLong; var activity="hiking"; var search = { userLong: "", userLat: "", activity: "" }; var placesArray = []; //for Places object function Place(obj) { this.name = obj.name; this.directions = obj.directions; this.lat = obj.lat; this.lon = obj.lon; this.descriptionMain = obj.activities[0].description; this.descriptionDetails = obj.description; this.length = obj.activities[0].length; } function getUserLoc(position) { userloc = position.coords.latitude + "," + position.coords.longitude; userLat = position.coords.latitude; userLong = position.coords.longitude; console.log(userLat + " " +userLong); activityClick(); } function activityClick(){ search.userLong = userLong; search.userLat = userLat; search.activity = activity; console.log(search); $.post('/search', {searchCrit:search}, function(data){ console.log(data); }).done(function(data){ data.places.forEach(function(x) { var place = new Place(x); placesArray.push(place); }); var template = $('#template').html(); var compileTemplate = Handlebars.compile(template); placesArray.forEach(function(place){ var html = compileTemplate(place); $('main').append(html); }) }) } getLocation();
import Logos from './Logos.svelte'; export { Logos };
const Sauce = require('../models/sauces') const fs = require('fs') // RETOURNE LA LISTE DES SAUCES exports.getSauces = (req, res, next) => { Sauce.find() .then(sauces => {res.status(200).json(sauces)}) .catch(error => {res.status(404).json({error})}) } // RETOURNE UNE SAUCE exports.getSauce = (req, res, next) => { Sauce.findOne({_id: req.params.id}) .then(sauce => {res.status(200).json(sauce)}) .catch(error => {res.status(404).json({error})}) } // ENVOIE UNE SAUCE exports.postSauce = (req, res, next) => { const sauce = new Sauce({ ...JSON.parse(req.body.sauce), imageUrl: `${req.protocol}://${req.get("host")}/images/${req.file.filename}`, likes: 0, dislikes: 0, usersLiked: [], usersDisliked: [] }) sauce.save() .then(() => res.status(201).json({ message: 'Sauce envoyé'})) .catch(error => {res.status(400).json({error})}) } // MODIFIE UNE SAUCE exports.editSauce = (req, res, next) => { // On récupére l'id de la sauce const sauceId = {_id: req.params.id} // On défini le contenue suivant le cas ou l'utilisateur envoie une image ou non const content = () => { if (!req.file) return {...req.body} return {...JSON.parse(req.body.sauce),imageUrl: `${req.protocol}://${req.get("host")}/images/${req.file.filename}`} } // On lance la fonction update const updateSauce = () => { Sauce.updateOne(sauceId, {...content(), _id: req.params.id}) .then(() => res.status(200).json({message: 'Objet modifié !'})) .catch(error => res.status(400).json({error})) } if(req.file) { Sauce.findOne(sauceId) .then(img => { if(!img) return res.status(401).json({error: 'Sauce introuvable!'}) const filename = img.imageUrl.split('/images/')[1] fs.unlink(`images/${filename}`, () => {updateSauce()}) }) .catch(error => res.status(500).json({error})) } else {updateSauce()} } // SUPPRIME UNE SAUCE exports.deleteSauce = (req, res, next) => { const sauceId = {_id: req.params.id} const DelSauce = () => { Sauce.deleteOne(sauceId) .then(() => res.status(200).json({message: 'Objet supprimé !'})) .catch(error => res.status(400).json({error})) } Sauce.findOne(sauceId) .then(img => { if(!img) return res.status(401).json({error: 'Sauce introuvable!'}) const filename = img.imageUrl.split('/images/')[1] fs.unlink(`images/${filename}`, () => {DelSauce()}) }) .catch(error => res.status(500).json({error})) } // GERE LES AJOUT/SUPR DE LIKE/DISLIKE exports.likeSauce = (req, res, next) => { var sauceId = {_id: req.params.id} // Défini les changements par rapport au status | st 0 -> pas de like/dislike | st 1 -> utilisateur présent dans tableau des likes | st 2 -> utilisateur dans tableau dislike const editFn = (st) => { // SI JE NE SUIS PAS DANS UN TABLEAU if (st === 0 && req.body.like === 1) return {$inc: {likes: 1},$push: {usersLiked: req.body.userId}, _id: req.params.id} if (st === 0 && req.body.like === -1) return {$inc: {dislikes: 1},$push: {usersDisliked: req.body.userId}, _id: req.params.id} // SI JE SUIS DANS LE TABLEAU LIKE if (st === 1 && req.body.like === 0) return {$inc: {likes: -1},$pull: {usersLiked: req.body.userId}, _id: req.params.id} if (st === 1 && req.body.like === -1) return {$inc: {likes: -1, dislikes: 1},$pull: {usersLiked: req.body.userId},$push: {usersDisliked: req.body.userId}, _id: req.params.id} // SI JE SUIS DANS LE TABLEAU DISLIKE if (st === 2 && req.body.like === 1) return {$inc: {likes: 1, dislikes: -1},$pull: {usersDisliked: req.body.userId},$push: {usersLiked: req.body.userId}, _id: req.params.id} if (st === 2 && req.body.like === 0) return {$inc: {dislikes: -1},$pull: {usersDisliked: req.body.userId}, _id: req.params.id} } // Met à jour const applyLike = (status) => { Sauce.updateOne(sauceId, editFn(status)) .then(() => res.status(200).json({message: 'Like publié !'})) .catch(error => res.status(400).json({error})) } Sauce.findOne(sauceId) .then(sauce => { if(!sauce) return res.status(401).json({error: 'Sauce introuvable!'}) if (sauce.usersLiked.find((user) => user === req.body.userId)) return applyLike(1) if (sauce.usersDisliked.find((user) => user === req.body.userId)) return applyLike(2) return applyLike(0) }) .catch(error => console.log(error)) }
const React = require('react'); var Place = React.createClass({ render: function() { return <div className='place' key={this.props.place.id}> <h1 className='name'>{this.props.place.name}</h1> <div className='rating'>{this.props.place.rating}</div> </div> } }); module.exports = Place;
exports.mutations = { setTab: (state, tabName) => (state.currentTab = tabName), setSidBarTab: (state, tabName) => (state.currentSidBarTab = tabName), setSearchProgressValue: (state, flag) => (state.searchProgress = flag), setAmountOfDataItemValue: (state, amount) => (state.amountOfDataItem = amount), setCurrentTenderSearchTypeValue: (state, searchType) => (state.currentTenderSearchType = searchType), setCurrentSearchParams: (state, searchParam) => (state.currentSearchParams = searchParam), setFabState: (state, fabState) => (state.fabState = fabState), setViewOption: (state, option) => (state.viewOption = option), setSearchTab: (state, searchTab) => (state.searchTab = searchTab), setDatePickerResetFlagState: (state, flag) => (state.datePickerState = flag), setTenderPageInfo: (state, info) => { state.tenderPageInfo.currentPage = info.current_page; state.tenderPageInfo.pageSize = info.page_size; state.tenderPageInfo.totalCount = info.data_count; state.tenderPageInfo.numberOfPages = Math.ceil( info.data_count / info.page_size ); state.tenderCountryCount = info.data_per_country; state.countryMapCenter = info.map_location.reverse(); }, setAwardPageInfo: (state, info) => { state.awardPageInfo.currentPage = info.current_page; state.awardPageInfo.pageSize = info.page_size; state.awardPageInfo.totalCount = info.data_count; state.awardPageInfo.numberOfPages = Math.ceil( info.data_count / info.page_size ); state.awardCountryCount = info.data_per_country; state.countryMapCenter = info.map_location.reverse(); }, setCompanyPageInfo: (state, info) => { state.companyPageInfo.currentPage = info.current_page; state.companyPageInfo.pageSize = info.page_size; state.companyPageInfo.totalCount = info.data_count; state.companyPageInfo.numberOfPages = Math.ceil( info.data_count / info.page_size ); state.companyCountryCount = info.data_per_country; state.countryMapCenter = info.map_location.reverse(); }, setCompliantPageInfo: (state, info) => { state.compliantPageInfo.currentPage = info.current_page; state.compliantPageInfo.pageSize = info.page_size; state.compliantPageInfo.totalCount = info.data_count; state.compliantPageInfo.numberOfPages = Math.ceil( info.data_count / info.page_size ); }, };
for(var i = 0; i < 81; i++) { var scriptId = 'u' + i; window[scriptId] = document.getElementById(scriptId); } $axure.eventManager.pageLoad( function (e) { }); gv_vAlignTable['u21'] = 'center';document.getElementById('u51_img').tabIndex = 0; u51.style.cursor = 'pointer'; $axure.eventManager.click('u51', u51Click); InsertAfterBegin(document.body, "<div class='intcases' id='u51LinksClick'></div>") var u51LinksClick = document.getElementById('u51LinksClick'); function u51Click(e) { windowEvent = e; ToggleLinks(e, 'u51LinksClick'); } InsertBeforeEnd(u51LinksClick, "<div class='intcaselink' onmouseout='SuppressBubble(event)' onclick='u51Clicku5a417dc79c9b4479b97f9fb35070f808(event)'>用例 1</div>"); function u51Clicku5a417dc79c9b4479b97f9fb35070f808(e) { self.location.href="resources/reload.html#" + encodeURI($axure.globalVariableProvider.getLinkUrl($axure.pageData.url)); ToggleLinks(e, 'u51LinksClick'); } InsertBeforeEnd(u51LinksClick, "<div class='intcaselink' onmouseout='SuppressBubble(event)' onclick='u51Clicku03afc02112d1451a8dc1c77aece99085(event)'>用例 2</div>"); function u51Clicku03afc02112d1451a8dc1c77aece99085(e) { self.location.href=$axure.globalVariableProvider.getLinkUrl('新建文章.html'); ToggleLinks(e, 'u51LinksClick'); } gv_vAlignTable['u25'] = 'center';gv_vAlignTable['u16'] = 'center';u46.tabIndex = 0; u46.style.cursor = 'pointer'; $axure.eventManager.click('u46', function(e) { if (true) { self.location.href='#'; } }); gv_vAlignTable['u46'] = 'top';gv_vAlignTable['u76'] = 'center';gv_vAlignTable['u48'] = 'top';gv_vAlignTable['u32'] = 'center';document.getElementById('u62_img').tabIndex = 0; u62.style.cursor = 'pointer'; $axure.eventManager.click('u62', function(e) { if (true) { self.location.href=$axure.globalVariableProvider.getLinkUrl('全部作品列表.html'); } }); document.getElementById('u53_img').tabIndex = 0; u53.style.cursor = 'pointer'; $axure.eventManager.click('u53', function(e) { if (true) { self.location.href=$axure.globalVariableProvider.getLinkUrl('新建文章.html'); } }); gv_vAlignTable['u1'] = 'center';gv_vAlignTable['u7'] = 'center';gv_vAlignTable['u67'] = 'center';gv_vAlignTable['u30'] = 'center';gv_vAlignTable['u34'] = 'center';document.getElementById('u64_img').tabIndex = 0; u64.style.cursor = 'pointer'; $axure.eventManager.click('u64', function(e) { if (true) { self.location.href='#'; } }); gv_vAlignTable['u19'] = 'center';gv_vAlignTable['u49'] = 'top';u17.tabIndex = 0; u17.style.cursor = 'pointer'; $axure.eventManager.click('u17', function(e) { if (true) { self.location.href='#'; self.location.href=$axure.globalVariableProvider.getLinkUrl('视图-卡片.html'); } }); gv_vAlignTable['u17'] = 'top';document.getElementById('u15_img').tabIndex = 0; u15.style.cursor = 'pointer'; $axure.eventManager.click('u15', function(e) { if (true) { self.location.href=$axure.globalVariableProvider.getLinkUrl('视图-卡片.html'); } }); gv_vAlignTable['u45'] = 'center';gv_vAlignTable['u36'] = 'center';document.getElementById('u75_img').tabIndex = 0; u75.style.cursor = 'pointer'; $axure.eventManager.click('u75', function(e) { if (true) { self.location.href=$axure.globalVariableProvider.getLinkUrl('创作-登录网页版.html'); } }); gv_vAlignTable['u57'] = 'center';u22.tabIndex = 0; u22.style.cursor = 'pointer'; $axure.eventManager.click('u22', function(e) { if (true) { self.location.href=$axure.globalVariableProvider.getLinkUrl('视图-卡片.html'); } }); gv_vAlignTable['u22'] = 'top';gv_vAlignTable['u13'] = 'top';gv_vAlignTable['u52'] = 'center';u43.tabIndex = 0; u43.style.cursor = 'pointer'; $axure.eventManager.click('u43', function(e) { if (true) { self.location.href='#'; } }); gv_vAlignTable['u43'] = 'top';gv_vAlignTable['u3'] = 'center';gv_vAlignTable['u47'] = 'top';gv_vAlignTable['u28'] = 'center';gv_vAlignTable['u50'] = 'top';gv_vAlignTable['u54'] = 'center';gv_vAlignTable['u39'] = 'center';gv_vAlignTable['u69'] = 'center';gv_vAlignTable['u71'] = 'center';document.getElementById('u31_img').tabIndex = 0; u31.style.cursor = 'pointer'; $axure.eventManager.click('u31', function(e) { if (true) { self.location.href=$axure.globalVariableProvider.getLinkUrl('编辑文章.html'); } }); gv_vAlignTable['u61'] = 'center';gv_vAlignTable['u26'] = 'top';gv_vAlignTable['u65'] = 'center';document.getElementById('u56_img').tabIndex = 0; u56.style.cursor = 'pointer'; $axure.eventManager.click('u56', function(e) { if (true) { self.location.href=$axure.globalVariableProvider.getLinkUrl('编辑文章.html'); } }); gv_vAlignTable['u5'] = 'center';gv_vAlignTable['u12'] = 'center';gv_vAlignTable['u42'] = 'center';document.getElementById('u72_img').tabIndex = 0; u72.style.cursor = 'pointer'; $axure.eventManager.click('u72', function(e) { if (true) { SetPanelVisibility('u74','','none',500); } }); gv_vAlignTable['u63'] = 'center';u37.tabIndex = 0; u37.style.cursor = 'pointer'; $axure.eventManager.click('u37', function(e) { if (true) { self.location.href='#'; } }); gv_vAlignTable['u37'] = 'top';document.getElementById('u58_img').tabIndex = 0; u58.style.cursor = 'pointer'; $axure.eventManager.click('u58', function(e) { if (true) { self.location.href=$axure.globalVariableProvider.getLinkUrl('编辑文章.html'); } }); gv_vAlignTable['u80'] = 'center';gv_vAlignTable['u10'] = 'center';u40.tabIndex = 0; u40.style.cursor = 'pointer'; $axure.eventManager.click('u40', function(e) { if (true) { self.location.href='#'; } }); gv_vAlignTable['u40'] = 'top';gv_vAlignTable['u14'] = 'top';gv_vAlignTable['u73'] = 'center';gv_vAlignTable['u78'] = 'center';document.getElementById('u29_img').tabIndex = 0; u29.style.cursor = 'pointer'; $axure.eventManager.click('u29', function(e) { if (true) { self.location.href=$axure.globalVariableProvider.getLinkUrl('编辑文章.html'); } }); gv_vAlignTable['u59'] = 'center';
//模块实现模块 var viewCommand = (function(){ var tpl = { //展示图片结构模板 product: [ '<div>', '<img src="{{src}}"/>', '<p>{{text}}</p>', '</div>' ].join(''), //展示标题结构模板 title: [ '<div class="title">', '<div class="main">', '<h2>{{title}}</h2>', '<p>{{tips}}</p>', '</div>', '</div>' ].join('') }; //格式化字符串缓存字符串 var html = ''; //格式化字符串,替换{{}}占位符 function formateString(str,obj){ //替换{{}}之间的字符串 return str.replace(/\{{(\w+)}\}/g,function(match,key){ return obj[key]; }) } //方法集合 var Action = { //创建方法 create: function(data,view){ console.log("create"); //如果数据是一个数组 if(data.length){ //遍历数组 for(var i=0,len = data.length; i < len; i++){ //将格式化之后的字符串缓存到html中 html += formateString(tpl[view],data[i]); } }else{ //直接格式化字符串缓存到html中 html += formateString(tpl[view],data); } }, //展示方法 display: function(container,data,view){ console.log("display"); //如果传入数据 if(data){ //根据给定数据创建视图 this.create(data,view); } //展示模块 document.getElementById(container).innerHTML = html; //展示后清空缓存的字符串 html = ''; } } //命令接口 return function excute(msg){ // console.log("excute"+msg); //解析命令,如果msg.param不是数组则将其转化位数组(apply方法要求第二个参数为数组) msg.param = Object.prototype.toString.call(msg.param) === "[object Array]"?msg.param:[msg.param]; //Action内部调用的方法引用this,所以此处为保证作用域this执行传入Action Action[msg.command].apply(Action, msg.param); } })(); //产品展示数据 var productData = [ { src: 'command/02.jpg', text: '绽放的桃花' }, { src: 'command/03.jpg', text: '阳光下的温馨' }, { src: 'command/04.jpg', text: '镜头前的绿色' } ]; //模块标题数据 var titleData = { title: '夏日里的一片温馨', tips: '暖暖的温情带给人们家的感受' }; viewCommand({ command: 'display', param: ['title',titleData,'title'] }); viewCommand({ command: 'create', param: [{ src: 'command/01.jpg', text: '迎着朝阳的野菊花' },'product'] }) viewCommand({ command: 'display', param:['product',productData,'product'] })
//Variables const formulario = document.querySelector('#formulario'); const listaTareas = document.querySelector('#lista-tareas'); let tarea = []; //Event Listener EventListener(); //cuando el usuario agreega nueva tarea function EventListener(){ formulario.addEventListener('submit',agregarTarea); //cuando el doc esta listo document.addEventListener('DOMContentLoaded', () =>{ tarea = JSON.parse(localStorage.getItem('tarea')) || [] ; crearHTML(); }) } //Funciones function agregarTarea(e){ e.preventDefault(); //textarea donde el usuario escribe const tareas = document.querySelector('#tarea').value; //validacion vacio if(tarea === ''){ mostrarError('No puede estar vacio'); return;//evitamos que se ejecuten mas lineas de codigo } const tareasObj = { id: Date.now(), tareas } //añadir array tareas tarea = [...tarea, tareasObj]; //ya agregado vamos a mostrar el HTML crearHTML(); //reiniciar form formulario.reset(); } //mostrar mensaje de error function mostrarError(error){ const mensajeError = document.createElement('p'); mensajeError.textContent = error; mensajeError.classList.add('error'); //insertarlo en el contenido const contenido = document.querySelector('#contenido'); contenido.appendChild(mensajeError); //elimina la alerta despues de 3s setTimeout( () => { mensajeError.remove(); },3000); } //muestra listado de tarea function crearHTML(){ limpiarHTML(); if(tarea.length > 0){ tarea.forEach( tareas =>{ //Agregar boton const btnEliminar = document.createElement('a'); btnEliminar.classList.add('borrar-tarea'); btnEliminar.innerText = 'X'; //añadir la funcion de eliminar btnEliminar.onclick = () =>{ borrarTarea(tareas.id); } //crear HTML const li = document.createElement('li'); //añadir texto li.innerText = tareas.tareas; //asignaar el boton li.appendChild(btnEliminar); //insertar en el html listaTareas.appendChild(li); }) } sincronizarStorage(); } //agregar las tareas al LS function sincronizarStorage(){ localStorage.setItem('tarea', JSON.stringify(tarea)); } //elimninar una tarea function borrarTarea(id){ tarea = tarea.filter (tarea => tarea.id !== id); crearHTML(); } //limpiar HTML function limpiarHTML(){ while(listaTareas.firstChild){ listaTareas.removeChild(listaTareas.firstChild); } }
(function () { angular .module('myApp') .controller('AdminSetUseController', AdminSetUseController) AdminSetUseController.$inject = ['$state', '$scope', '$rootScope']; function AdminSetUseController($state, $scope, $rootScope) { $rootScope.setData('showMenubar', true); $rootScope.setData('backUrl', "adminAllQuestionSet"); $scope.choice = 'used'; $scope.questions = $rootScope.settings.globalQuestions; if (!$scope.questions) { $scope.questions = []; } $rootScope.safeApply(); $scope.$on('$destroy', function () { if ($scope.teacherRef) $scope.teacherRef.off('value') if ($scope.questionSetRef) $scope.questionSetRef.off('value') if ($scope.groupRef) $scope.groupRef.off('value') }) $scope.init = function () { $rootScope.setData('loadingfinished', false); $scope.getTeachers(); $scope.getAllQuestionSets(); $scope.getAllGroups(); } $scope.getTeachers = function () { $scope.teacherRef = firebase.database().ref('Users').orderByChild('Usertype').equalTo('Teacher'); $scope.teacherRef.on('value', function (snapshot) { $scope.teachers = {}; snapshot.forEach(function (childsnapshot) { var teacherKey = childsnapshot.key; $scope.teachers[teacherKey] = { teacherEmail: childsnapshot.val()['ID'] }; }); $scope.ref_1 = true $scope.finalCalc(); }) } $scope.getAllQuestionSets = function () { $scope.questionSetRef = firebase.database().ref('QuestionSets').orderByChild('creator'); $scope.questionSetRef.on('value', function (snapshot) { $scope.questionSets = []; snapshot.forEach(function (questionSet) { $scope.questionSets[questionSet.key] = { questionSetKey: questionSet.key, setName: questionSet.val()['setname'], }; }); $scope.ref_2 = true $scope.finalCalc(); }); } $scope.getAllGroups = function () { $scope.groupRef = firebase.database().ref('Groups'); $scope.groupRef.on('value', function (snapshot) { $scope.groups = {}; snapshot.forEach(function (group) { $scope.groups[group.teacherKey] = $scope.groups[group.val().teacherKey] || {} $scope.groups[group.teacherKey][group.key] = group.val() }); $scope.ref_3 = true $scope.finalCalc(); }); } $scope.finalCalc = function () { if (!$scope.ref_1 || !$scope.ref_2 || !$scope.ref_3) return $scope.result = []; for (teacherKey in $scope.teachers) { var teacherEmail = $scope.teachers[teacherKey]['teacherEmail']; var groups = $scope.groups[teacherKey] || {}; for (groupKey in groups) { var groupName = groups[groupKey]['groupname']; var questionSets = groups[groupKey]['QuestionSets'] || {}; for (questionSetKey in questionSets) { if (questionSetKey == $rootScope.settings.globalQuestionSetKey) { var temp = { teacher: teacherEmail, groupName: groupName }; $scope.result.push(temp); break; } } } } $rootScope.setData('loadingfinished', true); $rootScope.safeApply(); } $scope.deleteQuestionSet = function () { // if (confirm("Collected data will be lost if question set is deleted.\n Please export data before deleting the question set.")) { $state.go('adminExportQuestionSet'); // } } $scope.deleteQuestion = function (obj, index) { $rootScope.setData('qustionData', angular.copy(obj)); $rootScope.setData('qustionIndex', index); // if (confirm("Collected data will be lost if question is deleted.\n Please export data before deleting the question.")) { $state.go('adminExportQuestion'); // } } } })();
import React from 'react'; class Panel extends React.Component{ constructor(props){ super(props); } componentWillMount(){ document.title = this.props.title + ' - 创易汇'; } render(){ return ( <div className="col-xs-12 col-sm-9 content"> <div className="panel panel-default"> <div className="panel-heading"> <h3 className="panel-title"> <a href="javascript:void(0);" className="toggle-sidebar"> <span className="fa fa-angle-double-left" data-toggle="offcanvas" title="Maximize Panel"></span> </a> {this.props.title} </h3> </div> <div className="panel-body scroll-bar"> {this.props.children} </div> </div> </div> ); } } export default Panel;
/** * Mongoose extension which makes sure that the slugs are unique no matter what. * Has minimum configuration operations, as it is suposed to be used for in house * developement. * @author Marius Kubilius <marius.kubilius@gmail.com> * @param schema * @todo add lithuanian accents. */ slugify = function(schema) { //define defaults var fr = 'àáâãäåçèéêëìíîïñðóòôõöøùúûüýÿ' // Accent chars to find var to = 'aaaaaaceeeeiiiinooooooouuuuyy' // Accent replacement var fields = {}; //if not defined define schema for title and slug. if (!schema.paths.slug) { fields.slug = { type: String , index:{unique: true, sparse: true} } } if (!schema.paths.title) { fields.title = String; } schema.add(fields); ['static', 'method'].forEach(function (method) { schema[method]('slugify', function (str) { str = str .replace(/^\s+|\s+$/g, '') .toLowerCase(); //replace all illegal characters and accents for (var i=0; i<fr.length; i++) { str = str.replace(new RegExp(fr.charAt(i), 'g'), to.charAt(i)); } return str .replace(/[^a-z0-9 -]/g, '') .replace(/\s+/g, '-'); }) }) // pre save check whether slug is modified ;) // Extract the slug on save, optionally overriding a previous value schema.pre('save', function (next) { var self = this; var slugChanged = self.isDirectModified('slug'); //check for duplicated slugs. var checkDupes = function(self, oldSlug, i){ self.collection.count({slug: self.slug}, function(err, count) { if (err) return next(err); if(count > 0) { self.slug = oldSlug + '-' + i; i++ checkDupes(self, oldSlug, i); } else { next(); } }); } if (slugChanged) { self.slug = self.slugify(self.slug); checkDupes(self, self.slug, 1); } if (!self.slug) { self.slug = self.slugify(self.title); checkDupes(self, self.slug, 1); } else { next(); } }); } module.exports = slugify;
//Loops ////DO WHILE LOOPS /* loops always start with a value of 0 var lcv1 = 0; do { lcv1 = lcv1 + 1 console.log(lcv); } while ( lcv1 < 6 ); var lcv = 2; // create a do while loop thay counts to 20 by 2's do { lcv = lcv + 2 console.log(lcv); } while ( lcv < 20); //create a do while loop that counts from 10 to zero var lcv2 = 10; do { lcv2 = lcv2 - 1; console.log("counting down from 10: "+lcv2 ); } while ( lcv2 > 0 ); ////////////////////////////////////////WHILE LOOPS /* lcv = 0 while(true || flase){ body of code, increment || decrement } */ var counting = 0; while(counting < 50){ counting += 5; console.log(counting); } // challenge create a countdown from 10 to 0.. //instead of 0, print blast off! var cdown= 10; while( cdown > 0){ cdown--; if(cdown == 0 ) { console.log("blast off"); } else{ console.log(cdown); } } ////////////////////////////FOR LOOP /* for (lcv = 0; true or false espression ; increment || decrement){ */ for (apples = 0 ; apples < 10; apples++){ console.log(apples); } //creating a for loop that pushes numvers into a empty array var numArry = []; for ( var num = 1; num < 11 ; num++){ console.log(num); numArry.push(num); } console.log(numArry) //Mixed arrays var ranThings = ["Bryce", 45, "Summer", true, []] console.log(ranThings); ///bronze challenge module #8 var hobbies = ["do it","make it","work it","stronger", "better",]; console.log(hobbies); /* var cars = ["mariokart","toadkart","peachkart","bowserkart"]; for ( var cars = ; cars < 10; cars++){ console.log(cars); } console.log(cars) */ //gold challenge module #8 //// var cats = ["taco", "six", "mowgz"] var dogs = ["si", "cisco"] var ppl = ["alex","jake"] var lists = [cats, dogs, ppl] for ( list in lists ){ var temp = lists[list] for ( t in temp = cats + dogs + ppl ) console.log(temp[t]) }
const stargazer = require('./wallets/stargazer'); const stellarkey = require('./wallets/stellarkey'); const wallets = [ 'Centaurus', 'Papaya', 'Stargazer', 'Stellarkey' ]; const getStellarQR = (params) => { switch (params.wallet.toLowerCase()) { case 'stellarkey': return stellarkey.getQR(params); case 'papaya': case 'stargazer': return stargazer.getQR(params); default: // same for centaurus return params.accountId; } }; module.exports = { wallets, getStellarQR };
import KoaRouter from "koa-router"; import controllers from "../controllers/index"; const router = new KoaRouter(); router .get("/public/get", function(ctx, next) { ctx.body = "public api!"; }) .post("/api/addAuthor", controllers.test.TestController.addAuthor) .get("/public/getAuthorList", controllers.test.TestController.getAuthorList) .put("/api/editAuthor/:id", controllers.test.TestController.editAuthor) .post("/api/addStory", controllers.test.TestController.addStory) .get("/api/test", controllers.test.TestController.testService); // .get('/project/list', controllers.monitor.project.projectApi.list) // .post('/project/save', controllers.monitor.project.projectApi.save) // .delete('/project/delete/:id', controllers.monitor.project.projectApi.deleteById) // .get('/project/search', controllers.monitor.project.projectApi.searchByName) // .get('/error/list/:appkey', controllers.monitor.error.errorsApi.list) // .put('/error/handler/:id', controllers.monitor.error.errorsApi.handler) // .get('/error/filter/:appkey', controllers.monitor.error.errorsApi.filter) // .get('/report/error', controllers.monitor.error.errorsApi.report) // .get('/performance/list/:appkey', controllers.monitor.performance.performanceApi.list) // .get('/report/performance', controllers.monitor.performance.performanceApi.report) // .get('/api/test', controllers.monitor.test.Test) // .all('/upload', controllers.upload.default) // .post('/auth/:action', controllers.auth.Post) // .post('/user/login', controllers.auth.Login) module.exports = router;
sap.ui.define([ "sap/ui/core/UIComponent" ], function(UIComponent) { "use strict"; return UIComponent.extend("com.sap.ui5con2019.d3js.Component", { metadata : { manifest : "json" }, init: function() { UIComponent.prototype.init.apply(this, arguments); this.getRouter().initialize(); var oModel = this.getModel(); window.oModel = oModel; // DON'T DO THIS, only for demo purposes oModel.setProperty('/ui5con', [ { "name": "flare", "title": "flare", "value": 0 }, { "name": "analytics", "title": "flare/analytics", "group": "analytics", "value": 0 }, { "name": "cluster", "title": "flare/analytics/cluster", "group": "analytics", "value": 0 }, { "name": "AgglomerativeCluster", "title": "flare/analytics/cluster/AgglomerativeCluster", "group": "analytics", "value": 3938 }, { "name": "CommunityStructure", "title": "flare/analytics/cluster/CommunityStructure", "group": "analytics", "value": 3812 }, { "name": "HierarchicalCluster", "title": "flare/analytics/cluster/HierarchicalCluster", "group": "analytics", "value": 6714 }, { "name": "MergeEdge", "title": "flare/analytics/cluster/MergeEdge", "group": "analytics", "value": 743 }, { "name": "graph", "title": "flare/analytics/graph", "group": "analytics", "value": 0 }, { "name": "BetweennessCentrality", "title": "flare/analytics/graph/BetweennessCentrality", "group": "analytics", "value": 3534 }, { "name": "LinkDistance", "title": "flare/analytics/graph/LinkDistance", "group": "analytics", "value": 5731 }, { "name": "MaxFlowMinCut", "title": "flare/analytics/graph/MaxFlowMinCut", "group": "analytics", "value": 7840 }, { "name": "ShortestPaths", "title": "flare/analytics/graph/ShortestPaths", "group": "analytics", "value": 5914 }, { "name": "SpanningTree", "title": "flare/analytics/graph/SpanningTree", "group": "analytics", "value": 3416 }, { "name": "optimization", "title": "flare/analytics/optimization", "group": "analytics", "value": 0 }, { "name": "AspectRatioBanker", "title": "flare/analytics/optimization/AspectRatioBanker", "group": "analytics", "value": 7074 }, { "name": "animate", "title": "flare/animate", "group": "animate", "value": 0 }, { "name": "Easing", "title": "flare/animate/Easing", "group": "animate", "value": 17010 }, { "name": "FunctionSequence", "title": "flare/animate/FunctionSequence", "group": "animate", "value": 5842 }, { "name": "interpolate", "title": "flare/animate/interpolate", "group": "animate", "value": 0 }, { "name": "ArrayInterpolator", "title": "flare/animate/interpolate/ArrayInterpolator", "group": "animate", "value": 1983 }, { "name": "ColorInterpolator", "title": "flare/animate/interpolate/ColorInterpolator", "group": "animate", "value": 2047 }, { "name": "DateInterpolator", "title": "flare/animate/interpolate/DateInterpolator", "group": "animate", "value": 1375 }, { "name": "Interpolator", "title": "flare/animate/interpolate/Interpolator", "group": "animate", "value": 8746 }, { "name": "MatrixInterpolator", "title": "flare/animate/interpolate/MatrixInterpolator", "group": "animate", "value": 2202 }, { "name": "NumberInterpolator", "title": "flare/animate/interpolate/NumberInterpolator", "group": "animate", "value": 1382 }, { "name": "ObjectInterpolator", "title": "flare/animate/interpolate/ObjectInterpolator", "group": "animate", "value": 1629 }, { "name": "PointInterpolator", "title": "flare/animate/interpolate/PointInterpolator", "group": "animate", "value": 1675 }, { "name": "RectangleInterpolator", "title": "flare/animate/interpolate/RectangleInterpolator", "group": "animate", "value": 2042 }, { "name": "ISchedulable", "title": "flare/animate/ISchedulable", "group": "animate", "value": 1041 }, { "name": "Parallel", "title": "flare/animate/Parallel", "group": "animate", "value": 5176 }, { "name": "Pause", "title": "flare/animate/Pause", "group": "animate", "value": 449 }, { "name": "Scheduler", "title": "flare/animate/Scheduler", "group": "animate", "value": 5593 }, { "name": "Sequence", "title": "flare/animate/Sequence", "group": "animate", "value": 5534 }, { "name": "Transition", "title": "flare/animate/Transition", "group": "animate", "value": 9201 }, { "name": "Transitioner", "title": "flare/animate/Transitioner", "group": "animate", "value": 19975 }, { "name": "TransitionEvent", "title": "flare/animate/TransitionEvent", "group": "animate", "value": 1116 }, { "name": "Tween", "title": "flare/animate/Tween", "group": "animate", "value": 6006 }, { "name": "data", "title": "flare/data", "group": "data", "value": 0 }, { "name": "converters", "title": "flare/data/converters", "group": "data", "value": 0 }, { "name": "Converters", "title": "flare/data/converters/Converters", "group": "data", "value": 721 }, { "name": "DelimitedTextConverter", "title": "flare/data/converters/DelimitedTextConverter", "group": "data", "value": 4294 }, { "name": "GraphMLConverter", "title": "flare/data/converters/GraphMLConverter", "group": "data", "value": 9800 }, { "name": "IDataConverter", "title": "flare/data/converters/IDataConverter", "group": "data", "value": 1314 }, { "name": "JSONConverter", "title": "flare/data/converters/JSONConverter", "group": "data", "value": 2220 }, { "name": "DataField", "title": "flare/data/DataField", "group": "data", "value": 1759 }, { "name": "DataSchema", "title": "flare/data/DataSchema", "group": "data", "value": 2165 }, { "name": "DataSet", "title": "flare/data/DataSet", "group": "data", "value": 586 }, { "name": "DataSource", "title": "flare/data/DataSource", "group": "data", "value": 3331 }, { "name": "DataTable", "title": "flare/data/DataTable", "group": "data", "value": 772 }, { "name": "DataUtil", "title": "flare/data/DataUtil", "group": "data", "value": 3322 }, { "name": "display", "title": "flare/display", "group": "display", "value": 0 }, { "name": "DirtySprite", "title": "flare/display/DirtySprite", "group": "display", "value": 8833 }, { "name": "LineSprite", "title": "flare/display/LineSprite", "group": "display", "value": 1732 }, { "name": "RectSprite", "title": "flare/display/RectSprite", "group": "display", "value": 3623 }, { "name": "TextSprite", "title": "flare/display/TextSprite", "group": "display", "value": 10066 }, { "name": "flex", "title": "flare/flex", "group": "flex", "value": 0 }, { "name": "FlareVis", "title": "flare/flex/FlareVis", "group": "flex", "value": 4116 }, { "name": "physics", "title": "flare/physics", "group": "physics", "value": 0 }, { "name": "DragForce", "title": "flare/physics/DragForce", "group": "physics", "value": 1082 }, { "name": "GravityForce", "title": "flare/physics/GravityForce", "group": "physics", "value": 1336 }, { "name": "IForce", "title": "flare/physics/IForce", "group": "physics", "value": 319 }, { "name": "NBodyForce", "title": "flare/physics/NBodyForce", "group": "physics", "value": 10498 }, { "name": "Particle", "title": "flare/physics/Particle", "group": "physics", "value": 2822 }, { "name": "Simulation", "title": "flare/physics/Simulation", "group": "physics", "value": 9983 }, { "name": "Spring", "title": "flare/physics/Spring", "group": "physics", "value": 2213 }, { "name": "SpringForce", "title": "flare/physics/SpringForce", "group": "physics", "value": 1681 }, { "name": "query", "title": "flare/query", "group": "query", "value": 0 }, { "name": "AggregateExpression", "title": "flare/query/AggregateExpression", "group": "query", "value": 1616 }, { "name": "And", "title": "flare/query/And", "group": "query", "value": 1027 }, { "name": "Arithmetic", "title": "flare/query/Arithmetic", "group": "query", "value": 3891 }, { "name": "Average", "title": "flare/query/Average", "group": "query", "value": 891 }, { "name": "BinaryExpression", "title": "flare/query/BinaryExpression", "group": "query", "value": 2893 }, { "name": "Comparison", "title": "flare/query/Comparison", "group": "query", "value": 5103 }, { "name": "CompositeExpression", "title": "flare/query/CompositeExpression", "group": "query", "value": 3677 }, { "name": "Count", "title": "flare/query/Count", "group": "query", "value": 781 }, { "name": "DateUtil", "title": "flare/query/DateUtil", "group": "query", "value": 4141 }, { "name": "Distinct", "title": "flare/query/Distinct", "group": "query", "value": 933 }, { "name": "Expression", "title": "flare/query/Expression", "group": "query", "value": 5130 }, { "name": "ExpressionIterator", "title": "flare/query/ExpressionIterator", "group": "query", "value": 3617 }, { "name": "Fn", "title": "flare/query/Fn", "group": "query", "value": 3240 }, { "name": "If", "title": "flare/query/If", "group": "query", "value": 2732 }, { "name": "IsA", "title": "flare/query/IsA", "group": "query", "value": 2039 }, { "name": "Literal", "title": "flare/query/Literal", "group": "query", "value": 1214 }, { "name": "Match", "title": "flare/query/Match", "group": "query", "value": 3748 }, { "name": "Maximum", "title": "flare/query/Maximum", "group": "query", "value": 843 }, { "name": "methods", "title": "flare/query/methods", "group": "query", "value": 0 }, { "name": "add", "title": "flare/query/methods/add", "group": "query", "value": 593 }, { "name": "and", "title": "flare/query/methods/and", "group": "query", "value": 330 }, { "name": "average", "title": "flare/query/methods/average", "group": "query", "value": 287 }, { "name": "count", "title": "flare/query/methods/count", "group": "query", "value": 277 }, { "name": "distinct", "title": "flare/query/methods/distinct", "group": "query", "value": 292 }, { "name": "div", "title": "flare/query/methods/div", "group": "query", "value": 595 }, { "name": "eq", "title": "flare/query/methods/eq", "group": "query", "value": 594 }, { "name": "fn", "title": "flare/query/methods/fn", "group": "query", "value": 460 }, { "name": "gt", "title": "flare/query/methods/gt", "group": "query", "value": 603 }, { "name": "gte", "title": "flare/query/methods/gte", "group": "query", "value": 625 }, { "name": "iff", "title": "flare/query/methods/iff", "group": "query", "value": 748 }, { "name": "isa", "title": "flare/query/methods/isa", "group": "query", "value": 461 }, { "name": "lt", "title": "flare/query/methods/lt", "group": "query", "value": 597 }, { "name": "lte", "title": "flare/query/methods/lte", "group": "query", "value": 619 }, { "name": "max", "title": "flare/query/methods/max", "group": "query", "value": 283 }, { "name": "min", "title": "flare/query/methods/min", "group": "query", "value": 283 }, { "name": "mod", "title": "flare/query/methods/mod", "group": "query", "value": 591 }, { "name": "mul", "title": "flare/query/methods/mul", "group": "query", "value": 603 }, { "name": "neq", "title": "flare/query/methods/neq", "group": "query", "value": 599 }, { "name": "not", "title": "flare/query/methods/not", "group": "query", "value": 386 }, { "name": "or", "title": "flare/query/methods/or", "group": "query", "value": 323 }, { "name": "orderby", "title": "flare/query/methods/orderby", "group": "query", "value": 307 }, { "name": "range", "title": "flare/query/methods/range", "group": "query", "value": 772 }, { "name": "select", "title": "flare/query/methods/select", "group": "query", "value": 296 }, { "name": "stddev", "title": "flare/query/methods/stddev", "group": "query", "value": 363 }, { "name": "sub", "title": "flare/query/methods/sub", "group": "query", "value": 600 }, { "name": "sum", "title": "flare/query/methods/sum", "group": "query", "value": 280 }, { "name": "update", "title": "flare/query/methods/update", "group": "query", "value": 307 }, { "name": "variance", "title": "flare/query/methods/variance", "group": "query", "value": 335 }, { "name": "where", "title": "flare/query/methods/where", "group": "query", "value": 299 }, { "name": "xor", "title": "flare/query/methods/xor", "group": "query", "value": 354 }, { "name": "_", "title": "flare/query/methods/_", "group": "query", "value": 264 }, { "name": "Minimum", "title": "flare/query/Minimum", "group": "query", "value": 843 }, { "name": "Not", "title": "flare/query/Not", "group": "query", "value": 1554 }, { "name": "Or", "title": "flare/query/Or", "group": "query", "value": 970 }, { "name": "Query", "title": "flare/query/Query", "group": "query", "value": 13896 }, { "name": "Range", "title": "flare/query/Range", "group": "query", "value": 1594 }, { "name": "StringUtil", "title": "flare/query/StringUtil", "group": "query", "value": 4130 }, { "name": "Sum", "title": "flare/query/Sum", "group": "query", "value": 791 }, { "name": "Variable", "title": "flare/query/Variable", "group": "query", "value": 1124 }, { "name": "Variance", "title": "flare/query/Variance", "group": "query", "value": 1876 }, { "name": "Xor", "title": "flare/query/Xor", "group": "query", "value": 1101 }, { "name": "scale", "title": "flare/scale", "group": "scale", "value": 0 }, { "name": "IScaleMap", "title": "flare/scale/IScaleMap", "group": "scale", "value": 2105 }, { "name": "LinearScale", "title": "flare/scale/LinearScale", "group": "scale", "value": 1316 }, { "name": "LogScale", "title": "flare/scale/LogScale", "group": "scale", "value": 3151 }, { "name": "OrdinalScale", "title": "flare/scale/OrdinalScale", "group": "scale", "value": 3770 }, { "name": "QuantileScale", "title": "flare/scale/QuantileScale", "group": "scale", "value": 2435 }, { "name": "QuantitativeScale", "title": "flare/scale/QuantitativeScale", "group": "scale", "value": 4839 }, { "name": "RootScale", "title": "flare/scale/RootScale", "group": "scale", "value": 1756 }, { "name": "Scale", "title": "flare/scale/Scale", "group": "scale", "value": 4268 }, { "name": "ScaleType", "title": "flare/scale/ScaleType", "group": "scale", "value": 1821 }, { "name": "TimeScale", "title": "flare/scale/TimeScale", "group": "scale", "value": 5833 }, { "name": "util", "title": "flare/util", "group": "util", "value": 0 }, { "name": "Arrays", "title": "flare/util/Arrays", "group": "util", "value": 8258 }, { "name": "Colors", "title": "flare/util/Colors", "group": "util", "value": 10001 }, { "name": "Dates", "title": "flare/util/Dates", "group": "util", "value": 8217 }, { "name": "Displays", "title": "flare/util/Displays", "group": "util", "value": 12555 }, { "name": "Filter", "title": "flare/util/Filter", "group": "util", "value": 2324 }, { "name": "Geometry", "title": "flare/util/Geometry", "group": "util", "value": 10993 }, { "name": "heap", "title": "flare/util/heap", "group": "util", "value": 0 }, { "name": "FibonacciHeap", "title": "flare/util/heap/FibonacciHeap", "group": "util", "value": 9354 }, { "name": "HeapNode", "title": "flare/util/heap/HeapNode", "group": "util", "value": 1233 }, { "name": "IEvaluable", "title": "flare/util/IEvaluable", "group": "util", "value": 335 }, { "name": "IPredicate", "title": "flare/util/IPredicate", "group": "util", "value": 383 }, { "name": "IValueProxy", "title": "flare/util/IValueProxy", "group": "util", "value": 874 }, { "name": "math", "title": "flare/util/math", "group": "util", "value": 0 }, { "name": "DenseMatrix", "title": "flare/util/math/DenseMatrix", "group": "util", "value": 3165 }, { "name": "IMatrix", "title": "flare/util/math/IMatrix", "group": "util", "value": 2815 }, { "name": "SparseMatrix", "title": "flare/util/math/SparseMatrix", "group": "util", "value": 3366 }, { "name": "Maths", "title": "flare/util/Maths", "group": "util", "value": 17705 }, { "name": "Orientation", "title": "flare/util/Orientation", "group": "util", "value": 1486 }, { "name": "palette", "title": "flare/util/palette", "group": "util", "value": 0 }, { "name": "ColorPalette", "title": "flare/util/palette/ColorPalette", "group": "util", "value": 6367 }, { "name": "Palette", "title": "flare/util/palette/Palette", "group": "util", "value": 1229 }, { "name": "ShapePalette", "title": "flare/util/palette/ShapePalette", "group": "util", "value": 2059 }, { "name": "SizePalette", "title": "flare/util/palette/SizePalette", "group": "util", "value": 2291 }, { "name": "Property", "title": "flare/util/Property", "group": "util", "value": 5559 }, { "name": "Shapes", "title": "flare/util/Shapes", "group": "util", "value": 19118 }, { "name": "Sort", "title": "flare/util/Sort", "group": "util", "value": 6887 }, { "name": "Stats", "title": "flare/util/Stats", "group": "util", "value": 6557 }, { "name": "Strings", "title": "flare/util/Strings", "group": "util", "value": 22026 }, { "name": "vis", "title": "flare/vis", "group": "vis", "value": 0 }, { "name": "axis", "title": "flare/vis/axis", "group": "vis", "value": 0 }, { "name": "Axes", "title": "flare/vis/axis/Axes", "group": "vis", "value": 1302 }, { "name": "Axis", "title": "flare/vis/axis/Axis", "group": "vis", "value": 24593 }, { "name": "AxisGridLine", "title": "flare/vis/axis/AxisGridLine", "group": "vis", "value": 652 }, { "name": "AxisLabel", "title": "flare/vis/axis/AxisLabel", "group": "vis", "value": 636 }, { "name": "CartesianAxes", "title": "flare/vis/axis/CartesianAxes", "group": "vis", "value": 6703 }, { "name": "controls", "title": "flare/vis/controls", "group": "vis", "value": 0 }, { "name": "AnchorControl", "title": "flare/vis/controls/AnchorControl", "group": "vis", "value": 2138 }, { "name": "ClickControl", "title": "flare/vis/controls/ClickControl", "group": "vis", "value": 3824 }, { "name": "Control", "title": "flare/vis/controls/Control", "group": "vis", "value": 1353 }, { "name": "ControlList", "title": "flare/vis/controls/ControlList", "group": "vis", "value": 4665 }, { "name": "DragControl", "title": "flare/vis/controls/DragControl", "group": "vis", "value": 2649 }, { "name": "ExpandControl", "title": "flare/vis/controls/ExpandControl", "group": "vis", "value": 2832 }, { "name": "HoverControl", "title": "flare/vis/controls/HoverControl", "group": "vis", "value": 4896 }, { "name": "IControl", "title": "flare/vis/controls/IControl", "group": "vis", "value": 763 }, { "name": "PanZoomControl", "title": "flare/vis/controls/PanZoomControl", "group": "vis", "value": 5222 }, { "name": "SelectionControl", "title": "flare/vis/controls/SelectionControl", "group": "vis", "value": 7862 }, { "name": "TooltipControl", "title": "flare/vis/controls/TooltipControl", "group": "vis", "value": 8435 }, { "name": "data", "title": "flare/vis/data", "group": "vis", "value": 0 }, { "name": "Data", "title": "flare/vis/data/Data", "group": "vis", "value": 20544 }, { "name": "DataList", "title": "flare/vis/data/DataList", "group": "vis", "value": 19788 }, { "name": "DataSprite", "title": "flare/vis/data/DataSprite", "group": "vis", "value": 10349 }, { "name": "EdgeSprite", "title": "flare/vis/data/EdgeSprite", "group": "vis", "value": 3301 }, { "name": "NodeSprite", "title": "flare/vis/data/NodeSprite", "group": "vis", "value": 19382 }, { "name": "render", "title": "flare/vis/data/render", "group": "vis", "value": 0 }, { "name": "ArrowType", "title": "flare/vis/data/render/ArrowType", "group": "vis", "value": 698 }, { "name": "EdgeRenderer", "title": "flare/vis/data/render/EdgeRenderer", "group": "vis", "value": 5569 }, { "name": "IRenderer", "title": "flare/vis/data/render/IRenderer", "group": "vis", "value": 353 }, { "name": "ShapeRenderer", "title": "flare/vis/data/render/ShapeRenderer", "group": "vis", "value": 2247 }, { "name": "ScaleBinding", "title": "flare/vis/data/ScaleBinding", "group": "vis", "value": 11275 }, { "name": "Tree", "title": "flare/vis/data/Tree", "group": "vis", "value": 7147 }, { "name": "TreeBuilder", "title": "flare/vis/data/TreeBuilder", "group": "vis", "value": 9930 }, { "name": "events", "title": "flare/vis/events", "group": "vis", "value": 0 }, { "name": "DataEvent", "title": "flare/vis/events/DataEvent", "group": "vis", "value": 2313 }, { "name": "SelectionEvent", "title": "flare/vis/events/SelectionEvent", "group": "vis", "value": 1880 }, { "name": "TooltipEvent", "title": "flare/vis/events/TooltipEvent", "group": "vis", "value": 1701 }, { "name": "VisualizationEvent", "title": "flare/vis/events/VisualizationEvent", "group": "vis", "value": 1117 }, { "name": "legend", "title": "flare/vis/legend", "group": "vis", "value": 0 }, { "name": "Legend", "title": "flare/vis/legend/Legend", "group": "vis", "value": 20859 }, { "name": "LegendItem", "title": "flare/vis/legend/LegendItem", "group": "vis", "value": 4614 }, { "name": "LegendRange", "title": "flare/vis/legend/LegendRange", "group": "vis", "value": 10530 }, { "name": "operator", "title": "flare/vis/operator", "group": "vis", "value": 0 }, { "name": "distortion", "title": "flare/vis/operator/distortion", "group": "vis", "value": 0 }, { "name": "BifocalDistortion", "title": "flare/vis/operator/distortion/BifocalDistortion", "group": "vis", "value": 4461 }, { "name": "Distortion", "title": "flare/vis/operator/distortion/Distortion", "group": "vis", "value": 6314 }, { "name": "FisheyeDistortion", "title": "flare/vis/operator/distortion/FisheyeDistortion", "group": "vis", "value": 3444 }, { "name": "encoder", "title": "flare/vis/operator/encoder", "group": "vis", "value": 0 }, { "name": "ColorEncoder", "title": "flare/vis/operator/encoder/ColorEncoder", "group": "vis", "value": 3179 }, { "name": "Encoder", "title": "flare/vis/operator/encoder/Encoder", "group": "vis", "value": 4060 }, { "name": "PropertyEncoder", "title": "flare/vis/operator/encoder/PropertyEncoder", "group": "vis", "value": 4138 }, { "name": "ShapeEncoder", "title": "flare/vis/operator/encoder/ShapeEncoder", "group": "vis", "value": 1690 }, { "name": "SizeEncoder", "title": "flare/vis/operator/encoder/SizeEncoder", "group": "vis", "value": 1830 }, { "name": "filter", "title": "flare/vis/operator/filter", "group": "vis", "value": 0 }, { "name": "FisheyeTreeFilter", "title": "flare/vis/operator/filter/FisheyeTreeFilter", "group": "vis", "value": 5219 }, { "name": "GraphDistanceFilter", "title": "flare/vis/operator/filter/GraphDistanceFilter", "group": "vis", "value": 3165 }, { "name": "VisibilityFilter", "title": "flare/vis/operator/filter/VisibilityFilter", "group": "vis", "value": 3509 }, { "name": "IOperator", "title": "flare/vis/operator/IOperator", "group": "vis", "value": 1286 }, { "name": "label", "title": "flare/vis/operator/label", "group": "vis", "value": 0 }, { "name": "Labeler", "title": "flare/vis/operator/label/Labeler", "group": "vis", "value": 9956 }, { "name": "RadialLabeler", "title": "flare/vis/operator/label/RadialLabeler", "group": "vis", "value": 3899 }, { "name": "StackedAreaLabeler", "title": "flare/vis/operator/label/StackedAreaLabeler", "group": "vis", "value": 3202 }, { "name": "layout", "title": "flare/vis/operator/layout", "group": "vis", "value": 0 }, { "name": "AxisLayout", "title": "flare/vis/operator/layout/AxisLayout", "group": "vis", "value": 6725 }, { "name": "BundledEdgeRouter", "title": "flare/vis/operator/layout/BundledEdgeRouter", "group": "vis", "value": 3727 }, { "name": "CircleLayout", "title": "flare/vis/operator/layout/CircleLayout", "group": "vis", "value": 9317 }, { "name": "CirclePackingLayout", "title": "flare/vis/operator/layout/CirclePackingLayout", "group": "vis", "value": 12003 }, { "name": "DendrogramLayout", "title": "flare/vis/operator/layout/DendrogramLayout", "group": "vis", "value": 4853 }, { "name": "ForceDirectedLayout", "title": "flare/vis/operator/layout/ForceDirectedLayout", "group": "vis", "value": 8411 }, { "name": "IcicleTreeLayout", "title": "flare/vis/operator/layout/IcicleTreeLayout", "group": "vis", "value": 4864 }, { "name": "IndentedTreeLayout", "title": "flare/vis/operator/layout/IndentedTreeLayout", "group": "vis", "value": 3174 }, { "name": "Layout", "title": "flare/vis/operator/layout/Layout", "group": "vis", "value": 7881 }, { "name": "NodeLinkTreeLayout", "title": "flare/vis/operator/layout/NodeLinkTreeLayout", "group": "vis", "value": 12870 }, { "name": "PieLayout", "title": "flare/vis/operator/layout/PieLayout", "group": "vis", "value": 2728 }, { "name": "RadialTreeLayout", "title": "flare/vis/operator/layout/RadialTreeLayout", "group": "vis", "value": 12348 }, { "name": "RandomLayout", "title": "flare/vis/operator/layout/RandomLayout", "group": "vis", "value": 870 }, { "name": "StackedAreaLayout", "title": "flare/vis/operator/layout/StackedAreaLayout", "group": "vis", "value": 9121 }, { "name": "TreeMapLayout", "title": "flare/vis/operator/layout/TreeMapLayout", "group": "vis", "value": 9191 }, { "name": "Operator", "title": "flare/vis/operator/Operator", "group": "vis", "value": 2490 }, { "name": "OperatorList", "title": "flare/vis/operator/OperatorList", "group": "vis", "value": 5248 }, { "name": "OperatorSequence", "title": "flare/vis/operator/OperatorSequence", "group": "vis", "value": 4190 }, { "name": "OperatorSwitch", "title": "flare/vis/operator/OperatorSwitch", "group": "vis", "value": 2581 }, { "name": "SortOperator", "title": "flare/vis/operator/SortOperator", "group": "vis", "value": 2023 }, { "name": "Visualization", "title": "flare/vis/Visualization", "group": "vis", "value": 16540 } ]) } }); });
let raceNumber = Math.floor(Math.random() * 1000); // give everyone a random number let registeredEarly = true; let age = 49; if (age > 18 && registeredEarly){ console.log(`this is your number ${raceNumber} and your race time will be at 9.30`) } else if(age > 18 && !registeredEarly){ console.log(`this is your number ${raceNumber} and your race time will be at 11.00`) } else if(age < 18){ console.log(`this is your number ${raceNumber} and your race time is 12.30`) } else { console.log("see the registratioin desk") }
import styled from '@emotion/styled'; const Modal = styled.div` z-index: 10; position: fixed; top: 0; left: 0; background: ${props => props.theme.colors.blackTransparent}; width: 100vw; height: 100vh; `; export default Modal;
const GEO_TYPES = [ 'box', 'cone', 'cylinder', 'octahedron', 'sphere', 'tetrahedron', 'torus', 'torusKnot', ]; function init () { const scene = new THREE.Scene (); const clock = new THREE.Clock (); // initialize objects const objMaterial = getMaterial ('basic', 'rgb(255, 255, 255)'); const geoTypes = GEO_TYPES; geoTypes.forEach (function (type) { const geo = getGeometry (type, 5, objMaterial); scene.add (geo); }); const lightLeft = getSpotLight (1, 'rgb(255, 220, 180)'); const lightRight = getSpotLight (1, 'rgb(255, 220, 180)'); const lightBottom = getPointLight (0.33, 'rgb(255, 220, 150)'); lightLeft.position.x = -5; lightLeft.position.y = 2; lightLeft.position.z = -4; lightRight.position.x = 5; lightRight.position.y = 2; lightRight.position.z = -4; lightBottom.position.x = 0; lightBottom.position.y = 10; lightBottom.position.z = 0; // load the environment map const path = '../../assets/cubemap/'; const format = '.jpg'; const fileNames = ['px', 'nx', 'py', 'ny', 'pz', 'nz']; const reflectionCube = new THREE.CubeTextureLoader ().load ( fileNames.map (function (fileName) { return path + fileName + format; }) ); scene.background = reflectionCube; // manipulate materials // const loader = new THREE.TextureLoader (); // objMaterial.roughnessMap = loader.load ('../../assets/textures/scratch.jpg'); // objMaterial.bumpMap = loader.load ('../../assets/textures/scratch.jpg'); // objMaterial.bumpScale = 0.01; // objMaterial.envMap = reflectionCube; // objMaterial.roughness = 0.5; // objMaterial.metalness = 0.7; // const maps = ['bumpMap', 'roughnessMap']; // maps.forEach (function (map) { // const texture = objMaterial[map]; // texture.wrapS = THREE.RepeatWrapping; // texture.wrapT = THREE.RepeatWrapping; // texture.repeat.set (1, 1); // }); // add other objects to the scene scene.add (lightLeft); scene.add (lightRight); scene.add (lightBottom); // camera const cameraGroup = new THREE.Group (); const camera = new THREE.PerspectiveCamera ( 45, // field of view window.innerWidth / window.innerHeight, // aspect ratio 1, // near clipping plane 1000 // far clipping plane ); camera.position.z = 20; camera.position.x = 0; camera.position.y = 5; camera.lookAt (new THREE.Vector3 (0, 0, 0)); cameraGroup.add (camera); cameraGroup.name = 'sceneCameraGroup'; scene.add (cameraGroup); // renderer const renderer = new THREE.WebGLRenderer (); renderer.setSize (window.innerWidth, window.innerHeight); renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFSoftShadowMap; document.getElementById ('webgl').appendChild (renderer.domElement); update (renderer, scene, camera, clock); return scene; } function getGeometry (type, size, material) { let geometry; const segmentMultiplier = 0.25; switch (type) { case 'box': geometry = new THREE.BoxGeometry (size, size, size); break; case 'cone': geometry = new THREE.ConeGeometry (size, size, 256 * segmentMultiplier); break; case 'cylinder': geometry = new THREE.CylinderGeometry ( size, size, size, 32 * segmentMultiplier ); break; case 'octahedron': geometry = new THREE.OctahedronGeometry (size); break; case 'sphere': geometry = new THREE.SphereGeometry ( size, 32 * segmentMultiplier, 32 * segmentMultiplier ); break; case 'tetrahedron': geometry = new THREE.TetrahedronGeometry (size); break; case 'torus': geometry = new THREE.TorusGeometry ( size / 2, size / 4, 16 * segmentMultiplier, 100 * segmentMultiplier ); break; case 'torusKnot': geometry = new THREE.TorusKnotGeometry ( size / 2, size / 6, 256 * segmentMultiplier, 100 * segmentMultiplier ); break; default: break; } const obj = new THREE.Mesh (geometry, material); obj.castShadow = true; obj.name = type; return obj; } function getMaterial (type, color) { let selectedMaterial; const materialOptions = { color: color === undefined ? 'rgb(255, 255, 255)' : color, wireframe: true, }; switch (type) { case 'basic': selectedMaterial = new THREE.MeshBasicMaterial (materialOptions); break; case 'lambert': selectedMaterial = new THREE.MeshLambertMaterial (materialOptions); break; case 'phong': selectedMaterial = new THREE.MeshPhongMaterial (materialOptions); break; case 'standard': selectedMaterial = new THREE.MeshStandardMaterial (materialOptions); break; default: selectedMaterial = new THREE.MeshBasicMaterial (materialOptions); break; } return selectedMaterial; } function getPointLight (intensity, color) { const light = new THREE.PointLight (color, intensity); light.castShadow = true; return light; } function getSpotLight (intensity, color) { color = color === undefined ? 'rgb(255, 255, 255)' : color; const light = new THREE.SpotLight (color, intensity); light.castShadow = true; light.penumbra = 0.5; //Set up shadow properties for the light light.shadow.mapSize.width = 1024; // default: 512 light.shadow.mapSize.height = 1024; // default: 512 light.shadow.camera.near = 0.1; // default light.shadow.camera.far = 500; // default light.shadow.camera.fov = 30; // default light.shadow.bias = 0.001; return light; } function update (renderer, scene, camera, clock) { // rotate camera around the origin const sceneCameraGroup = scene.getObjectByName ('sceneCameraGroup'); if (sceneCameraGroup) { sceneCameraGroup.rotation.y += 0.005; } // switch between objects const geoTypes = GEO_TYPES; const currentIndex = Math.floor ( clock.getElapsedTime () / 4 % geoTypes.length ); geoTypes.forEach (function (geo, index) { const currentObj = scene.getObjectByName (geo); if (index === currentIndex) { currentObj.visible = true; } else { currentObj.visible = false; } }); renderer.render (scene, camera); requestAnimationFrame (function () { update (renderer, scene, camera, clock); }); } const scene = init ();
import dashify from "dashify"; import { useState } from "react"; import Link from 'next/link' import { openLoading } from "../myFunctions"; import { auth, db, storage } from "../utils/fire-config/firebase"; import { useRouter } from "next/router"; const Signup = () => { const router = useRouter() const [content, setContent] = useState({ email: '', userName: '', password: '' }) const [image, setImage] = useState('') const [progress, setPprogress] = useState(null); const [{ alt, src }, setImg] = useState({ src: '/images/placeholder.png', alt: 'Upload an Image' }); const onChange = (e) => { const { value, name } = e.target; setContent(prevState => ({ ...prevState, [name]: value })); } const handleImg = (e) => { if (e.target.files[0]) { setImg({ src: URL.createObjectURL(e.target.files[0]), alt: e.target.files[0].name }); setImage(e.target.files[0]) } } const checkUserName = async (userName) => { let ref = await db.collection('users').where('userName', '==', userName).get(); return ref.empty } const handleSubmit = async () => { const { email, userName, password } = content; const isUserNameAvailable = await checkUserName(userName); if (isUserNameAvailable) { if (image) { openLoading('open'); let slug = dashify(userName); var file = new File([image], slug, { type: "image/png" }); const uploadTask = storage.ref(`images/${slug}`).put(file); uploadTask.on("state_change", (snapshot) => { const progress = Math.round((snapshot.bytesTransferred / snapshot.totalBytes) * 100); setPprogress(`${progress}%`) console.log({ progress }) if (snapshot.bytesTransferred === snapshot.totalBytes) { console.log('success!'); setPprogress('success!') } }, (error) => { console.log(error.message) }, () => { storage .ref(`images/${slug}`) .getDownloadURL() .then(photoURL => { // console.log({ photoURL }) auth.createUserWithEmailAndPassword(email, password) .then(authUser => { authUser.user.updateProfile({ displayName: userName, photoURL: photoURL }); let createdAt = new Date().toISOString(); const data = { email, userName, slug, password, photoURL, uid: authUser.user.uid, createdAt }; db.collection('users').doc(slug).set(data); router.back() }) .catch(error => { console.log(error.message); alert(error.message); }) openLoading('close'); }); } ); } else { alert('You have not selected any photo') } } else { let error = 'userNameError: User name already exiest!' document.querySelector('#userNameError').textContent = error; alert(error) } } return ( <div style={{ padding: '0 10%', display: 'grid', placeItems: 'center' }}> <h1>SIGN UP</h1> <br /> <form action="" onSubmit={(e) => { e.preventDefault(); handleSubmit() }}> <div> <label htmlFor="email">Email</label><br /> <input value={content.email} onChange={onChange} type="email" id="email" name="email" className="form-control" /> </div><br /> <div> <label htmlFor="userName">Username</label><br /> <div id="userNameError" style={{ color: 'red' }}></div> <input value={content.userName} onChange={onChange} type="text" id="userName" name="userName" className="form-control" /> </div><br /> <div> <label htmlFor="password">Password</label><br /> <input value={content.password} onChange={onChange} type="password" id="password" name="password" className="form-control" /> </div><br /> {/* <ImgPrev setImage={setImage} title="Upload author's avater" /> */} <div> <h1 className="form__title">Upload author's avater</h1> <div className="form__img-input-container"> <input type="file" accept=".png, .jpg, .jpeg" id="photo" className="visually-hidden" onChange={handleImg} /> <label htmlFor="photo" className="form-img__file-label"> {/* <svg width="150" height="150" viewBox="0 0 24 24" fill="none" stroke="#56ceef" strokeWidth="1" strokeLinecap="round" strokeLinejoin="round"> <path d="M5.52 19c.64-2.2 1.84-3 3.22-3h6.52c1.38 0 2.58.8 3.22 3" /> <circle cx="12" cy="10" r="3" /> <circle cx="12" cy="12" r="10" /> </svg> */} </label> <img src={src} alt={alt} width={120} height={120} className="form-img__img-preview" /> </div> </div> <br /> {progress && <div style={{ margin: '10px 0', display: 'flex', alignItems: 'center', flexDirection: 'column', width: '100%' }}> {progress} </div>} <br /> <button type="submit" className="btnSolid">SIGNUP</button> <div style={{ display: 'flex', alignItems: 'center' }}> <div style={{ marginLeft: 20, color: 'red' }}>Already had an account?</div> <Link href="/login"><a><button type="button" style={{ marginLeft: 20 }}>LOGIN</button></a></Link> </div> </form> <br /> <br /> <br /> <br /> </div> ) } export default Signup
import React from 'react' import 'scss/activity/birthday.component.scss' export default class Birthday extends React.Component { constructor (props) { super(props) this.state = {} } render () { return ( <div className='transition-group'> <div className='birthday'>birthday</div> </div> ) } }
describe.only('my suite', () => { test.only('one of my .only test', () => { expect(1 + 1).toEqual(2); }); }); describe('my other suite', () => { // Should fail, but isn't even run test('my only true test', () => { expect(1 + 1).toEqual(1); }); });
alert("oi, salveeeeeeeeeeeeeeeeeeeeeeeeee")
P.views.getTemplate = function() { if (!this.template && this.templateId) { if (window.Templates[this.templateId]) { this.template = window.Templates[this.templateId]; } } return this.template; }; P.views.serializeData = function() { if (!this.model) { return; } if (this.model.toTmplCtx) { return this.model.toTmplCtx(); } return this.model.toJSON(); }; P.views.Collection = Backbone.Marionette.CollectionView.extend({ className: 'v-Collection', getTemplate: P.views.getTemplate, serializeData: P.views.serializeData }); P.views.Composite = Backbone.Marionette.CompositeView.extend({ className: 'v-Composite', getTemplate: P.views.getTemplate, serializeData: P.views.serializeData }); P.views.Item = Backbone.Marionette.ItemView.extend({ className: 'v-Item', getTemplate: P.views.getTemplate, serializeData: P.views.serializeData }); P.views.Layout = Backbone.Marionette.LayoutView.extend({ className: 'v-Layout', getTemplate: P.views.getTemplate, serializeData: P.views.serializeData });
import Vue from 'vue' import VueRouter from 'vue-router' import TodoList from '@/views/todo-list/TodoList.vue'; import Author from '@/views/author/Author.vue'; Vue.use(VueRouter) const routes = [ { path: '/', name: 'Home', component: TodoList, }, { path: '/author', name: 'Author', component: Author, } ] const router = new VueRouter({ routes }) export default router
const keystone = require('keystone'); const simpleYoutubeApi = require("simple-youtube-api") const KttvVideo = keystone.list('KttvVideo'); const youtube = new simpleYoutubeApi(process.env.GOOGLE_API_KEY); //console.log(youtube); //Channel ID - UCaSM4GqhbaVmRT7fmmFmR1w exports.processAllVideos = () => { let count = 0; // lett // youtube.getPlaylist('https://www.youtube.com/playlist?list=PLDWf6WFfca8OaBsPiR8FEd3090z1CWAG_') youtube.getPlaylist('https://www.youtube.com/playlist?list=LL6-ymYjG0SU0jUWnWh9ZzEQ') .then(playlist => { // console.log(`The playlist's title is ${playlist.title}`); playlist.getVideos() .then(async videos => { await Promise.all( videos.map(async (video)=>{ // console.log(video); if (video.title !== 'Private video') { const isDuplicate = await checkDuplicate(video.id); // console.log(video); if (!isDuplicate) { const newVideo = new KttvVideo.model({ youtubeId: video.id, title: video.title, description: video.description, thumbnailUrl: video.thumbnails.high ? video.thumbnails.high.url : '', thumbnailMaxResUrl: video.thumbnails.maxres ? video.thumbnails.maxres.url : '', publishedAt: video.publishedAt, url: `https://www.youtube.com/watch?v=${video.id}` }); try { await newVideo.save(); count = count + 1; } catch (e){ console.log(e); } } else { //console.log('is duplicate'); } } else { //console.log('video is private'); } }) ) console.log(`${(videos.length > 1) ? 'All': ''} ${videos.length} video${(videos.length > 1) ? 's': ''} in the playlist have been processed.`); console.log(`${count} videos have been added to the DB.`); }) .catch(console.log); }) .catch(console.log); } /*module.export.processAllDuplicateVideos = () => { youtube.getPlaylist('https://www.youtube.com/playlist?list=PLDWf6WFfca8OaBsPiR8FEd3090z1CWAG_') .then(playlist => { // console.log(`The playlist's title is ${playlist.title}`); playlist.getVideos() .then(videos => { videos.forEach(video=>{ if (!checkDuplicate(video.youtubeId)){ } }) console.log(`This playlist has ${videos.length === 50 ? '50+' : videos.length} videos.`); }) .catch(console.log); }) .catch(console.log); }*/ exports.processLatestVideos = () => { /*youtube.getPlaylist('https://www.youtube.com/playlist?list=PLDWf6WFfca8OaBsPiR8FEd3090z1CWAG_') .then(playlist => { console.log(`The playlist's title is ${playlist.title}`); playlist.getVideos() .then(videos => { console.log(`This playlist has ${videos.length === 50 ? '50+' : videos.length} videos.`); }) .catch(console.log); }) .catch(console.log);*/ } const checkDuplicate = async (youtubeId) => { try { const video = await KttvVideo.model.findOne({youtubeId}).exec(); if (!video) { return false; } //is already in db return true; } catch (e) { throw new Error(e); return true; } }
//модалки ниже export const editPopup = '.popup_profile_edit'; export const addPopup = '.popup_profile_add'; export const imgPopup = '.popup_profile_image'; export const avatarUpdatePopup = '.popup_avatar_update'; export const deletePopup = '.popup_card-delete'; //кнопки открытия модалок ниже export const editBtn = document.querySelector('.profile__edit'); export const addBtn = document.querySelector('.profile__add'); export const imgBtn = document.querySelector('.popup__image'); export const cardImage = document.querySelector('card__image'); export const avatarBtn = document.querySelector('.profile__photo-container'); //кнопки закрытия модалок export const editCloseBtn = document.querySelector('.popup__close'); export const addCloseBtn = document.querySelector('.popup__close'); export const imgCloseBtn = document.querySelector('.popup__close'); //форма в ДОМе export const profileForm = document.querySelector('.form'); export const avatarForm = document.querySelector('.form-avatar'); export const nameInput = document.querySelector('.form__input_edit_name'); export const aboutInput = document.querySelector('.form__input_edit_about'); export const profileName = '.profile__name'; export const profileAbout = '.profile__about'; export const profileAvatar = '.profile__photo'; //форма для карточек в ДОМе export const cardPopupInputName = document.querySelector('.form__input_add_name'); export const cardPopupInputLink = document.querySelector('.form__input_add_link'); export const cardPopupBtn = document.querySelector('.form__save'); export const container = document.querySelector('.card'); export const cardPopupForm = document.querySelector('.form_card'); // модалка изображений export const imgPopupDiscription = document.querySelector('.popup__discription'); export const templateElement = document.querySelector('#template').content.querySelector('.card__item'); export const validationConfig = { form: '.form', inputSelector: '.form__input', submitButtonSelector: '.form__save', inactiveButtonClass: 'form__save_disabled', inputErrorClass: 'popup__input-error_active' };
import editorDispatcher from '../dispatcher/editorDispatcher'; import CONSTANTS from '../constants'; var editorActions = { create(data, silent) { editorDispatcher.dispatch({ action: CONSTANTS.EDITOR.CREATE, data: data, silent: silent }); }, update(data, silent) { editorDispatcher.dispatch({ action: CONSTANTS.EDITOR.UPDATE, data: data, silent: silent }); }, clear(silent) { editorDispatcher.dispatch({ action: CONSTANTS.EDITOR.CLEAR, silent: silent }); } } export default editorActions;
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import styles from './goldPackage.scss'; import { imagePath } from '../../../utils/assetUtils'; import * as actions from '../../../components/TalkToWeddingPlanner/actions'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import { Container, Row, Col } from 'reactstrap'; import HorizontalSlider from '../../../components/HorizontalSlider/horizontalSlider'; import Helmet from 'react-helmet'; import DatePicker from "react-datepicker"; let meta = { title:"Gold Wedding Package, The Best Package For A Grand Wedding", description:"From venues to photographers, get over 30 exclusive services at an amazing price. For a free consultation session get in touch with your wedding planner.", keywords:"" } const mapStateToProps = state => ({ user: state.session.user, ceremonies: state.home.ceremonies }); const mapDispatchToProps = dispatch => ({ actions: bindActionCreators({ ...actions }), dispatch }); const packageItems = [ { imgSrc: 'engagement.jpg', itemName: 'Engagement', itemList: ['3 Star venue (200 people)', 'Catering — Vegetarian', 'Venue Decor', 'Photography, videography, Light & sound'] }, { imgSrc: 'pasupudanchudu.jpg', itemName: 'pasupudanchudu', itemList: ['Catering — Vegetarian (100 people)', 'Venue Decor', 'Photography, videography, Light & sound'] }, { imgSrc: 'sangeeth.jpg', itemName: 'sangeeth', itemList: ['3 Star venue (150 people)', 'Catering — Vegetarian', 'Venue Decor', 'Photography, videography, Light & sound'] }, { imgSrc: 'pellikuturu.jpg', itemName: 'pellikuturu', itemList: ['3 Star venue (150 people)', 'Catering — Vegetarian', 'Venue Decor', 'Photography, videography, Light & sound'] }, { imgSrc: 'wedding.png', itemName: 'wedding', itemList: ['3 Star venue (500 people)', 'Catering — Vegetarian', 'Venue Decor', 'Photography', 'videography', 'Light & sound'] }, { imgSrc: 'reception.png', itemName: 'reception', itemList: ['3 Star venue (200 people)', 'Catering — Vegetarian', 'Venue Decor', 'Photography, videography, Light & sound'] }, { imgSrc: 'photoshoot.jpg', itemName: 'photoshoot', itemList: ['Photography, videography, Light & sound', 'Food for Couple'] }, { imgSrc: 'vratam.jpg', itemName: 'vratam', itemList: ['Catering — Vegetarian', 'Venue Decor', 'Photography, videography, Light & sound'] }, ] // const packageItemsFirst = packageItems.slice(0, 4); // const packageItemsSecond = packageItems.slice(4, 6); const minDate = new Date(Date.now()); var date = new Date(); //Max date is set to 4 years from today date. const maxDate = date.setDate(date.getDate() +1456); class GoldPackage extends Component { constructor(props) { super(props); this.state = {date : '' } this.handleDateChange = this.handleDateChange.bind(this); } sendDetailsToWeddingPlanner() { let name = document.getElementById('name').value; let email = document.getElementById('email').value; let phone = document.getElementById('phone').value; //let date = document.getElementById('date').value; let date = this.state.date; let city = document.getElementById('city').value; let comments = document.getElementById('comments').value; if (name || email || phone || date || city || comments) { const params = {}; params['origin'] = 'GOLD_PACKAGE'; params['name'] = name; params['email'] = email; params['phone'] = phone; params['event_date'] = date; params['city'] = city; params['description'] = comments; this.props.dispatch(actions.postContactDetails(params)); } } componentDidMount() { window.scrollTo(0, 0); } handleDateChange = (dt) => { if (dt != null) { var calendarDate = new Date(dt.toString().split(' ')[2] + '/' + dt.toString().split(' ')[1] + '/' + dt.toString().split(' ')[3]); var todayDate = new Date( minDate.toString().split(' ')[2] + "/" + minDate.toString().split(' ')[1] + "/" + minDate .toString().split(' ')[3]); var afterFourYearDate = new Date( maxDate.toString().split(' ')[2] + "/" + maxDate.toString().split(' ')[1] + "/" + maxDate .toString().split(' ')[3]); if(calendarDate < todayDate || afterFourYearDate > calendarDate){ document.getElementById('date').value = ''; this.setState({ date:'' }); return false; } } document.getElementById('date').focus(); this.setState({ date: dt }); } render() { return ( <div className={styles.goldPackage}> <Helmet> <title>{meta.title}</title> <meta name="description" content={meta.description} /> </Helmet> <div className={styles.goldCover}> <h1>Add a golden touch to your big day</h1> </div> <div className={styles.bannerTwo}> <h2>Knots&Vows Gold package includes</h2> </div> <div className={`${styles.goldContainer} container`}> <Row> { packageItems.slice(0, 4).map((item, index) => { return ( // <Col xs='6' sm='6' md='3' key={index}> <div className={styles.packageItem} key={index}> <div className={styles.packageItemImgBg}> <img className={styles.packageItemImg} src={imagePath(item.imgSrc)} alt={item.itemName} /> </div> <div className={styles.packageItemContent}> <div className={styles.packageItemName}> {item.itemName} </div> <ul> { item.itemList.length > 0 && item.itemList.map((listItem, index) => { return ( <li key={index}> {listItem} </li> ); }) } </ul> </div> </div> // </Col> ); }) } </Row> <Row> { packageItems.slice(4, 6).map((item, index) => { return ( // <Col xs='12' sm='6' key={index} > <div key={index} className={`${styles.packageItem} ${styles.large} ${index === 0 ? ' row-reverse-tab': ''}`}> <div className={`${styles.packageItemImgBg} ${styles.large}`}> <img className={styles.packageItemImg} src={imagePath(item.imgSrc)} alt={item.itemName} /> </div> <div className={styles.packageItemContent}> <div className={styles.packageItemName}> {item.itemName} </div> <ul> { item.itemList.length > 0 && item.itemList.map((listItem, index) => { return ( <li key={index}> {listItem} </li> ); }) } </ul> </div> </div> // </Col> ); }) } </Row> <Row> { packageItems.slice(6, 7).map((item, index) => { return ( // <Col xs='6' sm='6' md='3' key={index} > <div key={index} className={`${styles.packageItem} ${styles.lastPack}`}> <div className={styles.packageItemImgBg}> <img className={styles.packageItemImg} src={imagePath(item.imgSrc)} alt={item.itemName} /> </div> <div className={styles.packageItemContent}> <div className={styles.packageItemName}> {item.itemName} </div> <ul> { item.itemList.length > 0 && item.itemList.map((listItem, index) => { return ( <li key={index}> {listItem} </li> ); }) } </ul> </div> </div> // </Col> ); }) } <div className={`${styles.offerWrap} flex justify-center tab-only`}> <div className={`${styles.offerPrice} `}> <img className={styles.offerPriceImg} src={imagePath('offer-bg.jpg')} alt="offer" /> <div className={styles.offer}>Price starting at</div> <div className={styles.originalStrike}>Original Price ₹26,00,000</div> <div className={styles.original}>₹24,00,000</div> <div className={styles.save}>You Save<br />₹2 Lakhs</div> </div> </div> { packageItems.slice(7, 8).map((item, index) => { return ( // <Col xs='6' sm='6' md='3' key={index} > <div key={index} className={`${styles.packageItem} ${styles.lastPack}`}> <div className={styles.packageItemImgBg}> <img className={styles.packageItemImg} src={imagePath(item.imgSrc)} alt={item.itemName} /> </div> <div className={styles.packageItemContent}> <div className={styles.packageItemName}> {item.itemName} </div> <ul> { item.itemList.length > 0 && item.itemList.map((listItem, index) => { return ( <li key={index}> {listItem} </li> ); }) } </ul> </div> </div> // </Col> ); }) } </Row> <Row className="mobile-only"> <div className={`${styles.offerWrap} flex justify-center`}> <div className={`${styles.offerPrice} `}> <img className={styles.offerPriceImg} src={imagePath('offer-bg.jpg')} alt="offer" /> <div className={styles.offer}>Price starting at</div> <div className={styles.originalStrike}>Original Price ₹26,00,000</div> <div className={styles.original}>₹24,00,000</div> <div className={styles.save}>You Save<br />₹2 Lakhs</div> </div> </div> </Row> <Row> <Col> <h3><span className={styles.headerWithIcon}>To customise Knots&Vows Gold package talk to our experts</span></h3> <div className={styles.hrLine}></div> </Col> </Row> </div> <div className={`${styles.mediumPinkBg} container-fluid`}> <Container className={`${styles.goldContainer} ${styles.contactWrap}`}> <Row> <Col md='1'></Col> <Col md='5' className="text-center"> <img className={styles.contactImg} src={imagePath('gold-372.png')} alt="contact" /> </Col> <Col md='5' className='contact-form'> <h3>Get Your Gold <span className="tab-only"><br /></span> Wedding Package Now!</h3> <form> <Row> <Col xs='12'> <input maxLength="75" type="text" name="name" id="name" placeholder="Name" /> </Col> <Col xs='12'> <input maxLength="75" type="email" name="email" id="email" placeholder="Email" /> </Col> <Col xs='12'> <input pattern="[0-9]*" required maxLength="10" type="tel" name="phone" id="phone" placeholder="Phone" /> </Col> <Col xs='6'> {/* <input type="date" name="date" id="date" placeholder="Eg: 18-12-2018" /> */} <div> <DatePicker selected={this.state.date} onChange={e => this.handleDateChange(e)} dateFormat="dd/MM/yyyy" placeholderText="dd/mm/yyyy" id = "date" minDate={minDate} maxDate={maxDate} autoComplete = "off" /> </div> </Col> <Col xs='6'> <input maxLength="50" type="text" name="city" id="city" placeholder="City" /> </Col> <Col xs='12'> <textarea maxLength="200" name="comments" id="comments" rows="3" placeholder="Comments"></textarea> </Col> </Row> </form> <input type="submit" value="Send Message" className="ml-0 secondary-button home-btn" onClick={() => {this.sendDetailsToWeddingPlanner()}} /> </Col> </Row> </Container> </div> <div className={`${styles.goldContainer} container`}> <h2>Check out our other packages</h2> <Row> <Col> <div className={styles.packageBox}> <img src={imagePath('box-03.png')} alt="img" /> <div className={`${styles.packageDetail} `}> <h3>Royal Ruby</h3> <p>Add shine to your wedding celebration. Here’s a package that’s packed with wedding goodness.</p> <a className="primary-button home-btn" href='/packages/wedding-ruby-package' rel="noopener noreferrer" alt="">Royal Ruby</a> </div> </div> </Col> <Col> <div className={styles.packageBox}> <img src={imagePath('box-01.png')} alt="img" /> <div className={`${styles.packageDetail} `}> <h3>Genie</h3> <p>Your wish is our command. Choose what you need and make your dream team of wedding vendors.</p> <a className="primary-button home-btn" href='/wishlist' rel="noopener noreferrer" alt="">Your wish</a> </div> </div> </Col> </Row> </div> <Container className={styles.ceremonyContainer}> <Row className="mt-5" id="ceremonies"> <Col className={`${styles.ceremony} text-center`}> <h2>Pick a Ceremony...</h2> {this.props.ceremonies && <Col xs="12" className={` no-padding mb-5`}> <HorizontalSlider data={this.props.ceremonies} onSelect={(ceremony) => this.handleCeremonyClick(ceremony)} type="ceremony" /> </Col> } </Col> </Row> </Container> </div> ); } } GoldPackage.propTypes = { user: PropTypes.object, dispatch: PropTypes.func, ceremonies: PropTypes.array }; export default connect( mapStateToProps, mapDispatchToProps )(GoldPackage);
/** * thunk-redis - https://github.com/thunks/thunk-redis * * MIT Licensed */ const util = require('util') const thunks = require('thunks') const EventEmitter = require('events').EventEmitter const tool = require('./tool') const Queue = require('./queue') const initCommands = require('./commands').initCommands const createConnections = require('./connection').createConnections const thunk = thunks() var clientId = 0 module.exports = RedisClient function RedisState (options) { this.options = options this.database = 0 this.ended = false this.connected = false this.clusterMode = false this.timestamp = Date.now() this.clientId = ++clientId this.commandQueue = new Queue() this.pool = Object.create(null) // { // '127.0.0.1:7001': connection // ... // } // masterSocket.replicationIds = ['127.0.0.1:7003', ...] this.slots = Object.create(null) // { // '-1': defaultConnectionId // '0': masterConnectionId // '1': masterConnectionId // / ... // } } RedisState.prototype.getConnection = function (slot) { var connection = this.pool[this.slots[slot]] || this.pool[this.slots[-1]] if (!connection || connection.ended) throw new Error('connection(' + slot + ') not exist') return connection } function RedisClient (addressArray, options) { EventEmitter.call(this) tool.setPrivate(this, '_redisState', new RedisState(options)) var ctx = this this._redisState.thunkE = thunks(function (error) { ctx.emit('error', error) }) createConnections(this, addressArray) // useage: client.clientReady(taskFn), task will be call after connected this.clientReady = thunk.persist.call(this, function (callback) { ctx.once('connect', callback) }) } util.inherits(RedisClient, EventEmitter) initCommands(RedisClient.prototype) // id: '127.0.0.1:7000' or slot: -1, 0, 1, ... RedisClient.prototype.clientSwitch = function (id) { var redisState = this._redisState id = redisState.slots[id] || id if (!redisState.pool[id]) throw new Error(id + ' is not exist') redisState.slots[-1] = id return this } RedisClient.prototype.clientUnref = function () { if (this._redisState.ended) return tool.each(this._redisState.pool, function (connection) { if (connection.connected) connection.socket.unref() else { connection.socket.once('connect', function () { this.unref() }) } }) } RedisClient.prototype.clientEnd = function (hadError) { if (this._redisState.ended) return this._redisState.ended = true this._redisState.connected = false tool.each(this._redisState.pool, function (connection) { connection.disconnect() }) var commandQueue = this._redisState.commandQueue var message = (hadError && hadError.toString()) || 'The redis connection was ended' while (commandQueue.length) commandQueue.shift().callback(new Error(message)) this._redisState.pool = null this.emit('close', hadError) this.removeAllListeners() } RedisClient.prototype.clientState = function () { var redisState = this._redisState var state = { pool: {}, ended: redisState.ended, clientId: redisState.clientId, database: redisState.database, connected: redisState.connected, timestamp: redisState.timestamp, clusterMode: redisState.clusterMode, defaultConnection: redisState.slots[-1], commandQueueLength: redisState.commandQueue.length } tool.each(redisState.pool, function (connection) { state.pool[connection.id] = connection.replicationIds ? connection.replicationIds.slice() : [] }) return state }
import orderRepository from '../repositories/orderRepository.js' const orderController = () => ({ getOrders: async (req, res) => { try { const orders = await orderRepository.get() res.json(orders) } catch (error) { res.status(400).json({ message: 'Unable to list orders' }) } }, createOrder: async (req, res) => { try { const savedOrder = await orderRepository.create(req.body) res.status(201).json(savedOrder) } catch (error) { res.status(400).json({ message: 'Unable to creates an order' }) } } }) export default orderController()
import React from "react"; import "./Films-form.css"; const FilmForm = ({ getCharacters }) => ( <div id="form" className="form__body"> <h2 className="form__header">Пошук персонажів по епізоду</h2> <div className="form"> <div className="input-box"> <input id="someID" className="form__input" type="number" required=" " min={0} max={7} /> <label>Номер епізоду (1-7)</label> </div> </div> <button className="submit" onClick={() => { getCharacters(document.getElementById("someID").value); }} > Отримати інформацію </button> </div> ); export default FilmForm;
import styled from 'styled-components' export const BusinessStyle = styled.div` width: 6.86rem; margin: 0.24rem 0.24rem; img{ width: 6.86rem; height: 1.5rem; border-radius: 0.2rem; } ` export const HotListStyle = styled.div` width: 100%; padding: .28rem .32rem; .main{ width: 100%; display: flex; justify-content: space-between; align-content: space-between; flex-wrap: wrap; } `
/* 🤖 this file was generated by svg-to-ts*/ export const EOSIconsFlipToFront = { name: 'flip_to_front', data: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M3 13h2v-2H3v2zm0 4h2v-2H3v2zm2 4v-2H3a2 2 0 002 2zM3 9h2V7H3v2zm12 12h2v-2h-2v2zm4-18H9a2 2 0 00-2 2v10a2 2 0 002 2h10c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 12H9V5h10v10zm-8 6h2v-2h-2v2zm-4 0h2v-2H7v2z"/></svg>` };
let express = require('express'); let router = express.Router(); let Department = require('../models/Department'); let Ids = require('../models/IdsNext');// 引入模型 //-----------------------------------新增部门---------------------------------------- router.post('/add', (req,res) => { console.log('-------------添加部门-----------------------') let cn = req.body; let id = Ids.findByIdAndUpdate( {_id: 'departmentId'}, {$inc: {sequence_value: 1}}); id.then(data => { let department = new Department({ _id: data.sequence_value, name: cn.name, desc: cn.desc, }) department.save((err, doc) => { if (err) { res.send({msg: '添加失败!', state: '99'}) } else { res.send({msg: '添加成功!', state: '200'}) } }) }) }) //-----------------------------------岗位列表---------------------------------------- router.get('/list', (req, res) => { console.log('----------显示部门列表---------') let page = req.query.curPage; let rows = req.query.rows; let qc = {}, name = req.query.name; let name_pattern = new RegExp("^.*"+name+".*$"); if(name !== '' && name !== undefined){ qc.name = name_pattern } let query = Department.find(qc); query.skip((page-1)*rows); query.limit(parseInt(rows)); let result = query.exec(); result.then((data)=>{ // 获取总条数 Department.find(qc,(err,rs)=>{ res.send({msg: 'sucess', state: '200', data: data,total:rs.length}) }) }) }); // ----------------------------删除部门------------------------- router.post('/delete', (req,res) =>{ let ids = req.body._ids.split(','); let query = { _id: ids }; console.log('-------------删除部门--------------'); Department.deleteMany(query, (err, doc) => { if (err) { res.send({msg: '删除失败', state: '99'}) } else { res.send({msg: '删除成功', state: '200', data: doc}) } }) }); // ----------------------------根据Id查询部门编辑------------------------- router.get('/findById', (req, res) => { console.log('-----------------根据Id查询部门------------------') let query = { _id: req.query._id } Department.findById(query, (err,doc)=>{ res.send({msg: 'sucess', state: '200', data: doc}) }) }); // ----------------------------更新岗位------------------------- router.post('/update',(req,res) =>{ console.log('-----------------更新部门------------------'); let cn = req.body; let query = { _id: req.body._id } let param = { name: cn.name, desc: cn.desc } Department.findOneAndUpdate(query,{ $set: param},(err,doc)=>{ res.send({msg: 'sucess', state: '200'}) }) }); // -------------------------------查询所有部门名称------------------------ router.get('/findToAllDname',(req,res)=>{ console.log('-----------------查询所有的部门名称------------------'); Department.find({}, {_id:0 }).select('name').exec((err,rs)=>{ let cv = [] for (let i =0;i<rs.length;i++){ cv.push({value:rs[i].name}) } res.send({msg: 'sucess', state: '200', data: cv}) }) }) module.exports = router;
import React, { useState } from 'react'; import { Link } from 'react-router-dom'; import "../../assets/styles/components/Navigation.scss"; const Navigation = () => { // const [activeClasses, setActiveClasses] = useState(""); const changeActiveButton = (event) => { document.querySelector(".nav-wrapper .active").classList.remove("active"); const button = event.target.parentNode; button.classList.add("active"); } return ( <nav className="navigation"> <div className="nav-wrapper blue-grey darken-2"> <ul id="nav-mobile" className="left"> <li> <Link to="/" replace >Código QR</Link> </li> <li> <Link to="/change-password" replace>Cambiar contraseña</Link> </li> <li> <Link to="/create-user" replace>Crear usuario</Link> </li> </ul> </div> </nav> ); }; export default Navigation;
var searchData= [ ['y',['y',['../classde_1_1telekom_1_1pde_1_1codelibrary_1_1ui_1_1layout_1_1_p_d_e_absolute_layout_1_1_layout_params.html#a844c7afc130c41137faf536595d1d970',1,'de::telekom::pde::codelibrary::ui::layout::PDEAbsoluteLayout::LayoutParams']]] ];
import React, { Component } from 'react' export default class Detail extends Component { state = { data:[ {id:'1',title:'好消息1',content:'中国加油1'}, {id:'2',title:'好消息2',content:'中国加油2'}, {id:'3',title:'好消息3',content:'中国加油3'}, {id:'4',title:'好消息4',content:'中国加油4'} ] } render() { const {id} = this.props.match.params const result = this.state.data.find((arr) => { return arr.id === id }) return ( <ul> <li>id:{result.id}</li> <li>title:{result.title}</li> <li>content:{result.content}</li> </ul> ) } }
import React from 'react' import { connect } from 'react-redux'; import { getMonthName } from "../CommonFunctions/CommonFunctions"; import axios from "axios"; import { updateEngineering, deleteEngineering } from '../../actions/listAction'; import { showList } from '../../actions/listAction'; import { DELETE_ENGINEERING_URL, UPDATE_ENGINEERING_URL } from '../Constants/constants'; import { ON_SEARCH_URL } from '../Constants/constants'; class EngineeringList extends React.Component { constructor(props) { super(props) this.state = { showUpdate: false, podName: this.props.item.eng_pod_name, codeQualityCyclometric: this.props.item.cyclometric_complexity, technicalCode: this.props.item.technical_code, maintainabilityQuality: this.props.item.maintainability_quality, periodMonth: this.props.item.eng_month, periodYear: this.props.item.eng_year, securityDefects: this.props.item.eng_security_defect, comments: this.props.item.eng_comments } this.showUpdateDetails = this.showUpdateDetails.bind(this) this.readPeriodMonth = this.readPeriodMonth.bind(this) this.readPeriodYear = this.readPeriodYear.bind(this) this.readCyclometricCode = this.readCyclometricCode.bind(this) this.readTechnicalCode = this.readTechnicalCode.bind(this) this.readMaintainabilityQuality = this.readMaintainabilityQuality.bind(this) this.readSecurityDefect = this.readSecurityDefect.bind(this) this.readComments = this.readComments.bind(this) this.update = this.update.bind(this) this.delete = this.delete.bind(this) } readPeriodMonth(e) { this.setState({ periodMonth: e.target.value }) } readPeriodYear(e) { this.setState({ periodYear: e.target.value }) } readCyclometricCode(e) { this.setState({ codeQualityCyclometric: e.target.value }) } readTechnicalCode(e) { this.setState({ technicalCode: e.target.value }) } readMaintainabilityQuality(e) { this.setState({ maintainabilityQuality: e.target.value }) } readSecurityDefect(e) { this.setState({ securityDefects: e.target.value }) } readComments(e) { this.setState({ comments: e.target.value }) } update(event) { const engineering = { id: this.props.item.eng_id, podName: this.state.podName, codeQualityCyclometric: this.state.codeQualityCyclometric, technicalCode: this.state.technicalCode, maintainabilityQuality: this.state.maintainabilityQuality, securityDefects: this.state.securityDefects, periodMonth: this.state.periodMonth, periodYear: this.state.periodYear, comments: this.state.comments, } axios.defaults.headers.post["userName"] = "SWATHI"; axios.post( UPDATE_ENGINEERING_URL, engineering) .then(res => { this.props.updateEngineering(engineering) this.updated(engineering) }); this.showUpdateDetails() } updated(engineering){ console.log(engineering.periodMonth) axios.get(ON_SEARCH_URL + "Engineering" + "&month=" + engineering.periodMonth + "&year=" + engineering.periodYear+ "&podname=" + engineering.podName). then(res => { this.props.showList(res.data) }) } delete(event) { const engineering = { id: this.props.item.eng_id, podName: this.state.podName, codeQualityCyclometric: this.state.codeQualityCyclometric, technicalCode: this.state.technicalCode, maintainabilityQuality: this.state.maintainabilityQuality, securityDefects: this.state.securityDefect, periodMonth: this.state.periodMonth, periodYear: this.state.periodYear, comments: this.state.comments } axios.post( DELETE_ENGINEERING_URL, engineering) .then(res => { this.props.deleteEngineering(engineering) this.updated(engineering) }); } showUpdateDetails = () => { const temp = this.state.showUpdate this.setState({ showUpdate: !temp }) } render() { return ( <tr id={"table" + this.props.index}> {/*<td className="text-center">{this.props.item.eng_pod_name}</td> <td className="text-center">{getMonthName(this.props.item.eng_month)}</td> <td className="text-center">{this.props.item.eng_year}</td>*/} <td className="text-center">{this.state.showUpdate === true ?<button type="submit" className="btn btn-primary" onClick={this.update}>Save</button>:<button type="button" className="btn btn-info btn-update" onClick={(this.showUpdateDetails)}><i class="glyphicon glyphicon-edit"></i></button>}</td> <td className="text-center"><button type="button" className="btn btn-info btn-danger" onClick={this.delete}><span class="glyphicon glyphicon-trash"></span></button></td> <td className="text-center">{this.state.showUpdate === true ?<input type="text" value={this.state.codeQualityCyclometric} onChange={this.readCyclometricCode} />:this.props.item.cyclometric_complexity}</td> <td className="text-center">{this.state.showUpdate === true ?<input type="text" value={this.state.technicalCode} onChange={this.readTechnicalCode} />:this.props.item.technical_code}</td> <td className="text-center">{this.state.showUpdate === true ?<input type="text" value={this.state.maintainabilityQuality} onChange={this.readMaintainabilityQuality} />:this.props.item.maintainability_quality}</td> <td className="text-center">{this.state.showUpdate === true ?<input type="text" value={this.state.securityDefects} onChange={this.readSecurityDefect} />:this.props.item.eng_security_defect}</td> <td className="text-center">{this.state.showUpdate === true ?<textarea type="text" value={this.state.comments} onChange={this.readComments} />:this.props.item.eng_comments}</td> </tr> ) } } const mapStateToProps = (state) => { return { podContent: state.podContent, engineering: state.engineering.item, lists: state.lists } } export default connect(mapStateToProps, { updateEngineering, deleteEngineering, showList })(EngineeringList)
import {apiRequest} from './Base'; import {signUpUrl} from '../Constants'; export const signUpRequest = (parameters, block) => { return apiRequest(signUpUrl, 'POST', parameters, block); };
var chai = require('chai'); var assert = chai.assert; var Person = require('../src/person'); var bob = new Person('Bob Ross'); it('Person', function() { assert.deepEqual( Object.keys(bob).length, 6, 'Object.keys(bob).length should return 6.' ); assert.deepEqual( bob instanceof Person, true, 'bob instanceof Person should return true.' ); assert.deepEqual( bob.firstName, undefined, 'bob.firstName should return undefined.' ); assert.deepEqual( bob.lastName, undefined, 'bob.lastName should return undefined.' ); assert.deepEqual( bob.getFirstName(), 'Bob', 'bob.getFirstName() should return "Bob".' ); assert.deepEqual( bob.getLastName(), 'Ross', 'bob.getLastName() should return "Ross".' ); assert.deepEqual( bob.getFullName(), 'Bob Ross', 'bob.getFullName() should return "Bob Ross".' ); assert.strictEqual( (function() { bob.setFirstName('Haskell'); return bob.getFullName(); })(), 'Haskell Ross', 'bob.getFullName() should return "Haskell Ross" after bob.setFirstName("Haskell").' ); assert.strictEqual( (function() { var _bob = new Person('Haskell Ross'); _bob.setLastName("Curry"); return _bob.getFullName(); })(), 'Haskell Curry', 'bob.getFullName() should return "Haskell Curry" after bob.setLastName("Curry").' ); assert.strictEqual( (function() { bob.setFullName('Haskell Curry'); return bob.getFullName(); })(), 'Haskell Curry', 'bob.getFullName() should return "Haskell Curry" after bob.setFullName("Haskell Curry").' ); assert.strictEqual( (function() { bob.setFullName('Haskell Curry'); return bob.getFirstName(); })(), 'Haskell', 'bob.getFirstName() should return "Haskell" after bob.setFullName("Haskell Curry").' ); assert.strictEqual( (function() { bob.setFullName('Haskell Curry'); return bob.getLastName(); })(), 'Curry', 'bob.getLastName() should return "Curry" after bob.setFullName("Haskell Curry").' ); });
import React from "react"; import styled from "styled-components"; import Tootltips from "../Tooltips/Tooltips"; const Container = styled.div` width: 100%; height: 100%; display: flex; justify-content: center; align-items: center; flex-direction: column; color: rgba(255, 255, 255, 0.74); `; const Item = styled.div` margin-left: 100px; display: flex; align-items: center; width: 90%; `; const Text = styled.p` margin-top: 5px; font-size: 1rem; width: 150px; `; const FeeInput = styled.input` width: 150px; margin-left: 50px; color: rgba(255, 255, 255, 0.74); padding: 0 10px; background-color: rgba(0, 0, 0, 0.507); border-radius: 1rem; border-color: transparent; text-align: center; font-size: 1.1rem; font-weight: bold; &:focus { outline: none; } `; /*<Item> <Text>ETH/USD</Text> <FeeInput value="" readOnly></FeeInput> </Item>*/ const FeeCard = (props) => { let networkFee = ""; let BRLFee = ""; const gasPrice = parseInt(props.gasPrice / 10 ** 9); if (props.networkFee) networkFee = parseFloat(props.networkFee).toFixed(4); if (props.networkFee) { BRLFee = props.ethBRL * networkFee; BRLFee = parseFloat(BRLFee).toFixed(2); BRLFee = `~ R$ ${BRLFee}`; } return ( <Container> <Item> <Text>USD/ETH</Text> <FeeInput value={""} disabled readOnly></FeeInput> </Item> <Item> <Tootltips> <Text>Preco Gas</Text> </Tootltips> <FeeInput style={{ cursor: "pointer" }} value={`${gasPrice} Gwei`} readOnly disabled ></FeeInput> </Item> <Item> <Text>Taxa de Trasnsacao</Text> <FeeInput value={networkFee} disabled readOnly></FeeInput> </Item> <Item> <Text>Taxa em Reais</Text> <FeeInput value={BRLFee} disabled readOnly></FeeInput> </Item> <Item> <Text>Taxa percentual</Text> <FeeInput disabled readOnly></FeeInput> </Item> </Container> ); }; export default FeeCard;
const mongoose = require('mongoose') const Schema = mongoose.Schema const CommentSchema = Schema({ Commentname: String, email: String, password: String }) const Comment = mongoose.model('Comment', CommentSchema) module.exports = Comment
'use strict' const Sequelize = require('sequelize') module.exports = { actived: { type: Sequelize.BOOLEAN, defaultValue: true }, removed: { type: Sequelize.BOOLEAN, defaultValue: false } }
module.exports = (sequelize, DataTypes) => { const Series = sequelize.define('Series', { backdrop_path: DataTypes.STRING, genres: { type: DataTypes.STRING, get: function() { return JSON.parse(this.getDataValue('genres')); }, set: function(val) { return this.setDataValue('genres', JSON.stringify(val)); } }, networks: { type: DataTypes.STRING, get: function() { return JSON.parse(this.getDataValue('networks')); }, set: function(val) { return this.setDataValue('networks', JSON.stringify(val)); } }, episode_run_time: { type: DataTypes.STRING, get: function() { return JSON.parse(this.getDataValue('episode_run_time')); }, set: function(val) { return this.setDataValue('episode_run_time', JSON.stringify(val)); } }, first_air_date: DataTypes.STRING, homepage: DataTypes.STRING, name: DataTypes.STRING, number_of_seasons: DataTypes.STRING, original_language: DataTypes.STRING, original_title: DataTypes.STRING, overview: DataTypes.TEXT, poster_path: DataTypes.STRING, status: DataTypes.STRING, vote_average: DataTypes.STRING, vote_count: DataTypes.STRING }) return Series }
import React,{Component} from "react" import style from "./weiyuyuemodel.mcss" import {DatePicker} from 'antd' import moment from 'moment'; import 'moment/locale/zh-cn'; import { Select } from 'antd'; import { Cascader } from 'antd'; import { TimePicker,message} from 'antd'; const options = [{ value: 'zhejiang', label: 'Zhejiang', children: [{ value: 'hangzhou', label: 'Hangzhou', children: [{ value: 'xihu', label: 'West Lake', }, { value: 'xiasha', label: 'Xia Sha', disabled: true, }], }], }, { value: 'jiangsu', label: 'Jiangsu', children: [{ value: 'nanjing', label: 'Nanjing', children: [{ value: 'zhonghuamen', label: 'Zhong Hua men', }], }], }]; const Option = Select.Option; function onChange(time, timeString) { console.log(time, timeString); } function onChange(value, selectedOptions) { console.log(value, selectedOptions); } function filter(inputValue, path) { return (path.some(option => (option.label).toLowerCase().indexOf(inputValue.toLowerCase()) > -1)); } function handleChange(value) { console.log(`selected ${value}`); } function onChange(date, dateString) { console.log(date, dateString); } class UnreservedPopup extends Component { /** * 构造函数 * @param {*} props */ constructor(props) { super(props); this.state = ({ data:this.props.data || {}, }) console.log(this.state.data) } render (){ return <div className="box2"> <div className= {style['Wraper']}> <div className={style["Model-head"]}> 预约体检信息</div> <div className={style['Content']}> <div className={style['Title']}> <span className='ellipse'></span>预约信息 </div> <ul className="clearfix"> <li className={style['col-md-2']}><span className={style['col-666']}>体检类型</span> <Select defaultValue="lucy" style={{ width: 189 }} onChange={handleChange}> <Option value="jack">新单核保体检</Option> <Option value="lucy">新单核保体检</Option> <Option value="disabled" disabled>新单核保体检</Option> <Option value="Yiminghe">新单核保体检</Option> </Select> </li> <li className={style['col-md-2']}><span className={style['col-666']}>体检预约号</span><input type="text" /></li> <li className={style['col-md-2']}><span className={style['col-666']}>保单号</span><input type="text" /></li> <li className={style['col-md-2']}><span className={style['col-666']}>任务来源</span><Select defaultValue="lucy" style={{ width: 189 }} onChange={handleChange}> <Option value="jack">Jack</Option> <Option value="lucy">Lucy</Option> <Option value="disabled" disabled>Disabled</Option> <Option value="Yiminghe">yiminghe</Option> </Select></li> <li className={style['col-md-2']}><span className={style['col-666']}>任务生成时间</span><DatePicker style={{ width: 189 }} defaultValue={moment('2015-01-01', 'YYYY-MM-DD')} onChange={onChange} /></li> </ul> <div className={style['Title']}> <span className='ellipse'></span>体检人信息 </div> <ul className="clearfix"> <li className={style['col-md-2']}><span className={style['col-666']}>体检人姓名</span> <input type="text" /> </li> <li className={style['col-md-2']}><span className={style['col-666']}>分公司</span><Select defaultValue="lucy" style={{ width: 189 }} onChange={handleChange}> <Option value="jack">Jack</Option> <Option value="lucy">Lucy</Option> <Option value="disabled" disabled>Disabled</Option> <Option value="Yiminghe">yiminghe</Option> </Select></li> <li className={style['col-md-2']}><span className={style['col-666']}>证件类型</span><Select defaultValue="lucy" style={{ width: 189 }} onChange={handleChange}> <Option value="jack">Jack</Option> <Option value="lucy">Lucy</Option> <Option value="disabled" disabled>Disabled</Option> <Option value="Yiminghe">yiminghe</Option> </Select></li> <li className={style['col-md-2']}><span className={style['col-666']}>证件号码</span><input type="text" /></li> <li className={style['col-md-2']}><span className={style['col-666']}>投保人姓名</span><input type="text" /></li> <li className={style['col-md-2']}><span className={style['col-666']}>营销员姓名</span><input type="text" /></li> <li className={style['col-md-2']}><span className={style['col-666']}>营销员电话</span><input type="text" /></li> </ul> <div className={style['Title']}> <span className='ellipse'></span>预约信息 </div> <ul className="clearfix appointment-info" style={{marginBottom:"0px"}}> <li className={style['lh20']}><span className={style['col-666']}>体检机构</span> <Cascader style={{ width: 150 }} options={options} onChange={onChange} placeholder="Please select" showSearch={{ filter }} /> </li> <li className={style['lh20']}><span className={style['col-666']}>体检时间</span><DatePicker style={{ width: 189 }} defaultValue={moment('2015-01-01', 'YYYY-MM-DD')} onChange={onChange} /><TimePicker onChange={onChange} style={{ width: 250 }} defaultOpenValue={moment('00:00:00', 'HH:mm:ss')} /></li> <li style={{float:"left",width:"50%",marginBottom:"0px"}} className={style['lh20']}><span className={style['col-666']}>体检套餐</span> <div className={style['container']}> <span>体检项目A</span> <span>体检项目A</span> </div></li> <li style={{float:"left",width:"50%",marginBottom:"0px"}} className={style['lh20 col-md-2']}> <span className={style['col-666']}>追加体检项目</span> <div className={style['container']}> <span>体检项目A</span> <span>体检项目A</span> </div> </li> </ul> </div> </div> </div> } } export default UnreservedPopup;
const fs = require('fs'); const should = require('should'); const httpMocks = require('node-mocks-http'); const models = require('../../../server/models'); const VendorController = require('../../../server/controllers/vendors/controller'); let res, error, req, mockVendor; describe('Vendor Controller', () => { 'use strict'; mockVendor = { name: 'Test Vendor', description: 'Test Vendor description', imageUrl: 'https://some.image.url', imagePublicId:'vendors/Test Vendor' , location: 'Some test location', longitude:24.5 , latitude: -23.5, }; error = { message: 'An error occured' }; beforeEach(done => { res = httpMocks.createResponse({ eventEmitter: require('events').EventEmitter }); models.sequelize.sync({ force: true }).then(() => { done(); }); }); afterEach(done => { models.sequelize.sync({ force: true }).then(() => { done(); }); }); describe('Upload', () => { it('should upload a spreadsheet containing vendors', done => { const path = '../storage/'; const files = fs.readdirSync(path); console.log('testing...'); let req = httpMocks.createRequest({ file: files[0] }); VendorController.upload(req, res); res.on('end', () => { const data = res._getData(); console.log(data); done(); }); }); }); });
document.addEventListener('DOMContentLoaded', (event) => { window.addEventListener('load', function () { window.scrollTo(0, 0); }); window.addEventListener('scroll', function () { navbarScroll(); }); function navbarScroll() { var y = window.scrollY; if (y > 2) { $('.header-container').addClass('small'); } else if (y < 2) { $('.header-container').removeClass('small'); } }; scrollToMethodSobreMi(); scrollToMethodTrabajos(); scrollToMethodContact(); playCero(); function scrollToMethodSobreMi(){ const sobreMiButton = document.querySelector('#sobre-mi'); const presentationToScroll = document.querySelector('.presentation'); sobreMiButton.addEventListener('click', function(){ presentationToScroll.scrollIntoView({behavior: "smooth", block: "start", inline: "end"}); }); } function scrollToMethodTrabajos(){ const trabajosRbutton = document.querySelector('#trabajos-realizados'); const trabajosRtoScroll = document.querySelector('#grid-section'); trabajosRbutton.addEventListener('click', function(){ trabajosRtoScroll.scrollIntoView({behavior: "smooth", block: "start", inline: "nearest"}); }); } function scrollToMethodContact(){ const contactButton = document.querySelector('#Contacto'); const contacttoScroll = document.querySelector('#contact-box'); contactButton.addEventListener('click', function(){ contacttoScroll.scrollIntoView({behavior: "smooth", block: "nearest", inline: "center"}); }); } function playCero(){ const audio0223 = document.querySelector('.audio'); const play0223 = document.querySelector('#play0223'); play0223.addEventListener('click', function(){ audio0223.play(); }); }; function pauseCero(){ const audio0223 = document.querySelector('.audio'); const play0223 = document.querySelector('#play0223'); play0223.addEventListener('click', function(){ audio0223.pause(); }); }; });
import React, { Component } from 'react' import { BrowserRouter as Router, Route } from 'react-router-dom' import Home from './home' import NewSeries from './newSeries' import EditSeries from './editSeries' import NavBar from './navBar' import Series from './Series' const About = () => <section className="intro-section"><h1>Sobre</h1></section> class App extends Component { render() { return ( <Router> <div> <NavBar/> <Route path='/series-edit/:id' component={EditSeries} /> <Route exact path='/' component={Home} /> <Route exact path='/about' component={About} /> <Route exact path='/new' component={NewSeries} /> <Route path='/series/:genre' component={Series} /> </div> </Router> ) } } export default App
//document.getElementById("click").onclick = changeColor(); document.addEventListener('DOMContentLoaded', function () { // DOMContentLoaded Will load after DOM loaded var el = document.getElementById("myBtn"); el.addEventListener('click', changeColor) // var el = document.getElementById("btnAdd"); // el.addEventListener('click', addToDoList) }) function changeColor() { var bodyColor = document.body.style.backgroundColor; document.body.style.backgroundColor = bodyColor === 'red' ? 'green' : 'red'; var btn = document.getElementById('myBtn'); btn.className = 'buttonColor' // loadcss('test'); } // function loadcss(url) { // var head = document.getElementsByTagName('head')[0]; // var link = document.createElement('link'); // link.type = 'text/css'; // link.rel = 'stylesheet'; // link.href = url; // head.appendChild(link); // } // if (el.addEventListener) // el.addEventListener("click", changeColor, false ); // else if (el.attachEvent) // Used for old browsers // el.attachEvent('onclick', changeColor); // function changeColor() { // if ( document.body.style.backgroundColor == "red"){ // document.body.style.backgroundColor = "green"; // }else{ // document.body.style.backgroundColor = "Red"; // } // }; // document.getElementById("myBtn").addEventListener("click", function(){ // document.getElementById("myBtn").backgroundColor = "Red"; // });
module.exports ={ consumer_key:' EUv1FVaIlrzVM50HUmrhfMvQm', consumer_secret:' fsGn8hFZwn3iOo7OxtQCbB50WYhEewm1ntLH4jiRHkUTO393pm', access_token_key:'997136808415707138-qxjkgOJA99zYfBXH2jA765osqqRFHcO', access_token_secret:'PpILUHwFV7IGOOg6UJLifxXArDoFu614qvLEdIkr2kO56' };
function calculaCombustivel() { var tempo = prompt("Quanto tempo de viagem?"); var velocidadeMedia = prompt("Qual foi sua velocidade média?"); var distancia = tempo * velocidadeMedia; var litros = distancia / 12; console.log( `Sua velocidade média foi de ${velocidadeMedia}km/h, o tempo gasto na viagem foi ${tempo}h, gastando ${litros.toFixed( 2 )} litros de combustivel percorrendo ${distancia}Km` ); } calculaCombustivel();
import {PropTypes} from 'prop-types'; export const PersonType = PropTypes.shape({ Person: PropTypes.shape({ name: PropTypes.shape({first: PropTypes.string.isRequired, last: PropTypes.string.isRequired, title: PropTypes.string.isRequired}), email: PropTypes.string.isRequired, phone: PropTypes.string.isRequired, dob: PropTypes.string.isRequired }) });
/** * Represents a table at a card game. */ var Table = { /** * The number of players in the table. * @private * @type {Number} */ size: undefined, /** * An array that stores the players and their locations on the table. * @private * @type {Array} */ players: undefined, /** * A table can contain many piles that do not belong to players. For example, the center pile * in trick taking games. * @type {Array} */ piles: undefined, /** * * @constructor * @returns {Table} */ create: function(size) { }, /** * Get the player at the given position. * @param {Number} pos the position on the table * @returns {Player} the player at the given position * @throws {Exception} if the position given is out of range. */ getPlayerAt: function(pos) { if ( (pos < 0) || (pos >= this.players.length) ) { throw new Exception('Table.getPlayerAt: position given is out of range: ' + pos); } else { return this.players[pos]; } } };
import express from 'express'; import {postOption, fetchJsonByNode} from '../../../common/common'; import {host} from '../../globalConfig'; let api = express.Router(); //新增字典 api.post('/addDic', async(req,res) =>{ res.send(await fetchJsonByNode(req, `${host}/dictionary-service/dictionary/service/tenant/insert`,postOption(req.body))) }); export default api;
import React, { Component } from 'react'; import {View,Text,Modal, TextInput,TouchableOpacity,StyleSheet, ScrollView,Alert,FlatList,} from 'react-native'; import firebase from 'firebase'; import db from '../config'; import MyHeader from '../MyHeader'; import { ListItem } from 'react-native-elements'; export default class HomeWorks extends Component{ constructor(){ super(); this.state={ allDetails:[],grade:'',studentName:'',email:firebase.auth().currentUser.email } } getStudentDetails=()=>{ db.collection('students').where('email','==',this.state.email).get() .then(snap=>{ snap.forEach(doc=>{ this.setState({ grade:doc.data().grade, studentName:doc.data().name, allDetails:doc.data() }) }) }) } updateCompeleteHomeWork=()=>{ } keyExtractor=(item,index)=>index.toString() renderItem = ({item,i})=>{ return( <ListItem key={i} title={item.class} ti /> ) } render(){ return( <View> <View> <MyHeader title="AllHomeWorks" navigation={this.props.navigation} /> </View> <FlatList keyExtractor={this.key} renderItem={this.renderItem} data={this.state.allDetails} /> </View> ) } }
console.log("community")
var LCInfoField = React.createClass({ render: function() { var _this = this; // Make sure that all props provided are arrays. if (!(_this.props.infoField instanceof Array)) { _this.props.infoField = [_this.props.infoField]; } // Determine how the view should be displayed. var showIfVisible = null; var spanInfo = null; var infoFieldHolderUI = []; // If empty, hide. if (_this.props.infoField.length === 0 || _this.props.infoField[0] === "") { showIfVisible = { display: "none" }; // If there's only one, display inline. } else if (_this.props.infoField.length === 1) { spanInfo = _this.props.infoField; // If multiline, display as bullet points. } else { for (var i in _this.props.infoField) { infoFieldHolderUI.push(<li>{_this.props.infoField[i]}</li>); } } return ( <div className="card-info-field" style={showIfVisible}> <span className="card-info-title">{_this.props.title}</span> {spanInfo} <ul> {infoFieldHolderUI} </ul> </div> ); } }); module.exports = LCInfoField;
// JavaScript Document /*搜索框部分脚本*/ (function() { var p=$("#wrap_absolute>p"); var popUp=$("#wrap_absolute"); var dropDownList=$("#search_b"); var input=$(".material .search_a_input"); popUp.hover(function(){popUp.css("display","block");},function(){popUp.css("display","none");}); p.hover(function(){popUp.css("display","block");$(this).css("background-color","#d0e9f8");},function(){$(this).css("background-color","#fff");}) dropDownList.click(function(){popUp.css("display","block");}) dropDownList.mouseout(function(){popUp.css("display","none");}) p.click(function() { var text=$(this).text(); oldValue=dropDownList.text(); dropDownList.text(text); if(text=="全部") { if($.trim(input.val()).length==0 || input.val()=="输入关键词,在我的素材库内搜索素材") { input.val("输入关键词,在1.2亿篇文献中搜索素材").addClass("colorGrey"); } } if(text=="我的素材库") { if($.trim(input.val()).length==0 || input.val()=="输入关键词,在1.2亿篇文献中搜索素材") { input.val("输入关键词,在我的素材库内搜索素材").addClass("colorGrey"); } } $(this).text(oldValue); popUp.css("display","none"); }) /*文本框内的信息根据选中的类别变化*/ input.focus(function() { if(dropDownList.html()=="全部") { if($(this).val()=="输入关键词,在1.2亿篇文献中搜索素材") { $(this).val("").removeClass("colorGrey"); } } else { if(dropDownList.html()=="我的素材库") { if($(this).val()=="输入关键词,在我的素材库内搜索素材") { $(this).val("").removeClass("colorGrey"); } } } }) /*文本框内的信息根据选中的类别变化*/ input.blur(function() { if(dropDownList.html()=="全部") { if($(this).val()=="") { $(this).val("输入关键词,在1.2亿篇文献中搜索素材").addClass("colorGrey"); } } else { if(dropDownList.html()=="我的素材库") { if($(this).val()=="") { $(this).val("输入关键词,在我的素材库内搜索素材").addClass("colorGrey"); } } } }) })()
import React, { Component } from 'react' import { StatusBar, View, Text, Image, TouchableOpacity } from 'react-native' import { connect } from 'react-redux' import { Images } from '../Themes' // Styles import styles from './Styles/OnBoardingScreenStyle' class OnBoardingScreen extends Component { static navigationOptions = ({ navigation }) => ({ header: null }) constructor (props) { super(props) this.state = {} } render () { return ( <View style={styles.container}> <StatusBar barStyle='dark-content' backgroundColor='white' /> <Image source={Images.logo} style={styles.logo} resizeMode='stretch' /> <Text style={styles.about}>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed consequat tortor justo, at posuere ex blandit at.</Text> <TouchableOpacity style={styles.btnGetStarted} activeOpacity={0.9} onPress={() => this.props.navigation.navigate('App')}> <Text style={styles.btnGetStartedLabel}>Get Started</Text> </TouchableOpacity> </View> ) } } const mapStateToProps = (state) => { return { } } const mapDispatchToProps = (dispatch) => { return { } } export default connect(mapStateToProps, mapDispatchToProps)(OnBoardingScreen)
// libraries import React from 'react'; import { Link } from 'react-router-dom'; import styled from 'styled-components'; // components import Brand from './Brand'; // styled elements import g from './../js/global'; import List from '../elements/List'; const Header = () => { // + styles const HeaderContainer = styled.header` background-image: linear-gradient(${g.BGColor1}, rgb(10, 10, 10)); font-weight: 600; &::after{ content: ''; display: table; clear: both; } `; const NavContainer = styled.nav` color: white; margin: 0 ${g.Margin[0]}px; @media ${g.Sizes.M} { margin: 0 ${g.Margin[1]}px; } `; const BrandContainer = styled.div` float: left; @media ${g.Sizes.S} { float: none; text-align: center; a { justify-content: center; } } `; const RightNav = styled.nav` float: right; @media ${g.Sizes.S} { float: none; text-align: center; ul { display: block; } } `; const SLink = styled(Link)` text-decoration: none; color: white; a { text-decoration:none; color: white; } &:hover { transition: 0.3s; background-color: rgb(77, 77, 77); } `; // - styles return ( <HeaderContainer> <NavContainer> <BrandContainer> <Brand /> </BrandContainer> <RightNav> <List.ul> <SLink to='/'><List.li>Home</List.li></SLink> <SLink to='/games'><List.li>Games</List.li></SLink> <SLink to='/news'><List.li>News</List.li></SLink> <SLink to='/careers'><List.li>Careers</List.li></SLink> <SLink to='/contact'><List.li>Contact</List.li></SLink> <SLink to='/about'><List.li>About</List.li></SLink> </List.ul> </RightNav> </NavContainer> </HeaderContainer> ) } export default Header
'use strict'; angular .module('dashCtrl', ['ui.router', 'ngAnimate', 'satellizer', 'ngDragDrop', 'ui.bootstrap']);
import React from 'react'; import { Breadcrumb, BreadcrumbItem, Row, Col } from 'reactstrap'; import s from '../styles/Dashboard.module.scss'; export default function Dashboard() { return ( <div className={s.root}> <Breadcrumb> <BreadcrumbItem>YOU ARE HERE</BreadcrumbItem> <BreadcrumbItem active>Dashboard</BreadcrumbItem> </Breadcrumb> <h1 className='mb-lg'>Dashboard</h1> <Row className='content'> <Col sm={12} md={6}></Col> </Row> </div> ); }
import React from "react"; import Button from 'react-bootstrap'; class Home extends React.Component{ constructor(props){ super(props); this.state = { age : props.Age, status : 0, HomeLink : props.InitialHomeLink }; setTimeout(() => { this.setState({ status : this.state.status = 1} ) }, 3000); console.log("I am from Home Component's constructor"); } componentWillMount(){ console.log("In Component will mount method") } componentDidMount(){ console.log("Component did mount method") } componentWillReceiveProps(nextProps){ console.log("Updating part, componentWillReceiveProps ", nextProps); } shouldComponentUpdate(nextProps, nextState){ console.log("Updating part, shouldComponentUpdate", nextProps, nextState); return true; } componentWillUpdate(nextProps, nextState){ console.log("Updating part, componentWillUpdate ", nextProps, nextState); } componentDidUpdate(prevProps, prevState){ console.log("Updating part, componentDidUpdate ", prevProps, prevProps); } OnIncreaseAge(){ this.setState({ age : this.state.age + 3 }); console.log(this.state.age); } onChangeLink(){ this.props.OnChangeLink(this.state.HomeLink); } HandleHomeLinkChange(event){ this.setState({ HomeLink: event.target.value }) } render(){ return( <div> <h1>In Home Component</h1> <p>Name = {this.props.Name}</p> <p>Age = {this.state.age}</p> <p>status = {this.state.status}</p> <div> <button onClick={() => this.OnIncreaseAge()}> Click to Increase Age </button> </div> <div> <button onClick={this.props.Greet}> Click To Greet </button> </div> <div> <input type="text" value={this.state.HomeLink} onChange={(event) => this.HandleHomeLinkChange(event)}/> <button onClick={() => this.onChangeLink()}> Change Link </button> </div> </div> ); } } export {Home};
function checkEmptyElement(element) { var fe = element; if ( fe.val() == '' ) { fe.css({'border-color':'#ff0000'}) setTimeout(function(){ fe.removeAttr('style'); },500); return true; } return false; }; function checkNaNElement(element) { var fe = element; if ( isNaN(fe.val()) ) { fe.css({'border-color':'#0000ff'}) setTimeout(function(){ fe.removeAttr('style'); },500); return true; } return false; }; function ajaxCreate() { var checkempty = true; if (checkEmptyElement($('#CreateInputACCENUMB'))) checkempty = false; if (checkNaNElement($('#CreateInputACCENUMB'))) checkempty = false; if (checkEmptyElement($('#CreateInputCOUNTRY'))) checkempty = false; if (checkEmptyElement($('#CreateInputACCENAME'))) checkempty = false; if (checkEmptyElement($('#CreateInputYEAR'))) checkempty = false; if (checkNaNElement($('#CreateInputYEAR'))) checkempty = false; if (checkEmptyElement($('#CreateInputHEIGHT'))) checkempty = false; if (checkNaNElement($('#CreateInputHEIGHT'))) checkempty = false; if (checkEmptyElement($('#CreateInputDATEM'))) checkempty = false; if (checkNaNElement($('#CreateInputDATEM'))) checkempty = false; if (checkEmptyElement($('#CreateInputDATED'))) checkempty = false; if (checkNaNElement($('#CreateInputDATED'))) checkempty = false; if (checkNaNElement($('#CreateInputSTAB1'))) checkempty = false; if (checkNaNElement($('#CreateInputSTAB2'))) checkempty = false; if (checkNaNElement($('#CreateInputSTAB3'))) checkempty = false; if(checkempty == false) return; $('#createPopUp').animate({opacity: 0}, 198, function(){ $(this).css('display', 'none'); $('#createOverlay').fadeOut(297); }); $.ajax({ type: "POST", url: "createsample", data: { CreateInputACCENUMB:$('#CreateInputACCENUMB').val(), CreateInputCOUNTRY:$('#CreateInputCOUNTRY').val(), CreateInputACCENAME:$('#CreateInputACCENAME').val(), CreateInputYEAR:$('#CreateInputYEAR').val(), CreateInputHEIGHT:$('#CreateInputHEIGHT').val(), CreateInputDATEM:$('#CreateInputDATEM').val(), CreateInputDATED:$('#CreateInputDATED').val(), CreateInputSTAB1:$('#CreateInputSTAB1').val(), CreateInputSTAB2:$('#CreateInputSTAB2').val(), CreateInputSTAB3:$('#CreateInputSTAB3').val() }, success: function(response) { ajaxSearch(); $('#createPopUp').animate({opacity: 0}, 198, function(){ $(this).css('display', 'none'); $('#createOverlay').fadeOut(297); }); } }); };
bznsPreview: { Comment: { comment:String, userId:Number }, bznsProfile: { bizName:String, bizAddress:String, bizcategory: { catId:Number, catName:String }, bizcity:String }, Rating: { totalReviews:Number, avgRating:Number } }
"use strict"; let done = document.querySelector(".btn-success"); let taskName = document.querySelector("#taskName"); let actionState = document.querySelector("#actionState"); let date = document.querySelector("#date"); let listItems = document.querySelector(".list-group"); let addNew = document.querySelector("#inputTodo"); let doneIcon = [ `<i class="fa fa-check-square-o" aria-hidden="true"></i>`, `<i class="fa fa-undo" aria-hidden="true"></i>` ]; let curIndex; let updateState = false; const todos = []; (function() { main(); })(); function init() { taskName.textContent = "ADD TODO"; addNew.value = ""; } function list_template_gen(text, state, date, index, icon, _isDone) { // let className = _isDone ? "strike" : ""; return `<li class="list-group-item list-group-item-info" id = "${index}"> <div class="row"> <div class="col-md-9"> <div class="row"> <div class="col-sm-8"> ${text} </div> <div class="col-sm-4"> <span class="badge badge-pill badge-primary">${state}</span> <span class="badge badge-pill badge-secondary">${date}</span> </div> </div> </div> <div class="col-md-3"> <div class="btn-group" role="group"> <button type="button" class="btn btn-success" onClick = "taskDone(this.parentNode.parentNode.parentNode.parentElement.id)">${icon}</button> <button type="button" class="btn btn-warning"onClick = "taskEdit(this.parentNode.parentNode.parentNode.parentElement.id)"><i class="fa fa-pencil-square-o" aria-hidden="true"></i></button> <button type="button" class="btn btn-danger" onClick = "taskDel(this.parentNode.parentNode.parentNode.parentElement.id)"><i class="fa fa-trash" aria-hidden="true"></i></button> </div> </div> </div> </li>`; } function addItems() { todos.unshift({ id: todos.length + 1, task: addNew.value, state: "CREATED", date: new Date().toUTCString(), icon: doneIcon[0], isDone: false }); showItems(); } function showItems() { init(); let html = ""; for (let i = 0; i < todos.length; i++) { html += list_template_gen( todos[i].task, todos[i].state, todos[i].date, todos[i].id, todos[i].icon, todos[i].isDone ); } listItems.innerHTML = html; } function main() { init(); showItems(); } addNew.addEventListener("keypress", e => { let key = e.which || e.keyCode; if (key === 13) { if (!updateState) { addItems(); } else { updateState = false; todos[curIndex].task = addNew.value; todos[curIndex].state = "UPDATED"; todos[curIndex].date = new Date().toUTCString(); showItems(); } } }); function getIndex(parElem) { // console.log(parElem.parentElement.id); console.log(parElem); } function taskDone(id) { let element = document.getElementById(`${id}`); element.classList.toggle("strike"); } function taskDel(_id) { let removeIndex = todos.map(item => item.id).indexOf(parseInt(_id, 10)); todos.splice(removeIndex, 1); showItems(); } function taskEdit(_id) { updateState = true; taskName.textContent = "EDIT TODO"; curIndex = todos.map(item => item.id).indexOf(parseInt(_id, 10)); addNew.value = todos[curIndex].task; }
var Long = require('long'); var NBT = require('../dist/PowerNBT'); var assert = require('assert'); describe('NBT.NBTTagLong', function(){ describe('constructor', function(){ it('should be equal 0' , function(){ assert.equal(0, new NBT.NBTTagLong()); assert.equal(0, new NBT.NBTTagLong(undefined)); assert.equal(0, new NBT.NBTTagLong(null)); assert.equal(0, new NBT.NBTTagLong(0)); assert.equal(0, new NBT.NBTTagLong("")); assert.equal(0, new NBT.NBTTagLong("0")); }); it('should have name' , function(){ assert.equal("name", new NBT.NBTTagLong(0, "name").name); assert.equal("", new NBT.NBTTagLong(0, "").name); assert.equal("", new NBT.NBTTagLong(0).name); }); it('should have value' , function(){ assert.equal(1, new NBT.NBTTagLong(1)); }); }); describe('#type', function(){ it('should be equal TAG_LONG' , function(){ assert.equal(NBT.Type.TAG_LONG, new NBT.NBTTagLong().type); }); }); describe('#setValue', function(){ var tag = new NBT.NBTTagLong(); it('should change numeric value' , function(){ tag.setValue(20); assert.equal(20, tag); }); it('should change string value' , function(){ tag.setValue("-20"); assert.equal(-20, tag); tag.setValue("0x3a"); assert.equal(58, tag); tag.setValue("-0x3a"); assert.equal(-58, tag); }); it('should change tag value' , function(){ tag.setValue(new NBT.NBTTagLong(15)); assert.equal(15, tag); }); it('should apply max value', function(){ tag.setValue(NBT.NBTTagLong.MAX_VALUE); assert.equal(NBT.NBTTagLong.MAX_VALUE, tag); }); it('should apply min value', function(){ tag.setValue(NBT.NBTTagLong.MIN_VALUE); assert.equal(NBT.NBTTagLong.MIN_VALUE, tag); }); it('should apply max string value', function(){ tag.setValue(NBT.NBTTagLong.MAX_VALUE_STR); assert.equal(NBT.NBTTagLong.MAX_VALUE_STR, tag); }); it('should apply min string value', function(){ tag.setValue(NBT.NBTTagLong.MIN_VALUE_STR); assert.equal(NBT.NBTTagLong.MIN_VALUE_STR, tag); }); it('should apply overflow', function(){ tag.setValue("9223372036854775808"); assert.equal("-9223372036854775808", tag); tag.setValue("-9223372036854775809"); assert.equal("9223372036854775807", tag); }); }); describe('#clone', function(){ var a = new NBT.NBTTagLong(123); var b = a.clone(); it('should not return this', function(){ assert.notEqual(a, b); }); it('should return it instance', function(){ assert.ok(b instanceof NBT.NBTTagLong); }); it('clone should be equal to this as number', function(){ assert.equal(a.valueOf(), b.valueOf()); }); it('clone should be equal to this as string', function(){ assert.equal(a.toString(), b.toString()); }); }); });
import { SHOW_LIST, UPDATE_DEVOPS, EXPORT_LIST, UPDATE_ENGINEERING, DELETE_DEVOPS, DELETE_ENGINEERING } from '../constants/types' const initialState = { items: [], item: {} } export default function (state = initialState, action) { switch (action.type) { case SHOW_LIST: return { ...state, items:action.payload } case UPDATE_DEVOPS: return { ...state, item: action.payload } case UPDATE_ENGINEERING: return { ...state, item: action.payload } case EXPORT_LIST: return { ...state, items: action.payload } case DELETE_DEVOPS: return { ...state, item: action.payload } case DELETE_ENGINEERING: return { ...state, item: action.payload } default: return state; } }
import React from 'react'; import './announcements.css'; import DeleteAnnouncement from './deleteAnnouncement.js' import EditAnnouncement from './editAnnouncement.js' import { TiDelete } from 'react-icons/ti'; import ReactQuill from 'react-quill'; import "react-quill/dist/quill.bubble.css"; export default class announcementPost extends React.Component { deleteRef = React.createRef(); editRef = React.createRef(); constructor(props) { super(props); this.state = { loggedIn: props.loggedIn, id: props.details._id, title: props.details.title, date: props.details.createdAt, body: props.details.body, isCollapsed: props.isCollapsed } } componentDidUpdate(previousProps) { if (previousProps !== this.props) { this.setState({ loggedIn: this.props.loggedIn, id: this.props.details._id, title: this.props.details.title, body: this.props.details.body, date: this.props.details.createdAt, isCollapsed: this.props.isCollapsed }) } } onDelete = () => { this.deleteRef.current.openDialog(); } onEdit = () => { this.editRef.current.openDialog(); } to12HourTime = (hour, minute) => { let h = hour % 12 == 0? 12: hour % 12 let ampm = hour < 12? 'AM' : 'PM' return `${h}:${minute}${ampm}` } addComma = (date) => { return `${date.slice(0, -5)}, ${date.slice(-5)}` } render() { const d = new Date(this.state.date) const dateStr = this.addComma((d.toDateString()).slice(3)) + " at " + this.to12HourTime(d.getHours(), d.getMinutes()) return ( <> {this.state.loggedIn && <div className="admin-buttons"> <div className="Edit-Button" onClick={this.onEdit}> Edit </div> <TiDelete className="delete-announcement-button clickable" onClick={this.onDelete}/> </div> } <div className="announcement-post" > <EditAnnouncement ref={this.editRef} body={this.state.body} title={this.state.title} id={this.state.id} rerenderCallback={this.props.rerenderCallback} /> <DeleteAnnouncement ref={this.deleteRef} id={this.state.id} rerenderCallback={this.props.rerenderCallback} /> {this.state.isCollapsed? <> <p className="collapsed-title post-title"> {this.state.title} </p> <p className="post-date">{dateStr}</p> </> : <> <p className="post-title"> {this.state.title} </p> <p className="post-date"> {dateStr} </p> <ReactQuill className="post-body" value={this.state.body} readOnly={true} theme={"bubble"} /> </> } </div> </> ) } }
// Get from query hash String.prototype.getQueryHash = function (name, defaultVal) { name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); var regex = new RegExp("[\\#&$]" + name + "=([^&#]*)"), results = regex.exec(this); return results == null ? (defaultVal == undefined ? "" : defaultVal) : decodeURIComponent(results[1].replace(/\+/g, " ")); }; // function cityChange(country_id) // { // var data = "country="+country_id; // $.ajax({ // async: true, // url: 'index.php?route=account/account/country', // type: 'POST', // data: data , // success: function (html) { // $("#state").html(html) ; // } // }); // } function cityChange(country_id) { $.ajax({ url: 'index.php?route=account/account/country&country_id=' + country_id, dataType: 'json', beforeSend: function() { $('select[name=\'city\']').after(' <i class="fa fa-circle-o-notch fa-spin"></i>'); }, complete: function() { $('.fa-spin').remove(); }, success: function(json) { html = '<option value="">Chọn quận huyện</option>'; if (json['zone'] && json['zone'] != '') { for (i = 0; i < json['zone'].length; i++) { html += '<option value="' + json['zone'][i]['zone_id'] + '"'; if (json['zone'][i]['zone_id'] == '<?php echo $zone_id; ?>') { html += ' selected="selected"'; } html += '>' + json['zone'][i]['name'] + '</option>'; } } else { html += '<option value="0" selected="selected">Không tìm thấy</option>'; } $('#state').html(html); }, error: function(xhr, ajaxOptions, thrownError) { alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); } }); }; function scrollToDealer () { var targetOffset = $("#boxMapSearch").offset().top - 120; jQuery('html,body').animate({scrollTop: targetOffset},1000); } $(document).ready(function(){ $('#btn_list').click(function () { var $this = $(this); if ($this.hasClass('active')) { $this.removeClass(); $('ul.list-filters').css({ "display": "none" }); } else { $this.addClass('active'); $('ul.list-filters').css({ "display": "block" }); } }); /* $(".result-wrapper").slimScroll({ height: '560px', size: '10px', position: 'right', color: '#cccccc', alwaysVisible: true, distance: '20px', railVisible: false, railColor: '#222', railOpacity: 1, wheelStep: 10, allowPageScroll: true, disableFadeOut: true }); */ });
const { Router } = require("express"); const routes = Router(); const CategoryController = require("../controllers/category") routes.post('/', CategoryController.post); routes.get('/', CategoryController.get); routes.put('/:id', CategoryController.put); routes.delete('/:id', CategoryController.delete); module.exports = routes;
import ProductCart from "../ProductCart"; import "./styles.css"; function ShoppingCart({ currentSale, removeProduct, setCurrentSale }) { const initial = currentSale .reduce((acc, element) => (acc += element.price), 0) .toFixed(2); return ( <div className="shoppingCart"> <header className="shoppingCart__title"> <p>Carrinho de compras</p> </header> {currentSale.length ? ( <ul className="list-cart"> {currentSale.map((product, index) => ( <li id={index} key={index}> <ProductCart removeProduct={removeProduct} product={product} /> </li> ))} { <div className="shoppingCart__amount"> <div className="shoppingCart__amount_description"> <p>Total</p> <p className="value">{initial}</p> </div> <button onClick={() => setCurrentSale([])}>Remover todos</button> </div> } </ul> ) : ( <div className="list-clear"> <h3>Sua sacola está vazia!</h3> <p>Adicione itens</p> </div> )} </div> ); } export default ShoppingCart;
const fs = require('fs'); const path = require('path'); const shell = require('child_process').execSync; exports.default = async context => { const projectRoot = path.join(__dirname, '..'); const studioMainPath = path.join(projectRoot, 'projects', 'studio-main'); console.log('Copy Renderer...'); if (!fs.existsSync(path.join(studioMainPath, 'renderer'))) { shell(`cp -r ${path.join(projectRoot, 'dist', 'muzika-studio-renderer')} ${path.join(studioMainPath, 'renderer')}`); } };
'use strict'; const path = require('path'); module.exports = appInfo => { const config = exports = { mysql: { // 单数据库信息配置 client: { // host host: '127.0.0.1', // 端口号 port: '3306', // 用户名 user: 'root', // 密码 password: '123456', // 数据库名 database: 'dailydata', }, // 是否加载到 app 上,默认开启 app: true, // 是否加载到 agent 上,默认关闭 agent: false, }, sequelize: { dialect: 'mysql', host: '127.0.0.1', port: 3306, database: 'dailydata', timestamps: false, }, }; // use for cookie sign key, should change to your own and keep security config.keys = appInfo.name + '_1530422156442_3681'; // add your config here config.middleware = []; config.mysql = { // database configuration client: { host: '127.0.0.1', port: '3306', user: 'root', password: '12345', database: 'xhh', }, // load into app, default true app: true, // load into agent, default false agent: false, }; config.view = { defaultViewEngine: 'nunjucks', root: [ path.join(appInfo.baseDir, 'app/view'), path.join(appInfo.baseDir, 'path/to/another'), ].join(',') }; return config; };
// -- HTTP const httpData = { baseUrl: null, headers: {}, timeout: 10000 } const http = {} Object.defineProperty(http, 'baseUrl', { get: function () { return httpData.baseUrl }, set: function (newValue) { httpData.baseUrl = newValue } }) Object.defineProperty(http, 'headers', { get: function () { return httpData.headers } }) Object.defineProperty(http, 'setHeader', { value: function (name, value) { httpData.headers[name] = value } }) Object.defineProperty(http, 'timeout', { get: function () { return httpData.timeout }, set: function (newValue) { httpData.timeout = newValue } }) // -- CONFIG const config = {} Object.defineProperty(config, 'http', { value: http }) export default config export function __cleanupConfig__() { httpData.baseUrl = null httpData.headers = {} }
import app from '../lib/app'; export default { tracks: { library: { // Tracks of the library view all: null, // All tracks sub: null, // Filtered tracks (e.g search) }, playlist: { all: null, sub: null, }, }, tracksCursor : 'library', // 'library' or 'playlist' queue : [], // Tracks to be played queueCursor : null, // The cursor of the queue oldQueue : null, // Queue backup (in case of shuffle) playlists : null, playerStatus : 'stop', // Player status toasts : [], // The array of toasts repeat : app.config.get('audioRepeat'), // the current repeat state (one, all, none) shuffle : app.config.get('audioShuffle'), // If shuffle mode is enabled library : { refreshing : false, refresh : { processed: 0, total: 0, }, }, };
import React, { useContext, useState } from "react"; import "./Login.css"; import google from "../../images/google.png"; import { UserContext } from "../../App"; import { useHistory, useLocation } from "react-router"; import { handleGoogleSignIn, initializeLoginFramework } from "./LoginManager"; const Login = () => { // useContext() const [loggedInUser, setLoggedInUser] = useContext(UserContext); // PrivateRoute const history = useHistory(); const location = useLocation(); let { from } = location.state || { from: { pathname: "/" } }; // useState() for firebase const [user, setUser] = useState({ isSignin: false, name: "", email: "", password: "", photo: "", success: false, error: "", }); initializeLoginFramework(); const handleAllFunctionResponse = (response, redirect) => { setUser(response); setLoggedInUser(response); if (redirect) { history.replace(from); } }; // google validation using firebase const googleSignIn = () => { handleGoogleSignIn().then((response) => { handleAllFunctionResponse(response, true); }); }; return ( <div className="login"> <h1 className="loginHeader"> Welcome to <br /> Electronics Repair Service </h1> <h4 className="loginTitle">Login With</h4> <div className="socialButton"> <button className="button" onClick={googleSignIn}> <img src={google} className="googleImage" /> Continue with Google </button> </div> </div> ); }; export default Login;
// Filename: views/Search.FilterView.js // Search Filter View // --------------- define([ 'cat', 'jquery', 'underscore', 'backbone', 'marionette', 'ev', 'models/Filter', // 'text!templates/search-filter-simple.html', 'jquery.chosen' ], function(cat, $, _, Backbone, Marionette, ev, Filter, searchFilterTpl){ return Marionette.ItemView.extend({ // template: _.template( searchFilterTpl ), initialize: function(options) { this.options = options; this.template = options.template; _.bindAll(this,'initChosen','updateEntryRows'); this.updateSearch = _.debounce(this.updateEntryRows, 500); this.listenTo( this.model, 'change', this.updateSearch, this ); this.listenTo( this.model, 'change:categories[*].selected', this.updateSearch, this ); this.listenTo( this.model, 'change:mediatypes[*].selected', this.updateSearch, this ); this.listenTo( this.model, 'change:essentials[*].selected', this.updateSearch, this ); this.listenTo( this.model, 'change:authors[*].selected', this.updateSearch, this ); this.listenTo( this.model, 'change:tags[*].selected', this.updateSearch, this ); this.listenTo( this.model, 'change:viewtime[*].selected', this.updateSearch, this ); ev.vent.on('resized',this.updateChosen,this); }, events: { 'focus #search_query': 'searchFocus', 'keyup #search_query': 'searchQuery', 'keyup': 'checkKey', 'click #advanced_filter_btn': 'advancedFilter', 'click #featured_search_btn' : 'featuredSearches', 'change .chzn-select': 'filterUpdate', 'click .search-choice-close': 'filterUpdate', 'click #featured_searches_set ul li a': 'featuredSearch', 'click .clear_search': 'clearSearch' }, onRender: function() { var self = this; _.defer( self.initChosen ); }, featuredSearch: function( vent ) { vent.preventDefault(); $('#search_query').val(vent.currentTarget.outerText); $('#search_query').trigger('keyup'); $('#search_query').focus(); }, filterUpdate: function( vent ){ var collectionName = vent.target.id; _.each(vent.target, function( opt ){ if (opt.selected) { this.model.get(collectionName).at(opt.index).set({ selected: true }); } else { this.model.get(collectionName).at(opt.index).set({ selected: false }); } }, this); var chosenString = ""; var chosenCount = $(vent.target).parent().find('.chzn-container .search-choice').size(); var chosenID = '#' + collectionName + '_chzn'; // Add 'and' if($(chosenID + ' .search-choice').size() > 1){ $(chosenID + ' .and').remove(); $(chosenID + ' .search-choice:last').prepend('<span class="and"> and </span>'); } // Add , if($(chosenID + ' .search-choice').size() > 2){ $(chosenID + ' .comma').remove(); $(chosenID + ' .search-choice').slice(0, -2).append('<span class="comma">, </span>'); } if(chosenCount > 0){ $('.chzn-choices .search-choice').each(function(){ chosenString += '<span class="filter_tag">' + $('span:not(".and, .comma")', this).text() + '<a href="javascript:void(0)" class="search-choice-close close_btn" rel="0"></a></span>'; }); $('#tag_container').html(chosenString); } else { chosenString = ""; $('#tag_container').html(''); } }, updateEntryRows: function() { // iterate through search model to create search query post vars var searchModel = this.model; var selectedFilters = 0; function mapFilterArray( collection ) { var selectedSet = searchModel.get(collection).where({ selected: true }); var newArray = _.map(selectedSet,function( tag ){ return tag.get('title'); }); selectedFilters += newArray.length; return newArray; } cat.Filter.tagList = mapFilterArray('tags'); cat.Filter.categoryList = mapFilterArray('categories'); cat.Filter.authorList = mapFilterArray('authors'); cat.Filter.essentialList = mapFilterArray('essentials'); cat.Filter.mediaList = mapFilterArray('mediatypes'); cat.Filter.viewtimeList = mapFilterArray('viewtime'); cat.Filter.keywords = searchModel.get('keywords'); if (selectedFilters === 0 && this.model.get('keywords') === '') { this.clearSearch(); return; } ev.vent.trigger('filter', searchModel); $('#form_search .loader').css('display', 'none'); $('#form_search .clear_search').css('display', 'block'); }, checkKey: function (vent) { if(vent.keyCode == 13) { vent.preventDefault(); return false; } else { this.pageScrollTo('#content_filter',100); $('#search_query').focus(); } }, searchFocus: function ( target ) { var offset = (cat.Options.phone) ? 0 : 100; this.pageScrollTo('#content_filter',offset); $('#featured_searches').stop().dequeue().transition({ height: '100px' }, 200, 'easeOutExpo', function(){ $(this).css('overflow', 'visible'); }); }, clearSearch: function ( vent ) { if (vent) vent.preventDefault(); this.model.set({ keywords: '' },{silent: true}); cat.Filter.keywords = this.model.get('keywords'); ev.vent.trigger('filter:remove', this.model); $('#form_search .clear_search').css('display', 'none'); $('#form_search .loader').css('display', 'none'); $('#form_search input').val(''); this.updateSearch(this.model); }, searchQuery: function ( vent ) { var self = this; if (vent.target.value.length > 0) { $('#form_search .clear_search').css('display', 'none'); $('#form_search .loader').css('display', 'block'); this.model.set({ keywords: vent.target.value }); } else { this.clearSearch(); } }, pageScrollTo: function( target, offset ) { var scrollTo = $(target).offset().top - offset; $('html, body').stop().dequeue().animate({ scrollTop: scrollTo }, 500); }, featuredSearches: function() { if(cat.Options.screenType == 'phone' || cat.Options.screenType == 'desktop-small'){ var resultsHeight = $('#featured_searches_set ul').outerHeight(); if($('#featured_search_btn').hasClass('active')) { $('#featured_search_btn').removeClass('active'); $('#featured_searches_set, #featured_searches').stop().dequeue().transition({ height: 0 }, 200, 'easeOutExpo'); } else { $('#featured_search_btn').addClass('active'); $('#featured_searches_set, #featured_searches').stop().dequeue().transition({ height: resultsHeight + 'px' }, 200, 'easeOutExpo'); } } return false; }, advancedFilter: function() { if(!cat.Options.searchActive){ cat.Options.searchActive = true; } else { cat.Options.searchActive = false; } if (cat.Options.searchActive) { this.openFilters(); } else { this.closeFilters(); } // this.checkSelectedTags(); return false; }, openFilters: function() { // $('#advanced_filter_btn').text('Advanced Filters –'); $('#advanced_filter_btn').addClass('active'); this.pageScrollTo('#content_filter', -34); this.filtersHeight(); }, closeFilters: function() { // $('#advanced_filter_btn').text('Advanced Filters +'); $('#advanced_filter_btn').removeClass('active'); $('#filters').css('overflow', 'hidden'); $('#filters').stop().dequeue().transition({ height: 0 }, 200, 'easeOutExpo'); this.searchFocus(); }, filtersHeight: function(){ var filtersHeight = $('#filters .container').outerHeight(); $('#filters').stop().dequeue().transition({ height: filtersHeight+30 + 'px' }, 200, 'easeOutExpo', function(){ $(this).css('overflow', 'visible'); }); }, checkSelectedTags: function() { var resultsHeight = $('#filter_tags .search_wrapper').outerHeight(); if($('#filter_tags .filter_tag').size() > 0){ $('#filter_tags').stop().dequeue().transition({ height: resultsHeight + 'px' }, 200, 'easeOutExpo', function(){ $(this).css('overflow', 'visible'); }); } else { $('#filter_tags').css('overflow', 'hidden'); $('#filter_tags').stop().dequeue().transition({ height: 0 }, 200, 'easeOutExpo'); } }, initChosen: function() { $('.dropdown_set .chzn-container').each(function (index) { $(this).css({ 'min-width': '100%', 'max-width': '100%' }); }); $('.chzn-select').chosen().removeClass('hide'); }, updateChosen: function(){ $('.dropdown_set .chzn-container').each(function (index) { $(this).css({ 'min-width': '100%', 'max-width': '100%' }); }); }, createResults: function(){ var allChoices = ''; var allChoicesTotal = 0; var currentSearch = $('#search_query').val(); var results = ''; $('.chzn-choices').each(function(){ var i = 0; var choices = ''; var totalResults = $('.search-choice', this).size(); $('.search-choice', this).each(function(){ i++; choices += $('span', this).text(); if(i < totalResults){ choices += ' & '; } }); allChoicesTotal++; if(totalResults > 0 && allChoicesTotal > 1){ if(allChoices !== '') allChoices += ', '; } allChoices += choices; }); if (allChoices === '' && currentSearch === ''){ results = 'No results.'; $('#featured_entries').collapse('show'); $('#filter_results').collapse('hide'); $('.search_title').each(function(){ $(this).addClass('hide'); }); } else { if (currentSearch !== '') currentSearch = '"' + currentSearch + '"'; results = '123 Results '; if (currentSearch !== '') results += 'for '; results += currentSearch; if (allChoices !== '') results += ' in '; results += allChoices; // $('#filter_results span').text(results); if ($('#featured_entries').hasClass('in')) { $('#featured_entries').collapse('hide'); } if (!$('#filter_results').hasClass('in')) { $('#filter_results').collapse('show'); } $('.search_title').each(function(){ $(this).removeClass('hide'); }); } this.filtersHeight(); } }); });
import { GET_DOGS, ADD_DOG, DELETE_DOG, DOGS_LOADING, DOGS_LOADING_FAIL } from '../actions/types'; const initialState = { dogs: [], loading: false }; export default function(state = initialState, action) { switch (action.type) { case GET_DOGS: return { ...state, dogs: [...action.payload], loading: false }; case ADD_DOG: return { ...state, dogs: [action.payload, ...state.dogs], loading: false }; case DELETE_DOG: return { ...state, dogs: state.dogs.filter(dog => dog._id !== action.payload), loading: false }; case DOGS_LOADING: return { ...state, loading: true }; case DOGS_LOADING_FAIL: return { ...state, loading: false }; default: return state; } }
import React, {Component} from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import Board from '../components/Board'; import BackToGames from '../components/BackToGames'; import { fetchGames } from '../actions/games'; import { playerAction } from '../actions/game'; import { IN_PROGRESS, DRAW } from '../utils/gamesConstants'; import { startPool, stopPool, setCurrentGame, resetCurrentGame } from '../actions/session'; const style = { textAlign: 'center' }; class Game extends Component { componentWillMount() { this.props.startPooling() if (this.props.game) { this.props.setCurrentGame() } }; componentWillUnmount(){ this.props.resetCurrentGame() this.props.stopPooling() }; render(){ const { onPlayerAction, username, game } = this.props; const result = () => { if (game.state.status === IN_PROGRESS) { return null } if (game.state.status === DRAW) { return 'Draw' } return 'You ' + (game.state.winner === username ? 'Won' : 'Lost') }; const playerSymbol = () => game.creatorUsername === username ? 'cross' : 'circle'; const turn = () => { if (game.state.status !== IN_PROGRESS) { return } return game.state.currentPlayer === username ? 'Your turn!' : 'Waiting for opponent ...' }; return ( <div style={style}> <BackToGames /> <br/> You are the { playerSymbol() } <br/> <Board game={ game } username={ username } onPlayerAction={ onPlayerAction } /> <br/> <div>{ turn() }</div> <br/> <div>{ result() }</div> </div> ) } } const mapDispatchToProps = (dispatch, ownProps,a) => { const gameId = ownProps.match.params.id return ({ onPlayerAction(cell) { dispatch( playerAction(gameId, cell)) }, fetchGames(input) { dispatch(fetchGames()) }, startPooling() { dispatch(startPool()) }, stopPooling() { dispatch(stopPool()) }, setCurrentGame() { dispatch(setCurrentGame(gameId)) }, resetCurrentGame() { dispatch(resetCurrentGame()) }, }) } const mapStateToProps = (state, ownProps) => { const gameId = ownProps.match.params.id const game = state.games ? state.games[gameId] : null return ({ username: state.session.username, game: game }) }; Game.propTypes = { onPlayerAction: PropTypes.func.isRequired, fetchGames: PropTypes.func.isRequired, startPooling: PropTypes.func.isRequired, stopPooling: PropTypes.func.isRequired, setCurrentGame: PropTypes.func.isRequired, resetCurrentGame: PropTypes.func.isRequired, username: PropTypes.string.isRequired, game: PropTypes.object.isRequired }; Game = connect(mapStateToProps, mapDispatchToProps)(Game); export default Game;
export const fetchWithCount = async (count) => { const response = await fetch(`http://localhost:3000/api/v1/tossups/${count}`); if(!response.ok) { throw Error('Hmm something went wrong please refresh the page') } return response.json(); } export const fetchWithOptions = async (count, selectedCategories) => { const category = selectedCategories.join('&') const response = await fetch(`http://localhost:3000/api/v1/tossups/${category}/${count}`); if(!response.ok) { throw Error('Hmm something went wrong please refresh the page') } return response.json(); }
var Phaser = Phaser || {}; var GameTank = GameTank || {}; var game = new Phaser.Game(512, 416, Phaser.CANVAS, 'game'); game.state.add("BootState", new GameTank.BootState()); game.state.add("PreloadState", new GameTank.PreloadState()); game.state.add("StartState", new GameTank.StartState()); game.state.add("GameState", new GameTank.GameState()); game.state.add("OverState", new GameTank.OverState()); game.state.start("BootState");
import styled from "styled-components/macro" export const Container = styled.ul` margin: 0; padding: 1rem 0 0 0; > a { text-decoration: none; } ` export const MenuItem = styled.li`` export const MenuItemTop = styled.div` display: flex; align-items: center; transition: .1s linear background-color; cursor: pointer; :hover { background-color: ${(props) => props.theme.accent}; } ` export const MenuTitle = styled.p` color: ${(props) => props.theme.title}; flex-grow: 1; text-transform: uppercase; font-size: 18px; line-height: 1.3125rem; pointer-events: none; ` export const MenuIcon = styled.div` color: ${(props) => props.theme.title}; padding: 0 20px; pointer-events: none; svg { height: 19px; width: 19px; } ` export const MenuItemDropdown = styled.div` display: flex; flex-direction: column; gap: 5px; padding: 0 4rem; ` export const DropdownItem = styled.div` :first-child { margin-top: 1rem; } :last-child { margin-bottom: 1rem; } a { font-size: 0.875rem; line-height: 16px; color: ${(props) => props.theme.title}; text-decoration: none; :hover { color: ${props => props.theme.accent}; } } `
import React, { forwardRef } from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import styles from './Button.css'; const VARIANT = { PRIMARY: 'PRIMARY', SECONDARY: 'SECONDARY', NO_OUTLINE: 'NO_OUTLINE', }; const SIZE = { LARGE: 'LARGE', MEDIUM: 'MEDIUM', SMALL: 'SMALL', SQUARE: 'SQUARE', }; const variantClasses = { [VARIANT.PRIMARY]: styles.primary, [VARIANT.SECONDARY]: styles.secondary, [VARIANT.NO_OUTLINE]: styles.noOutline, }; const sizeClasses = { [SIZE.LARGE]: styles.large, [SIZE.MEDIUM]: styles.medium, [SIZE.SMALL]: styles.small, [SIZE.SQUARE]: styles.square, }; /** * Renders a button * @param {Object} options * @prop {String} variant * @prop {String} size * @prop {Boolean} fullWidth * @param ref * @returns {*} * @constructor */ const Button = forwardRef(({ variant, size, fullWidth, danger, children, ...buttonProps }, ref) => { const buttonClasses = clsx(variantClasses[variant], sizeClasses[size], { [styles.fullWidth]: fullWidth, [styles.danger]: danger, }); return ( // eslint-disable-next-line react/button-has-type, react/jsx-props-no-spreading <button ref={ref} className={buttonClasses} {...buttonProps}> {children} </button> ); }); Button.propTypes = { variant: PropTypes.oneOf(Object.values(VARIANT)).isRequired, size: PropTypes.oneOf(Object.values(SIZE)).isRequired, type: PropTypes.oneOf(['button', 'submit', 'reset']), fullWidth: PropTypes.bool, children: PropTypes.node, danger: PropTypes.bool, }; Button.defaultProps = { type: 'button', fullWidth: false, children: null, danger: false, }; export default Object.assign(Button, { VARIANT, SIZE });
var mongoose = require('mongoose'); var RegionSchema = new mongoose.Schema({ name: {type: String, required: true }, emails : [String], isDelete : {type : Boolean, default : false } }); var Region = mongoose.model('Region', RegionSchema); module.exports =Region;
/** * Created by alidad on 6/17/14. */ console.log("loading app"); angular.module('mypoc', ['ngRoute','ngResource']) .config([ '$routeProvider' ,'$locationProvider','$compileProvider','$logProvider', function ($routeProvider,$locationProvider,$compileProvider,$logProvider) { $logProvider.debugEnabled(true); $routeProvider .when('/grailsAngular/home', {templateUrl: 'views/home.html', controller: 'homeCtrl'}); $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|file|ijet2):/); $locationProvider.html5Mode(true); }]);