text
stringlengths
7
3.69M
import { createGlobalStyle } from "styled-components"; export const GlobalStyle = createGlobalStyle` html { font-size: 16px; } body { margin: 0; padding: 0; height: 100%; font-family: 'Noto Sans TC', Open-Sans, Arial; font-weight: 400; background: #e9e9e9; color: #505050; transition: all 0.5s linear; } * { box-sizing: border-box; } h1, p { margin: 0; } input, input[type="button"], input[type="submit"], input[type="file"], input[type="reset"], button, textarea, select { outline: none; letter-spacing: 1px; appearance: none; outline-style: none; -webkit-appearance: none; } input, textarea { resize: none; } `; export default GlobalStyle;
import React, {Component} from 'react' import {Switch} from 'react-router' import {BrowserRouter as Router, browserHistory, Link,} from 'react-router-dom' import Route from 'react-router-dom/Route' //applicaiton components import requireAuthentication from './Components/Auth/RequireAuth' import Home from './Components/Home' import Login from './Components/Login' import Logout from './Components/Logout' import Signup from './Components/Signup' import ForgotPassword from './Components/ForgotPassword' import ResetPassword from './Components/ForgotPassword/ResetPassword' import ChangePassword from './Containers/ChangePassword' import Layout from './Components/Layout' import Dashboard from './Containers/Dashboard' import ExecutiveDashboard from './Containers/Dashboard/ExecutiveDashboard' import Scans from './Containers/Scans' import CreateScan from './Containers/Scans/Create' import Applications from './Containers/Applications' import Repos from './Containers/Repos' import repoSummary from './Containers/ReposFinding' import repoFindings from './Containers/ReposFinding/repoFindings' import repoVulnerabilityTrend from './Containers/ReposFinding/RepoCharts' import toolResults from './Containers/ReposFinding/ToolResults' import Analytics from './Containers/Analytics' import Filters from './Containers/Filters' import Users from './Containers/Users' import EditUser from './Containers/Users/Edit' import Groups from './Containers/Groups' import CreateGroup from './Containers/Groups/Create' import EditGroup from './Containers/Groups/Edit' import Roles from './Containers/Roles' import CreateRole from './Containers/Roles/Create' import EditRole from './Containers/Roles/Edit' import Permissions from './Containers/Permissions' import CreatePermission from './Containers/Permissions/Create' import EditPermission from './Containers/Permissions/Edit' import ScanTypes from './Containers/ScanTypes' import newScanType from './Containers/ScanTypes/Create' import EditScanType from './Containers/ScanTypes/Edit' import Tools from './Containers/Tools' import CreateTool from './Containers/Tools/Create' import EditTool from './Containers/Tools/Edit' import signupRoleConfiguration from './Containers/DefaultRole' import hardcodeSecretsConfiguration from './Containers/HardCodeSecrets' import severityLevelConfiguration from './Containers/SeverityLevel' import Jira from './Containers/Jira' import Git from './Containers/Git' import ConfigureMails from './Containers/ConfigureMails' import SMTPSettings from './Containers/SMTPSettings' import Findings from './Containers/Findings' import findingDetail from './Containers/Findings/FindingDetail' import NotFound from './Components/NotFound' //botstrap inclusion import 'expose-loader?$!expose-loader?jQuery!jquery' import 'bootstrap/dist/css/bootstrap.min.css' import 'bootstrap/dist/js/bootstrap.min.js' export default class Root extends Component { render() { return ( <Router> <Switch> <Route exact path="/" component={Home}/> <Route path="/home" component={Home}/> <Route path="/login" component={Login}/> <Route path="/logout" component={Logout}/> <Route path="/signup" component={Signup}/> <Route path="/forgot_password" component={ForgotPassword}/> <Route path="/reset_password/:passwordToken?" component={ResetPassword}/> <Route path="/not_found" component={NotFound}/> <Layout> <Route exact path="/change_password" name="ChangePassword" component={requireAuthentication(ChangePassword)}/> <Route path="/excutive_dashboard/:ownerType/:scanType" component={requireAuthentication(ExecutiveDashboard)}/> <Route path="/dashboard/:ownerType/:scanType" component={requireAuthentication(Dashboard)}/> <Route path="/scans/:ownerType/:scanType" component={requireAuthentication(Scans)}/> <Route path="/add_scan/:ownerType/:scanType" component={requireAuthentication(CreateScan)}/> <Route path="/applications/:ownerType/:scanType" component={requireAuthentication(Applications)}/> <Route path="/repos/:ownerType/:scanType/:group?" component={requireAuthentication(Repos)}/> <Route path="/repo_vulnerability_trend/:ownerType/:scanType?/:group?" component={requireAuthentication(repoSummary)}/> <Route path="/repo_findings/:ownerType/:scanType?/:group?" component={requireAuthentication(repoFindings)}/> <Route path="/tool_results/:ownerType/:scanType?/:group?" component={requireAuthentication(toolResults)}/> <Route path="/analytics/:ownerType" component={requireAuthentication(Analytics)}/> <Route path="/filters/:ownerType/:scanType?" component={requireAuthentication(Filters)}/> <Route path="/users" component={requireAuthentication(Users)}/> <Route path="/edit_user/:id" component={requireAuthentication(EditUser)}/> <Route path="/groups" component={requireAuthentication(Groups)}/> <Route path="/add_group" component={requireAuthentication(CreateGroup)}/> <Route path="/edit_group/:id" component={requireAuthentication(EditGroup)}/> <Route path="/roles" component={requireAuthentication(Roles)}/> <Route path="/add_role" name="roles-creation" component={requireAuthentication(CreateRole)}/> <Route path="/edit_role/:id" component={requireAuthentication(EditRole)}/> <Route path="/permissions" component={requireAuthentication(Permissions)}/> <Route path="/add_permission" component={requireAuthentication(CreatePermission)}/> <Route path="/edit_permission/:id" component={requireAuthentication(EditPermission)}/> <Route path="/scan_types" component={requireAuthentication(ScanTypes)}/> <Route path="/create_scan_type" component={requireAuthentication(newScanType)}/> <Route path="/edit_scan_type/:id" component={requireAuthentication(EditScanType)}/> <Route path="/tools" component={requireAuthentication(Tools)}/> <Route path="/add_tool" component={requireAuthentication(CreateTool)}/> <Route path="/edit_tool/:id" component={requireAuthentication(EditTool)}/> {/* <Route path="/severity_level_configuration" component={requireAuthentication(severityLevelConfiguration)}/> */} <Route path="/signup_role_configuration" component={requireAuthentication(signupRoleConfiguration)}/> <Route path="/hardcode_secrets_configuration" component={requireAuthentication(hardcodeSecretsConfiguration)}/> <Route path="/jira" component={requireAuthentication(Jira)}/> <Route path="/git" component={requireAuthentication(Git)}/> <Route path="/configure_mail" component={requireAuthentication(ConfigureMails)}/> <Route path="/smtp_settings" component={requireAuthentication(SMTPSettings)}/> <Route path="/findings/:scan" component={requireAuthentication(Findings)}/> <Route path="/finding_detail/:parentId/:id" component={requireAuthentication(findingDetail)}/> </Layout> </Switch> </Router> ) } };
var rs = require("readline-sync"); var options = ["open door", "Look for Key"]; var keyFound = false; while(true){ var selection = rs.keyInSelect(options, "What would you like to do?"); if(selection === 0){ // check for key if(keyFound){ console.log("You win!"); } else { console.log("It seems to require a key..."); } } } if(selection === 1){ // provide a new set of options for where to look } if(selection === -1){ // ok start the loop }
document.getElementById('lastname').addEventListener('blur',function () { alert('Merci de votre participation') } )
export default { consolidated_weather: [ { id: 5374798431518720, weather_state_name: "Heavy Cloud", weather_state_abbr: "hc", wind_direction_compass: "E", created: "2018-08-31T14:53:02.233040Z", applicable_date: "2018-08-31", min_temp: 11.3475, max_temp: 20.6275, the_temp: 20.055, wind_speed: 3.712765878420027, wind_direction: 98.0349093205706, air_pressure: 1026.065, humidity: 60, visibility: 10.059999602322437, predictability: 71 }, { id: 4905014531194880, weather_state_name: "Light Cloud", weather_state_abbr: "lc", wind_direction_compass: "SSE", created: "2018-08-31T14:53:03.224010Z", applicable_date: "2018-09-01", min_temp: 11.515, max_temp: 22.4725, the_temp: 21.55, wind_speed: 5.518180291867495, wind_direction: 160.70938600570042, air_pressure: 1029.1, humidity: 53, visibility: 13.006231110315756, predictability: 70 }, { id: 4936801919696896, weather_state_name: "Light Cloud", weather_state_abbr: "lc", wind_direction_compass: "SE", created: "2018-08-31T14:53:02.835750Z", applicable_date: "2018-09-02", min_temp: 12.032499999999999, max_temp: 22.919999999999998, the_temp: 21.895, wind_speed: 4.598029762061561, wind_direction: 140.99633491892195, air_pressure: 1027.1, humidity: 50, visibility: 13.409501014077785, predictability: 70 }, { id: 5101188034854912, weather_state_name: "Light Cloud", weather_state_abbr: "lc", wind_direction_compass: "NNE", created: "2018-08-31T14:53:03.116780Z", applicable_date: "2018-09-03", min_temp: 11.24, max_temp: 23.345, the_temp: 22.755000000000003, wind_speed: 3.5419268894873936, wind_direction: 17.960382088023533, air_pressure: 1024.25, humidity: 54, visibility: 14.750420046925953, predictability: 70 }, { id: 5968283949858816, weather_state_name: "Heavy Cloud", weather_state_abbr: "hc", wind_direction_compass: "NNE", created: "2018-08-31T14:53:03.817550Z", applicable_date: "2018-09-04", min_temp: 12.112499999999999, max_temp: 19.7575, the_temp: 19.235, wind_speed: 7.337304972828681, wind_direction: 17.4588809062278, air_pressure: 1029.615, humidity: 66, visibility: 12.178253996659508, predictability: 71 }, { id: 5608500755431424, weather_state_name: "Light Cloud", weather_state_abbr: "lc", wind_direction_compass: "NNE", created: "2018-08-31T14:53:05.700490Z", applicable_date: "2018-09-05", min_temp: 11.275, max_temp: 19.5075, the_temp: 18.85, wind_speed: 7.256837535459582, wind_direction: 30.726374006622848, air_pressure: 1035.91, humidity: 68, visibility: 9.997862483098704, predictability: 70 } ], time: "2018-08-31T17:32:19.697610+01:00", sun_rise: "2018-08-31T06:11:15.102812+01:00", sun_set: "2018-08-31T19:49:20.099912+01:00", timezone_name: "LMT", parent: { title: "England", location_type: "Region / State / Province", woeid: 24554868, latt_long: "52.883560,-1.974060" }, sources: [ { title: "BBC", slug: "bbc", url: "http://www.bbc.co.uk/weather/", crawl_rate: 180 }, { title: "Forecast.io", slug: "forecast-io", url: "http://forecast.io/", crawl_rate: 480 }, { title: "HAMweather", slug: "hamweather", url: "http://www.hamweather.com/", crawl_rate: 360 }, { title: "Met Office", slug: "met-office", url: "http://www.metoffice.gov.uk/", crawl_rate: 180 }, { title: "OpenWeatherMap", slug: "openweathermap", url: "http://openweathermap.org/", crawl_rate: 360 }, { title: "Weather Underground", slug: "wunderground", url: "https://www.wunderground.com/?apiref=fc30dc3cd224e19b", crawl_rate: 720 }, { title: "World Weather Online", slug: "world-weather-online", url: "http://www.worldweatheronline.com/", crawl_rate: 360 }, { title: "Yahoo", slug: "yahoo", url: "http://weather.yahoo.com/", crawl_rate: 180 } ], title: "London", location_type: "City", woeid: 44418, latt_long: "51.506321,-0.12714", timezone: "Europe/London" };
var loadSample = function(url, callback) { var request = new XMLHttpRequest(); request.open('GET', url, true); request.responseType = 'arraybuffer'; request.onload = function() { console.log('url loaded'); context.decodeAudioData(request.response, callback); } console.log('reading url'); request.send(); }
const { User } = require('../models') const middleware = require('../middleware') const LogUserIn = async (req, res) => { try { const user = await User.findOne({ where: { email: req.body.email }, raw: true }) if ( user && (await middleware.comparePassword(user.passwordDigest, req.body.password)) ) { let payload = { id: user.id, email: user.email } let token = middleware.createToken(payload) return res.send({ user: payload, token }) } res.status(401).send({ status: 'Error', msg: 'Unauthorized' }) } catch (error) { throw error } } const CreateNewUser = async (req, res) => { try { const { email, password, name } = req.body let passwordDigest = await middleware.hashPassword(password) const user = await User.create({ email, passwordDigest, name }) res.send(user) } catch (error) { throw error } } const ChangePassword = async (req, res) => { try { const user = await User.findOne({ where: { email: req.body.email } }) if ( user && (await middleware.comparePassword( user.dataValues.passwordDigest, req.body.oldPassword )) ) { const { newPassword } = req.body let passwordDigest = await middleware.hashPassword(newPassword) await user.update({ passwordDigest }) res.send({ status: 'success', msg: 'Password Updated' }) } res.status(401).send({ status: 'Error', msg: 'Unauthorized' }) } catch (error) { throw error } } const DeleteUserAccount = async (req, res) => { try { const user = await User.findOne({ where: { email: req.body.email }, raw: true }) if ( user && (await middleware.comparePassword(user.passwordDigest, req.body.password)) ) { await User.destroy({ where: { email: req.body.email } }) return res.send({ msg: `User Deleted with email ${req.body.email}` }) } res.status(401).send({ status: 'Error', msg: 'Unauthorized' }) } catch (error) { throw error } } const CheckSession = async (req, res) => { const { payload } = res.locals res.send(payload) } module.exports = { CreateNewUser, LogUserIn, ChangePassword, DeleteUserAccount, CheckSession }
// @flow /* ********************************************************** * File: sensorSettingsComponent.js * * Brief: React component for changing settings on sensors. * this is a poor name - consider renaming as this component * also includes generators. * * Authors: Craig Cheney * * 2017.09.25 CC - Changed name to SettingsPage (from * sensorSettingsComponent) * 2017.08.30 CC - Document created * ********************************************************* */ import React, { Component } from 'react'; import { Grid, Col, Row } from 'react-bootstrap'; import DeviceBlock from './DeviceBlock'; import log from '../../utils/loggingUtils'; import type { thunkType } from '../../types/functionTypes'; import type { devicesStateType } from '../../types/stateTypes'; import type { idType } from '../../types/paramTypes'; import type { setDeviceActiveActionType, setSensorChannelsActionT } from '../../types/actionTypes'; // log.debugLevel = 5; log.debug('sensorSettingsComponent: debug level', log.debugLevel); /* Props used in component */ type propsType = { devices: devicesStateType, /* Functions */ setDeviceActive: (deviceId: idType, newState: boolean) => setDeviceActiveActionType, setSensorActive: ( deviceId: idType, sensorId: idType, newState: boolean ) => thunkType, setGeneratorActive: ( deviceId: idType, generatorId: idType, newState: boolean ) => thunkType, setSensorChannels: ( deviceId: idType, sensorId: idType, newChannels: number[] ) => setSensorChannelsActionT, setSensorParams: ( deviceId: idType, sensorId: idType, paramName: string, paramValue: number ) => thunkType, zeroSensor: ( deviceId: idType, sensorId: idType ) => thunkType }; export default class settingsPage extends Component<propsType> { getDeviceBlocks(): [] { const deviceBlockList = []; const deviceIdList = Object.keys(this.props.devices); /* Iterate through each device */ for (let i = 0; i < deviceIdList.length; i++) { const deviceId = deviceIdList[i]; const device = this.props.devices[deviceId]; /* Only display connected devices */ if (device.state === 'connected') { deviceBlockList.push( <DeviceBlock key={i} id={deviceId} device={device} setDeviceActive={this.props.setDeviceActive} setSensorActive={this.props.setSensorActive} setSensorChannels={this.props.setSensorChannels} setSensorParams={this.props.setSensorParams} setGeneratorActive={this.props.setGeneratorActive} zeroSensor={this.props.zeroSensor} /> ); } } /* Display empty text */ if (deviceBlockList.length === 0) { const style = { backgroundColor: '#D1CAC8', borderRadius: '5px', marginTop: '10px', minHeight: '75px', textAlign: 'center' }; deviceBlockList.push( <div style={style}> <i >NO DEVICES CONNECTED</i> </div> ); } /* Return the device List */ return deviceBlockList; } /* Render function */ render() { const deviceBackgroundStyle = { backgroundColor: '#c7e9b4', minHeight: '400px', }; return ( <Grid fluid> <Row> <Col md={12}> <Col md={12} style={deviceBackgroundStyle}> {this.getDeviceBlocks()} </Col> </Col> </Row> </Grid> ); } } /* [] - END OF FILE */
function person(fname, lname, age, skills, dateofbirth, address, married, profession) { this.fname = fname; this.lname = lname; this.age = age; this.skills = skills; this.dateofbirth = dateofbirth; this.address = address; this.married = married; this.profession = profession; } var person1 = new person("nikhil", "goud", 22, ["c"], "24/10/1996", {city: "hyderabad", pincode: "521185"}, "false", "sr analyst"); var person2 = new person("harish", "chinna", 21, "HTML", "08/06/1997", {city: "Ameerpet", pincode: "500038"}, "false", "jr analyst"); print = function() { console.log(person1); console.log(person2); } ();
var files_dup = [ [ "Attendance Management System", "dir_7159a0b79bffcc693b8d3696d3c54cc7.html", "dir_7159a0b79bffcc693b8d3696d3c54cc7" ] ];
//https://github.com/levelgraph/levelgraph var level = require("level-browserify"); var levelgraph = require("levelgraph"); // just use this in the browser with the provided bundle var db = levelgraph(level("data/testyourdb")); //console.log(db); //Inserting a triple in the database is extremely easy: var triple = { subject: "David", predicate: "type", object: "Personne" }; db.put(triple, function(err) { console.log("0, triplet ajouté"); // do something after the triple is inserted }); var triple = { subject: "David", predicate: "developpeurDe", object: "Smag0", "graphe": "Projet" }; db.put(triple, function() { db.get({ subject: "David" }, function(err, list) { console.log("1"); console.log(list); }); }); //Retrieving it through pattern-matching is extremely easy: db.get({ subject: "David" }, function(err, list) { console.log("2"); console.log(list); }); db.get({ predicate: "type", object:"Personne" }, function(err, list) { console.log("3"); console.log(list); }); //It even supports a Stream interface: var stream = db.getStream({ predicate: "b" }); stream.on("data", function(data) { console.log("4"); console.log(data); }); db.get({ subject: "a" }, function(err, list) { console.log("5"); console.log(list); });
import React from 'react' import './loaderHOC.css' // Loader HOC , при запросе к API выводится loader const LoaderHOC = (WrappedComponent) => (props) => { return props.loading ? (<div className='loader'></div>) : <WrappedComponent {...props} /> } export default LoaderHOC
(function () { "use strict"; function LShapeComponent(x, y, width, height, basicLength) { this.width = width; this.height = height; this.speedY = basicLength; this.basicLength = basicLength; this.done = false; (() => { // combination of one Square component and one Rectangle componet this.squareComponent = new SquareComponent(x - basicLength / 2, y, basicLength, basicLength, basicLength); this.rectangleComponent = new RectangleComponent(x + basicLength / 2 , y + height / 2 , basicLength * 3, basicLength, basicLength); this.coordinates = this.squareComponent.coordinates.concat(this.rectangleComponent.coordinates); })(); } LShapeComponent.prototype.getTopLeftCoord = function () { let squareTopleftCoord = this.squareComponent.getTopLeftCoord(); let rectangleTopLeftcoord = this.rectangleComponent.getTopLeftCoord(); return squareTopleftCoord[1] < rectangleTopLeftcoord[1] ? squareTopleftCoord : rectangleTopLeftcoord; }; LShapeComponent.prototype.getTopRightCoord = function () { let squareTopRightCoord = this.squareComponent.getTopRightCoord(); let rectangleTopRightcoord = this.rectangleComponent.getTopRightCoord(); return squareTopRightCoord[1] < rectangleTopRightcoord[1] ? squareTopRightCoord : rectangleTopRightcoord; } LShapeComponent.prototype.getBottomLeftCoord = function () { } LShapeComponent.prototype.getBottomRightCoord = function () { }; LShapeComponent.prototype.update = function (bottomY, matrix) { let newSpeedY = 0; this.squareComponent.checkCrashBottom(bottomY, matrix); this.rectangleComponent.checkCrashBottom(bottomY, matrix); newSpeedY = Math.min(this.squareComponent.speedY, this.rectangleComponent.speedY); this.done = this.squareComponent.done || this.rectangleComponent.done; this.squareComponent.speedY = newSpeedY; this.rectangleComponent.speedY = newSpeedY; // update pos this.squareComponent.updateCoord(); this.rectangleComponent.updateCoord(); }; LShapeComponent.prototype.changeHorizontalSpeed = function (speedX, matrix, boundaryLeft, boundaryRight) { if (speedX > 0) { this.squareComponent.checkCrashRight(speedX, boundaryRight, matrix); this.rectangleComponent.checkCrashRight(speedX, boundaryRight, matrix); let x = Math.min(this.squareComponent.speedX, this.rectangleComponent.speedX); this.squareComponent.updateX(x); this.rectangleComponent.updateX(x); } else { this.squareComponent.checkCrashLeft(speedX, boundaryLeft, matrix); this.rectangleComponent.checkCrashLeft(speedX, boundaryLeft, matrix); let x = Math.max(this.squareComponent.speedX, this.rectangleComponent.speedX); this.squareComponent.updateX(x); this.rectangleComponent.updateX(x); } } LShapeComponent.prototype.revertHorizontalSpeed = function () { this.squareComponent.revertHorizontalSpeed(); this.rectangleComponent.revertHorizontalSpeed(); } LShapeComponent.prototype.isGameOver = function (boundaryTop) { return this.squareComponent.isGameOver(boundaryTop) || this.rectangleComponent.isGameOver(boundaryTop) } LShapeComponent.prototype.squareOnTopTransform = function (boundaryLeft, boundaryRight, bottomY, matrix) { let coordX = this.squareComponent.getBottomRightCoord()[0] + this.squareComponent.width; let rightBound = coordX + this.squareComponent.width; let coordY = this.squareComponent.getBottomRightCoord()[1]; let lowerBound = coordY + this.squareComponent.height; let offset = this.squareComponent.height; // ignore if crash into canvas if (coordY + this.squareComponent.height * 2 > bottomY) return false; // ignore if crash into other components for (let i = coordX; i < rightBound; i++){ for (let j = coordY; j< lowerBound; j++){ if(matrix[i][j][0] === 1) return false; } } // change coord first,revert later if transform fail this.rectangleComponent.coordinates.forEach((item) => { item[1] += offset; }); let transform = this.rectangleComponent.transform(boundaryLeft, boundaryRight, bottomY, matrix); if(!transform){ this.rectangleComponent.coordinates.forEach((item) => { item[1] -= offset; }); return false; } return true; } LShapeComponent.prototype.squareOnRightTransform = function (boundaryLeft, boundaryRight, bottomY, matrix) { let coordX = this.squareComponent.getBottomRightCoord()[0] + 1; let rightBound = coordX + this.squareComponent.width; let coordY = this.squareComponent.getBottomRightCoord()[1] + 1; let lowerBound = coordY + this.squareComponent.height; let offset = this.squareComponent.height; // ignore if crash into canvas if (rightBound - 1 > boundaryRight) return false; // ignore if crash into other components for (let i = coordX; i < rightBound; i++){ for (let j = coordY; j< lowerBound; j++){ if(matrix[i][j][0] === 1) return false; } } // change coord first,revert later if transform fail this.rectangleComponent.coordinates.forEach((item) => { item[1] -= offset * 2; }); let transform = this.rectangleComponent.transform(boundaryLeft, boundaryRight, bottomY, matrix); if(!transform){ this.rectangleComponent.coordinates.forEach((item) => { item[1] += offset * 2; }); return false; } return true; } LShapeComponent.prototype.squareOnBottomTransform = function (boundaryLeft, boundaryRight, bottomY, matrix) { let coordX = this.squareComponent.getBottomLeftCoord()[0] - 1; let leftBound = coordX - this.squareComponent.width; let coordY = this.squareComponent.getTopLeftCoord()[1]; let lowerBound = coordY + this.squareComponent.height; let offset = this.squareComponent.height; // ignore if crash into other components for (let i = coordX; i > leftBound; i--){ for (let j = coordY; j < lowerBound; j++){ if(matrix[i][j][0] === 1) return false; } } // change coord first,revert later if transform fail this.rectangleComponent.coordinates.forEach((item) => { item[0] += offset * 2; item[1] += offset; }); let transform = this.rectangleComponent.transform(boundaryLeft, boundaryRight, bottomY, matrix); if(!transform){ this.rectangleComponent.coordinates.forEach((item) => { item[0] -= offset * 2; item[1] -= offset; }); return false; } return true; } LShapeComponent.prototype.squareOnLeftTransform = function (boundaryLeft, boundaryRight, bottomY, matrix) { let coordX = this.squareComponent.getTopLeftCoord()[0] - 1; let leftBound = coordX - this.squareComponent.width; let coordY = this.squareComponent.getBottomLeftCoord()[1]; let upperBound = coordY - this.squareComponent.height * 2; let offset = this.squareComponent.height; // ignore if crash into canvas if (coordX - this.squareComponent.width + 1 < boundaryLeft) return false; // ignore if crash into other components for (let i = coordX; i > leftBound; i--){ for (let j = coordY; j > upperBound; j--){ if(matrix[i][j][0] === 1) return false; } } // change coord first,revert later if transform fail this.rectangleComponent.coordinates.forEach((item) => { item[0] -= offset * 2; }); let transform = this.rectangleComponent.transform(boundaryLeft, boundaryRight, bottomY, matrix); if(!transform){ this.rectangleComponent.coordinates.forEach((item) => { item[0] += offset * 2; }); return false; } return true; } LShapeComponent.prototype.transform = function (boundaryLeft, boundaryRight, bottomY, matrix) { let offset = this.squareComponent.height; let squareOnTop = this.squareComponent.getBottomRightCoord()[1] < this.rectangleComponent.getTopRightCoord()[1]; let squareOnRight = this.squareComponent.getTopLeftCoord()[0] > this.rectangleComponent.getTopRightCoord()[0]; let squareOnBottom = this.squareComponent.getTopLeftCoord()[1] > this.rectangleComponent.getBottomLeftCoord()[1]; let squareOnLeft = this.squareComponent.getBottomRightCoord()[0] < this.rectangleComponent.getBottomLeftCoord()[0]; if(squareOnTop){ let transform = this.squareOnTopTransform(boundaryLeft, boundaryRight, bottomY, matrix); if(!transform) return; this.squareComponent.coordinates.forEach((item) => { item[0] += offset; }); } else if(squareOnRight){ let transform = this.squareOnRightTransform(boundaryLeft, boundaryRight, bottomY, matrix); if(!transform) return; this.squareComponent.coordinates.forEach((item) => { item[0] += offset; item[1] += offset; }); } else if(squareOnBottom){ let transform = this.squareOnBottomTransform(boundaryLeft, boundaryRight, bottomY, matrix); if(!transform) return; this.squareComponent.coordinates.forEach((item) => { item[0] -= offset; }); } else if(squareOnLeft){ let transform = this.squareOnLeftTransform(boundaryLeft, boundaryRight, bottomY, matrix); if(!transform) return; this.squareComponent.coordinates.forEach((item) => { item[0] -= offset; item[1] -= offset }); } const oldWidth = this.width; this.width = this.height; this.height = oldWidth; this.coordinates = this.squareComponent.coordinates.concat(this.rectangleComponent.coordinates); } window.LShapeComponent = LShapeComponent || {}; })();
/** * Created by Jasmine on 3/27/16. */ (function($) { $.fn.ellipsisBtn = function (options) { var config = $.extend({ type: 'start', original_text: "跳转", ellipsis_text: "正在跳转", ellipsis_icon: ".", ellipsis_number: 3, ellipsis_interval: 500 }, options), current_ellipsis = 0, type; var _start = function($target) { $target = $($target); if ($target.attr('data-interval')) { throw new Error("Ellipsis helper already used on target!"); } if ($target.is('button')) { config.original_text = $target.html(); $target.html(config.ellipsis_text); type = "button" } else if ($target.is('input')) { config.original_text = $target.val(); $target.val(config.ellipsis_text); type = "input" } else { throw new Error("Invalid DOM type"); } $target.addClass('disabled-btn'); var id = setInterval(function(){ if (current_ellipsis < config.ellipsis_number) { if (type=="button") { $target.append(config.ellipsis_icon); } else { $target.val($target.val() + config.ellipsis_icon); } current_ellipsis++; } else { if (type=="button") { $target.html(config.ellipsis_text); } else { $target.val(config.ellipsis_text); } current_ellipsis = 0; } }, config.ellipsis_interval); $target.attr('data-interval',id); $target.attr('data-text', config.original_text); }; var _stop = function($target) { $target = $($target); config.original_text = $target.attr('data-text') ? $target.attr('data-text') : config.original_text; if ($target.is('button')) { $target.html(config.original_text); } else if ($target.is('input')) { $target.val(config.original_text); } else { throw new Error("Invalid DOM type"); } $target.removeClass('disabled-btn'); clearInterval($target.attr('data-interval')); $target.removeAttr('data-interval'); $target.removeAttr('data-text'); }; return this.each(function(){ if (config.type == "stop") { _stop(this); } else { _start(this); } }); } }(jQuery));
import React from 'react' import moment from 'moment' import { Row, Col, Card } from 'react-materialize' import { Icon } from 'react-icons-kit' import {ic_stars} from 'react-icons-kit/md/ic_stars' import '../../styles/orgEventReviews.css' const OrgReviewCardM = ({ review, idx }) => { const { avatar, created_at, content, votes, first_name } = review return ( <Card className='review_card' key={idx}> <Row> <Col> <Row> <img className='avatar' src={avatar} alt='avatar'></img> </Row> <Row className='reviewer' > <p>{first_name}</p> </Row> <Row> <p>{`Posted in ${moment(created_at).format('MMMM YYYY')}`}</p> </Row> <Row className='review_content'> <p>{content}</p> </Row> <Row> <p><Icon className='event_card_icon' icon={ic_stars} />{votes}/5</p> </Row> </Col> </Row> </Card> ) } export default OrgReviewCardM {/* <Row> <Col m={4} l={2}> <img className='avatar' src={review.avatar} alt='avatar'></img> <p>{review.first_name}</p> </Col> <Col m={8} l={10}> <p>{`${review.city}, ${review.state}`}</p> <p>{`Posted in ${moment(review.created_at).format('MMMM YYYY')}`}</p> <p>{review.content}</p> <p>{review.votes}/5</p> </Col> </Row> */}
Page({ data: { projId: 0, title: '', intro: '', vision: '', members: [], myProjects: [] }, onShareAppMessage: function () { if (!parseInt(this.data.projId)) { return } var str = '点击链接,加入' + this.data.title return { title: str, path: '/pages/include/start?projId=' + this.data.projId } }, onShow: function () { console.log('project onshow') this.setData({ projId: parseInt(getApp().globalData.projId) }) this.updateProjInfo() this.updateMarker() }, updateMarker: function () { var that = this wx.request({ url: 'https://www.kingco.tech/freeman/api/getMarker.php', data: { uid: getApp().globalData.uid, proj_id: this.data.projId }, success: function (res) { console.log('getMark success=>') var resData = JSON.parse(res.data.trim()) console.log(resData) that.setData({ marker: resData }) } }) }, updateProjInfo: function () { console.log('updateProjInfo') getApp().globalData.projUpdated = false var that = this var app = getApp() var projId = app.globalData.projId console.log('projID:' + projId) wx.request({ url: 'https://www.kingco.tech/freeman/api/getProjInfo.php', data: { uid: app.globalData.uid, proj_id: projId }, success: function (res) { console.log('getProjInfo success=>') var resData = JSON.parse(res.data.trim()) console.log(resData) if (resData.vision.length > 12) { resData.vision = resData.vision.substring(0, 12) + '……' } if (resData.title.length > 10) { resData.title = resData.title.substring(0, 10) } resData.members = resData.members.map(function (item) { if (item.nick_name.length > 3) { item.nick_name = item.nick_name.substring(0, 3) } return item }) if (resData) { that.setData({ projId: resData.proj_id, title: resData.title, intro: resData.intro, vision: resData.vision, members: resData.members }) } else { console.log('get projInfo failed!') } } }) wx.request({ url: 'https://www.kingco.tech/freeman/api/getMyProject.php', data: { uid: app.globalData.uid }, success: function (res) { console.log('getMyProject Success=>') console.log(res) var resData = JSON.parse(res.data.trim()) if (resData) { that.setData({ myProjects: resData }) } } }) }, createProj: function () { wx.navigateTo({ url: '/pages/project/newproj' }) }, onProjChange: function (e) { console.log(e.detail.value) var index = e.detail.value var projId = this.data.myProjects[index].proj_id var app = getApp() if (projId !== app.globalData.projId) { app.globalData.projId = projId this.updateProjInfo() wx.request({ url: 'https://www.kingco.tech/freeman/api/changeCurProj.php', data: { uid: app.globalData.uid, proj_id: projId } }) } }, getQrcode: function () { var projId = getApp().globalData.projId if (!projId) { return } wx.showToast({ title: '请稍候……', icon: 'loading', duration: 10000, mask: true }) wx.request({ url: 'https://www.kingco.tech/freeman/api/getQrcode.php', data: { path: 'pages/project/project?projId=' + projId, width: 250 }, success: function (res) { console.log('getQrcode success=>') console.log(res) var resData = JSON.parse(res.data.trim()) if (!resData.name) { return } wx.hideToast() wx.navigateTo({ url: '/pages/include/qrcode?name=' + resData.name }) } }) }, qrScan: function () { getApp().qrScan() } })
var RequestHelper = require('app/model/RequestHelper'); var Actions = require('app/resources/Actions'); var Basic = require('app/model/Model'); var <%=umodelName%>, Mdl = Core.Class.Model, lcStorage = Core.localStorage; function <%=modelName%>(){ } //demo sub model for get request <%=modelName%>.prototype.testSubModelGR = new Mdl({ request: function (data,callback) { RequestHelper.request(Actions.actionForTestSubModelGR,data,callback,this); } }); //demo sub model for post request <%=modelName%>.prototype.testSubModelPR = new Mdl({ post: function (data,callback) { RequestHelper.post(Actions.actionForTestSubModelPR,data,callback,this); } }); //demo sub model for pages <%=modelName%>.prototype.testSubModelPG = new Mdl({ page: 0, page_size: 20, resetPage: function(){ this.page = 0; }, request: function (data,callback) { var _this = this; data.page = this.page; data.page_size = this.page_size; RequestHelper.getJSON({ data: data, action: Actions.actionForTestSubModelPG, complete: function (data) { if (data.success) { _this.set(data.data); _this.page++; } callback && callback(data.success); } }); } }); //demo sub model for JSONP <%=modelName%>.prototype.testSubModelJSONP = new Mdl({ request: function () { RequestHelper.JSONP({ action: Actions.actionForTestSubModelJ+'&callback=afterRequestTestSubModelJSONP' }); } }); window.afterRequestTestSubModelJSONP = function(data){ <%=umodelName%>.testSubModelJSONP.set(data); } //end demo sub model for JSONP <%=umodelName%> = new <%=modelName%>; module.exports = <%=umodelName%>;
module.exports = function(app) { Ember.TEMPLATES['components/img-slider'] = require('./template.hbs'); require('./style.less'); app.ImgSliderComponent = Ember.Component.extend({ classNames: ['img-slider'], image: '', index: 0, big: false, model: [], // images array init() { this._super(); if (this.get('big')) this.classNames.addObject('big'); this.setImgByIndex(); }, getIndex() { return parseInt(this.index) || 0; }, setImgByIndex: function() { var model = this.get('model'); var index = this.getIndex(); if (!model || !model.length) return; var imagesCount = this.model.length; if (index >= imagesCount) { index = 0; } else if (index < 0) { index = imagesCount - 1; } this.setProperties({ image: model[index], index: index, }); this.sendAction('action', index); }.observes('model', 'index'), actions: { img(i) { this.set('index', i); }, next() { this.set('index', this.getIndex() + 1); }, prev() { this.set('index', this.getIndex() - 1); }, } }); };
// core frameworks import React, {Component, PropTypes} from 'react'; import ReactDOM from 'react-dom'; import {Provider} from 'react-redux'; import {Router, browserHistory} from 'react-router'; import {syncHistoryWithStore} from 'react-router-redux'; import configureStore from './store/configureStore'; import i18n from './i18n'; import modal from './reducers/modal' import invariant from 'invariant'; import createReducer from './utils/createReducer'; import createSaga,{cancelSagas} from './utils/createSaga'; import _ from 'lodash' export default class App { constructor(config) { this.config = config || {} this._model = [] } set routes(routes) { this._routes = routes } set reducers(reducers) { this._reducers = reducers } set middlewares(middlewares) { this._middlewares = middlewares } set model(model) { this._model = model.map(checkModel) } fetchLocalePromise(needsI18n, userLocale, defaultLocale) { if (needsI18n && userLocale != defaultLocale) { return i18n.fetchLocaleData(userLocale) .then(localeData => { return {locale: userLocale, localeData} }) } else { return Promise.resolve({locale: userLocale, localeData: {}}) } } replaceReducer(nextReducers, models) { let reducers = { modal, ...nextReducers }, sagas = []; _.forEach(models,model=>{ const {namespace, state, effects} = model; reducers[namespace] = createReducer(namespace, state,model.reducers); if (effects) sagas.push(createSaga(effects, model)); }) cancelSagas(this.store) this.store.hotReplaceReducer(reducers) // start saga sagas.forEach(this.store.run); } createRootComponent({locale, localeData}) { const reducers = { modal, ...this._reducers } const sagas = [] _.forEach(this._model,model=>{ const {namespace, state, effects} = model; reducers[namespace] = createReducer(namespace, state,model.reducers); if (effects) sagas.push(createSaga(effects, model)); }) // create store const initialState = window.__INITIAL_STATE__ || {}; const store = configureStore(reducers, initialState, this._middlewares) // start saga sagas.forEach(store.run); this.store = store; const history = syncHistoryWithStore(browserHistory, store) const i18nTools = new i18n.Tools({localeData, locale}); return ( <Provider store={store}> <i18n.Provider i18n={i18nTools}> <Router history={history} children={this._routes}/> </i18n.Provider> </Provider> ) } async render(el) { const {locales, defaultLocale} = this.config; const userLocale = i18n.getUserLocale(defaultLocale); const {locale, localeData} = await this.fetchLocalePromise(locales != null, userLocale, defaultLocale) const RootComponent = this.createRootComponent({locale, localeData}) if (el) { ReactDOM.render(RootComponent, el) } else { return RootComponent; } } } function checkModel(m) { // Clone model to avoid prefixing namespace multiple times const model = {...m}; const {namespace} = model; invariant( namespace, 'app.model: namespace should be defined' ); invariant( namespace !== 'routing', 'app.model: namespace should not be routing, it\'s used by react-redux-router' ); return model; }
module.exports = function (sequelize, DataTypes) { const Team = sequelize.define("Team", { team_id: { type: DataTypes.INTEGER, allowNull: false, }, team_name: { type: DataTypes.STRING, allowNull: true }, sport_name: { type: DataTypes.STRING, allowNull: true }, league_id: { type: DataTypes.INTEGER, allowNull: false, }, logo_url: { type: DataTypes.STRING, allowNull: false, } }); return Team; };
/* eslint-disable eslint-comments/disable-enable-pair */ /* eslint-disable camelcase */ /* eslint-disable no-case-declarations */ /* eslint-disable default-case */ /* eslint-disable no-multi-assign */ const path = require('path'); const fs = require('fs'); const fetch = require('node-fetch'); const cheerio = require('cheerio'); const slash = require('slash2'); // 获取头像列表 const getAvatarList = async (filename) => { const sourcePath = 'https://github.com/ant-design/ant-design-pro-site/contributors-list/master'; const url = `${sourcePath}${slash(filename)}`; const html = await fetch(url) .then((res) => { if (res.status === 200) { return res.text(); } throw new Error(''); }) .catch(() => { // console.log(e) }); if (!html) { return []; } const $ = cheerio.load(html || ''); const data = []; $('li a').map((index, ele) => { data.push({ username: $(ele).text().trim(), url: $(ele).children('img').attr('src'), }); return false; }); return data; }; const getKebabCase = (str) => str.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`).replace(/\/-/g, '/'); // Add custom fields to MarkdownRemark nodes. module.exports = exports.onCreateNode = async ({ node, actions, getNode }) => { const { createNodeField } = actions; switch (node.internal.type) { case 'MarkdownRemark': const { permalink } = node.frontmatter; const { relativePath, sourceInstanceName } = getNode(node.parent); let slug = permalink; const filePath = path.join(__dirname, '../', sourceInstanceName, relativePath); const stats = fs.statSync(filePath); const mtime = new Date(stats.mtime).getTime(); const mdFilePath = path.join(sourceInstanceName, relativePath); createNodeField({ node, name: 'modifiedTime', value: mtime, }); if (!slug) { slug = `${sourceInstanceName}/${relativePath .replace('.en-US.md', '') .replace('.zh-CN.md', '-cn') .replace('.md', '')}`; } createNodeField({ node, name: 'slug', value: slash(getKebabCase(slug.replace('/index', ''))), }); createNodeField({ node, name: 'underScoreCasePath', value: slash(slug.replace('/index', '')), }); createNodeField({ node, name: 'path', value: slash(mdFilePath), }); const html = await getAvatarList(mdFilePath); createNodeField({ node, name: 'avatarList', value: JSON.stringify(html), }); break; } };
import React, { useEffect } from "react"; import { useDispatch, useSelector } from "react-redux"; import { fetchStats } from "./action"; import { Row, Nav, NavItem, NavLink, Container } from "reactstrap"; import { Link } from "react-router-dom"; const Home2 = () => { const dispatch = useDispatch(); const { loading, stats } = useSelector((state) => ({ loading: state.HomeReducers.loading, stats: state.HomeReducers.stats, })); useEffect(() => { dispatch(fetchStats()); }, [dispatch]); return ( <> {loading ? ( <div>loading....</div> ) : ( <> <Container> {stats !== null && ( <Row className="row"> <ul> {stats.articles.map((article, index) => ( <li key={index}> {/* <Nav> <NavItem> */} <a href="#content1" target="if1"> {article.source.name} </a> {/* </NavItem> </Nav> */} {/* <div id="content1" class="toggle" style="display:none">{article.description}</div> */} </li> ))} </ul> {/* <div id="content1" class="toggle"> */} <iFrame name="if1"> {stats.articles.map((article, index) => ( <li key={index}>{article.description}</li> ))} </iFrame> {/* </div> */} </Row> )} </Container> </> )} </> ); }; export default Home2;
/* * * relatedProductsController.js * * Copyright (c) 2018 HEB * All rights reserved. * * This software is the confidential and proprietary information * of HEB. * @author vn73545 * @since 2.20.0 */ 'use strict'; /** * The controller for the Related Products Controller. */ (function() { var app=angular.module('productMaintenanceUiApp'); app.controller('RelatedProductsController', relatedProductsController); relatedProductsController.$inject = ['$sce','urlBase','$scope','$http','BatchUploadResultsFactory','BatchUploadApi', 'ngTableParams', '$log']; /** * Constructs the controller. * @param excelUploadResultsFactory the modal factory. */ function relatedProductsController($sce, urlBase, $scope, $http, batchUploadResultsFactory, batchUploadApi, ngTableParams, $log) { var self = this; self.PAGE_SIZE = 100; self.WAIT_TIME = 120; self.downloading = false; $scope.actionUrl = urlBase+'/pm/relatedProducts/downloadTemplate'; /** * Whether or not the controller is waiting for data * @type {boolean} */ self.isWaiting = false; /** * Attributes for each row in the table * @type {Array} */ self.attributes = []; /** * Used to keep track of the number of columns in the table * @type {Array} */ self.columns = []; /** * The maximum number of priorities an attribute has. * @type {number} */ self.maxNumberofPriorities = 0; /** * Used to keep track of the attribute name * @type {Array} */ self.attributeNames = []; self.success; self.error; self.disableUpload=true; /** * Initiates the construction of the eCommerce Attribute batch upload */ self.init = function () { }; self.checkShowModal = function(){ var file = document.getElementById("ecommerce-attr"); self.disableUpload=!file.files.length>0; }; /** * Batch upload related products. **/ self.uploadRelatedProductsCall = function(){ self.success=undefined; self.error=undefined; self.isWaiting=true; var file = document.getElementById("ecommerce-attr").files[0]; var name = document.getElementById("nameRequest").value; var fd = new FormData(); fd.append('file', file); fd.append('name', name); batchUploadApi.uploadRelatedProducts(fd,function (resp) { document.getElementById('form-upload').reset(); var ele=document.getElementById("nameRequest"); if(ele!=null){ ele.value=''; } self.isWaiting=false; self.error=undefined; batchUploadResultsFactory.showResultsModal(resp.transactionId); },function(err){ document.getElementById('form-upload').reset(); var ele=document.getElementById("nameRequest"); if(ele!=null){ ele.value=''; } self.isWaiting=false; self.success=undefined; self.error=err.data.message; }); }; } })();
import AssetManager from './manager.vue' export default AssetManager
import { RefCountedCache } from '../../core/ref-counted-cache.js'; // Pure static class, implementing the cache of lightmaps generated at runtime using Lightmapper // this allows us to automatically release realtime baked lightmaps when mesh instances using them are destroyed class LightmapCache { static cache = new RefCountedCache(); // add texture reference to lightmap cache static incRef(texture) { this.cache.incRef(texture); } // remove texture reference from lightmap cache static decRef(texture) { this.cache.decRef(texture); } static destroy() { this.cache.destroy(); } } export { LightmapCache };
import React, { memo, useContext } from "react"; import { Button, Typography, Container } from "@material-ui/core"; import FlexBox from "components/FlexBox"; import DoneImg from "../../assets/done.svg"; import useRegisterStyle from "./style"; import RegisterContext from "./RegisterContext"; import { register } from "services/auth"; import { useToasts } from "react-toast-notifications"; import { useRouter } from "hooks/useRouter"; const ConclusionStep = memo(({ back }) => { const classes = useRegisterStyle(); const { push } = useRouter(); const data = useContext(RegisterContext); const { addToast } = useToasts(); function handleSubmit() { register(data) .then(res => { res = res.data; if (!res.isSuccess) { addToast("Não foi possível efetuar o cadastro", { appearance: "error", autoDismiss: true }); return true; } addToast("Cadastrado efetuado com sucesso!", { appearance: "success", autoDismiss: true }); setTimeout(() => { push('/provider/home'); }, 3000) return false; }) .catch(err => { addToast(err, { appearance: "error", autoDismiss: true }); }); return false; } return ( <FlexBox direction="column" justify="space-between" align="center"> <Container fixed style={{ padding: 50 }}> <Typography variant="subtitle2"> Obrigado por realizar seu cadastro no nome da empresa {data.name} </Typography> <img alt="Tudo certo" className={classes.doneImg} src={DoneImg} /> <Typography variant="h5" color="primary"> Tudo certo com registro, deseja finalizar? </Typography> <FlexBox className={classes.footerContainer} direction="row" justify="space-between" > <Button className={classes.backButton} variant="outlined" onClick={back} > Voltar </Button> <Button variant="contained" color="primary" onClick={handleSubmit}> Finalizar </Button> </FlexBox> </Container> </FlexBox> ); }); export default ConclusionStep;
import React from 'react'; import { useTagsData } from '../../../reduxStore/Highlights/selectors'; import ImageLoader from '../LoadSpinner/ImageLoader'; const Post = ({ postImg, Tags, title, article_link, article_title, key }) => { const tags = useTagsData(); return ( <div className="feature" key={key}> <div className="img-sm"> <img src={postImg !== null ? postImg : <ImageLoader/>} alt="" /> </div> <div className="feature-content"> <div className="feature-pills"> {Tags.length > 0 ? ( Tags.slice(0, 3).map((Tag) => ( <span key={Tag.id} className="highlights-tag"> {tags.filter((tag) => tag.id === Tag).map((t) => t.name)} </span> )) ) : ( <div /> )} </div> <h4>{title}</h4> <span className="feature-link"> <a href={article_link} target="_blank"> {article_title || "Read Article"} {'-->'} </a> </span> </div> </div> ); }; export default Post;
export const $primaryColor = '#FFC864'; export const $secondaryColor = '#7DFFBA'; export const $alternativeColor = '#973BCC'; export const $defaultLinkColor = '#494949'; export const $defaultBackground = '#EFF0F1'; export const $defaultLinkActiveColor = '#34DDE6'; export const $grayLightColor = '#E0E0E0' export const $dangerColor = '#FF0000C4';
import {h} from 'hyperapp'; import {Cross} from '../../theme/Icons' import {Box} from '../../theme/Box' import {stopBubbling} from '../../utils' import './style.css' export const Modal = ({title, close, bottom, ...rest}, children) => ( <div class="modal-container" onclick={close} {...rest}> <Box class="modal" onclick={stopBubbling} top={[ <h2>{title}</h2>, <div class="close" onclick={close}> <Cross /> </div> ]} bottom={bottom} > {children} </Box> </div> )
var express = require('express'); var fileUpload = require('express-fileupload'); var Notificacion = require('../models/notification') var fs = require('fs'); var app = express() app.use(fileUpload()); //========================================// //==========GET DE NOTIFICACIONES=========// //========================================// app.get('/', function(req, res, next) { Notificacion.find({ },( err, info )=>{ if(err) { res.status(500).json({ ok: false, mensaje: 'Error al realizar la peticion', error: err }); } res.status(200).json({ ok: true, message: info }); }) }); //========================================// //=======CREACION DE NOTIFICACIONES=======// //========================================// app.post('/', (req, res)=>{ var body = req.body; var _notificacion = new Notificacion({ titulo: body.titulo, nota: body.nota, autor: body.autor, archivo: body.archivo }) Notificacion.deleteMany({}, (err, infoBorrado) => { if (err) { return res.status(500).json({ ok: false, mensaje: 'Error al borrar info', errors: err }); } if (!infoBorrado) { return res.status(400).json({ ok: false, mensaje: 'No existe info', errors: { message: 'No existe info' } }); } _notificacion.save((err, notificacionGuardada)=>{ if(err) { res.status(500).json({ ok: false, mensaje: 'Error al realizar la peticion', error: err }); } res.status(200).json({ ok: true, mensaje: `Solicitud Procesada correctamente` }) }) }) }); //========================================// //==========PUT DE NOTIFICACIONES=========// //========================================// app.put('/:id',(req, res)=>{ var id = req.params.id var body = req.body Notificacion.findById(id,(err,info)=>{ if(err){ return res.status(500).json({ ok: false, mensaje: 'Error al realizar la peticion', error: err }); } if(!info){ return res.status(500).json({ ok: false, mensaje: 'No existe usuario', error: err }); } info.titulo = body.titulo, info.archivo = body.archivo, info.nota = body.nota, info.autor = body.autor, info.video = body.video info.save((err, infoGuardada)=>{ if(err){ return res.status(400).json({ ok: false, mensaje: 'Error al actualzar usuario', error: err }); } res.status(200).json({ ok: true, message: infoGuardada }); }) }) }) //========================================// //======DELETE DE NOTIFICACIONES==========// //========================================// app.delete('/:id', (req, res) => { var id = req.params.id; Notificacion.findByIdAndRemove(id, (err, infoBorrado) => { if (err) { return res.status(500).json({ ok: false, mensaje: 'Error al borrar info', errors: err }); } if (!infoBorrado) { return res.status(400).json({ ok: false, mensaje: 'No existe info con ese id', errors: { message: 'No existe info con ese id' } }); } res.status(200).json({ ok: true, info: infoBorrado }); }); }); module.exports = app;
// search() // function search(){ var header = document.getElementsByClassName("header")[0]; var loop = document.getElementsByClassName("loop")[0]; // 获取banner卷进去的高度 var height = loop.offsetHeight; window.onscroll = function() { var top = document.documentElement.scrollTop; if(top>height) { header.style.background = "rgba(201,21,35,0.85)" }else { var opacty = top/this.height*0.85; header.style.background = "rgba(201,21,35,"+opacty+")"; } } // }
let i = -1; setInterval(function() { const pics = ["pfp.png", "Checker_Piece_Red.png"]; let pic = document.getElementsByTagName("img")[0]; i++; let photo = pics[i % 2]; // pic.setAttribute("src", photo); pic.srcset = photo; // console.log(i); }, 1000);
const mongoose = require("../../../shared/http/db"); const OwnerSchema = new mongoose.Schema({ name: { type: String, required: true, }, sex: { type: String, required: true, enum: ["m", "f", "M", "F"], }, cpf: { type: String, requierd: true, }, cars: { type: mongoose.Schema.Types.ObjectId, refs: "Car", }, }); module.exports = OwnerSchema;
'use strict'; const gulp = require('gulp'); const replace = require('gulp-replace'); gulp.task('font-awesome', () => { const blockPath = 'vendor.blocks/font-awesome'; gulp.src('node_modules/font-awesome/fonts/*') .pipe(gulp.dest(blockPath)); gulp.src('node_modules/font-awesome/css/font-awesome.css') .pipe(replace('../fonts/', '')) .pipe(gulp.dest(blockPath)); }); gulp.task('vendor', [ 'font-awesome' ]);
import { combineReducers, createStore, applyMiddleware, compose } from "redux"; import thunkMiddleware from "redux-thunk"; import { rulesReducer } from "./reducers/rules-reducer"; const appReducer = combineReducers({ rules: rulesReducer, }); const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; export const store = createStore( appReducer, composeEnhancers(applyMiddleware(thunkMiddleware)) );
/** * This view provides a check of the quality of a knowledge element (e.g., requirement, * code file, decision knowledge element, or work item). * * Requires: condec.api.js, condec.quality.check.api.js * * Is required by: condec.knowledge.page.js, condec.rationale.backlog.js, * templates/tabs/qualityCheck.vm */ (function(global) { var ConDecQualityCheck = function ConDecQualityCheck() { }; /** * Initializes the view. * * external references: condec.knowledge.page.js * condec.rationale.backlog.js, * * @param viewIdentifier identifies the html elements of the view * @param node the selected node, used to extract the Jira issue key * used in the rationale backlog and overview * can be ignored otherwise */ ConDecQualityCheck.prototype.initView = function(viewIdentifier, node) { console.log("ConDecQualityCheck initView"); var projectKey = conDecAPI.getProjectKey(); var issueKey; if (node) { issueKey = node.key; } else { issueKey = conDecAPI.getIssueKey(); } var filterSettings = { "projectKey": projectKey, "selectedElement": issueKey, }; fillQualityCheckTab(filterSettings, viewIdentifier); }; /** * Fills the quality check tab with information by making REST-calls. * * @param filterSettings containing the projectKey and the selected element * @param viewIdentifier identifies the html elements of the view */ function fillQualityCheckTab(filterSettings, viewIdentifier) { conDecDoDCheckingAPI.getQualityCheckResults(filterSettings, (qualityCheckResults) => { fillQualityProblems(qualityCheckResults, viewIdentifier); var problems = qualityCheckResults.filter(checkResult => checkResult.criterionViolated); updateTabStatus(problems, viewIdentifier); }); } /** * Fills the table with information about the quality check for a selected knowledge element. * * @param checkResults a list of the quality criterion check results for a selected knowledge element * @param viewIdentifier identifies the html elements of the view */ function fillQualityProblems(checkResults, viewIdentifier) { var qualityCheckTableBody = document.getElementById("quality-check-table-body-" + viewIdentifier); qualityCheckTableBody.innerHTML = ""; checkResults.forEach(function(checkResult) { var tableRow = document.createElement("tr"); var criterionNameCell = document.createElement("td"); criterionNameCell.innerText = checkResult.name; tableRow.appendChild(criterionNameCell); var statusCell = document.createElement("td"); var icon; if (checkResult.criterionViolated) { statusCell.classList = "condec-error"; icon = conDecNudgingAPI.createIcon("aui-iconfont-cross-circle"); } else { statusCell.classList = "condec-fine"; icon = conDecNudgingAPI.createIcon("aui-iconfont-check-circle"); } statusCell.appendChild(icon); statusCell.insertAdjacentText('beforeend', " " + checkResult.explanation); tableRow.appendChild(statusCell); qualityCheckTableBody.appendChild(tableRow); }); } /** * Sets the colour of the tab according to the quality problems. * * @param qualityProblems a list of the quality problems of the element * @param viewIdentifier identifies the html elements of the view */ function updateTabStatus(qualityProblems, viewIdentifier) { var qualityCheckTab = document.getElementById("menu-item-quality-check-" + viewIdentifier); if (!qualityProblems || !qualityProblems.length) { conDecNudgingAPI.setAmbientFeedback(qualityCheckTab, "condec-fine"); } else if (qualityProblems.length <= 2) { conDecNudgingAPI.setAmbientFeedback(qualityCheckTab, "condec-warning"); } else { conDecNudgingAPI.setAmbientFeedback(qualityCheckTab, "condec-error"); } } global.conDecQualityCheck = new ConDecQualityCheck(); })(window);
import styled from 'styled-components'; import { Body } from '../../../../theme/typography'; export const Paragraph = styled.p` ${Body}; color: ${({ color, theme }) => color === 'blueBayoux' ? theme.colors.secondary.blueBayoux : theme.colors.primary.white}; padding-bottom: ${({ paddingBottom }) => paddingBottom ? `${paddingBottom}rem` : null}; padding-top: ${({ paddingTop }) => (paddingTop ? `${paddingTop}rem` : null)}; & strong { font-weight: 700; } & code { background-color: ${({ theme }) => theme.colors.secondary.periwinkle}; border-radius: 4px; padding: 0.8rem 0.4rem; } & a { color: ${({ theme }) => theme.colors.primary.denim}; &:hover { color: ${({ theme }) => theme.colors.primary.blackPearl}; } } `;
/** * @author mokuteno / https://github.com/manymeeting * @author syt123450 / https://github.com/syt123450 */ import { AbstractDataProcessor } from "./AbstractDataProcessor.js"; /** * This default data preprocessor is used to create mentionedCountries for controller. * The process() function will be called when InitHandler's init() function is called. */ function DefaultDataPreprocessor () {} DefaultDataPreprocessor.prototype = new AbstractDataProcessor(); DefaultDataPreprocessor.prototype.constructor = DefaultDataPreprocessor; DefaultDataPreprocessor.prototype.processDetail = function ( controller ) { if ( controller.dataGroup ) { controller.dataGroupHandler.createMentionedCountries(); } else { controller.singleDataHandler.createMentionedCountries(); } }; export { DefaultDataPreprocessor }
import mongoose, { Schema } from 'mongoose'; import bcrypt from 'bcryptjs'; const UserSchema = new Schema({ email: { type: String, unique: true, lowercase: true }, password: String, fullname: String, profile_image: String, // your active request current_request: { type: Schema.Types.ObjectId, ref: 'Request', default: null }, // your request that has been matched my_matched_request: { type: Schema.Types.ObjectId, ref: 'PastRequest', default: null }, // request of the user you've been matched with other_matched_request: { type: Schema.Types.ObjectId, ref: 'PastRequest', default: null }, // store the various chatrooms a user is involved in chatroom: [], // will be an array of ratings ratings: [], // your past requests request_history: [], // your past matches match_history: [], // your interests interests: [], matched_socket: String, chat_socket: String, }, { toJSON: { virtuals: true, }, }); UserSchema.pre('save', function beforeUserSave(next) { const user = this; if (!user.isModified('password')) { return next(); } bcrypt.genSalt(10, (err, salt) => { if (err) return next(err); bcrypt.hash(user.password, salt, (err, hash) => { if (err) return next(err); user.password = hash; next(); }); }); }); // remove sensitive information from UserSchema, for when looking to view // the profile of a matched user -- used in getOtherProfile UserSchema.methods.cleanUser = function cleanUser(user) { return { _id: this._id, fullname: this.fullname, interests: this.interests, profile_image: this.profile_image }; }; // check if passport is correct UserSchema.methods.comparePassword = function comparePassword(candidatePassword, callback) { bcrypt.compare(candidatePassword, this.password, (err, isMatch) => { if (err) return callback(err); return callback(null, isMatch); }); }; const UserModel = mongoose.model('User', UserSchema); export default UserModel;
/* dataflow.js - actor-based single-assignment dataflow variable The MIT License (MIT) Copyright (c) 2016 Dale Schumacher Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ "use strict"; var dataflow = module.exports; //var defaultLog = console.log; var defaultLog = function () {}; var factory = dataflow.factory = function factory(sponsor, log) { log = log || defaultLog; var saUnbound = (function () { var saUnboundBeh = function saUnboundBeh(m) { log('saUnbound'+this.self+':', m); if (typeof m === 'function') { // m = customer this.behavior = saWaiting([m]); } else if (typeof m === 'object') { // m = value this.behavior = saBound(m); } else { log(this.self+' IGNORED', typeof m); } }; return function saUnbound() { return saUnboundBeh; // reusable behavior function }; })(); var saWaiting = function saWaiting(list) { return function saWaitingBeh(m) { log('saWaiting'+this.self+':', m, list); if (typeof m === 'function') { // m = customer list.push(m); } else if (typeof m === 'object') { // m = value this.behavior = saBound(m); list.forEach(function (item, index, array) { item(m); // broadcast value }); list = null; // release waiting list } else { log(this.self+' IGNORED', typeof m); } }; }; var saBound = function saBound(value) { return function saBoundBeh(m) { log('saBound'+this.self+':', m, value); if (typeof m === 'function') { // m = customer m(value); } else { log(this.self+' IGNORED', typeof m); } }; }; return { unbound: function unbound() { return sponsor(saUnbound()); }, waiting: function waiting(list) { return sponsor(saWaiting(list)); }, bound: function bound(value) { return sponsor(saBound(value)); }, log: log }; };
const mongoose = require('mongoose') const stampCardTemplate = new mongoose.Schema({ // uuid:{ // type:String, // required:true // }, reward_name:{ type:String, required:true }, published:{ type:Boolean, required:true }, num_stamps:{ type:Number, required:true }, participants:{ type:Array, required:true, }, start_date:{ type:String, required:true }, end_date:{ type:String, required:true }, reward_details:{ type:String, required:true }, //stretch goal stamp_icon:{ } }) const stampCard = mongoose.model('stampCard', stampCardTemplate); module.exports = stampCard;
import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Grid from '@material-ui/core/Grid'; import Paper from '@material-ui/core/Paper'; import Typography from '@material-ui/core/Typography'; import SvgIcon from "@material-ui/core/SvgIcon"; const useStyles = makeStyles((theme) => ({ root: { flexGrow: 1, }, pageHeader: { padding: theme.spacing(1), display: 'flex', marginBottom: theme.spacing(1), }, pageIcon: { display: 'inline-block', padding: theme.spacing(2), color: theme.palette.primary.main, }, pageTitle: { paddingLeft: theme.spacing(4), '& .MuiTypography-subtitle2': { opacity: '0.6' } }, })); export default function PageHeader(props) { const {title, subtitle, icon, fontSize, isSvg=false} = props const classes = useStyles(); return ( <div className={classes.root}> <Paper elevation={3}> <Grid container className={classes.pageHeader} > {/* <Grid item className={classes.pageIcon}> {icon} </Grid> */} <Grid item className={classes.pageIcon}> {isSvg ? <SvgIcon fontSize={fontSize || "large"} > {icon} </SvgIcon> : {icon} } </Grid> <Grid item className={classes.pageTitle}> <Typography variant="h6" > {title} </Typography> <Typography variant="subtitle2" > {subtitle} </Typography> </Grid> </Grid> </Paper> </div> ) }
import styles from './PitchLabel.module.scss'; import classnames from 'classnames'; import { DEGREES_IN_CIRCLE } from 'util/constants'; export default function PitchLabel({pitchNamesSorted, diameter, chordNamesSorted}) { const semitones = pitchNamesSorted.length; return <div className={styles.root}>{pitchNamesSorted.map(function(name, index) { const degrees = DEGREES_IN_CIRCLE / semitones * index; const hasAccidental = name?.length === 2 || name?.length === 3; const isSmall = name?.length > 3; let transform; let transformOrigin; const radius = -0.475; const accidentalRadis = radius * 0.96; if (isSmall) { transform = `translate(0%, -50%) rotate(${degrees}deg) translate(0%, 50%) translateY(${diameter * radius}px) rotate(${90}deg)`; transformOrigin = `0 50%`; } else { transformOrigin = `50% 0`; if (hasAccidental) { transform = `translate(-50%, 0) rotate(${degrees}deg) translateY(${diameter * accidentalRadis}px) `; } else { transform = `translate(-50%, 0) rotate(${degrees}deg) translateY(${diameter * radius}px) `; } } return <div className={classnames(styles.button, isSmall && styles.small, hasAccidental && styles.hasAccidental, !chordNamesSorted[index] && styles.deemphesized)} key={index} style={{transform, transformOrigin}} >{name}</div> })}</div> }
var dropdown = document.querySelector("nav .dropdown"); var button = document.querySelector("nav .menu"); var body = document.querySelector("body"); var navbar = document.querySelector("nav .content"); function menu(){ if(dropdown.style.display ==="grid"){ dropdown.style.display = "none"; button.innerHTML = "menu" body.style.gridAutoRows ="100px 88vh auto 10em"; }else { dropdown.style.display = "grid"; button.innerHTML = "close" body.style.gridAutoRows ="100px 88vh auto 10em"; navbar.style.height = "100px"; } } window.addEventListener("resize", function(){ if (window.innerWidth > 500) { dropdown.style.display = "none"; button.innerHTML = "menu"; } })
// ==== FONTS ==== // var gulp = require('gulp'), del = require('del'), plugins = require('gulp-load-plugins')({ camelize: true }), config = require('../../gulpconfig'); gulp.task('fonts-cleanup', function() { return del([ config.fonts.dest ]); }); gulp.task('fonts-cleanup-dist', function() { return del([ config.fonts.destDist ]); }); // Copy everything under `src/fonts` indiscriminately gulp.task('fonts', ['fonts-cleanup'], function() { return gulp.src(config.fonts.src) .pipe(plugins.changed(config.fonts.dest)) .pipe(gulp.dest(config.fonts.dest)); }); gulp.task('fonts-dist', ['fonts-cleanup-dist'], function() { return gulp.src(config.fonts.src) .pipe(plugins.changed(config.fonts.destDist)) .pipe(gulp.dest(config.fonts.destDist)); });
module.exports = function(appplication) { appplication.get('/', function(req, res){ res.render("home/index"); }); };
/* global describe, it, expect */ import React from 'react' import { render } from 'setup-test' import TableResponsive from '.' describe('TableResponsive', () => { it('should render as default', () => { const { container } = render( <TableResponsive minWidth="1200px" rowData={[ { id: '1', name: 'first', email: 'first@example.com' }, { id: '2', name: 'second', email: 'second@example.com' }, ]} /> ) expect(container).toMatchSnapshot() }) })
import React, { useState, useEffect } from 'react'; import axios from "../axios"; import {useAuth} from "../contexts/AuthContext"; import RemoveCircleRoundedIcon from '@material-ui/icons/RemoveCircleRounded'; import RemoveIcon from '@material-ui/icons/Remove'; const DailyEventInfo = (props) => { const {currentEvent2, currentUser,contentAdd, foodAddedHandler, foodAdded,subToDailyCal, changeEventCal, currentDate} = useAuth(); const [userInfo, setUserInfo] = useState(0); const [currentEventInfo, setCurrentEventInfo] = useState(); const [loading, setLoading] = useState(true); const deleteHandler = (food)=>{ console.log(food); axios.post("/deleteFood", { date : currentDate, email : currentUser.email, event : currentEvent2, food : food.food, cal : food.calories }).then(res=>{ console.log(res); },err=>{ console.log(err); }) foodAddedHandler(); subToDailyCal(food.calories); changeEventCal(food.calories, currentEvent2, "minus") } return ( <div className="daily-event-info"> {props.info ? (props.info.length === 0 ? <div className="daily-event-info-inner"> <p>Please Add Food by Clicking on + Icon</p> </div> : props.info.map((food)=>{ return( <div className="daily-event-info-inner"> <p>{food.food}</p> {/* {console.log(foodAdded)} */} <div> <span>{food.calories} Cal</span> <RemoveIcon onClick = {()=>{ deleteHandler(food); props.deleteFood(food.food) }} className = "removeIcon"/> </div> </div> ); }) ): <div className="daily-event-info-inner"> <p>Loading...</p> </div>} </div> ); } export default DailyEventInfo;
import ComparisonContentDisplay from './comparison/Display' import DetailContentDisplay from './detail/Display' import MovieContentDisplay from './movie/Display' import ObjContentDisplay from './obj/Display' import PictureContentDisplay from './picture/Display' import MapContentDisplay from './map/MapDisplay' export default ({ content }) => { switch (content.type) { case 'comparison': { return <ComparisonContentDisplay content={content} /> } case 'detail': { return <DetailContentDisplay content={content} /> } case 'movie': { return <MovieContentDisplay content={content} /> } case 'obj': { return <ObjContentDisplay content={content} /> } case 'picture': { return <PictureContentDisplay content={content} /> } case 'map': { return <MapContentDisplay content={content} /> } default: { return null } } }
function loadJSON(file, callback) { var xobj = new XMLHttpRequest(); xobj.open('GET', file, true); xobj.onreadystatechange = function () { if (xobj.readyState == 4 && xobj.status == "200") { callback(xobj.responseText); } }; xobj.send(null); } function index() { loadJSON('http://stream.coolguyradio.com/status-json.xsl', function(response){ var data = JSON.parse(response); var status = document.getElementById('coolguy_status') status.innerHTML = ''; var marquee = document.createElement("marquee"); var intro = "Previous recording: "; var info = data.icestats.source var livePresent infoString = '' infoString = infoString.concat(JSON.stringify(info)); if(infoString.includes("Piano")){ status.textContent = "**LIVE PIANO BROADCAST** "; livePresent = true } else if(infoString.includes("Living")){ status.textContent = "**LIVE LIVING ROOM BROADCAST** "; livePresent = true } else if(Array.isArray(info) && !(livePresent)){ info.forEach(function(e){ if (e.genre === "various"){ marquee.textContent = intro.concat(e.title); marquee.setAttribute('width', '200px'); status.appendChild(marquee); } }); } else{ try{ marquee.textContent = intro.concat(info.title); marquee.setAttribute('width', '200px'); status.appendChild(marquee); } catch(e){ marquee.textContent = "Server Status: Big Problem!"; marquee.setAttribute('width', '200px'); status.appendChild(marquee); } } } ); } document.addEventListener('DOMContentLoaded', function (e){ index(); // refresh setInterval(function() { index(); }, 20 * 1000); });
import * as Actions from './actions'; import initialState from '../store/initialState'; // stateには現在のstoreの状態、actionにはActionsがreturnした値(プレーンなオブジェクト)が入る export const UsersReducer = (state = initialState.users, action) => { // Actionのtypeに応じてどの状態をどのように変更していくかを書いていく switch (action.type) { case Actions.SIGN_IN: return { ...state, ...action.payload /*,で区切った後さらに...変数名とすることでstateにaction.payloadの中身をマージ */ // 展開した結果 // users: { // isSignedIn: false, // uid: '', // username: '' // isSignedIn: { // uid: userState.uid, // username: userState.username // } 必ずinitialStateを展開後にマージをする。プロティが重複しているものは後に追加した方のプロパティが上書きされる // } } default: return state; } }
import $ from 'jquery'; function animate() { /* Animate image when scrolling to it */ let $animatedIcons = $('.section-6'); // Add classnames here let $window = $(window); let lastScrollTop = 0; function checkIfInView() { let windowHeight = $window.height(); let windowTopPosition = $window.scrollTop(); let windowBottomPosition = windowTopPosition + windowHeight; /* Show the navbar if scrolling upwards */ //if(windowTopPosition > 62) { if(windowTopPosition < lastScrollTop) { $('.Header, .MobileHeader').removeClass('scroll-down').addClass('scroll-up'); } else { $('.Header, .MobileHeader').removeClass('scroll-up').addClass('scroll-down'); } //} /*else { $('.Header').removeClass('scoll-down').removeClass('scroll-up'); }*/ lastScrollTop = windowTopPosition; } $window.on('scroll', checkIfInView); /* Scroll to anchor text */ let $html_body = $('html, body'); $('a[href^=\\#]').click(function(e) { if ($(window).width() < 768) { return; } //e.preventDefault(); let dest = $(this).attr('href'); let scrollTop = dest === '#home' ? 0 : $(dest).offset().top; $html_body.animate({ scrollTop: scrollTop }, 'slow'); }); } export default animate;
const mongoose = require('mongoose'); var nodemailer = require('nodemailer'); const jwt = require('jsonwebtoken'); const model = mongoose.model('Correntista'); const isObjectEmpty = require('../services/isObjectEmpty'); const logger = require('../services/logger'); const api = {}; const crypto = require('crypto'); const hash = require('../services/hash'); module.exports = function (app) { api.geraHash = function (req, res) { console.log("Senha: ", req.body.senha) console.log("Hash: ", hash.gerar(app, req.body.senha)) res.status(200).send({ "success": "Verificar token no prompt do server" }) } api.options = function (req, res) { res.send() } api.autentica = function (req, res) { if (req.is('application/json')) { // Gera o Hash com a senha passada // Seta o hash do body //console.log("senha sem hash: ", req.body.senha) req.body.senha = hash.gerar(app, req.body.senha) //console.log("senha com hash: ",req.body.senha) // Procura pelo usuario no banco // Comparando o CPF e a Senha(hash) // TODO: Remover senha da consulta return model .findOne({ cpf: req.body.cpf, senha: req.body.senha }) .then(function (user) { // Checa se realmente trouxe um usuário if (!user) { console.log("Login e senha são invalidos"); // Envia response de não autorizado res.status(401).send({ success: false, message: 'Usuario e senha são invalidos' }); } else { // var transporter = nodemailer.createTransport({ // service: 'gmail', // auth: { // user: 'grupo2.gama.avanade@gmail.com', // pass: '#goorange' // } // }); // var mailOptions = { // from: 'grupo2.gama.avanade@gmail.com', // to: 'anderfilth@hotmail.com', // subject: 'Teste com Node.js', // text: 'Login funcionou!' // }; // transporter.sendMail(mailOptions, function(error, info){ // if (error) { // console.log(error); // } else { // console.log('Email sent: ' + info.response); // } // }); // Gera o token com o jwt e um secret const token = jwt.sign({ id: user._id, login: user.cpf }, app.get('secret'), { expiresIn: 3600 }); //Devolve o token pelo header da resposta e no body res.set('x-access-token', token); let correntista = { "cpf": user.cpf, "nome": user.nome, "agencia": user.agencia, "contaCorrente": user.contaCorrente, "saldo": user.saldo, "updated_at": user.updated_at, "created_at": user.created_at } // correntista.transacaoPendente = undefined // correntista._id // res.set("Access-Control-Allow-Origin", "*") // console.log(correntista._id.isFrozen()) res.send({ correntista: correntista, token: token }); } }, function (error) { console.log(error, "Usuario e senha são invalidos"); // Em caso de erro devolve uma resposta res.status(401).send({ success: false, message: 'Usuario e senha são invalidos' }) }); } else { res.send({ success: false, message: 'content-type invalido, aceito somente application/json' }) } } api.verificatoken = function (req, res, next) { const token = req.headers['x-access-token']; // Verifica se tem um token na requisição if (token) { // Verifica se o token passo é valido jwt.verify(token, app.get('secret'), function (err, decoded) { if (err) { // Em caso de não ser valido devolve uma resposta de não autorizado res.status(401).send({ success: false, message: 'Falha ao tentar autenticar o token!' }); return } // Se o token for Valido passa para as outras rotas na aplicação req.usuario = decoded; // console.log(req.usuario); next(); }); } else { console.log('token não enviado'); // Em caso de não ser valido devolve uma resposta de não autorizado res.status(401).send({ success: false, message: 'Token não enviado!' }) } } api.renovaToken = function (req, res) { const token = req.headers['x-access-token']; console.log(req.usuario, token) res.send() } api.criaCorrentista = function (req, res) { const usuario = req.usuario const body = req.body console.log("criaCorrentista", usuario) //Verifica se usuario é admin if (usuario.admin) { // Gera um hash para a senha passada body.senha = hash.gerar(app, req.body.senha) // Gera o usuário no Banco model.create(req.body) .then( (correntista) => { res.send(correntista) }, (erro) => { res.status(403).send({ success: false, message: 'Token não enviado!' }) }) } else { res.status(401).send({ success: false, message: 'Usuario não é admin' }) } } return api; }
const express = require('express'); const router = express.Router(); const createToken = () => { let token = '' const characters = 'abcdefghijklmnopqrstuvxyzABCDEFGHIJKLMNOPQRSTUVXYZ123456789' for (let i = 0; i < 12; i++) { const number = Math.floor(Math.random() * characters.length) token += characters[number] } return token } const validateEmail = (email) => { return /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.+-]+\.com$/.test(email); } router.get('/', (req, res) => { const { email, password } = req.body; if (!validateEmail(email) || typeof (password) !== 'number' || password.toString().length < 4 || password.toString().length > 8) { console.log(req.body) res.status(401).send({ message: 'email or password is incorrect' }) } res.send({ token: createToken() }) }) module.exports = router;
(function () { 'use strict'; /** * Search Service */ angular .module('app') .factory('searchService', service); function service($http) { var searchFeatures = []; $http.get('./searches.json').then(function (data) { searchFeatures = data.data; }); return {search: search}; function search(text) { var searchResults = []; if (searchFeatures.length > 0 && text.length > 0) { searchFeatures.forEach(function (feature) { if (feature.searchText.toLowerCase().indexOf(text.toLowerCase()) > -1) { searchResults.push(feature); } }); } return searchResults; } } })();
"use strict"; Object.defineProperty(exports, "exportDataGrid", { enumerable: true, get: function get() { return _export_data_grid.exportDataGrid; } }); Object.defineProperty(exports, "exportPivotGrid", { enumerable: true, get: function get() { return _export_pivot_grid.exportPivotGrid; } }); var _export_data_grid = require("./exporter/exceljs/export_data_grid"); var _export_pivot_grid = require("./exporter/exceljs/export_pivot_grid");
arr = [-1, 1.5, 2, 2.5, 4, 5]; num = 4; function numFinder(arr, num) { let left = 0; let right = arr.length-1; while(left <= right) { var mid = Math.floor((left + right)/2); if(arr[mid] == num) { return console.log(arr[mid]) } else if(arr[mid] < num) { left = mid + 1; } else if(arr[mid] > num) { right = mid - 1; } } return console.log('no number') } numFinder(arr, num);
//STEP 1 // let yourName = prompt('What is your name?'); // alert('Your name has ' + yourName.length + ' chracters'); //STEP 2 // let yourName = prompt('What is your name?'); // let number = prompt('Pick a number between 1 and ' + (yourName.length)); // let letter = yourName.charAt(number-1); // alert('The letter based on the number you selected is: ' + letter); //STEP 3 // let firstName = prompt('What is your first name?'); // let lastName = prompt('What is your last name?'); // let fullName = (firstName + ' ').concat(lastName); // alert('Your full name is ' + fullName); //STEP 4 // let text = 'The quick brown fox jumps over the lazy dog'; // alert('The index of the word is ' + (text.indexOf('fox'))); //STEP 5 // let text = 'The quick brown fox jumps over the lazy fox'; // alert('The index of the last instance of the word is ' + (text.lastIndexOf('fox'))); //STEP 6 // let text = 'The quick brown fox jumped over the lazy dog'; // let fullName = prompt('Please enter your full name'); // alert(text.replace('the lazy dog', fullName)); //STEP 7 // let text = 'The quick brown fox jumps over the lazy dog'; // let word = prompt('Please enter any word'); // let findWord = text.search(word); // if (findWord === -1) { // alert('The word can not be found in the text'); // } else { // alert(('The word can be found at an index of ' + findWord )); // } //STEP 8 // let old_string = 'The quick brown fox jumps over the lazy dog'; // let new_string = old_string.slice(30, 48); // alert(new_string.toUpperCase()); //STEP 9 // let text = ' THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG '; // alert(text.trim().toLowerCase()); //STEP 10 // let text = 'the quick brown fox jumps over the lazy dog'; // alert(text.charAt(0).toUpperCase()+text.slice(1));
import React from 'react' import PropTypes from 'prop-types' // redux import { bindActionCreators } from 'redux' import { connect } from 'react-redux' // module import { ActionCreators as AppActions } from '../../modules/app/actions' import { ActionCreators as AccountActions } from '../../modules/form-templates/actions' import FormsSelectors from '../../modules/form-templates/selectors' import { getLocale } from '../../modules/app/selectors' // components import {createTranslate} from '../../locales/translate' import { FormError } from '../components/forms/FormError' import makeStandardToolbar from '../components/behavioral/StandardListToolbar' import {SmartTable, Column, renderLinkToDetail} from '../components/SmartTable' import {Pagination} from '../components/Pagination' const labelNamespace = 'formTemplates' const StandardToolbar = makeStandardToolbar(AccountActions, FormsSelectors, labelNamespace, 'form-templates') const mapDispatchToProps = (dispatch) => { return { actions: bindActionCreators(AccountActions, dispatch), appActions: bindActionCreators(AppActions, dispatch) } } class ListFormsPage extends React.PureComponent { constructor (props) { super(props) this.message = createTranslate(labelNamespace, this) } componentWillMount () { this.props.actions.clearSelectedItems() this.props.actions.setEditedEntity(null) this.props.actions.fetchList(this.props.urlParams) } componentWillReceiveProps (nextProps) { if (nextProps.urlParams !== this.props.urlParams) { this.props.actions.fetchList(nextProps.urlParams) } } canSelectRow (row) { return !row.isSystem } render () { const {formError, locale} = this.props return ( <div> <StandardToolbar location={this.props.location} /> <FormError error={formError} locale={locale} /> <SmartTable rows={this.props.entities} selectable selectedItemIds={this.props.selectedItemIds} onRowSelected={this.props.actions.toggleSelectedItem} location={this.props.location} canSelectRow={this.canSelectRow} > <Column name="name" label={this.message('name')} renderer={renderLinkToDetail} /> </SmartTable> {this.props.totalPages > 1 && <div className="ui centered grid"> <div className="center aligned column"> <Pagination location={this.props.location} totalPages={this.props.totalPages} /> </div> </div> } </div> ) } } const mapStateToProps = (state, props) => { return { urlParams: FormsSelectors.getUrlParams(state, props), entities: FormsSelectors.getEntitiesPage(state), totalPages: FormsSelectors.getTotalPages(state, props), listFilters: FormsSelectors.getFilters(state, props), selectedItemIds: FormsSelectors.getSelectedItemIds(state), locale: getLocale(state), formError: FormsSelectors.getSubmitError(state), isDeleteEnabled: FormsSelectors.isListDeleteEnabled(state) } } ListFormsPage.propTypes = { urlParams: PropTypes.object.isRequired, entities: PropTypes.array.isRequired, totalPages: PropTypes.number.isRequired, listFilters: PropTypes.object.isRequired, selectedItemIds: PropTypes.array.isRequired, locale: PropTypes.string.isRequired, location: PropTypes.object.isRequired } const ConnectedListFormsPage = connect(mapStateToProps, mapDispatchToProps)(ListFormsPage) export default ConnectedListFormsPage
import CommonModule from "../common.module"; describe('config singleton', () => { let config; beforeEach(window.module(CommonModule)); beforeEach(inject((_config_) => { config = _config_; })); it('contains configurations', () => { // Assert expect(config.COUNTRIES_API_BASE).toEqual('/countries'); }); });
import React, {useEffect, useRef} from 'react'; import GoalButtons from './goalButtons'; const Goal = (props) => { const goalRef = useRef(null); useEffect(()=>{ console.log(goalRef.current); }, []) return ( <div className='goals'> <div ref={ goalRef } className={ props.goal.completed === false ? null : 'completed' } onClick={ () => { props.showTasks(props.goal.id) } }> { props.goal.goalName } </div> <GoalButtons goal={ props.goal } deleteGoal={ props.deleteGoal } completeGoal={ props.completeGoal } goals={ props.goals } /> </div> ) } export default Goal;
// Write your Pizza Builder JavaScript in this file. // $(".btn-crust").removeClass("active"); $(".btn-sauce").removeClass("active"); if ($(".green-pepper").is(":hidden")) { $(".btn-green-peppers").removeClass("active"); } else { $(".btn-green-peppers").addClass("active"); } if ($(".mushroom").is(":hidden")) { $(".btn-mushrooms").removeClass("active"); } else { $(".btn-mushrooms").addClass("active"); } if ($(".pep").is(":hidden")) { $(".btn-pepperonni").removeClass("active"); } else { $(".btn-pepperonni").addClass("active"); } //$( "div:contains('John')" ) // setting crust to default crust $(".crust").removeClass("crust-gluten-free"); $("li:contains('gluten-free')").hide(); // switching w/o gluten $(".btn-crust").click(function() { if ($(".crust-gluten-free")[0]) { $(".crust").removeClass("crust-gluten-free"); $(".btn-crust").removeClass("active"); $("li:contains('gluten-free')").hide(); } else { $(".crust").addClass("crust-gluten-free"); $(".btn-crust").addClass("active"); $("li:contains('gluten-free')").show(); } }); // setting sauce to default sauce $(".sauce").removeClass("sauce-white"); $("li:contains('white sauce')").hide(); // switching w/o white $(".btn-sauce").click(function() { if ($(".sauce-white")[0]) { $(".sauce").removeClass("sauce-white"); $(".btn-sauce").removeClass("active"); $("li:contains('white sauce')").hide(); } else { $(".sauce").addClass("sauce-white"); $(".btn-sauce").addClass("active"); $("li:contains('white sauce')").show(); } }); $(".btn-green-peppers").click(function() { $(".green-pepper").toggle(); if ($(".green-pepper").is(":hidden")) { $(".btn-green-peppers").removeClass("active"); $("li:contains('green peppers')").hide(); } else { $(".btn-green-peppers").addClass("active"); $("li:contains('green peppers')").show(); } }); $(".btn-mushrooms").click(function() { $(".mushroom").toggle(); if ($(".mushroom").is(":hidden")) { $(".btn-mushrooms").removeClass("active"); $("li:contains('mushrooms')").hide(); } else { $(".btn-mushrooms").addClass("active"); $("li:contains('mushrooms')").show(); } }); $(".btn-pepperonni").click(function() { $(".pep").toggle(); if ($(".pep").is(":hidden")) { $(".btn-pepperonni").removeClass("active"); $("li:contains('pepperonni')").hide(); } else { $(".btn-pepperonni").addClass("active"); $("li:contains('pepperonni')").show(); } }); $(".btn").click(function() { var optionsTexts = []; var optionsPrices = []; var totalPrice = 0; $("aside li:visible").each(function() { optionsTexts.push($(this).text()); optionsPrices = optionsTexts.map(function(oneOption) { console.log(oneOption); return parseInt( oneOption.slice(oneOption.indexOf("$") + 1, oneOption.indexOf(" ")) ); }); console.log(optionsPrices); totalPrice = optionsPrices.reduce(function(acc, onePrice) { return acc + onePrice; }, 10); console.log(totalPrice); $("aside strong").text(totalPrice); }); }); $(document).ready(function() { var optionsTexts = []; var optionsPrices = []; var totalPrice = 0; $("aside li:visible").each(function() { optionsTexts.push($(this).text()); optionsPrices = optionsTexts.map(function(oneOption) { console.log(oneOption); return parseInt( oneOption.slice(oneOption.indexOf("$") + 1, oneOption.indexOf(" ")) ); }); console.log(optionsPrices); totalPrice = optionsPrices.reduce(function(acc, onePrice) { return acc + onePrice; }, 10); console.log(totalPrice); $("aside strong").text("$" + totalPrice); }); });
import React from 'react'; import styled from 'styled-components' const ModalElement = styled.div` position: fixed; top: 0; right: 0; bottom: 0; left: 0; background-color: rgba(0, 0, 0, 0.3); `; const Modal = () => { return ( <ModalElement> <button>Click</button> </ModalElement> ); } export default Modal;
const initialState = { isLoggedIn: false, tampung:[] } const fetchData = (state = initialState, action) => { switch (action.type) { case "FETCH": return { tampung:action.payload.tampung } case "REGISTER": return { ...state, tampung: [...state.tampung, action.payload.dataRegister] } case "DELETE": return { ...state, tampung: state.tampung.filter((item, index) => index !== action.payload), } default: return state } } export default fetchData
export const serializeForm = (elements) => { let form = {}; try { JSON.stringify(elements); return elements } catch (e) { } for (let i = 0; i < elements.length; i++) { if (elements[i].value) form[elements[i].name] = elements[i].value; } return form; }; export const resetForm = (form) => { document.getElementById(form).reset(); };
import React, { PureComponent, Fragment } from 'react'; import { Card, Button, Modal, Table} from 'antd'; import Axios from './../../axios'; // import Utils from '/../../utils/utils'; import { connect } from 'react-redux'; import { actionCreators } from './store'; import CreateEmpForm from './createempform.js'; import FilterForm from './filterform.js'; class Employee extends PureComponent{ state = { type: '', isVisible:false, title: '', userInfo: {}, selectedkeys: [], selectedRows: [] } render(){ const columns = [ { title:'id', dataIndex:'id' },{ title: '用户名', dataIndex: 'emp_name' }, { title: '性别', dataIndex: 'sex', render(sex){ return sex === 1?'男':'女' } }, { title: '状态', dataIndex: 'state', render(state){ return { '1':'已婚', '2':'未婚' }[state] } }, { title: '生日', dataIndex: 'birthday' }, { title: '联系地址', dataIndex: 'address' } ]; const rowSelection = { type: 'checkbox', selectedRowKeys: this.state.selectedkeys, onChange: (selectedRowKeys, selectedRows)=>{ console.log(selectedRowKeys, selectedRows) this.setState({ selectedkeys: selectedRowKeys, selectedRows: selectedRows }) } }; const paginationSet = { pageSize: 15, }; let footer = {}; if(this.state.type === 'detail'){ footer = { footer: null } }; return ( <Fragment> {/*button部分*/} <Card style={{ marginTop: 10 }} className="operate-wrap"> <Button type="primary" icon="plus" onClick={()=>this.hanleOperate('create')}>创建员工</Button> <Button type="primary" icon="delete" onClick={() => this.hanleOperate('delete')}>删除员工</Button> <Button type="primary" icon="edit" style={{float:'right'}} onClick={() => this.hanleOperate('edit')}>编辑员工</Button> <Button type="primary" icon="team" style={{float:'right'}} onClick={() => this.hanleOperate('detail')}>员工详情</Button> </Card> {/*查询UI部分*/} <Card> <FilterForm fiterSubmit={this.filterSubmit.bind(this)}/> </Card> {/*表格数据展示部分*/} <div className="table-content-wrap"> <Table columns={columns} rowSelection={rowSelection} dataSource={this.props.list} pagination={paginationSet} /> </div> {/*弹框部分*/} <Modal title={this.state.title} width={600} visible={this.state.isVisible} onOk={this.handleSubmit} onCancel={()=>{ this.createEmpForm.props.form.resetFields(); this.setState({ isVisible:false }) }} { ...footer } > <CreateEmpForm type={this.state.type} userInfo={this.state.userInfo} wrappedComponentRef={(inst)=>{this.createEmpForm = inst;}}/> </Modal> </Fragment> ); } componentDidMount(){ this.props.requestEmpList(); } //查询 filterSubmit = (submitInfo)=>{ this.props.requestEmpSingle(); } // 功能区Button操作 hanleOperate = (type)=>{ let item = this.state.selectedRows[0]; if(type === 'create'){ this.setState({ type, isVisible:true, title:'创建员工' }) }else if(type === 'edit'){ if (!item){ Modal.info({ title: "提示", content: '请选择一个用户' }) return; } this.setState({ type, isVisible: true, title: '编辑员工', userInfo:item }) }else if(type === 'detail'){ if (!item){ Modal.info({ title: "提示", content: '请选择一个用户' }) return; } this.setState({ type, isVisible: true, title: '员工详情', userInfo: item }) }else{ if (!item) { Modal.info({ title: "提示", content: '请选择一个用户' }) return; } let _this = this; Modal.confirm({ title:'确认删除', content:'是否要删除当前选中的员工', onOk(){ Axios.ajax({ url:'/emp/delete', params:{ id:item.id } }).then((res)=>{ if(res.code === 0){ _this.setState({ isVisible:false }) // _this.requestList(); } }) } }) } } // 创建员工提交 handleSubmit = ()=>{ let type = this.state.type; let data = this.createEmpForm.props.form.getFieldsValue(); Axios.ajax({ url:type ==='create'?'/user/add':'/user/edit', params: data }).then((res)=>{ if(res.code === 0){ this.userForm.props.form.resetFields(); this.setState({ isVisible:false }) this.requestList(); } }) }; }; const mapStateToProps = (state)=>({ list: state.getIn(['employee', 'list']).toJS(), }); const mapDispatchToProps = (dispatch)=>({ //请求员工列表信息 requestEmpList(){ dispatch(actionCreators.requestEmpListAction()) }, //查询单个员工 requestEmpSingle(){ dispatch(actionCreators.requestEmpSingleAction()) } }) export default connect(mapStateToProps, mapDispatchToProps)(Employee);
let skyIsBlue = "true", waterIsWet = "true" if(skyIsBlue) console.log("This") if(waterIsWet == skyIsBlue) console.log("Is") if(skyIsBlue == waterIsWet == "true") console.log("the truth") else console.log("a lie") //What does it print?
export default { projections: { AuditView: { name: { __caption__: 'Name' } }, TypeE: { name: { __caption__: 'Name' } }, TypeL: { name: { __caption__: 'Name' }, createTime: { __caption__: 'Создание' }, creator: { __caption__: 'Создатель' }, editTime: { __caption__: 'Редактирование' }, editor: { __caption__: 'Редактор' } } } };
import React from 'react' import { Grid, Cell } from '..' import Box from './Box.jsx' class GridDemo extends React.Component { render () { let props = this.props return ( <Grid gutter={props.gutter}> {props.grid.cells.map(function(cell, i) { return ( <Cell key={i} min={cell.min} marginBottom={16}> <Box>{cell.min} min</Box> </Cell> ) })} </Grid> ) } } GridDemo.propTypes = { gutter: React.PropTypes.number, grid: React.PropTypes.object } export default GridDemo
// Import Express var express = require("express"); var path = require("path"); // Create App var app = express(); var PORT = process.env.PORT || 3000; app.use(express.json()) app.use(express.urlencoded({ extended: true })) // Tables Array var tables = [ { name: "Kat Ruth", phoneNum: "816-222-2222", email: "kat@kat.com", uniqueId: "0220202101" }, { name: "Matt Jay", phoneNum: "816-111-1111", email: "matt@matt.com", uniqueId: "0220202102" } ]; // Waitlist Array var waitlist = [{ name: "Lil Wayne", phoneNum: "777-777-7777", email: "waynes@world.com", uniqueId: "0220202103" }]; // Index/Home View app.get('/', function (req, res) { res.sendFile(path.join(__dirname, "index.html")); }); // Tables View app.get('/tables', function (req, res) { res.sendFile(path.join(__dirname, "tables.html")); }); // Reserve View app.get('/reserve', function (req, res) { res.sendFile(path.join(__dirname, "reserve.html")); }); // Tables Route app.get('/api/tables', function (req, res) { res.json(tables); }); // Waitlist Route app.get('/api/waitlist', function (req, res) { res.json(waitlist); }); app.delete('/api/tables/:uniqueID', function (req, res) { const id = req.params.uniqueID; for (let i = 0; i < tables.length; i++) { if (id === tables[i].uniqueId) { tables.splice(i, 1) } } res.end(); }) app.delete('/api/waitlist/:uniqueID', function (req, res) { const id = req.params.uniqueID; for (let i = 0; i < waitlist.length; i++) { if (id === waitlist[i].uniqueId) { waitlist.splice(i, 1) } } res.end(); }) // Delete All app.delete('/api/waitlist', function (req, res) { waitlist = []; res.end(); }); app.delete('/api/tables', function (req, res) { tables = []; res.end(); }); // Post New Table app.post('/api/tables', function (req, res) { if (tables.length < 3) { tables.push(req.body); res.send("tables"); } else { waitlist.push(req.body) res.send("waitlist"); } }) // Listener... app.listen(PORT, function () { console.log(`Listening on Port ${PORT}`); });
import React, { useEffect } from "react"; import PropTypes from "prop-types"; import { connect } from "react-redux"; import { setCurrentTab, } from "../actions/MovieActions"; import CastTableRow from "../components/CastTableRow"; export const MovieActorsView = ({ dispatch, cast, }) => { useEffect(() => { dispatch(setCurrentTab("actors")); }, []); const rows = cast.map(actor => { return <CastTableRow key={actor.id} actor={actor} /> }); return (<div style={{ padding: 20, maxWidth: 1000, margin: "0 auto" }}> {rows} </div>); }; MovieActorsView.propTypes = { dispatch: PropTypes.func.isRequired, }; MovieActorsView.defaultProps = { cast: [], }; export default connect(({ movie }) => ({ cast: movie.credits.cast, }))(MovieActorsView);
const AbstractUI = require('./AbstractUI'); const { mongooseUtil } = require('../utils/mongooseUtil') const { SchoolSchedule } = require('../beans/SchoolSchedule') const { Person } = require('../beans/Person') const { FileUpload } = require('../beans/FileUpload') class SchoolUI extends AbstractUI { async getPWidget(request, callback) { if (request.query.action == "getDailyReading") { await this.getDailyReading(request, callback); } else { throw new Error(`${request.params.action} not implemented in ${this.constructor.name}`) } } async getWidget(request, callback) { if (request.params.action == "getAllFacultyModules") { await this.getAllFacultyModules(request, callback); } else if (request.params.action == "deleteActivity") { await this.deleteActivity(request, callback); } else if (request.params.action == "saveActivity") { await this.saveActivity(request, callback); } else if (request.params.action == "getActivity") { await this.getActivity(request, callback); } else if (request.params.action == "getActivities") { await this.getActivities(request, callback); } else if (request.params.action == "getSubmissions") { await this.getSubmissions(request, callback); } else if (request.params.action == "getStudents") { await this.getStudents(request, callback); } else { throw new Error(`${request.params.action} not implemented in ${this.constructor.name}`) } } async getAllFacultyModules(request, callback) { let filter = {}; await mongooseUtil.findRecords(SchoolSchedule, filter, "facultyEmail", function (err, records) { if (records != null) { callback(records); } else { callback(""); } }); } async deleteActivity(request, callback) { await mongooseUtil.findSingleRecord(SchoolSchedule, { 'section': request.params.term1, 'subject': request.params.term2 }, async function (err, record) { console.log(err, record); record.activities.id(request.params.term3).remove(); record = await record.save(); callback(record.activities); }) } async saveActivity(request, callback) { await mongooseUtil.findSingleRecord(SchoolSchedule, { 'section': request.body.section, 'subject': request.body.subject }, async function (err, record) { console.log(err, record); if (request.body.activityId) { record.activities.forEach(activity => { if (activity._id == request.body.activityId) { activity.type = request.body.type; activity.title = request.body.title; activity.content = request.body.content; activity.time = request.body.time; } }); } else { let activity = {}; activity.type = request.body.type; activity.title = request.body.title; activity.content = request.body.content; activity.time = request.body.time; record.activities.push(activity); } record = await record.save(); callback(record.activities); }) } async getSubmissions(request, callback) { const section = request.params.term1; const subject = request.params.term2; const activityId = request.params.term3; await mongooseUtil.findRecords(FileUpload, { "uploadType": "activity-student", "key": section + "-" + subject, "subKey": activityId, }, "lastName", function (err, records) { if (records != null) { callback(records); } else { callback(""); } }); } async getDailyReading(request, callback) { const section = request.query.term1; const subject = request.query.term2; await mongooseUtil.findSingleRecord(FileUpload, { "key": section + "-" + subject }, function (err, record) { if (record != null) { callback(record); } else { callback("No attachment."); } }); } async getStudents(request, callback) { const section = request.params.term1; const subject = request.params.term2; await mongooseUtil.findRecords(Person, { "schedules.section": section, "schedules.subject": subject, "personSubType": "Student" }, "firstName", function (err, records) { if (records != null) { callback(records); } else { callback(""); } }); } async getActivity(request, callback) { const section = request.params.term1; const subject = request.params.term2; const activityId = request.params.term3; await mongooseUtil.findSingleRecord(SchoolSchedule, { "section": section, "subject": subject, "activities._id": activityId }, function (err, record) { if (record != null) { callback(record.activities); } else { callback(""); } }); } async getActivities(request, callback) { const section = request.params.term1; const subject = request.params.term2; await mongooseUtil.findSingleRecord(SchoolSchedule, { "section": section, "subject": subject }, function (err, record) { if (record != null) { callback(record.activities); } else { callback(""); } }); } getLeftMenu(user) { return { groupName: "School", group: "School", name: "SchoolUI", label: "School" }; } } const schoolUI = new SchoolUI() module.exports = schoolUI;
'use strict' const http = require('http') const path = require('path') const express = require('express') const bodyParser = require('body-parser') const socketIo = require('socket.io') const mongodb=require('mongodb'); var {mongoose}=require('./mongoose/mongoose'); const api=require('./routes/api.js'); const {DeliveryAgent}=require('./models/delivery-agents'); const port=3000; const app = express() const server = http.createServer(app) const io = socketIo(server) const agentsMap = new Map() app.use(express.static(path.join(__dirname, '../public'))) app.use('/',api); app.use(bodyParser.json()); io.on('connection', socket => { socket.on('updateLocation', pos => { agentsMap.set(socket.id, pos) }) socket.on('requestLocations', (email) => { DeliveryAgent.findOne({ customerEmail: email }, function (err, agent) { if(err) console.log(err); else { socket.emit('locationsUpdate', [ [ socket.id, { lat: agent.latitude, lng: agent.longitude } ] ]); } }); }) socket.on('disconnect', () => { agentsMap.delete(socket.id) }) }) server.listen(port, err => { if (err) { throw err } console.log('server started on port 3000') })
import React from "react"; import { Auth } from "components/pages/Auth"; import { render, fireEvent, screen, waitFor } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import TestingRouter from "../utils/TestingRouter"; describe("Auth page component", () => { it("Should redirect to main page if isAuthenticated", () => { const redirectUrl = "/"; const isAuthenticated = true; const { container } = render( <TestingRouter ComponentWithRedirection={() => ( <Auth isAuthenticated={isAuthenticated} /> )} RedirectUrl={redirectUrl} /> ); expect(container.innerHTML).toEqual(expect.stringContaining(redirectUrl)); }); it("Should render correctly in login mode", () => { const { getByText, getByLabelText } = render(<Auth />); getByText("Login"); getByLabelText("Email"); getByLabelText("Password"); getByText("Submit"); getByText("New? Register Instead"); }); it("Should change to register mode on btn click", () => { const { getByText } = render(<Auth />); const changeModeBtn = getByText("New? Register Instead"); fireEvent.click(changeModeBtn); getByText("Register"); }); it("Should render correctly in register mode", () => { const { getByText, getByLabelText } = render(<Auth />); const changeModeBtn = getByText("New? Register Instead"); fireEvent.click(changeModeBtn); getByText("Register"); getByLabelText("Email"); getByLabelText("Password"); getByLabelText("First Name"); getByLabelText("Last Name"); getByLabelText("Nick Name", { exact: false }); getByLabelText("Current Job Position", { exact: false }); getByLabelText("Job Experience", { exact: false }); getByLabelText("Tech Stack", { exact: false }); getByText("Submit"); getByText("Already a User? Login instead"); }); it("Should change to login mode on btn click", async () => { const { getByText } = render(<Auth />); const changeModeBtn = getByText("New? Register Instead"); fireEvent.click(changeModeBtn); fireEvent.click(changeModeBtn); getByText("Login"); }); }); describe("Forms action", () => { const mockLogin = jest.fn(); const mockRegister = jest.fn(); const arbitrary = { correct: "Qwe", }; const email = { correct: "qwe@mail.ru", wrongFormat: "qweasdasd", }; const password = { correct: "qwe123", tooShort: "1", tooLong: "a".repeat(100), noDigit: "qweqweqweqweqwe", }; const optional = { firstName: "Aaron", lastName: "Burr", nickName: "mooph", jobPosition: "frontend dev", jobExperience: "1 year", techStack: "mern", }; const setInputValue = (labelName, value) => { const input = screen.getByLabelText(labelName); userEvent.type(input, value); }; it("Should fire login function and pass login and passport data as arguments", async () => { const { getByRole } = render(<Auth login={mockLogin} />); setInputValue("Email", email.correct); setInputValue("Password", password.correct); const submitBtn = getByRole("button", { name: "Submit" }); fireEvent.click(submitBtn); await waitFor(() => { expect(mockLogin).toHaveBeenCalledWith({ email: email.correct, password: password.correct, }); }); }); it("Should not fire login on incorrect email", async () => { const { getByRole } = render(<Auth login={mockLogin} />); setInputValue("Email", email.wrongFormat); setInputValue("Password", password.correct); const submitBtn = getByRole("button", { name: "Submit" }); userEvent.click(submitBtn); await waitFor(() => { expect(mockLogin).not.toHaveBeenCalled(); }); }); it("Should fire register function and pass login and passport data as arguments", async () => { const { getByRole, getByText } = render(<Auth register={mockRegister} />); const changeModeBtn = getByText("New? Register Instead"); userEvent.click(changeModeBtn); setInputValue("Email", email.correct); setInputValue("Password", password.correct); setInputValue("First Name", optional.firstName); setInputValue("Last Name", optional.lastName); setInputValue(/Nick Name/i, optional.nickName); setInputValue(/Current Job Position/i, optional.jobPosition); setInputValue(/Job Experience/i, optional.jobExperience); setInputValue(/Tech Stack/i, optional.techStack); const submitBtn = getByRole("button", { name: "Submit" }); fireEvent.click(submitBtn); await waitFor(() => { expect(mockRegister).toHaveBeenCalledWith({ email: email.correct, password: password.correct, firstName: optional.firstName, lastName: optional.lastName, nickName: optional.nickName, jobPosition: optional.jobPosition, jobExperience: optional.jobExperience, techStack: optional.techStack, }); }); }); });
import ItemOptionAction from './ui.form.item_option_action'; import { data } from '../../core/element_data'; import { extend } from '../../core/utils/extend'; import { getFullOptionName } from './ui.form.utils'; class WidgetOptionItemOptionAction extends ItemOptionAction { tryExecute() { var { value } = this._options; var instance = this.findInstance(); if (instance) { instance.option(value); return true; } return false; } } class TabOptionItemOptionAction extends ItemOptionAction { tryExecute() { var tabPanel = this.findInstance(); if (tabPanel) { var { optionName, item, value } = this._options; var itemIndex = this._itemsRunTimeInfo.findItemIndexByItem(item); if (itemIndex >= 0) { tabPanel.option(getFullOptionName("items[".concat(itemIndex, "]"), optionName), value); return true; } } return false; } } class TabsOptionItemOptionAction extends ItemOptionAction { tryExecute() { var tabPanel = this.findInstance(); if (tabPanel) { var { value } = this._options; tabPanel.option('dataSource', value); return true; } return false; } } class ValidationRulesItemOptionAction extends ItemOptionAction { tryExecute() { var { item } = this._options; var instance = this.findInstance(); var validator = instance && data(instance.$element()[0], 'dxValidator'); if (validator && item) { var filterRequired = item => item.type === 'required'; var oldContainsRequired = (validator.option('validationRules') || []).some(filterRequired); var newContainsRequired = (item.validationRules || []).some(filterRequired); if (!oldContainsRequired && !newContainsRequired || oldContainsRequired && newContainsRequired) { validator.option('validationRules', item.validationRules); return true; } } return false; } } class CssClassItemOptionAction extends ItemOptionAction { tryExecute() { var $itemContainer = this.findItemContainer(); var { previousValue, value } = this._options; if ($itemContainer) { $itemContainer.removeClass(previousValue).addClass(value); return true; } return false; } } var tryCreateItemOptionAction = (optionName, itemActionOptions) => { switch (optionName) { case 'editorOptions': case 'buttonOptions': return new WidgetOptionItemOptionAction(itemActionOptions); case 'validationRules': return new ValidationRulesItemOptionAction(itemActionOptions); case 'cssClass': return new CssClassItemOptionAction(itemActionOptions); case 'badge': case 'disabled': case 'icon': case 'template': case 'tabTemplate': case 'title': return new TabOptionItemOptionAction(extend(itemActionOptions, { optionName })); case 'tabs': return new TabsOptionItemOptionAction(itemActionOptions); default: return null; } }; export default tryCreateItemOptionAction;
var _api = require("../api.js"); var _api2 = _interopRequireDefault(_api); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } Page({ data: { flag: false, wrapAnimate: "", bgOpacity: 0, frameAnimate: "", showFrame: true, showMediumFrame: false, showSmallFrame: false, womanWidth: "10vw", manPercent: "21%", womanPercent: "79%", abstract: "", direct: "", disciplineList: [], college: [] }, disciplineTap: function disciplineTap(e) { var majorCode = e.currentTarget.dataset.code; if (!majorCode) return; if (majorCode.length == 4) { wx.navigateTo({ url: "/packages/selectMajor/middleMajorDetail/middleMajorDetail?majorcode=" + majorCode }); } else { wx.navigateTo({ url: "/packages/selectMajor/majorDetail/majorDetail?majorcode=" + majorCode + "&cityid=" + this.cityId }); } // const that = this; // let id = e.currentTarget.id; // that.setData({ // smallFrameTitle: "小雷", // disciplineType: "small", // showSmallFrame: true // }) // this.showFrame(); }, caculateWomanWidth: function caculateWomanWidth(percent) { return 30.67 * percent; }, catchMove: function catchMove() {}, collegeTap: function collegeTap(e) { var that = this; var id = e.currentTarget.id; var college = that.data.college; if (college[id].show) { college[id].show = false; college[id].rotates = "none"; } else { college[id].show = true; college[id].rotates = "(90deg)"; } that.setData({ college: college }); }, showFrame: function showFrame() { this.setData({ flag: true, wrapAnimate: "wrapAnimate", frameAnimate: "frameAnimate" }); }, hideFrame: function hideFrame() { var that = this; that.setData({ wrapAnimate: "wrapAnimateOut", frameAnimate: "frameAnimateOut" }); setTimeout(function() { that.setData({ flag: false }); }, 400); }, InstitutesGet: function InstitutesGet(collegeId) { var that = this; _api2.default.InstitutesGet("Colleges/Institutes/Get?collegeId=" + collegeId, "POST").then(function(res) { for (var i = 0; i < res.result.length; i++) { res.result[i].show = false; res.result[i].rotates = "none"; res.result[i].leftIcon = "/image/right_logo.png"; res.result[i].id = i + 1; } that.setData({ college: res.result }); }); }, onLoad: function onLoad(options) { this.cityId = wx.getStorageSync("cityId").cityId; var that = this; that.InstitutesGet(options.collegeid); var college = that.data.college; if (options.autoOpenId) { for (var i in that.data.college) { if (options.autoOpenId == that.data.college[i].id) { college[i].show = true; college[i].rotates = "(90deg)"; that.setData({ college: college }); } } } that.selectComponent("#navigationcustom").setNavigationAll("院系/专业", true); } });
var owner = 'mbostock'; var repoName = 'd3'; var gitdownload = require('../tasks/lib/download-github-repo.js'); gitdownload(owner + '/' + repoName, 'outputPath/' + repoName, function (err) { console.log('failed: download ' + repoName); callback(); });
{ "account1":[ { "accountNumber": "0400", "ownerName":"Mark Jones", "openingBalance": "500" } ], "account2":[ { "accountNumber": "9302", "ownerName":"Sarah Moore", "openingBalance": "25" } ] }
let prev = document.title; export default ({ getState }) => (next) => (action) => { const { title } = getState().board || {}; if (title !== prev) { prev = document.title = title ? `${title} - Nekoboard` : 'Nekoboard'; } return next(action); };
const proFile = document.querySelector('#bigBody') fetch('https://randomuser.me/api/?results=30') .then((resp) => resp.json()) .then(function (data) { let users = data.results; console.log(users); // console.log(users[0].nat); // exit(); return users.map((user) => { const mainCard = document.createElement('div'); const subCard = document.createElement('div'); const bodyFrame = document.createElement('div'); const cardBody = document.createElement('div'); const rec = document.createElement('div'); const cardImg = document.createElement('div'); const profilePix = document.createElement('img'); const profName = document.createElement('h5'); const p1 = document.createElement('p'); const p2 = document.createElement('p'); const p3 = document.createElement('p'); mainCard.appendChild(subCard); subCard.append(rec, cardImg, bodyFrame); bodyFrame.appendChild(cardBody); cardImg.appendChild(profilePix); proFile.appendChild(mainCard); mainCard.classList.add("card", "ab-3"); subCard.classList.add("row", "g-0"); rec.classList.add("col-md-2"); cardImg.classList.add("col-md-3"); bodyFrame.classList.add("col-md-5"); cardBody.classList.add("card-body"); profilePix.classList.add("img-fluid", "profileImg"); // let image = li.appendChild(img); let firstName = user.name.first; let lastName = user.name.last; let heading = cardBody.appendChild(profName); let eMail = cardBody.appendChild(p1); let email = user.email; let city = user.location.city; let nat = user.nat; let ciTy = cardBody.appendChild(p2) let naT = cardBody.appendChild(p3) // paragraph.innerHTML = firstname + " " lastname) heading.innerHTML = `${firstName} ${lastName}`; eMail.innerHTML = ` Email: ${email}`; p2.innerHTML = `City: ${city}`; p3.innerHTML = `Nationality: ${nat}`; profilePix.src = user.picture.large; }); }) .catch(function (error) { console.log(error); });
/** * @Name patient.controller.js * * @Description Patient Operations * * @package * @subpackage * @author Suhaib <muhammad.suhaib@shifa.com.pk> * @Created on October 02, 2020 2021 */ const Common = require("./../model/common.model"); const Patient = require("./../model/patient.model"); const Doctor = require("./../model/doctor.model"); const h = require("./../utils/helper"); const utility = require("./../utils/utility"); const patientUtil = require("./../utils/patient.util"); const mayTapi = require("./../services/maytapi.service"); const zoomService = require("./../services/zoom.service"); const reportService = require("./../services/report.service"); const request = require('request'); const rp = require('request-promise-native'); const moment = require('moment'); const fs = require('fs'); const PatientController = {}; /**************************************** Diagnosis ****************************************/ PatientController.getDiagnosisHistory = async (req, res) => { let code = 500, message = "Error! Retrieving Diagnosis List", returnObj = {}; try { let filter = h.getProps2(req); let result = await Patient.getPatientDiagnosis(filter); code = 200; returnObj = result; } catch (e) { returnObj = { result: false, message: message }; throw e; } finally { res.status(code).send(returnObj); } }; PatientController.deletePatientVisitDiagnosis = async (req, res) => { let code = 500, message = "Error! Deleting Diagnosis", returnObj = {}; try { let filter = h.getProps2(req); let singleObj = patientUtil._deleteDiagnosisDTO(req.user); if (h.checkExistsNotEmpty(filter, 'code')) { const result = await Common.update(singleObj, 'REGISTRATION.diagnosis', { visit_id: filter.visit_id, icd_code: filter.code }, req.user); code = 200; message = 'Diagnosis Deleted Successfully'; returnObj = { result: result, message: message }; } else { code = 400; message = 'Diagnosis Code not Provided'; returnObj = { result: false, message: message }; } } catch (e) { returnObj = { result: false, message: message }; throw e; } finally { res.status(code).send(returnObj); } }; /**************************************** Diagnostics **************************************/ PatientController.deletePatientVisitDiagnostics = async (req, res) => { let code = 500, message = "Error! Deleting Diagnostics", returnObj = {}; try { let filter = h.getProps2(req); let singleObj = patientUtil._deleteDiagnosticsDTO(); if (h.checkExistsNotEmpty(filter, 'code')) { const result = await Common.update(singleObj, 'REGISTRATION.diagnostics', { visit_id: filter.visit_id, service_id: filter.code }, req.user); code = 200; message = 'Diagnostics Deleted Successfully'; returnObj = { result: result, message: message }; } else { code = 400; message = 'Diagnostics ID not Provided'; returnObj = { result: false, message: message }; } } catch (e) { returnObj = { result: false, message: message }; throw e; } finally { res.status(code).send(returnObj); } }; PatientController.getPatientDiagnosticResults = async (req, res) => { let code = 500, message = "Error! Retrieving Patient Diagnostics", returnObj = {}; try { let filter = h.getProps2(req); const lab = await Patient.getPatientLabResults(filter); const radiology = await Patient.getPatientRadiologyResults(filter); const cardiology = await Patient.getPatientCardiologyResults(filter); const neurology = await Patient.getPatientNeurologyResults(filter); const gastro = await Patient.getPatientGastroResults(filter); code = 200; returnObj = h.resultObject({ lab, radiology, cardiology, neurology, gastro }, true, code); } catch (e) { returnObj = h.resultObject([], false, code, message); throw e; } finally { res.status(code).send(returnObj); } }; /**************************************** Medicines ****************************************/ PatientController.getMedicinesHistory = async (req, res) => { let code = 500, message = "Error! Retrieving Medicine History", returnObj = {}; try { let filter = h.getProps2(req); const medicines = await Patient.getPatientMedicineHistory(filter); const visits = h.pluck(medicines, 'visit_date').filter((v, i, a) => a.findIndex(t => (t === v)) === i); const doctors = patientUtil._formatDoctors(medicines).filter((v, i, a) => a.findIndex(t => (t.doctor_id === v.doctor_id && t.doctor_name === v.doctor_name)) === i); for (const m of medicines) { let filter = { code: m.medicine_code }; let res = await Doctor.getMedicineFrequencies(filter); if (res.length === 0) { res = await Doctor.getMedicineFrequenciesAll(filter); } m.medication_frequency = res; } code = 200; returnObj = h.resultObject({ medications: patientUtil._formatMedicinesHistory(medicines), visits, doctors }, true, code); } catch (e) { returnObj = h.resultObject([], false, code, message); throw e; } finally { res.status(code).send(returnObj); } }; PatientController.deletePatientVisitMedicines = async (req, res) => { let code = 500, message = "Error! Deleting Medicine", returnObj = {}; try { let filter = h.getProps2(req); let singleObj = patientUtil._deleteMedicinesDTO(); if (h.checkExistsNotEmpty(filter, 'code')) { const result = await Common.update(singleObj, 'REGISTRATION.medicine_prescription', { visit_id: filter.visit_id, medicine_code: filter.code }, req.user); code = 200; message = 'Medicine Deleted Successfully'; returnObj = { result: result, message: message }; } else if (h.checkExistsNotEmpty(filter, 'medication')) { const result = await Common.update(singleObj, 'REGISTRATION.medicine_prescription', { visit_id: filter.visit_id, medicine: filter.medication }, req.user); code = 200; message = 'Medicine Deleted Successfully'; returnObj = { result: result, message: message }; } else { code = 400; message = 'Medicine Code / Name not Provided'; returnObj = { result: false, message: message }; } } catch (e) { returnObj = { result: false, message: message }; throw e; } finally { res.status(code).send(returnObj); } }; /**************************************** Allergies ****************************************/ PatientController.deletePatientVisitAllergies = async (req, res) => { let code = 500, message = "Error! Deleting Allergy", returnObj = {}; try { let filter = h.getProps2(req); if (h.checkExistsNotEmpty(filter, 'code')) { if (h.checkExistsNotEmpty(filter, 'type')) { let singleObj = '', table = 'pharmacy_shifa.class_alergy', where = { mrno: filter.mrno, gen_code: filter.code }; if (filter.type.toLowerCase() === 'brand') { singleObj = patientUtil._deleteBrandAllergyDTO(); table = 'registration.moar_drug_brand_allergy'; where = { mr_no: filter.mrno, medicine_code: filter.code }; } else if (filter.type.toLowerCase() === 'generic') { singleObj = patientUtil._deleteGenericAllergyDTO(); } else if (filter.type.toLowerCase() === 'sub class') { where = { mrno: filter.mrno, sub_class_code: filter.code }; singleObj = patientUtil._deleteGenericAllergyDTO(); } const result = await Common.update(singleObj, table, where, req.user); code = 200; message = 'Allergy Deleted Successfully'; returnObj = { result: result, message: message }; } else { code = 400; message = 'Allergy Type not Provided'; returnObj = { result: false, message: message }; } } else { code = 400; message = 'Allergy Code not Provided'; returnObj = { result: false, message: message }; } } catch (e) { returnObj = { result: false, message: message }; throw e; } finally { res.status(code).send(returnObj); } }; /**************************************** Vitals *******************************************/ PatientController.getPatientVisitVitalsAndDefinitions = async (req, res) => { let code = 500, message = "Error! Retrieving Patient Visit Vitals", returnObj = {}; try { const visit = req.visit; const vitals = await Common.getPatientVisitVitalsAndDefinitions(visit); code = 200; returnObj = { "pc": visit.pc, "vitals": vitals }; } catch (e) { returnObj = { result: false, message: message }; throw e; } finally { res.status(code).send(returnObj); } }; PatientController.getPreviousVisitVitals = async (req, res) => { let code = 500, message = "Error! Retrieving Patient Vital History", returnObj = {}; try { // let filter = h.getProps2(req); const previous_visit = await Patient.getPreviousVisit(req.visit); if (h.checkExistsNotEmpty(previous_visit, 'visit_id')) { let result = await Common.getVisitVitals(previous_visit); code = 200; returnObj = result; } else { code = 200; returnObj = []; } } catch (e) { returnObj = { result: false, message: message }; throw e; } finally { res.status(code).send(returnObj); } }; /*************************************** Previous Visits ***********************************/ PatientController.getOPDPreviousVisits = async (req, res) => { let code = 500, message = "Error! Retrieving Patient Vital History", returnObj = {}; try { const result = await Patient.getOPDPreviousVisits(req.patient); code = 200; returnObj = result; } catch (e) { returnObj = { result: false, message: message }; throw e; } finally { res.status(code).send(returnObj); } }; /*************************************** Visits ********************************************/ PatientController.getPatientVisitDetails = async (req, res) => { let code = 500, message = "Error! Retrieving Patient Visit Details", returnObj = {}; try { const visit = req.visit; result = await patientVisitDetails(visit); code = 200; returnObj = result; } catch (e) { returnObj = { result: false, message: message }; throw e; } finally { res.status(code).send(returnObj); } }; PatientController.savePatientVisitDetails = async (req, res) => { let code = 500, message = "Error! Saving Patient Visit Details", returnObj = {}; try { const postData = h.getProps2(req); const visit = req.visit; const constNotesDTO = patientUtil._constNotesDTO(postData); const updated = await Common.update(constNotesDTO, 'REGISTRATION.const_notes', { visit_id: visit.visit_id }, req.user) // Working await saveVitals(visit, postData.vitals, req.user); // Working await saveDiagnosis(visit, postData.diagnosis, req.user); // Working await saveDiagnostics(visit, postData.diagnostics, req.user); // Working await saveAllergies(visit, postData.allergies, req.user); // Working await saveMedicines(visit, postData.medications, req.user); // Working result = await patientVisitDetails(visit); code = 200; message = 'Data Saved Successfully'; returnObj = { result: result, message: message }; } catch (e) { returnObj = { result: false, message: message }; throw e; } finally { res.status(code).send(returnObj); } }; PatientController.checkPatientNKDA = async (req, res) => { let code = 500, message = "Error! Saving Patient NKDA", returnObj = {}; try { const postData = h.getProps2(req);// const nkda = await Patient.checkPatientNKDA(visit); const nkda = await Patient.checkPatientNKDA(postData); data = { "mrno": postData.mrno, "description": 'NKDA', "active": postData.nkda == 1 ? 'Y' : 'N', } if (h.checkExistsNotEmpty(nkda, 'active')) { await Common.update(data, 'registration.tbl_nkda', { mrno: postData.mrno }, req.user) // } else if (h.checkExistsNotEmpty(nkda, 'active') && nkda.active == 'Y') { // } else if (h.checkExistsNotEmpty(nkda, 'active') && nkda.active == 'N') { // console.log('N'); } else { await Common.insert(data, 'registration.tbl_nkda', req.user) } code = 200; message = 'Data Saved Successfully'; returnObj = { result: true, message: message }; } catch (e) { returnObj = { result: false, message: message }; throw e; } finally { res.status(code).send(returnObj); } }; PatientController.deleteVisit = async (req, res) => { let code = 500, message = "Error! Deleting Patient Visit", returnObj = {}; try { const postData = h.getProps2(req); const visit = req.visit; const constNotesDTO = patientUtil._deleteConstNotesDTO(postData); const result = await Common.update(constNotesDTO, 'REGISTRATION.const_notes', { visit_id: visit.visit_id }, req.user) // Working code = 200; message = 'Visit Deleted Successfully'; returnObj = { result: result, message: message }; } catch (e) { returnObj = { result: false, message: message }; throw e; } finally { res.status(code).send(returnObj); } }; /*************************************** Reports *******************************************/ PatientController.patientReport = async (req, res) => { let code = 500, message = "Error! Retrieving Patient Vital History", returnObj = {}; try { const visit = req.visit; const result = await Common.getDoctorReport(visit); const REPORT_URL = process.env.REPORT_SERVER_URL + result.prescription + process.env.REPORT_SERVER_AUTH + '&VISIT_ID=' + visit.visit_id; const optionsStart = { uri: REPORT_URL, method: "GET", encoding: "binary", // it also works with encoding: null headers: { "Content-type": "application/pdf" } }; request(optionsStart, async (err, resp, body) => { let loc = './uploads/reports/'; const filename = 'report_' + visit.visit_id + '_' + new Date().valueOf() + '.pdf' let writeStream = fs.createWriteStream(loc + filename); writeStream.write(body, 'binary'); await writeStream.end(); code = 200; returnObj = { filename: filename }; res.status(code).send(returnObj); }); } catch (e) { returnObj = { result: false, message: message }; res.status(code).send(returnObj); throw e; } } PatientController.patientReportMedicalRecord = async (req, res) => { let code = 500, message = "Error! Retrieving Patient Vital History", returnObj = {}; try { const visit = req.visit; const result = await Common.getDoctorReport(visit); const REPORT_URL = process.env.REPORT_SERVER_URL + 'patient_visit_detail_medrec.rdf' + process.env.REPORT_SERVER_AUTH + '&VISIT_ID=' + visit.visit_id; const optionsStart = { uri: REPORT_URL, method: "GET", encoding: "binary", // it also works with encoding: null headers: { "Content-type": "application/pdf" } }; request(optionsStart, async (err, resp, body) => { let loc = './uploads/reports/'; const filename = 'report_medical_record_' + visit.visit_id + '_' + new Date().valueOf() + '.pdf' let writeStream = fs.createWriteStream(loc + filename); writeStream.write(body, 'binary'); await writeStream.end(); code = 200; returnObj = { filename: filename }; res.status(code).send(returnObj); }); } catch (e) { returnObj = { result: false, message: message }; res.status(code).send(returnObj); throw e; } } PatientController.patientDiagnosticReport = async (req, res) => { let code = 500, message = "Error! Retrieving Patient Report", returnObj = {}; try { filter = h.getProps2(req); await reportService.getPDF(filter); // const visit = req.visit; // const result = await Common.getDoctorReport(visit); // const REPORT_URL = process.env.REPORT_SERVER_URL + result.prescription + process.env.REPORT_SERVER_AUTH + '&VISIT_ID=' + visit.visit_id; // const optionsStart = { // uri: REPORT_URL, // method: "GET", // encoding: "binary", // it also works with encoding: null // headers: { // "Content-type": "application/pdf" // } // }; // request(optionsStart, async (err, resp, body) => { // let loc = './uploads/reports/'; // const filename = 'report_' + visit.visit_id + '_' + new Date().valueOf() + '.pdf' // let writeStream = fs.createWriteStream(loc + filename); // writeStream.write(body, 'binary'); // await writeStream.end(); // code = 200; // returnObj = { // filename: filename // }; // res.status(code).send(returnObj); // }); returnObj = true; } catch (e) { throw e; } finally { res.status(code).send(returnObj); } } PatientController.getPatientNeurologyReport = async (req, res) => { let code = 500, message = "Error! Retrieving Patient Neurology Report", returnObj = {}; try { let filter = h.getProps2(req); if (h.checkExistsNotEmpty(filter, 'test_name') && h.checkExistsNotEmptyGreaterZero(filter, 'test_code')) { returnObj = await reportService.genericReport(filter, 'Neurology'); code = returnObj.statusCode; } else { code = 400; returnObj = h.resultObject([], false, code, 'Please provide Test name & code'); } } catch (e) { returnObj = h.resultObject([], false, code, message); throw e; } finally { res.status(code).send(returnObj); } }; PatientController.getPatientCardiologyReport = async (req, res) => { let code = 500, message = "Error! Retrieving Patient Cardiology Report", returnObj = {}; try { let filter = h.getProps2(req); if (h.checkExistsNotEmpty(filter, 'test_code')) { returnObj = await reportService.genericReport(filter, 'Cardiology'); code = returnObj.statusCode; } else { code = 400; returnObj = h.resultObject([], false, code, 'Please provide Test code'); } } catch (e) { returnObj = h.resultObject([], false, code, message); throw e; } finally { res.status(code).send(returnObj); } }; PatientController.getPatientRadiologyReport = async (req, res) => { let code = 500, message = "Error! Retrieving Patient Radiology Report", returnObj = {}; try { let filter = h.getProps2(req); filter = h.appendUserDetails(filter, req); if (h.checkExistsNotEmptyGreaterZero(filter, 'test_code') && h.checkExistsNotEmpty(filter, 'test_status') && (filter.test_status == 'YN' || filter.test_status == 'YY')) { returnObj = await reportService.genericReport(filter, 'Radiology'); code = returnObj.statusCode; } else { code = 400; returnObj = h.resultObject([], false, code, 'Please provide Test code'); } } catch (e) { returnObj = h.resultObject([], false, code, message); throw e; } finally { res.status(code).send(returnObj); } }; PatientController.getPatientLabReport = async (req, res) => { let code = 500, message = "Error! Retrieving Patient Lab Report", returnObj = {}; try { let filter = h.getProps2(req); filter = h.appendUserDetails(filter, req); if (h.checkExistsNotEmptyGreaterZero(filter, 'test_code')) { returnObj = await reportService.genericReport(filter, 'Lab'); code = returnObj.statusCode; } else { code = 400; returnObj = h.resultObject([], false, code, 'Please provide Test code'); } } catch (e) { returnObj = h.resultObject([], false, code, message); throw e; } finally { res.status(code).send(returnObj); } }; PatientController.getPatientGastroReport = async (req, res) => { let code = 500, message = "Error! Retrieving Patient Gastro Report", returnObj = {}; try { let filter = h.getProps2(req); filter = h.appendUserDetails(filter, req); if (h.checkExistsNotEmptyGreaterZero(filter, 'test_code')) { returnObj = await reportService.genericReport(filter, 'Gastro'); code = returnObj.statusCode; } else { code = 400; returnObj = h.resultObject([], false, code, 'Please provide Test code'); } } catch (e) { returnObj = h.resultObject([], false, code, message); throw e; } finally { res.status(code).send(returnObj); } }; /*************************************** Share Reports *************************************/ PatientController.sharePatientReport = async (req, res) => { let code = 500, message = "Error! Sharing Patient Report", returnObj = {}; try { const visit = req.visit; const filter = h.getProps2(req); const REPORT_URL = await getDoctorReportURL(visit); const filepathname = './uploads/reports/' + 'report_' + visit.visit_id + '_' + new Date().valueOf() + '.pdf'; const report = await getPatientReport(REPORT_URL, filepathname); // Text Message const content = await Patient.patientVisitMesssageTemplate(visit); await textSMS(content, filter.to_number); // Report Message const data = await h.base64EncodeFile(filepathname); await fileSMS(data, filter.to_number); code = 200; returnObj = { result: true, filename: 'Report Shared' }; } catch (e) { returnObj = { result: false, message: message }; throw e; } finally { res.status(code).send(returnObj); } } PatientController.shareZoomInvite = async (req, res) => { let code = 500, message = "Error! Sending Invitation Link", returnObj = {}; try { const visit = req.visit; const filter = h.getProps2(req); const content = await Patient.patientVisitMesssageTemplate(visit); const invitation = await zoomService.createMeeting(content); const log = await saveInvitationLog({ ...visit, ...invitation, phoneno: filter.to_number[0] }, invitation); if (h.checkExistsNotEmptyGreaterZero(log, 'meetingid')) { // Invitation Link Message await linkSMS({ ...content, ...invitation }, filter.to_number); code = 200; const { uuid, id, host_email, start_url } = invitation; returnObj = h.resultObject({ uuid, id, host_email, start_url }, true, code); } else { returnObj = h.resultObject([], false, code, message); } } catch (e) { returnObj = h.resultObject([], false, code, message); throw e; } finally { res.status(code).send(returnObj); } } const saveInvitationLog = async (log, invitation) => { try { const data = patientUtil._invitationLogDTO(log, invitation); const result = await Common.insert(data, 'CDR.INVITATION_LINKS', {}); return result.shift(); } catch (e) { throw e; } } const getDoctorReportURL = async (visit) => { const result = await Common.getDoctorReport(visit); const url = process.env.REPORT_SERVER_URL + result.prescription + process.env.REPORT_SERVER_AUTH + '&VISIT_ID=' + visit.visit_id; return url; } const getPatientReport = async (url, path) => { let result = false; try { const options = { method: "GET", encoding: "binary", // it also works with encoding: null headers: { "Content-type": "application/pdf" } }; let response = await rp(url, options); let writeStream = fs.createWriteStream(path); writeStream.write(response, 'binary'); await writeStream.end(); result = true; } catch (e) { throw e; } finally { return result; } // return filename; } const linkSMS = async (o, to_numbers) => { const message = `Dear Client,\nZoom Invitation Details of Patient *${o.patient}* for consultation with consultant *${o.consultant}* on _${o.vdate}_ is:\n*Meeting ID:* _${o.id}_\n*Password:* _${o.password}_\n*Join URL:* _${o.join_url}_\nFor assistance call +92518464646.`; for (const to_number of to_numbers) { const resp = await mayTapi.sendSMS({ message: message, type: 'text', to_number: to_number }); } } const textSMS = async (o, to_numbers) => { const message = `Dear Client,\nPrescription Report of Patient *${o.patient}* for consultation with consultant *${o.consultant}* on _${o.vdate}_ is dispatched.\nFor assistance call +92518464646.`; for (const to_number of to_numbers) { const resp = await mayTapi.sendSMS({ message: message, type: 'text', to_number: to_number }); } } const fileSMS = async (o, to_numbers) => { const message = o; for (const to_number of to_numbers) { const resp = await mayTapi.sendSMS({ message: message, type: 'media', to_number: to_number, text: 'Prescription Report.pdf' }); } } const patientVisitDetails = async (visit, current = true) => { try { const allergies = await Patient.getPatientAllergies(visit); const diagnosis = await Patient.getPatientDiagnosis(visit); const diagnostics = await Patient.getPatientDiagnostics(visit); const medicines = await Patient.getPatientMedicine(visit); for (const m of medicines) { let filter = { code: m.medicine_code }; let res = await Doctor.getMedicineFrequencies(filter); if (res.length === 0) { res = await Doctor.getMedicineFrequenciesAll(filter); } m.medication_frequency = res; } const vitalsAndDefinitions = await Common.getPatientVisitVitalsAndDefinitions(visit); const nkda = await Patient.checkPatientNKDA(visit); let previousVitals = []; const previous_visit = await Patient.getPreviousVisit(visit); if (h.checkExistsNotEmpty(previous_visit, 'visit_id')) { previousVitals = await Common.getVisitVitals(previous_visit); } const invitations = await Patient.getPatientInvites(visit); const result = { visit_id: visit.visit_id, allergies: patientUtil._formatAllergies(allergies), presentingComplaints: patientUtil._formatPresentingComplaints(visit), clinicalDetails: patientUtil._formatClinicalDetails(visit), impression: patientUtil._formatImpression(visit), followupEnter: patientUtil._formatFollowUp(visit), followupSelect: patientUtil._formatFollowUpSelect(visit), other_instruction: patientUtil._formatOtherInstruction(visit), visit_date: patientUtil._formatVisitDate(visit), entry_date: visit.entry_date, diagnosis: patientUtil._formatDiagnosis(diagnosis), diagnostics: patientUtil._formatDiagnostics(diagnostics), managementPlan: patientUtil._formatManagementPlan(visit), physicalExamination: patientUtil._formatPhysicalExamination(visit), medications: patientUtil._formatMedicines(medicines), vitals: patientUtil._formatVitals(vitalsAndDefinitions, previousVitals), nkda: h.checkExistsNotEmpty(nkda, 'active') && nkda.active == 'Y' ? 1 : 0, home_services: patientUtil._formatHomeServices(visit), invitations: invitations, invitation: patientUtil._formatInvite(invitations.shift()), } return result; } catch (e) { throw e; } } const saveVitals = async (visit, vitals, user) => { try { const result = []; const details = { visit_id: visit.visit_id, "mr#": visit.mrno }; await Common.delete('REGISTRATION.vital_signs', { visit_id: visit.visit_id }, user); for (const e of vitals) { if (h.checkExistsNotEmpty(e, 'result')) { let singleObj = utility._visitVitalObject(e, visit.spec_id, visit.visit_id); const inserted = await Common.insert(singleObj, 'REGISTRATION.vital_signs', user); if (e.vital_id == 1) { details.bp_s = e.result; } else if (e.vital_id == 2) { details.bp_d = e.result; } else if (e.vital_id == 3) { details.weight = e.result; } else if (e.vital_id == 4) { details.height = e.result; } else if (e.vital_id == 5) { details.temprature = e.result; } else if (e.vital_id == 7) { details.pulse = e.result; } else if (e.vital_id == 13) { details.head = e.result; } result.push(inserted); } } details.id = moment().format('MMYYDDHHmmss'); const inserted_details = await Common.insert(details, 'registration.VITAL_SIGN_DETAIL', user); } catch (e) { throw e; } } const saveDiagnosis = async (visit, diagnosis, user) => { try { for (const e of diagnosis) { if (h.checkExistsNotEmptyGreaterZero(e, 'code')) { let singleObj = patientUtil._diagnosisDTO(e, visit); let check = await Patient.checkPatientDiagnosis(e, visit); if (h.checkExistsNotEmpty(check, 'visit_id')) { const updated = await Common.update(singleObj, 'REGISTRATION.diagnosis', { visit_id: singleObj.visit_id, icd_code: singleObj.icd_code }, user); } else { const inserted = await Common.insert(singleObj, 'REGISTRATION.diagnosis', user); } } } } catch (e) { throw e; } } const saveDiagnostics = async (visit, diagnostics, user) => { try { for (const e of diagnostics) { if (h.checkExistsNotEmptyGreaterZero(e, 'service_id')) { let singleObj = patientUtil._diagnosticsDTO(e, visit); let check = await Patient.checkPatientDiagnostics(e, visit); if (h.checkExistsNotEmpty(check, 'visit_id')) { const updated = await Common.update(singleObj, 'REGISTRATION.diagnostics', { visit_id: singleObj.visit_id, service_id: singleObj.service_id }, user); } else { const inserted = await Common.insert(singleObj, 'REGISTRATION.diagnostics', user); } } } } catch (e) { throw e; } } const saveAllergies = async (visit, allergies, user) => { try { for (const e of allergies) { if (h.checkExistsNotEmpty(e, 'allergyCode')) { if (e.defaultSelectedAllergyType === 'generic') { let subclass = await Patient.allergyClassSubClass(e); let singleObj = patientUtil._genericAllergiesDTO(e, visit, subclass); let check = await Patient.checkPatientGenericAllergies(singleObj); if (h.checkExistsNotEmpty(check, 'mrno')) { let search = { mrno: singleObj.mrno }; if (h.checkExistsNotEmpty(singleObj, 'gen_code')) { search['gen_code'] = singleObj.gen_code; } if (h.checkExistsNotEmpty(singleObj, 'sub_class_code')) { search['sub_class_code'] = singleObj.sub_class_code; search['class_code'] = singleObj.class_code; } const updated = await Common.update(singleObj, 'PHARMACY_SHIFA.CLASS_ALERGY', search, user); } else { const inserted = await Common.insert(singleObj, 'PHARMACY_SHIFA.CLASS_ALERGY', user); } } else if (e.defaultSelectedAllergyType === 'brand') { let singleObj = patientUtil._brandAllergiesDTO(e, visit); let check = await Patient.checkPatientBrandAllergies(e, visit); if (h.checkExistsNotEmpty(check, 'mrno')) { const updated = await Common.update(singleObj, 'REGISTRATION.MOAR_DRUG_BRAND_ALLERGY', { medicine_code: singleObj.medicine_code, mr_no: singleObj.mr_no }, user); } else { const inserted = await Common.insert(singleObj, 'REGISTRATION.MOAR_DRUG_BRAND_ALLERGY', user); } } } } } catch (e) { throw e; } } const saveMedicines = async (visit, medicines, user) => { try { for (const e of medicines) { if (h.checkExistsNotEmpty(e, 'medicine_code')) { let singleObj = patientUtil._medicinesDTO(e, visit); let check = await Patient.checkPatientMedicines(e, visit); if (h.checkExistsNotEmpty(check, 'medicine_code')) { const updated = await Common.update(singleObj, 'REGISTRATION.medicine_prescription', { visit_id: singleObj.visit_id, medicine_code: singleObj.medicine_code, isactive: 'Y' }, user); } else { const inserted = await Common.insert(singleObj, 'REGISTRATION.medicine_prescription', user); } } else { let singleObj = patientUtil._medicinesDTO(e, visit); let check = await Patient.checkPatientNonFormularyMedicines(e, visit); if (h.checkExistsNotEmpty(check, 'medicine')) { const updated = await Common.update(singleObj, 'REGISTRATION.medicine_prescription', { visit_id: singleObj.visit_id, medicine: singleObj.medicine, isactive: 'Y' }, user); } else { const inserted = await Common.insert(singleObj, 'REGISTRATION.medicine_prescription', user); } } } } catch (e) { throw e; } } module.exports = PatientController;
import React from 'react'; import classes from './OrderSummary.css'; import Aux from '../../../hoc/Auxilliary'; import Button from '../../Button/Button'; const OrderSummary = props => { let transformedIngredients = Object.keys(props.ingredients).map((key) => { return <li key={key}> {key} : {props.ingredients[key]} </li> }) //console.log(transformedIngredients) return ( <Aux> <div className={classes.OrderSummary}> Ingredients Summary: <ul> {transformedIngredients} </ul> <p><strong>Price: {props.price}</strong></p> <Button buttonType='Danger' clicked={props.goBackClicked}>Go Back</Button> <Button buttonType='Success' clicked={props.previewClicked}>Preview</Button> <Button buttonType='CrossIcon' clicked={props.crossIconClicked}>X</Button> </div> </Aux> ) } export default OrderSummary;
import {Game} from "./game"; export class GameGui extends Game { constructor(doc) { super(doc); this.map.setGame(this); this.setStatus(); this.sounds = { station: new Howl({src: ['/snd/station.wav'], volume: 0.5}), remove: new Howl({src: ['/snd/remove.wav'], volume: 0.5}), drag: new Howl({src: ['/snd/drag.wav'], volume: 0.3}), success: new Howl({src: ['/snd/success.wav'], volume: 0.5}), merge: new Howl({src: ['/snd/merge.wav'], volume: 1}), clip: new Howl({src: ['/snd/clip.wav'], volume: 1}), } } sound(name, options = {}) { // const option = options || {}; if(options.onlyIfNotPlaying && this.sounds[name].playing()) return; if(typeof(options.stereo) === 'undefined') options.stereo = -1 + this.map.mousePos.x / this.map.canvas.width * 2; if(options.stopAllOthers) _.each(this.sounds, function(s) {s.stop();}); // console.log(this.map.mousePos.x, options.stereo); this.sounds[name].stereo(options.stereo).rate(1.0 + Math.random() / 4).play(); } stop() { _.each(this.sounds, function(s) {s.unload();}); } canModifyMap() { const uid = Meteor.userId(); let rv = false; if(uid && this.map && this.map._id) { const game = Games.findOne(this.map._id); rv = game && game.players && game.players.some(function(m) { return m._id === uid }); if(typeof(rv) === "undefined") rv = false; } if(this._canModifyMap !== rv) { console.log('canModifyMap changed to', rv); this._canModifyMap = rv; this._canModifyMapDep.changed(); } return rv; } setStatus() { let status = 'Ready<br/>'; if(!Meteor.user()) status = 'You must be loggued to play<br/>'; else { if(!this.canModifyMap()) status = 'You can not modify this map. Are you a team member ?'; // FIXME P1 // else if(this.map.stations.length === 0) status = 'You should place your first station<br/>'; // else if(this.map.stations.length < 3) status = 'You should build more rails<br/>'; } this.gameStatus.set(status); } }
import React, {useEffect,useState} from 'react' import api from './api/api' import SideBar from './components/SideBar/SideBar' import DevList from './components/DevList/DevList' import './global.css' import './App.css' export default () => { const [latitude,setLatitude] = useState('') const [longitude,setLongitude] = useState('') const [username,setUsername] = useState('') const [techs,setTechs] = useState('') const [devs,setDevs] = useState([]) useEffect(()=>{ async function loadDevs(){ const response = await api.get('/devs') setDevs(response.data) } loadDevs() },[]) useEffect( () => { navigator.geolocation.getCurrentPosition( (position) =>{ setLatitude(position.coords.latitude) setLongitude(position.coords.longitude) }, (err) => { console.log(err) }, { timeout: 30000 }) },[]) async function handleSubmit(e){ e.preventDefault() await api.post('/devs',{ github_username: username, techs, latitude, longitude }) .then(response => { if(!response.data.message){ setDevs([ ...devs,response.data ]) } }).catch(err => { console.log(err) }) } return ( <div id = "app"> <SideBar setUsername = {setUsername} setTechs = {setTechs} setLatitude = {setLatitude} setLongitude = {setLongitude} handleSubmit = {handleSubmit} latitude = {latitude} longitude = {longitude} username = {username} techs = {techs} /> <DevList devs = {devs}/> </div> ) }
import React, { Component } from "react"; import { Mutation } from "react-apollo"; import gql from "graphql-tag"; import Error from "../ErrorMessage"; import { CURRENT_USER_QUERY } from "../Accounts/User"; import PropTypes from "prop-types"; import Router from "next/router"; /* GraphQl Query */ /* Mutation Query */ const RESET_PASSWORD_MUTATION = gql` mutation RESET_PASSWORD_MUTATION( $password: String! $confirmPassword: String! $resetToken: String! ) { resetUserPassword( password: $password confirmPassword: $confirmPassword resetToken: $resetToken ) { id email name } } `; class ResetPassword extends Component { static propTypes = { resetToken: PropTypes.string.isRequired, }; state = { password: "", confirmPassword: "", }; addToState = e => { this.setState({ [e.target.name]: e.target.value }); }; render() { return ( <Mutation mutation={RESET_PASSWORD_MUTATION} variables={{ resetToken: this.props.resetToken, password: this.state.password, confirmPassword: this.state.confirmPassword, }} refetchQueries={[{ query: CURRENT_USER_QUERY }]} > {(reset, { error, loading, called }) => ( <form className="forms" onSubmit={async e => { e.preventDefault(); await reset(); this.setState({ password: "", confirmPassword: "", }); Router.push({ pathname: "/store", }); }} method="post" > <h1 className="header1">Change Your Password</h1> <span>Enter and confirm your password</span> <Error error={error} /> {!error && !loading && called && ( <> <p>Success✅ - Redirecting...</p> </> )} <input type="password" placeholder="Enter Password" name="password" required autoFocus value={this.state.password} onChange={this.addToState} /> <input type="password" placeholder="Confirm Password" name="confirmPassword" required value={this.state.confirmPassword} onChange={this.addToState} /> <button className="btn" type="submit"> Sav{loading ? "ing" : "e"} Changes </button> </form> )} </Mutation> ); } } export default ResetPassword;
import AccessibilityModule from '../../index'; describe('ImgData', () => { describe('register role', () => { let cjsImg; let imgEl; let altVal; let crossOriginVal; let heightVal; let isIsMap; let longDescVal; let sizesVal; let srcVal; let srcSetVal; let useMapVal; let widthVal; beforeEach(() => { cjsImg = new createjs.Shape(); // dummy object altVal = 'an image'; crossOriginVal = 'anonymous'; heightVal = 99; isIsMap = true; longDescVal = 'url.html'; sizesVal = '(max-height = 500px) 1000px'; srcVal = 'img.jpg'; srcSetVal = 'img480.jpg 480w; img800.jpg 800w'; useMapVal = '#map'; widthVal = 999; AccessibilityModule.register({ accessibleOptions: { alt: altVal, crossOrigin: crossOriginVal, height: heightVal, isMap: isIsMap, longDesc: longDescVal, sizes: sizesVal, src: srcVal, srcSet: srcSetVal, useMap: useMapVal, width: widthVal, }, displayObject: cjsImg, parent: container, role: AccessibilityModule.ROLES.IMG, }); stage.accessibilityTranslator.update(); imgEl = parentEl.querySelector('img'); }); describe('rendering', () => { it('creates img element', () => { expect(imgEl).not.toBeNull(); }); it('sets "alt" attribute', () => { expect(imgEl.alt).toEqual(altVal); }); it('sets "crossOrigin" attribute', () => { expect(imgEl.crossOrigin).toEqual(crossOriginVal); }); it('sets "height" attribute', () => { expect(imgEl.height).toEqual(heightVal); }); it('sets "isMap" attribute', () => { expect(imgEl.isMap).toEqual(isIsMap); }); it('sets "longDesc" attribute', () => { expect(imgEl.getAttribute('longDesc')).toEqual(longDescVal); }); it('sets "sizes" attribute', () => { expect(imgEl.sizes).toEqual(sizesVal); }); it('sets "src" attribute', () => { expect(imgEl.getAttribute('src')).toEqual(srcVal); }); it('sets "srcSet" attribute', () => { expect(imgEl.srcset).toEqual(srcSetVal); }); it('sets "useMap" attribute', () => { expect(imgEl.useMap).toEqual(useMapVal); }); it('sets "width" attribute', () => { expect(imgEl.width).toEqual(widthVal); }); }); describe('children checking', () => { const cjsChild = new createjs.Shape(); // dummy object AccessibilityModule.register({ displayObject: cjsChild, role: AccessibilityModule.ROLES.CELL, }); it('throws error attempting addChild()', () => { expect(() => { cjsImg.accessible.addChild(cjsChild); }).toThrowError(/img cannot have children/); }); it('throws error attempting addChildAt()', () => { expect(() => { cjsImg.accessible.addChildAt(cjsChild); }).toThrowError(/img cannot have children/); }); }); describe('options getters and setters', () => { it('can read and set "alt" property', () => { expect(cjsImg.accessible.alt).toEqual(altVal); const newVal = 'a new image'; cjsImg.accessible.alt = newVal; expect(cjsImg.accessible.alt).toEqual(newVal); }); it('can read and set "crossOrigin" property', () => { expect(cjsImg.accessible.crossOrigin).toEqual(crossOriginVal); const newVal = 'use-credentials'; cjsImg.accessible.crossOrigin = newVal; expect(cjsImg.accessible.crossOrigin).toEqual(newVal); }); it('can read and set "height" property', () => { expect(cjsImg.accessible.height).toEqual(heightVal); const newVal = 100; cjsImg.accessible.height = newVal; expect(cjsImg.accessible.height).toEqual(newVal); }); it('can read and set "isMap" property', () => { expect(cjsImg.accessible.isMap).toEqual(isIsMap); const newVal = false; cjsImg.accessible.isMap = newVal; expect(cjsImg.accessible.isMap).toEqual(newVal); }); it('can read and set "longDesc" property', () => { expect(cjsImg.accessible.longDesc).toEqual(longDescVal); const newVal = 'new_url.html'; cjsImg.accessible.longDesc = newVal; expect(cjsImg.accessible.longDesc).toEqual(newVal); }); it('can read and set "sizes" property', () => { expect(cjsImg.accessible.sizes).toEqual(sizesVal); const newVal = '(max-height = 999px) 9999px'; cjsImg.accessible.sizes = newVal; expect(cjsImg.accessible.sizes).toEqual(newVal); }); it('can read and set "src" property', () => { expect(cjsImg.accessible.src).toEqual(srcVal); const newVal = 'img_new.jpg'; cjsImg.accessible.src = newVal; expect(cjsImg.accessible.src).toEqual(newVal); }); it('can read and set "srcSet" property', () => { expect(cjsImg.accessible.srcSet).toEqual(srcSetVal); const newVal = 'img960.jpg 960w; img1920.jpg 1920w'; cjsImg.accessible.srcSet = newVal; expect(cjsImg.accessible.srcSet).toEqual(newVal); }); it('can read and set "useMap" property', () => { expect(cjsImg.accessible.useMap).toEqual(useMapVal); const newVal = '#newmap'; cjsImg.accessible.useMap = newVal; expect(cjsImg.accessible.useMap).toEqual(newVal); }); it('can read and set "width" property', () => { expect(cjsImg.accessible.width).toEqual(widthVal); const newVal = 1000; cjsImg.accessible.width = newVal; expect(cjsImg.accessible.width).toEqual(newVal); }); }); }); });
const fs = require('fs') const path = require('path') const readline = require('readline'); var LineReaderSync = require("line-reader-sync") var async = require('async'); const MongoClient = require('mongodb').MongoClient; var moment = require('moment') //時間 var moment = require('moment-timezone') //時區 //引用 nodemailer var nodemailer = require('nodemailer'); var date = moment().tz('Asia/Taipei').format('YYYY-MM-DD'); //宣告發信物件 var transporter = nodemailer.createTransport({ service: 'Gmail', auth: { user: "d02405035@ems.npu.edu.tw", pass: "kk950411" } }); var news = [] var contents = '' var email = '' var category = '' var emaiList = [] // var emaiList = [{ email: '123@gmail.com', category: '社會新聞' }, // { email: '12sds3@gmail.com', category: '社會新聞' }, // { email: '12dsdsdsds3@gmsdsail.com', category: '全部新聞' }] // 將emailList.txt的使用者資訊存到list async function parseFile(filePath) { lrs = new LineReaderSync(filePath) // 將讀取資料流導入 Readline 進行處理 while (true) { line = lrs.readline() if (line === null) { // console.log("EOF"); break; } if (line.indexOf("@email:") == 0) { for (i = 7; i < line.length; i++) { if (line[i] != ' ' && line[i] != '\n') { email += line[i] } } } if (line.indexOf("@category:") == 0) { for (i = 10; i < line.length; i++) { if (line[i] != ' ' && line[i] != '\n') { category += line[i] } } } if (email != "" && category != "") { // email = email.trim() user = { 'email': email, "category": category, } // emaiList.push(user) if (category == '全部新聞') { await searchAll(email) } else { await search(email, category) } // console.log(user) // console.log(category) email = '' category = '' } } // } } async function searchAll(email) { console.log("searchAll") var date = moment().tz('Asia/Taipei').format('YYYY-MM-DD'); return new Promise((resolve, reject) => { MongoClient.connect("mongodb://localhost:27017/mymondb", function (err, db) { if (err) throw err; db.collection('news', function (err, collection) { collection.find( { $and: [ { "date": date }, ], }, { score: { $meta: "textScore" } } ).sort({ score: { $meta: "textScore" } }) .toArray(function (err, items) { if (err) throw err; console.log("All results " + items.length + " results!"); contents = '' news = [] emailObj = { 'email': email, 'category': category, 'news': items.length, } console.log(emailObj) news.push(emailObj) // items.length長度為0就會是undefined for (var i in items) { if (items[i]['title'] == undefined) { var itemOne = '' } else { var itemOne = items[i]['title'] } break } itemOne = itemOne.replace(/\s+/g, '') // 第一行印出第一個item的title和剩餘items長度 contents += '<ul>' + '<h3 ' + 'style=\"font-family:\'EB Garamond\';\"' + '>' + itemOne + ',' + '還有 ' + (news[0]['news'] - 1).toString() + ' 則最新報導</h3><hr><ul>' // 印出每一項title和紀錄位置,點擊title可以跳至該位置 for (var i in items) { contents += '<li> <a href=\"#' + i + '\"' + 'style=\"text-decoration:none;\"' + '>' + items[i]["title"].replace(/\s+/g, '') + '</a> </li>' } contents += '</ul ></ul > <ul>' + '<hr>' // 印出title,description,image for (var i in items) { contents += ' <a name=\"' + i + '\"' + '</a>' + '<a href=\"' + items[i]["url"] + '\"' + 'target=\"_blank\"' + '>' + '<h3>' + items[i]["title"].replace(/\s+/g, '') + '</h3>' + '</a>' + ' <p>' + ' <h4 style="color:Gray;" " font-family: \'EB Garamond\';">' + '關鍵字:' + items[i]["keywords"] + '</h4>' + '</p>' + '<img src="' + items[i]["image"] + '"' + ' alt="News" width="400" height="265">' + '<p>' + items[i]["description"] + '</p >' + '</br>' } // 結束 contents += ' </ul ><ul> <hr> <p style="color:Gray;" " font-family: \'EB Garamond\';">You are subscribed to email updates from newsletter . </p></ul> ' // console.log(contents) resolve() db.close(); //關閉連線 sendMail() }); }); }); }); } async function search(email, category) { console.log("search") var date = moment().tz('Asia/Taipei').format('YYYY-MM-DD'); return new Promise((resolve, reject) => { MongoClient.connect("mongodb://localhost:27017/mymondb", function (err, db) { if (err) throw err; db.collection('news', function (err, collection) { collection.find( { $and: [ { "date": date }, { "category": category }, ], }, { score: { $meta: "textScore" } } ).sort({ score: { $meta: "textScore" } }) .toArray(function (err, items) { if (err) throw err; console.log("All results " + items.length + " results!"); contents = '' news = [] emailObj = { 'email': email, 'category': category, 'news': items.length, } console.log(emailObj) news.push(emailObj) // items.length長度為0就會是undefined for (var i in items) { if (items[i]['title'] == undefined) { var itemOne = '' } else { var itemOne = items[i]['title'] } break } itemOne = itemOne.replace(/\s+/g, '') // 第一行印出第一個item的title和剩餘items長度 contents += '<ul>' + '<h3 ' + 'style=\"font-family:\'EB Garamond\';\"' + '>' + itemOne + ',' + '還有 ' + (news[0]['news'] - 1).toString() + ' 則最新報導</h3><hr><ul>' // 印出每一項title和紀錄位置,點擊title可以跳至該位置 for (var i in items) { contents += '<li> <a href=\"#' + i + '\"' + 'style=\"text-decoration:none;\"' + '>' + items[i]["title"].replace(/\s+/g, '') + '</a> </li>' } contents += '</ul ></ul > <ul>' + '<hr>' // 印出title,description,image for (var i in items) { contents += ' <a name=\"' + i + '\"' + '</a>' + '<a href=\"' + items[i]["url"] + '\"' + 'target=\"_blank\"' + '>' + '<h3>' + items[i]["title"].replace(/\s+/g, '') + '</h3>' + '</a>' + ' <p>' + ' <h4 style="color:Gray;" " font-family: \'EB Garamond\';">' + '關鍵字:' + items[i]["keywords"] + '</h4>' + '</p>' + '<img src="' + items[i]["image"] + '"' + ' alt="News" width="400" height="265">' + '<p>' + items[i]["description"] + '</p >' + '</br>' } // 結束 contents += ' </ul ><ul> <hr> <p style="color:Gray;" " font-family: \'EB Garamond\';">You are subscribed to email updates from newsletter . </p></ul> ' // console.log(contents) resolve() db.close(); //關閉連線 sendMail() }); }); }); }); } async function sendMail() { var options = { //寄件者 from: 'd02405035@ems.npu.edu.tw', //收件者 to: news[0]["email"], //副本 // cc: 'd02405035@gmail.com', // //密件副本 // bcc: 'account4@gmail.com', //主旨 subject: date + '*' + news[0]["category"] + '*', // Subject line //純文字 text: 'Newsletter', // plaintext body //嵌入 html 的內文 html: contents, }; //發送信件方法 transporter.sendMail(options, function (error, info) { if (error) { console.log(error); } else { console.log('訊息發送: ' + info.response); } }); } /** Clear ES index, parse and index all files from the books directory */ async function readAndSend() { try { let files = fs.readdirSync('./userEmail').filter(file => file.slice(-4) === '.txt') file = files[0] console.log(`Reading File - ${file}`) const filePath = path.join('./userEmail', file) // // console.log("t1") await parseFile(filePath) console.log(emaiList) // console.log(filePath) // console.log("t2") // resolve() } catch (err) { console.error(err) } } readAndSend() // console.log(contents[0]["email"]) //email // var items = [{ email: 'd02405035@gmail.com' }, { // title: '中職/連3個半季拋彩帶! 桃猿勇奪職棒29年上半季冠軍', url: 'https://sports.ettoday.net/news/1192976' // }, // { title: '2個月前才釀17死 廣西發公文禁止端午節龍舟活動', url: 'https://www.ettoday.net/news/20180617/1193033.htm' }] // var str = '' // for (var i in items) { // // console.log(contents[i]['url']) // if (i != 0) { // str += '<li> <a href=\"' + items[i]["url"] + '\">' + items[i]["title"] + '</a> </li>' // } // } // str += ' </a > </li > </ul > <hr> <p style="color:Gray;" " font-family: \'EB Garamond\';">You are subscribed to email updates from newsletter . </p> <p style="color:Gray;" "background-color:LightGray;" " font-family: \'EB Garamond\';" > To stop receiving these emails, you may unsubscribe now.</p > ', // console.log(str)
// Given a string and an int n, return a string made of the first and last n chars from the string. The string length will be at least n. // Examples // nTwice('hello', 2) → helo // nTwice('Chocolate', 3) → Choate // nTwice('Chocolate', 1) → Ce function nTwice(str, n) { let first = str.substring(0, n); let last = str.substring(str.length - n); return first + last; }
//serve some mock api "use strict" // const fs = require('fs') // const path = require('path'); const express = require('express') const app = express() const request = require('superagent') const domainXtj = 'http://app.xiaotaojiang.com' const apiBanner = '/ws/settings/json/discover.banners' const apiArticle = '/articles' const apiArticleDetail = '/ws/articles' //allow CORS app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); }); app.get('/', (req, res) => { res.send('hello world') }) app.get('/banners', (req, res) => { // res.sendFile(path.normalize(__dirname + '/mock/banner.json')) request .get(domainXtj + apiBanner) .end((error, response) => { if(error) throw error res.json(response.body) }) }) app.get('/articles', (req, res) => { let start = req.query.start let limit = req.query.limit request .get(domainXtj + apiArticle) .query({start: start}) .query({limit: limit}) .end((error, response) => { if(error) throw error res.json(response.body) }) }) app.get('/article/:id', (req, res) => { let articleId = req.params.id console.log('/article ' + articleId) request .get(domainXtj + apiArticleDetail + '/' + articleId) .end((error, response) => { if(error) throw error res.json(response.body) }) }) app.listen(8080)
import React from 'react'; import PropTypes from 'prop-types'; import styles from '../CSS/reservationCosts.css'; // cleaningFee={cleaningFee} occupancyFee={occupancyFee} serviceFee={serviceFee} price={price} function ReservationCosts(props) { const { cleaningFee, occupancyFee, serviceFee, price, checkinDate, checkoutDate, } = props; let nights = 0; if (checkinDate.year !== null && checkoutDate.year !== null) { const checkin = new Date(checkinDate.year, checkinDate.month, checkinDate.day); const checkout = new Date(checkoutDate.year, checkoutDate.month, checkoutDate.day); const difference = checkout.getTime() - checkin.getTime(); const days = difference / (1000 * 3600 * 24); nights = days; } return ( <div className={styles.div} style={{ paddingBottom: '10px', paddingTop: '3px' }}> <div className={styles.prices} style={{ display: 'flex', justifyContent: 'space-between' }}> <span>{`$${price} x ${nights}`}</span> <span>{`$${price * nights}`}</span> </div> <hr className={styles.thinLine} /> <div className={styles.prices} style={{ display: 'flex', justifyContent: 'space-between' }}> <span>Cleaning Fee</span> <span>{`$${cleaningFee}`}</span> </div> <hr className={styles.thinLine} /> <div className={styles.prices} style={{ display: 'flex', justifyContent: 'space-between' }}> <span>Service Fee</span> <span>{`$${serviceFee}`}</span> </div> <hr className={styles.thinLine} /> <div className={styles.prices} style={{ display: 'flex', justifyContent: 'space-between' }}> <span>Occupancy Fee</span> <span>{`$${occupancyFee}`}</span> </div> <hr className={styles.thinLine} /> <div className={styles.prices} style={{ display: 'flex', justifyContent: 'space-between' }}> <span style={{ fontWeight: 'bold' }}>Total</span> <span style={{ fontWeight: 'bold' }}>{`$${cleaningFee + occupancyFee + serviceFee + price * nights}`}</span> </div> </div> ); } ReservationCosts.propTypes = { cleaningFee: PropTypes.number.isRequired, occupancyFee: PropTypes.number.isRequired, serviceFee: PropTypes.number.isRequired, price: PropTypes.number.isRequired, checkinDate: PropTypes.shape({ day: PropTypes.number.isRequired, month: PropTypes.number.isRequired, year: PropTypes.number.isRequired, }).isRequired, checkoutDate: PropTypes.shape({ day: PropTypes.number.isRequired, month: PropTypes.number.isRequired, year: PropTypes.number.isRequired, }).isRequired, }; export default ReservationCosts;
import React, {Component} from 'react'; import PureRenderMixin from 'react-addons-pure-render-mixin'; import {Link, hashHistory} from 'react-router'; import SearchInput from '../SearchInput'; import './style.scss'; export default class HomeHeader extends Component { constructor() { super(); this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this) } componentDidMount() { } onSearchHandel = (keyCode) => { hashHistory.push('/search/all/' + encodeURIComponent(keyCode)) }; render() { return ( <div className="headerBox"> <div className="mapBox"> <Link to='/city'> <span>{this.props.userInfo}</span> <i className="icon-keyboard_arrow_down"></i> </Link> </div> <div className="searchBox"> <i className="icon-search"></i> <SearchInput value="" searchHandel={this.onSearchHandel}/> </div> <div className="userBox"> <Link to='/login'> <i className="icon-user"></i> </Link> </div> </div> ) } }
module.exports = require('./uki-core'); require('./uki-view'); module.exports.createStylesheet(__requiredCss);
angular.module('homeTrip', []);
// server/app.js /* eslint-disable import/no-extraneous-dependencies */ /* eslint-disable global-require */ /* eslint-disable no-console */ const express = require('express'); const compression = require('compression'); const morgan = require('morgan'); const path = require('path'); const bodyParser = require('body-parser'); const jwt = require('express-jwt'); const jwksRsa = require('jwks-rsa'); const cors = require('cors'); const app = express(); const Word = require('./actions/word'); const { translate } = require('./actions/translate'); const API = require('./actions/api'); // webpack-dev-middleware if (process.env.NODE_ENV !== 'production') { const webpack = require('webpack'); const webpackConfig = require('../config/webpack.dev.config.js'); const compiler = webpack(webpackConfig); const webpackDevMiddleware = require('webpack-dev-middleware'); const webpackHotMiddleware = require('webpack-hot-middleware'); // Dev app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: webpackConfig.output.publicPath, })); // HMR app.use(webpackHotMiddleware(compiler, { log: console.log, path: '/__webpack_hmr', heartbeat: 10 * 1000, })); } // Setup logger app.use(morgan(':remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] :response-time ms')); // Setup gzip app.use(compression()); // Serve index app.use(express.static(path.resolve(__dirname, '..', 'dist'))); // Serve static assets app.use('/public', express.static(path.resolve(__dirname, '.', 'public'))); // Enable CORS app.use(cors()); // Enable the use of request body parsing middleware app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true, })); // Create middleware for checking the JWT const checkJwt = jwt({ secret: jwksRsa.expressJwtSecret({ cache: true, rateLimit: true, jwksRequestsPerMinute: 5, jwksUri: 'https://crispgm.au.auth0.com/.well-known/jwks.json', }), audience: 'api.word-kanban.words', issuer: 'https://crispgm.au.auth0.com/', algorithms: ['RS256'], }); app.get('/translate', checkJwt, (req, res) => { translate(req, res); }); app.get('/word/get', checkJwt, (req, res) => { return Word.get(req, res); }); app.post('/word/create', checkJwt, (req, res) => { return Word.create(req, res); }); app.post('/word/move', checkJwt, (req, res) => { return Word.move(req, res); }); app.post('/word/update', checkJwt, (req, res) => { return Word.update(req, res); }); app.post('/word/delete', checkJwt, (req, res) => { return Word.remove(req, res); }); app.get('/word/export', checkJwt, (req, res) => { return Word.exportData(req, res); }); app.get('/user/activity', checkJwt, (req, res) => { return Word.userRecord(req, res); }); app.get('/api/token', checkJwt, (req, res) => { return API.getToken(req, res); }); app.post('/api/generate', checkJwt, (req, res) => { return API.generateToken(req, res); }); app.post('/api/delete', checkJwt, (req, res) => { return API.deleteToken(req, res); }); app.post('/api/v1/word', (req, res) => { return API.createWord(req, res); }); app.get('/api/v1/words', (req, res) => { return API.getWords(req, res); }); // Always return the main index.html app.get('*', (req, res) => { res.sendFile(path.resolve(__dirname, '..', 'dist', 'index.html')); }); // Handle 404 app.use((req, res, next) => { res.redirect(404, '/#/404'); next(); }); module.exports = app;
$("#tab-menu li a").click(function() { $(this).blur(); if (!$(this).closest("li").hasClass("active")) { $("#tab-menu li").removeClass("active"); $(this).closest("li").addClass("active"); $(".tab-content").hide(); $("#content-" + $(this).data("tab")).fadeIn(500); if ($(this).data("tab") == "reports") { $("body").trigger("reports-show"); } else { $("body").trigger("reports-hide"); } } return false; }); $("#form-new").on("keyup", "input", function() { // bind this using .on() so that it also applies to new items added if ($(this).val() == "") { $(this).parent("li").addClass("has-error"); } else { $(this).parent("li").removeClass("has-error"); } }); $("#form-new").on("click", ".sensor-delete", function() { // bind this using .on() so that it also applies to new items added if (!$(this).hasClass("disabled")) { $(this).parent("li").remove(); } return false; }); $("#form-new").on("click", ".param-delete", function() { // bind this using .on() so that it also applies to new items added if (!$(this).hasClass("disabled")) { $(this).parent("li").remove(); } return false; }); $(".new-sensor").click(function() { if (!$(this).hasClass("disabled")) { $(this).parent("li").before('<li class="list-group-item sensor-item"><input type="text" value="" class="form-control sensor-name" placeholder="Enter sensor name"><a class="btn btn-danger sensor-delete" href="#"><i class="fa fa-trash-o"></i></a></li>'); $(this).closest("ul").children(".sensor-item").last().children(".sensor-name").focus(); } return false; }); $("#form-new").submit(function() { var $this = $(this); if ($(".sensor-item", $this).hasClass("has-error")) return false; $("input, button, select", $this).prop("disabled", true).blur(); $("a", $this).addClass("disabled"); $(".buttons-group .btn-primary", $this).html('<i class="fa fa-refresh fa-spin"></i> Adding').blur(); $(".sensor-item", $this).each(function(index, element) { if ($(".sensor-name", element).val() == "") { $(this).remove(); } }); var data = { "name": $("#new-name").val(), "sensors": [], "store": $("#new-store option:selected").val() }; var params = {}; $(".param-item", $this).each(function(index, element) { params[$(".param-key", element).val()] = $(".param-value", element).val(); }); if (!jQuery.isEmptyObject(params)) data.params = params; $(".sensor-item", $this).each(function(index, element) { data.sensors.push($(".sensor-name", element).val()); }); console.log(data); $.post("ajax-new.jsp", {"post": JSON.stringify(data)}, function success(httpdata, textStatus, jqXHR) { var button = $(".buttons-group .btn-primary", $this); button.html('<i class="fa fa-check"></i> Added').addClass("btn-success"); setTimeout(function() { window.location = "?system="+data.name; }, 1500); }, "json").fail(function() { alert("Error: permission denied - could not write to the config file."); var button = $(".buttons-group .btn-primary", $this); button.html('<i class="fa fa-exclamation-triangle"></i> Error').addClass("btn-warning"); setTimeout(function() { button.html('<i class="fa fa-plus-square"></i>&nbsp;&nbsp;Add').removeClass("btn-warning"); }, 1500); }).always(function() { $("input, button, select", $this).prop("disabled", false); $("a", $this).removeClass("disabled"); }); return false; }); $("#form-new").on("reset", function() { $(".sensor-item", this).remove(); }); $(".sensor-params").on("keyup", "input", function() { // bind this using .on() so that it also applies to new items added if ($(this).val() == "") { $(this).parent("li").addClass("has-error"); } else { $(this).parent("li").removeClass("has-error"); } }); $(".sensor-params").on("click", ".param-delete", function() { // bind this using .on() so that it also applies to new items added if (!$(this).hasClass("disabled")) { $(this).parent("li").removeClass("param-item").addClass("param-item-deleted"); } return false; }); $(".new-param").click(function() { if (!$(this).hasClass("disabled")) { $(this).parent("li").before('<li class="list-group-item param-item param-item-new"><input type="text" value="" class="form-control param-key"><input type="text" value="" class="form-control param-value"><a class="btn btn-danger param-delete" href="#"><i class="fa fa-trash-o"></i></a></li>'); $(this).closest("ul").children(".param-item-new").last().children(".param-key").focus(); } return false; }); $(".sensor-params").submit(function() { var $this = $(this); if ($(".param-item", $this).hasClass("has-error")) return false; $("input, button", $this).prop("disabled", true).blur(); $("a", $this).addClass("disabled"); $(".buttons-group .btn-primary", $this).html('<i class="fa fa-refresh fa-spin"></i> Saving').blur(); $(".param-item-deleted input", $this).prop("disabled", false); $(".param-item-deleted", $this).remove(); $(".param-item-new", $this).each(function(index, element) { if ($(".param-key", element).val() == "" || $(".param-value", element).val() == "") { $(this).remove(); } }); $(".param-item-new", $this).removeClass("param-item-new"); var data = {}; $(".param-item", $this).each(function(index, element) { data[$(".param-key", element).val()] = $(".param-value", element).val(); }); $.post("ajax-sensor-params.jsp?system=" + $("#systems-list .dropdown-toggle").text().trim() + "&sensor=" + $this.data("system"), {"post": JSON.stringify(data)}, function success(data, textStatus, jqXHR) { var button = $(".buttons-group .btn-primary", $this); button.html('<i class="fa fa-check"></i> Saved').addClass("btn-success"); setTimeout(function() { button.html("Save").removeClass("btn-success"); }, 1500); }, "json").fail(function() { alert("Error: permission denied - could not write to the config file."); var button = $(".buttons-group .btn-primary", $this); button.html('<i class="fa fa-exclamation-triangle"></i> Error').addClass("btn-warning"); setTimeout(function() { button.html("Save").removeClass("btn-warning"); }, 1500); }).always(function() { $("input, button", $this).prop("disabled", false); $("a", $this).removeClass("disabled"); }); return false; }); $(".sensor-params").on("reset", function() { $(".param-item-new", this).remove(); $(".param-item-deleted", this).removeClass("param-item-deleted").addClass("param-item"); }); $("#data-store").submit(function() { var $this = $(this); $("select, button", $this).prop("disabled", true).blur(); $(".btn-primary", $this).html('<i class="fa fa-refresh fa-spin"></i> Saving').blur(); var data = {"store": $("#data-store-name option:selected").val()}; $.post("ajax-datastore.jsp?system=" + $("#systems-list .dropdown-toggle").text().trim(), {"post": JSON.stringify(data)}, function success(data, textStatus, jqXHR) { var button = $(".btn-primary", $this); button.html('<i class="fa fa-check"></i> Saved').addClass("btn-success"); setTimeout(function() { button.html("Save").removeClass("btn-success"); }, 1500); }, "json").fail(function() { alert("Error: permission denied - could not write to the config file."); var button = $(".btn-primary", $this); button.html('<i class="fa fa-exclamation-triangle"></i> Error').addClass("btn-warning"); setTimeout(function() { button.html("Save").removeClass("btn-warning"); }, 1500); }).always(function() { $("select, button", $this).prop("disabled", false); }); return false; }); var changingEngines = false; $("#engines .toggle-switch").bootstrapSwitch({ size: "normal", onSwitchChange: function(event, state) { changingEngines = true; var data = {"engines": $("#engines input[type=checkbox]:checked").map(function() { return $(this).val(); }).get()}; $.post("ajax-engines.jsp?system=" + $("#systems-list .dropdown-toggle").text().trim(), {"post": JSON.stringify(data)}, function success(data, textStatus, jqXHR) { changingEngines = false; }, "json").fail(function() { alert("Error: permission denied - could not write to the config file."); if (!changingEngines) { $("#engines")[0].reset(); changingEngines = false; } }); } }); var changingReporting = false; $("#reporting .toggle-switch").bootstrapSwitch({ size: "normal", onSwitchChange: function(event, state) { if (!changingReporting) { changingReporting = true; $("#reporting input[type=checkbox]").not(this).prop("checked", false).trigger("change.bootstrapSwitch", false); var data = {"reporting": $("#reporting input[type=checkbox]:checked").map(function() { return $(this).val(); }).get()[0]}; $.post("ajax-reporting.jsp?system=" + $("#systems-list .dropdown-toggle").text().trim(), {"post": JSON.stringify(data)}, function success(data, textStatus, jqXHR) { changingReporting = false; window.location.href += "#report-change"; location.reload(); }, "json").fail(function() { alert("Error: permission denied - could not write to the config file."); $("#reporting")[0].reset(); changingReporting = false; }); } } }); $(function() { if (window.location.hash == "#report-change") { $("a[data-tab='engines']").click(); setTimeout(function() { window.scrollTo(0, document.body.scrollHeight); }, 500); window.location.hash = ""; } $(window).bind("unload", function() { $("input, button, select").prop("disabled", false); if ($("#form-new")) $("#form-new")[0].reset(); if ($("#engines")) $("#engines")[0].reset(); if ($("#data-store")) $("#data-store")[0].reset(); }); });
// import React, { Component } from 'react'; // import axios from 'axios'; // import '../css/product.css'; // export default class Product extends Component{ // constructor(){ // super() // this.state= { // size: '', // track: '', // trackColor: '', // aussieLine: '', // reelColor: '', // reelSize: '', // handleColor: '', // } // } // // componentDidMount(){ // // axios.get() // // .then(response) // // this.setState(() => ({ // // })) // // } // // } // render(){ // return( // <div> // <div className="line one"> // <div> // <label for='size' className="fn">Size:</label> // <input // className="productValue" // type="text" // name="size" // placeholder="80cm"/> // </div> // <div> // <label for='track' className="fn">Track:</label> // <input list="browsers" name="browser" /> // <datalist id="browsers"> // <option value="Enclosed Track"></option> // <option value="Open Track"></option> // <option value="Deep-Open Track"></option> // </datalist> // </div> // <div> // <label for='tcolor' className="fn">Track Color:</label> // <input list="browsers1" name="browser1" /> // <datalist id="browsers1"> // <option value="Purple Pearl"></option> // <option value="Sky Blue"></option> // <option value="Red Pearl"></option> // <option value="Galaxy Blue"></option> // </datalist> // </div> // </div> // <div className="line two"> // <div> // <label for='line' className="fn">Aussie Line:</label> // <input list="browsers2" name="browser2" /> // <datalist id="browsers2"> // <option value="Braid Line"></option> // <option value="Pro Line"></option> // </datalist> // </div> // <div> // <label for='reelColor' className="fn">Reel Color:</label> // <input list="browsers3" name="browser3" /> // <datalist id="browsers3"> // <option value="Red"></option> // <option value="White"></option> // <option value="Blue"></option> // <option value="Green"></option> // <option value="Black"></option> // <option value="Pink"></option> // <option value="Yellow"></option> // <option value="Orange"></option> // <option value="Purple"></option> // </datalist> // </div> // <div> // <label className="fn">Reel Size:</label> // <input list="browsers4" name="browser" /> // <datalist id="browsers4"> // <option value="50mm"></option> // <option value="100mm"></option> // </datalist> // </div> // </div> // <div className="line three"> // <div> // <label className="fn">Handle Color:</label> // <input list="browsers3" name="browser3" /> // <datalist id="browsers3"> // </datalist> // </div> // </div> // </div> // ) // } // }
import React from 'react' const FullName = () => { return ( <div className="text-white bg-blue-600 h-6 w-32 rounded-sm text-center"> <h1>Isa Haji</h1> </div> ) } export default FullName
// USGBC LEED Plaque - IDEO D-Shop (Tobias Toft and Ethan Klein) // IDEO password for LEED api username: ideo password: password // the Object Literal 'plaque' contains our js code. // reference any function or property via 'plaque.width' etc. var plaque = plaque || { width: 750, height: 750, radius: 216/2, // radius for the inner-most track radiusIncrement: 37, totalScore: 24, fadeSpeed: 1000, page: 'home', LEED: '1000005063', ID: '', key: '', buildingData: {}, catColors: {'energy': '#D0DD3D', 'water': '#55CAF5', 'waste': '#84CCAF', 'transportation': '#A39F92', 'human': '#F2AC41', 'human_fuel': '#9e8fc4'}, // #ldpf-37 human_fuel added for co2 and voc charts color under human experience section trackColors: {}, assosiatedCategories: [], setupTrack: {}, setupTrack_main: {}, setupTrack_lastMonth: {}, setupTrack_lastYear: {}, physicalScale : 1, // plaque.setup gets called when the DOM is ready setup: function(args, forcefully) { plaque.page = args.page; plaque.tl = new TimelineMax(); plaque.raphael = Raphael(args.container, plaque.width, plaque.height); plaque.customShapes(); if (plaque.page == "overview"){ plaque.getData(forcefully); } else{ plaque.getData(); // get json } // to be called if backend is problematic (comment out line above - getData()) // plaque.offline() }, kill: function(){ TweenMax.killAll(); }, //Initiate all animations from here animateAll: function() { if (plaque.page === "overview") { $("#score-puck").fadeIn(plaqueNav.pageSwitchSpeed); } var scorepuck = document.getElementById('score-puck'); if (plaque.buildingData.certification == "" || plaque.buildingData.certification == "Denied" || plaque.buildingData.certification == "None") { $('.nav .home').html("Score"); $('.nav .home').css("padding-top", "25px"); $('img.leed_logo_small').attr("src", '/static/dashboard/img/leed_logo_blank_small.png') //$('score-puck').css("background", "url(../img/score-puck_nonleed.svg) no-repeat"); //var scorepuck = document.getElementById('score-puck'); scorepuck.style.backgroundImage = 'url(/static/dashboard/img/score-puck_nonleed.svg)'; } else{ $('.nav .home').html("LEED Score"); $('.nav .home').css("padding-top", "22px"); $('img.leed_logo_small').attr("src", '/static/dashboard/img/leed_logo_small.png'); scorepuck.style.backgroundImage = 'url(/static/dashboard/img/score-puck.svg)'; } plaque.animateTracks(0); }, animateTracks: function(delay){ //Animate tracks in delay /= 1000; //convert ms to s for tweenmax if (plaque.page == "overview"){ for (var i = (plaque.assosiatedCategories).length-1; i > -1; i--) { plaque.setupTrack[plaque.assosiatedCategories[i]["category"]].animateIn(delay); }; } else{ plaque.setupTrack_main[plaque.page].animateIn(delay); plaque.setupTrack_lastMonth[plaque.page].animateIn(delay); plaque.setupTrack_lastYear[plaque.page].animateIn(delay); } }, // track constructor track: function(args) { this.val = 0; this.rVal = args.val; //for storing a potential real value for visualizing sub 12 o'clock values this.max = args.max; this.radius = args.radius; this.name = args.label; this.front = plaque.raphael.set(); //top layer (for most text) this.back = plaque.raphael.set(); //bottom layer (for gfx + max labels) this.color = args.color; this.thickness = args.thickness || 30; this.factors = args.factors; this.type = args.type || "default"; this.args = args; if (args.type === 'detail-main'){ this.averages = {local:args.averages.local, global:(args.averages.global || -1)}; } //check for special cases of naming and data availability var name = this.name; var disabledClass = ""; if (this.type === "detail-main"){ // SDH : don't use the current month name name = "current"; //plaque.getMonthName(); } if (args.val < 0){ name = "No previous data to compare"; disabledClass = " disabled"; } //lighten color if necessary if (args.type === 'detail-sub'){ this.color = tinycolor.lighten(this.color, 20).toHexString(); } //draw ghost track this.ghost = plaque.raphael.path().attr({arc: [100, 100, this.radius, false, this.thickness]}).attr({stroke: '#ddd', opacity: 0}); //draw max label var x = this.ghost.getPointAtLength(this.ghost.getTotalLength()).x; var y = 306; //for some reason Raphael.js does not calculate the correct/same Y value for all track radii, so we're setting it manually. this.maxLabel = plaque.raphael.text(x, y, this.max).attr({'opacity': 0}); this.maxLabel.node.setAttribute('class', 'arc-label max'+disabledClass); //set Y offset depending on track type var offsetY = 0; //standard center (2px adjusted) if (args.type === 'detail-main'){ offsetY = -30; } //draw name label this.label = plaque.raphael.text(140, plaque.height/2-this.radius+2+offsetY, name).attr({'text-anchor': 'start', opacity:0}); this.label.node.setAttribute('class', 'arc-label name'+disabledClass); //draw factor labels if available var factorLabels = []; var that = this; if (this.factors){ var factors; $.each(this.factors, function(index, factor){ var factorLabel = plaque.raphael.text(140, plaque.height/2-that.radius+offsetY+20+index*15, factor).attr({'text-anchor': 'start', opacity:0}); factorLabel.node.setAttribute('class', 'arc-label factors'); factorLabels.push(factorLabel); that.front.push(factorLabel); }); } // draw icon if (args.icon != false){ var image = "/static/dashboard/img/icon_water.png"; for (var i = 0; i < plaque.assosiatedCategories.length; i++) { if (plaque.assosiatedCategories[i]["label"] == this.name){ image = plaque.assosiatedCategories[i]["img_path"]; break; } }; // if (this.name === "Human Experience") { // image = "/static/dashboard/img/icon_human.png"; // } else { // image = "/static/dashboard/img/icon_" + this.name.toLowerCase() + ".png"; // } this.icon = plaque.raphael.image(image, 109, (plaque.height/2 - this.radius - 10) + offsetY, 20, 20).attr({opacity:0}); } //draw track & get endpoint this.track = plaque.raphael.path().attr({arc: [this.val, this.max, this.radius, true, this.thickness]}).attr({stroke: this.color, opacity:0}); this.endPoint = this.track.getPointAtLength(this.track.getTotalLength()+1); //draw little triangle at the end of the track this.triangle = plaque.raphael.path().attr({triangle: [this.endPoint.x, this.endPoint.y, this.thickness, this.thickness]}).attr({"fill": this.color, "stroke": 0, opacity:0}); this.drawNeedle = function(category, parent){ //draw average needle var averageVal; if (category === 'local'){ averageVal = parent.averages.local; } else { averageVal = parent.averages.global; } var mid = {x: plaque.width/2, y: plaque.height/2}; var avg = averageVal/parent.max; var avgPoint; if (averageVal == parent.args.val){ avgPoint = parent.endPoint; } else { // offset the beginning a little so that it doesn't bunch up with the labels avgPoint = parent.ghost.getPointAtLength(((parent.ghost.getTotalLength()- 74)*avg) + 74); } var avgAngle = (Math.atan2(mid.y-avgPoint.y, mid.x-avgPoint.x) * 180/Math.PI) - 90; //angle in degrees if (1000*avg < parent.track.thresholds.break1) { avgAngle = 0; } else if (avgAngle > -90 && avgAngle < -1) { avgAngle = -90; } var returnObj = []; if (averageVal != parent.args.val) { var label = plaque.raphael.text(avgPoint.x-4, avgPoint.y, averageVal).attr({opacity:0}); label.transform("r"+avgAngle+" ," + avgPoint.x + "," + avgPoint.y + "r"+-avgAngle); //then rotate label.node.setAttribute('class', 'arc-label value average'); returnObj.push(label); } if (parent.averages.local == parent.averages.global) { if (category == "local") avgAngle += 20; else avgAngle -= 20; } var needle = plaque.raphael.image("/static/dashboard/img/needle.png", avgPoint.x-10, avgPoint.y-53, 15, 13).attr({opacity:0}); needle.transform("r"+avgAngle+" ," + avgPoint.x + "," + avgPoint.y); //then rotate returnObj.push(needle); var icon = plaque.raphael.image("/static/dashboard/img/" + category + ".png", avgPoint.x-38, avgPoint.y-130, 75, 75).attr({opacity:0}); icon.transform("r"+avgAngle+" ," + avgPoint.x + "," + avgPoint.y + "r"+-avgAngle); //then rotate returnObj.push(icon); return returnObj; } this.fadeInAverages = function(parent){ if (parent.type === 'detail-main'){ var needles = []; if (parent.type === "detail-main"){ $.each(parent.drawNeedle('global', parent), function(index, item){ needles.push(item); }); if (parent.averages.local != null){ $.each(parent.drawNeedle('local', parent), function(index, item){ needles.push(item); }); } } if(needles.length > 0){ TweenMax.to(needles, 0.5, {raphael:{opacity:1}}); } } } //draw value label this.valueLabel = plaque.raphael.text(this.endPoint.x, this.endPoint.y, this.val).attr({opacity:0}); this.valueLabel.node.setAttribute('class', 'arc-label value'); //Put stuff on their layers to make sure the order is correct this.back.push(this.track, this.maxLabel, this.ghost); this.back.toBack(); this.front.push(this.label, this.valueLabel); this.front.toFront(); //Function for the intro animation this.animateIn = function(del){ //Animate ghost first var objs = [this.ghost, this.maxLabel, this.icon, this.label]; if (factorLabels.length > 0){ TweenMax.to(factorLabels, 1, {raphael:{opacity:1}, delay:del}); } TweenMax.to(objs, 1, {raphael:{opacity:1}, delay:del}); if (args.val > 0){ //Fix value if it results in an animation below 12 o'clock var twelveoclock = this.max*(this.track.thresholds.break1/1000); var adjusted = false; if (args.val < twelveoclock) { args.val += twelveoclock; //momentarily altering val while animating, real val is stored in rVal adjusted = true; } //Then the rest TweenMax.to(this.track, 1, {raphael:{opacity:1}, delay:del}); TweenMax.to(this.triangle, 1, {raphael:{opacity:1}, delay:del}); //And last the needles and the track var timing = (args.val/args.max) * 4; //4 = max 4 seconds TweenMax.to(this, timing, {val: args.val, ease:Cubic.easeOut, onUpdate:plaque.changeTrack, onUpdateParams:[this, adjusted], onComplete:this.fadeInAverages, onCompleteParams:[this], delay:del}); } } //Function for mid-animation visual simplification this.simplify = function(){ TweenMax.to(this.ghost, 2, {raphael:{opacity:0}}); TweenMax.to(this.valueLabel, 2, {raphael:{opacity:0}}); } }, // gets called by tweenmax at each moment of animation changeTrack: function(obj, adjusted) { var val = obj.val; if (adjusted){ val = obj.rVal; } obj.track.attr({arc: [obj.val, obj.max, obj.radius, true, obj.thickness]}); //Update fill, calculate the endpoint obj.endPoint = obj.track.getPointAtLength(obj.track.getTotalLength()-1); //Check if we have a valid endPoint, otherwise skip ahead – it'll be ready in the next iteration if(!isNaN(obj.endPoint.x) && !isNaN(obj.endPoint.y)){ //Calculate angle between center and endpoint, so we can rotate the triangle var mid = {x: plaque.width/2, y: plaque.height/2}; var angle = (Math.atan2(mid.y-obj.endPoint.y, mid.x-obj.endPoint.x) * 180/Math.PI) - 90; //angle in degrees if (obj.track.progress < obj.track.thresholds.break1) { angle = 0; } else if (angle > -90 && angle < -1) { angle = -90; } //Flatten triangle if we reach the end of the track var stopY = obj.ghost.getPointAtLength(obj.ghost.getTotalLength()-1).y + obj.thickness + 5; var triangleHeight = obj.thickness; if (obj.track.progress > 750 && obj.endPoint.y < stopY){ triangleHeight += obj.endPoint.y - stopY; } //Rotate that pesky triangle obj.triangle.attr({triangle: [obj.endPoint.x, obj.endPoint.y, obj.thickness, triangleHeight]}); //move first obj.triangle.transform("r"+angle+"," + obj.endPoint.x + "," + obj.endPoint.y); //then rotate //Move the label var lblY = obj.endPoint.y; if (obj.track.progress > 750){ lblY = Math.max(obj.maxLabel.attr('y')-1, lblY); } obj.valueLabel.attr({x: obj.endPoint.x, y: lblY, text: Math.round(val)}); } // fade-in value label after 12oclock if (obj.track.progress >= obj.track.thresholds.break1) { TweenMax.to(obj.valueLabel, 0.2, {raphael:{opacity:1}}) } // Update the total score puck obj.val = val; if (plaque.page === "overview") { $('#score-puck>.text').text(Math.round(plaque.data.totalScore)); } }, //Set up the 5 tracks setupTracks: function() { for (var i = (plaque.assosiatedCategories).length-1; i > -1; i--) { if (plaque.page == "overview"){ //For Overview number_of_gaps = (plaque.assosiatedCategories).length - 1 total_gap = number_of_gaps * 7 total_track_thickness = 178 - total_gap track_thickness = parseInt(total_track_thickness/((plaque.assosiatedCategories).length)) delta_track_thickness = track_thickness - 30 increment_in_radiusIncrement = delta_track_thickness/2 factor = (5-(plaque.assosiatedCategories).length)* 7 new_radiusIncrement = this.radiusIncrement + increment_in_radiusIncrement + factor track_radius = (plaque.radius+factor)+new_radiusIncrement*(((plaque.assosiatedCategories).length-1)-i) // track_radius = plaque.radius + ((total_track_thickness + 7)*(((plaque.assosiatedCategories).length-1)-i)) plaque.setupTrack[plaque.assosiatedCategories[i]["category"]] = new plaque.track({label: plaque.assosiatedCategories[i]["label"], val: plaque.data[plaque.assosiatedCategories[i]["category"]]["score"], max: plaque.data[plaque.assosiatedCategories[i]["category"]]["max"], radius: track_radius, color: plaque.assosiatedCategories[i]["color"], thickness: track_thickness}); } else{ //For individual categories factors_arr = (plaque.assosiatedCategories[i]["factors"]).split(',') plaque.setupTrack_main[plaque.assosiatedCategories[i]["category"]] = new plaque.track({label: plaque.assosiatedCategories[i]["label"], val: plaque.data[plaque.assosiatedCategories[i]["category"]]["score"], max: plaque.data[plaque.assosiatedCategories[i]["category"]]["max"], radius: 225, color: plaque.assosiatedCategories[i]["color"], thickness: 100, type: 'detail-main', factors: factors_arr, averages: {local:plaque.data[plaque.assosiatedCategories[i]["category"]]["localAverage"], global:plaque.data[plaque.assosiatedCategories[i]["category"]]["globalAverage"]}}); plaque.setupTrack_lastMonth[plaque.assosiatedCategories[i]["category"]] = new plaque.track({label: plaque.getMonthName(-1), val: plaque.data[plaque.assosiatedCategories[i]["category"]]["lastMonth"], max: plaque.data[plaque.assosiatedCategories[i]["category"]]["max"], radius: 150, color: plaque.assosiatedCategories[i]["color"], thickness: 35, icon: false, type: 'detail-sub'}); plaque.setupTrack_lastYear[plaque.assosiatedCategories[i]["category"]] = new plaque.track({label: plaque.getMonthName(-12, true), val: plaque.data[plaque.assosiatedCategories[i]["category"]]["lastYear"], max: plaque.data[plaque.assosiatedCategories[i]["category"]]["max"], radius: 107, color: plaque.assosiatedCategories[i]["color"], thickness: 35, icon: false, type: 'detail-sub'}); } }; }, //Set up Raphael.js custom attributes customShapes: function() { //Triangle plaque.raphael.customAttributes.triangle = function(x, y, size, height) { var path = ["M", x, y-size/2]; //start out in the top left corner path = path.concat(["L", x+5, y-size/2]); //short straight line path = path.concat(["L", x+5+height/2, y]); //line to the tip path = path.concat(["L", x+5, y+size/2]); //line back to lower left corner path = path.concat(["L", x, y+size/2]); //short straight line path = path.concat(["z"]).join(" "); return {path: path}; }; //Custom arc plaque.raphael.customAttributes.arc = function (value, total, radius, shortened, thickness) { var strokewidth = thickness; var stopline = (plaque.height/2) - plaque.radius + strokewidth - 7; //stop y var startline = 104; //start x if (thickness === 100) { stopline = (plaque.height/2) - plaque.radius + 34 - 7; //stop y } if (plaque.page !== "overview") { startline = 100; //start x } //progress is max 1000 units this.progress = 1000/total * value; this.thresholds = {break1: 220, break2: 950}; var hwidth = plaque.radius + (4 * plaque.radiusIncrement) + strokewidth/2; //horizontal line max width //start path var path = ["M", startline, plaque.width/2-radius]; //first draw the straight line until we hit thresholds.break1 hwidth = Math.min(hwidth, hwidth * this.progress/this.thresholds.break1); if (plaque.page !== "overview") { hwidth = Math.min((plaque.width/2)-startline, hwidth * this.progress/this.thresholds.break1); } path.push(["H", hwidth+startline]); //draw arc until progress hits thresholds.break2 if (this.progress > this.thresholds.break1){ var alpha = Math.min(Math.map(this.progress, this.thresholds.break1, this.thresholds.break2, 0, 270), 270); var a = (90 - alpha) * Math.PI / 180; var x = plaque.width/2 + radius * Math.cos(a); var y = plaque.height/2 - radius * Math.sin(a); path.push(['M',plaque.width/2,plaque.height/2-radius]); path.push(['A', radius, radius, 0, +(alpha > 180), 1, x, y]); //and the last 100 is the little bit at the end if (this.progress > this.thresholds.break2){ path.push(['M',x,y]); if (shortened) {stopline += 4;} //shorten the stopline path.push(['V',Math.map(this.progress, this.thresholds.break2, 1000, stopline+(plaque.height/2-stopline), stopline) ]); } } //return the complete path return {path: path, 'stroke-width': strokewidth}; }; }, offline: function() { var dataFromRemote; // if the ajax call has already been made and plaque.data exists, don't make the call again if (plaque.data) { //Set up data dependent graphics $(".plaque_score").text(plaque.data.currentCertificationScore); plaque.setupTracks(); plaque.animateAll(); } else { // build default object plaque.data = { 'totalScore': 30, 'baseScore': 12, 'currentCertificationScore': 69, //Placeholder, needs to be pulled from BR 'nationalAvg': 70, 'water': { score: 12, color: plaque.trackColors.water, max: 15, localAverage: 7, globalAverage: 5, lastMonth: 4, lastYear: 7 }, 'humanexperience': { score: 13, color: plaque.trackColors.human, max: 15, localAverage: 12, globalAverage: 10, lastMonth: 4, lastYear: 7 }, 'transportation': { score: 15, color: plaque.trackColors.transportation, max: 15, localAverage: 12, globalAverage: 5, lastMonth: -1, lastYear: -1 }, 'energy': { score: 12, color: plaque.trackColors.energy, max: 15, localAverage: 6, globalAverage: 5, lastMonth: 6, lastYear: 7 }, 'waste': { score: 30, color: plaque.trackColors.waste, max: 30, localAverage: 30, globalAverage: 22, lastMonth: 4, lastYear: 7 } }; //Set up data dependent graphics $(".plaque_score").text(plaque.data.currentCertificationScore); plaque.setupTracks(); plaque.animateAll(); } }, getData: function(forceCall) { var forceCall = (typeof forceCall === "undefined") ? false : forceCall; var dataFromRemote; // if the ajax call has already been made and plaque.data exists, don't make the call again if (plaque.data && !forceCall) { //Set up data dependent graphics $(".plaque_score").text(plaque.data.currentCertificationScore); plaque.setupTracks(); plaque.animateAll(); } else { // login with key http://shakeup.buildingrobotics.com/buildings/LEED:1000005228/performance/?key=fe0f7438f87cc6ee74a963bd // Building Robotics test building: http://shakeup.buildingrobotics.com/buildings/LEED:1000005063/performance/?key=dae17c00693b7dda7c020d09 var now = new Date() var lastMonthTS = (now.getFullYear()) + "-" + ("0" + (now.getMonth() + 1)).slice(-2) + "-01"; now.setMonth(now.getMonth() + 1); var lastYearTS = (now.getFullYear() - 1) + "-" + ("0" + (now.getMonth() + 1)).slice(-2) + "-01"; // Building with meter data: http://shakeup.buildingrobotics.com/buildings/LEED:1000009301/meters/ // 2013-09-06: DG: Added "&within=31" to get latest reading avaialble in previous month/year if(plaque.LEED != '0' && logIn == 'True' && access_to_project == 'True') { $.when($.ajax({ type: "GET", url: "/buildings/LEED:" + plaque.LEED + "/performance/"}), $.ajax({ type: "GET", url: "/comparables/"}), $.ajax({ type: "GET", url: "/buildings/LEED:" + plaque.LEED + "/performance/?at=" + lastMonthTS + "&within=1"}), $.ajax({ type: "GET", url: "/buildings/LEED:" + plaque.LEED + "/performance/?at=" + lastYearTS + "&within=1"})) .done(function(score, global_avgs, last_month, last_year) { var dataFromRemote = score[0]; bldg = plaque.buildingData; global_avgs = global_avgs[0]; last_month = last_month[0].scores; last_year = last_year[0].scores; $.ajax({ type: "GET", url: "/comparables/" + bldg.state + "/"}) .success(function (local_avgs) { //Check maxima values if (dataFromRemote.maxima==undefined){ $.ajax({ type: "GET", url: "/weights/", async: false, success: function (data_maxima) { dataFromRemote.maxima = data_maxima } }); } //Calc a matching score var totalScore = plaque.checkValue(dataFromRemote.scores.water) + plaque.checkValue(dataFromRemote.scores.human_experience) + plaque.checkValue(dataFromRemote.scores.transport) + plaque.checkValue(dataFromRemote.scores.energy) + plaque.checkValue(dataFromRemote.scores.waste) + plaque.checkValue(dataFromRemote.scores.base); // initialize all data plaque.data = { 'totalScore': totalScore, 'baseScore': dataFromRemote.scores.base, 'currentCertificationScore': dataFromRemote.scores.base, 'nationalAvg': global_avgs.water_avg + global_avgs.human_experience_avg + global_avgs.transport_avg + global_avgs.energy_avg + global_avgs.waste_avg + global_avgs.base_avg, 'water': { score: plaque.checkValue(dataFromRemote.scores.water), color: "#55CAF5", //"#78c5b5" max: plaque.checkValue(dataFromRemote.maxima.water), localAverage: local_avgs.water_avg, globalAverage: global_avgs.water_avg, lastMonth: last_month.water, lastYear: last_year.water, }, 'humanexperience': { score: plaque.checkValue(dataFromRemote.scores.human_experience), color: "#F2AC41", //"#6c7fb9" max: plaque.checkValue(dataFromRemote.maxima.human_experience), localAverage: local_avgs.human_experience_avg, globalAverage: global_avgs.human_experience_avg, lastMonth: last_month.human_experience, lastYear: last_year.human_experience, }, 'transportation': { score: plaque.checkValue(dataFromRemote.scores.transport), color: "#A39F92", //"#b5a68c" max: plaque.checkValue(dataFromRemote.maxima.transport), localAverage: local_avgs.transport_avg, globalAverage: global_avgs.transport_avg, lastMonth: last_month.transport, lastYear: last_year.transport, }, 'energy': { score: plaque.checkValue(dataFromRemote.scores.energy), color: plaque.trackColors.energy, max: plaque.checkValue(dataFromRemote.maxima.energy), localAverage: local_avgs.energy_avg, globalAverage: global_avgs.energy_avg, lastMonth: last_month.energy, lastYear: last_year.energy, }, 'waste': { score: plaque.checkValue(dataFromRemote.scores.waste), color: "#84CCAF", //"#c5da4f" max: plaque.checkValue(dataFromRemote.maxima.waste), localAverage: local_avgs.waste_avg, globalAverage: global_avgs.waste_avg, lastMonth: last_month.waste, lastYear: last_year.waste, } }; //Set up data dependent graphics $(".plaque_score").text(plaque.data.currentCertificationScore); plaque.setupTracks(); plaque.animateAll(); }).fail(function() { if (dataFromRemote.maxima==undefined){ $.ajax({ type: "GET", url: "/weights/", async: false, success: function (data_maxima) { dataFromRemote.maxima = data_maxima } }); } //Calc a matching score var totalScore = plaque.checkValue(dataFromRemote.scores.water) + plaque.checkValue(dataFromRemote.scores.human_experience) + plaque.checkValue(dataFromRemote.scores.transport) + plaque.checkValue(dataFromRemote.scores.energy) + plaque.checkValue(dataFromRemote.scores.waste) + plaque.checkValue(dataFromRemote.scores.base); // initialize all data plaque.data = { 'totalScore': totalScore, 'baseScore': dataFromRemote.scores.base, 'currentCertificationScore': dataFromRemote.scores.base, 'nationalAvg': global_avgs.water_avg + global_avgs.human_experience_avg + global_avgs.transport_avg + global_avgs.energy_avg + global_avgs.waste_avg + global_avgs.base_avg, 'water': { score: plaque.checkValue(dataFromRemote.scores.water), color: plaque.trackColors.water, max: plaque.checkValue(dataFromRemote.maxima.water), globalAverage: global_avgs.water_avg, lastMonth: last_month.water, lastYear: last_year.water, }, 'humanexperience': { score: plaque.checkValue(dataFromRemote.scores.human_experience), color: plaque.trackColors.human, max: plaque.checkValue(dataFromRemote.maxima.human_experience), globalAverage: global_avgs.human_experience_avg, lastMonth: last_month.human_experience, lastYear: last_year.human_experience, }, 'transportation': { score: plaque.checkValue(dataFromRemote.scores.transport), color: plaque.trackColors.transportation, max: plaque.checkValue(dataFromRemote.maxima.transport), globalAverage: global_avgs.transport_avg, lastMonth: last_month.transport, lastYear: last_year.transport, }, 'energy': { score: plaque.checkValue(dataFromRemote.scores.energy), color: plaque.trackColors.energy, max: plaque.checkValue(dataFromRemote.maxima.energy), globalAverage: global_avgs.energy_avg, lastMonth: last_month.energy, lastYear: last_year.energy, }, 'waste': { score: plaque.checkValue(dataFromRemote.scores.waste), color: plaque.trackColors.waste, max: plaque.checkValue(dataFromRemote.maxima.waste), globalAverage: global_avgs.waste_avg, lastMonth: last_month.waste, lastYear: last_year.waste, } }; //Set up data dependent graphics $(".plaque_score").text(plaque.data.currentCertificationScore); plaque.setupTracks(); plaque.animateAll(); }) }) } else if (plaque.LEED == '0' || logIn == 'False' || access_to_project == 'False') { var dataFromRemote; $.when($.ajax({ type: "GET", url: "/buildings/LEED:" + plaque.LEED + "/performance/"})) .done(function(score) { if(score == "LEED Score is not public for LEED ID " + plaque.LEED) { if(plaqueNav.getParameterByName('req_access') == 'true') { $("#permission_needed_request").click(); } else { $('#leed_score_not_public').modal('show'); } } else{ plaque.drawPlaquefromPublicScore(score); } }).fail(function() { dataFromRemote = { "scores": { "energy": null, "water": null, "base": null, "human_experience": null, "waste": null, "effective_at": null, "transport": null } }; plaque.drawPlaquefromPublicScore(dataFromRemote); }); } } }, drawPlaquefromPublicScore: function(dataFromRemote){ //Check maxima values if (dataFromRemote.maxima==undefined){ $.ajax({ type: "GET", url: "/weights/", async: false, success: function (data_maxima) { dataFromRemote.maxima = data_maxima } }); } //Calc a matching score var totalScore = plaque.checkValue(dataFromRemote.scores.water) + plaque.checkValue(dataFromRemote.scores.human_experience) + plaque.checkValue(dataFromRemote.scores.transport) + plaque.checkValue(dataFromRemote.scores.energy) + plaque.checkValue(dataFromRemote.scores.waste) + plaque.checkValue(dataFromRemote.scores.base); // initialize all data plaque.data = { 'totalScore': totalScore, 'baseScore': dataFromRemote.scores.base, 'currentCertificationScore': dataFromRemote.scores.base, 'water': { score: plaque.checkValue(dataFromRemote.scores.water), color: plaque.trackColors.water, max: plaque.checkValue(dataFromRemote.maxima.water), }, 'humanexperience': { score: plaque.checkValue(dataFromRemote.scores.human_experience), color: plaque.trackColors.human, max: plaque.checkValue(dataFromRemote.maxima.human_experience), }, 'transportation': { score: plaque.checkValue(dataFromRemote.scores.transport), color: plaque.trackColors.transportation, max: plaque.checkValue(dataFromRemote.maxima.transport), }, 'energy': { score: plaque.checkValue(dataFromRemote.scores.energy), color: plaque.trackColors.energy, max: plaque.checkValue(dataFromRemote.maxima.energy), }, 'waste': { score: plaque.checkValue(dataFromRemote.scores.waste), color: plaque.trackColors.waste, max: plaque.checkValue(dataFromRemote.maxima.waste), } }; //Set up data dependent graphics $(".plaque_score").text(plaque.data.currentCertificationScore); plaque.setupTracks(); plaque.animateAll(); }, checkValue: function(value){ if (!value){ return 0; //we don't want nothing } else { return value; } }, getMonthName: function(offset, withYear){ var now = new Date(); var yearString = ""; if (typeof(offset)=='undefined'){ offset = 0; } now.setMonth(now.getMonth()+offset); if (withYear){ yearString = " " + now.getFullYear(); } return plaque.months[now.getMonth()] + yearString; }, racetracksize: function (page_name) { if (Modernizr.touch){ plaque.physicalScale = 1; } var relative_width = 765; var container_width = $('.main_container').width(); if (container_width < 1300){ var required_plaque_size = (((container_width)/1300).toFixed(2))*1.7; if (required_plaque_size > 1){ required_plaque_size = 1; } $("#racetrack_" + page_name).css('-webkit-transform', 'scale(' + required_plaque_size + ')'); var calculate_left = (1300-container_width) / 1.7 // $("#track_container").css('margin-left', 361 - calculate_left); } else{ $("#racetrack_" + page_name).css('-webkit-transform', 'scale(' + plaque.physicalScale + ')'); // $("#track_container").css('margin-left', '361px'); } }, months: [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ], }; //Extend Math class with a map function Math.map = function (value, low1, high1, low2, high2) { return low2 + (high2 - low2) * (value - low1) / (high1 - low1); } $( window ).resize(function() { if (plaque.assosiatedCategories.length){ for (var i = 0; i < plaque.assosiatedCategories.length; i++) { if ($('#racetrack_' + plaque.assosiatedCategories[i]["category"]) ) { plaque.racetracksize(plaque.assosiatedCategories[i]["category"]); } }; } });
import * as Yup from 'yup'; import Location from 'react-app-location'; const isNullableDate = Yup.string().test('is-date', '${path}:${value} is not a valid date', date => !date || !isNaN(Date.parse(date))); const string = Yup.string(); const integer = Yup.number().integer(); const naturalNbr = integer.moreThan(-1); const wholeNbr = integer.positive(); const identity = wholeNbr.required(); const order = Yup.string().oneOf(['asc', 'desc']).default('asc'); const Locations = { Home: new Location('/'), Resorts: new Location('/resorts'), Resort: new Location('/resorts/:id', { id: identity }), ResortDetails: new Location('/resorts/:id/details', { id: identity }), ResortLifts: new Location('/resorts/:id/lifts', { id: identity }), ResortStats: new Location('/resorts/:id/stats', { id: identity }, { groupBy: Yup.string().oneOf(['Season', 'Month', 'Day', 'Hour', 'Lift']).default('Season') }), Lifts: new Location('/lifts', null, { page: naturalNbr.default(0), rowsPerPage: Yup.number().oneOf([25, 50, 75, 100]).default(25), order: order, orderBy: Yup.string().oneOf(['name', 'typeID', 'resortID', 'isActive']).default('name'), showFilter: Yup.boolean().default(false), isActive: Yup.boolean(), typeID: wholeNbr, resortID: wholeNbr.nullable(), //'No resort assigned' is equivalent to ResortID=null name: Yup.string(), }), Lift: new Location('/lifts/:id', { id: identity }), LiftDetails: new Location('/lifts/:id/details', { id: identity }), LiftUplifts: new Location('/lifts/:id/uplifts', { id: identity }, { page: naturalNbr.default(0), rowsPerPage: Yup.number().oneOf([25, 50, 75, 100]).default(25), order: order, orderBy: Yup.string().oneOf(['date', 'waitSeconds',]).default('date'), showFilter: Yup.boolean().default(false), seasonYear: wholeNbr, month: wholeNbr, day: wholeNbr, hour: wholeNbr, }), LiftStats: new Location('/lifts/:id/stats', { id: identity }, { groupBy: Yup.string().oneOf(['Season', 'Month', 'Day', 'Hour']).default('Season') }), WaitTime: new Location('/waittime/:slug?', { slug: string.required() }, { date: isNullableDate }), //graphQL implementation of wait-time site }; export default Locations;
export default class UserError extends Error{ statusCode = 400; }