Initial additions

pull/1/head
Rob Hedgpeth 2019-12-16 15:02:28 -08:00
rodzic bfaeef8790
commit 35d3b72ffc
37 zmienionych plików z 17043 dodań i 0 usunięć

191
Flights/README.md 100644
Wyświetl plik

@ -0,0 +1,191 @@
# Flights
**Flights** is a web application written in [ReactJS](https://reactjs.org) and [NodeJS](https://nodejs.org) that, backed by the power of the [MariaDB Node Connector](https://github.com/MariaDB/mariadb-connector-nodejs) and [MariaDB ColumnStore database](https://mariadb.com/docs/features/mariadb-columnstore/), allows you to investigate over 150 million [flight records from the United States Department of Transportation](https://www.transtats.bts.gov/DL_SelectFields.asp?Table_ID=236&DB_Short_Name=On-Time)!
<p align="center" spacing="10">
<img src="media/demo.gif" />
</p>
This `README` will walk you through the steps for getting this app up and running (locally) within minutes!
# Table of Contents
1. [Getting started with MariaDB](#overview)
1. [The Basics](#intro-mariadb)
2. [Downloadng and installing MariaDB ColumnStore](#installation)
3. [Using the MariaDB columnar database](#mariadb-columnar)
2. [Requirements](#requirements)
3. [Getting started with the app](#getting-started)
1. [Grab the code](#grab-code)
2. [Build the code](#build-code)
3. [Run the app](#run-app)
4. [Support and Contribution](#support-contribution)
## Overview <a name="overview"></a>
### Introduction to MariaDB <a name="intro-mariadb"></a>
[MariaDB platform](https://mariadb.com/products/mariadb-platform/) unifies [MariaDB TX (transactions)](https://mariadb.com/products/mariadb-platform-transactional/) and [MariaDB AX (analytics)](https://mariadb.com/products/mariadb-platform-analytical/) so transactional applications can retain unlimited historical data and leverage powerful, real-time analytics in order to provide data-driven customers with more information, actionable insight and greater value – and businesses with endless ways to monetize data. It is the enterprise open source database for hybrid transactional/analytical processing at scale.
<p align="center">
<img src="media/platform.png" />
</p>
### Downloadng and installing MariaDB ColumnStore <a name="installation"></a>
[MariaDB ColumnStore](https://mariadb.com/docs/features/mariadb-columnstore/) extends [MariaDB Server](https://mariadb.com/products/) with distributed storage and massively parallel processing to support scalable, high-performance analytics. It can be deployed as the analytics component of MariaDB Platform using MariaDB MaxScale for change-data-capture and hybrid transactional/analytical query routing, or as a standalone columnar database for interactive, ad hoc analytics at scale. You can find more information on how to download and install ColumnStore [here](https://mariadb.com/downloads/#mariadb_platform-mariadb_columnstore).
### Using the MariaDB columnar database <a name="mariadb-columnar"></a>
[MariaDB ColumnStore](https://mariadb.com/docs/features/mariadb-columnstore/) provides distributed, columnar storage for scalable analytical processing. MariaDB ColumnStore is a component of MariaDB Platform. The primary documentation is located in the [MariaDB Public Knowledge Base](https://mariadb.com/kb/en/library/mariadb-columnstore/).
This application uses three a tables (`airlines`, `airports`, `flights`) within a single MariaDB ColumnStore database.
```sql
CREATE TABLE `airlines` (
`iata_code` char(2) DEFAULT NULL,
`airline` varchar(30) DEFAULT NULL
) ENGINE=Columnstore DEFAULT CHARSET=utf8;
```
```sql
CREATE TABLE `airports` (
`iata_code` char(3) DEFAULT NULL,
`airport` varchar(80) DEFAULT NULL,
`city` varchar(30) DEFAULT NULL,
`state` char(2) DEFAULT NULL,
`country` varchar(30) DEFAULT NULL,
`latitude` float DEFAULT NULL,
`longitude` float DEFAULT NULL
) ENGINE=Columnstore DEFAULT CHARSET=utf8;
```
```sql
CREATE TABLE `flights` (
`year` smallint(6) DEFAULT NULL,
`month` tinyint(4) DEFAULT NULL,
`day` tinyint(4) DEFAULT NULL,
`day_of_week` tinyint(4) DEFAULT NULL,
`fl_date` date DEFAULT NULL,
`carrier` char(2) DEFAULT NULL,
`tail_num` char(6) DEFAULT NULL,
`fl_num` smallint(6) DEFAULT NULL,
`origin` varchar(5) DEFAULT NULL,
`dest` varchar(5) DEFAULT NULL,
`crs_dep_time` char(4) DEFAULT NULL,
`dep_time` char(4) DEFAULT NULL,
`dep_delay` smallint(6) DEFAULT NULL,
`taxi_out` smallint(6) DEFAULT NULL,
`wheels_off` char(4) DEFAULT NULL,
`wheels_on` char(4) DEFAULT NULL,
`taxi_in` smallint(6) DEFAULT NULL,
`crs_arr_time` char(4) DEFAULT NULL,
`arr_time` char(4) DEFAULT NULL,
`arr_delay` smallint(6) DEFAULT NULL,
`cancelled` smallint(6) DEFAULT NULL,
`cancellation_code` smallint(6) DEFAULT NULL,
`diverted` smallint(6) DEFAULT NULL,
`crs_elapsed_time` smallint(6) DEFAULT NULL,
`actual_elapsed_time` smallint(6) DEFAULT NULL,
`air_time` smallint(6) DEFAULT NULL,
`distance` smallint(6) DEFAULT NULL,
`carrier_delay` smallint(6) DEFAULT NULL,
`weather_delay` smallint(6) DEFAULT NULL,
`nas_delay` smallint(6) DEFAULT NULL,
`security_delay` smallint(6) DEFAULT NULL,
`late_aircraft_delay` smallint(6) DEFAULT NULL
) ENGINE=Columnstore DEFAULT CHARSET=utf8;
```
For more information about MariaDB ColumnStore databases please check out the [MariaDB blog](https://mariadb.com/search-results/?q=columnstore)!
## Requirements <a name="requirements"></a>
This project assumes you have familiarity with building web applications using ReactJS and NodeJS technologies.
* Download and install [MariaDB ColumnStore database](https://go.mariadb.com/download-mariadb-server-community.html?utm_source=google&utm_medium=ppc&utm_campaign=MKG-Search-Google-Branded-DL-NA-Server-DL&gclid=CjwKCAiAwZTuBRAYEiwAcr67OUBIqnFBo9rUBhYql3VZV_nhlSKzkwoUv7vhA6gwNdGoBSc2uWe7SBoCX_oQAvD_BwE).
* Download and install [NodeJS](https://nodejs.org/).
* git (Optional) - this is required if you would prefer to pull the source code from GitHub repo.
- Create a [free github account](https://github.com/) if you dont already have one
- git can be downloaded from git-scm.org
## Getting started <a name="getting-started"></a>
In order to build and run the application you will need to have NodeJS installed. You can find more information [here](https://nodejs.org/).
### [Create the schema and load the dataset](https://github.com/mariadb-corporation/mariadb-columnstore-samples/tree/master/flights) <a name="create-schema"></a>
This application uses data from the United States Department of Transportation that is imported into a MariaDB ColumnStore database. For instructions on how to retrieve the dataset and import it into a MariaDB ColumnStore database please see the instructions [here](https://github.com/mariadb-corporation/mariadb-columnstore-samples/tree/master/flights) provided by [Todd Stoffel](https://github.com/toddstoffel).
### Grab the code <a name="grab-code"></a>
Download this code directly or use [git](git-scm.org) (through CLI or a client) to retrieve the code.
### Configure the code <a name="configure-code"></a>
Update the MariaDB connection configuration [here](src/db.js).
```js
const pool = mariadb.createPool({
host: '<host_address_here>',
user:'<username_here>',
password: '<password_here>',
database: 'flights',
multipleStatements: true,
connectionLimit: 5
});
```
### Build the code <a name="build-code"></a>
Once you have retrieved a copy of the code you're ready to build and run the project! However, before running the code it's important to point out that the application uses several Node Packages.
For the client-side:
- [dx-react-grid](https://www.npmjs.com/package/@devexpress/dx-react-grid)
- [props-type](https://www.npmjs.com/package/props-type)
- [react](https://www.npmjs.com/package/react)
- [react-dom](https://www.npmjs.com/package/react-dom)
- [react-scripts](https://www.npmjs.com/package/react-scripts)
- [recharts](https://www.npmjs.com/package/recharts)
For the server-side:
- [body-parser](https://www.npmjs.com/package/body-parser)
- [concurrently](https://www.npmjs.com/package/concurrently)
- [express](https://www.npmjs.com/package/express)
- [mariadb](https://www.npmjs.com/package/mariadb) (the best database in world)
**Quick tip:** You can also execute the CLI command `npm install` within the src and client folders. Doing so will target the the relative `package.json` files to install all dependencies.
### Run the app <a name="run-app"></a>
Once you've pulled down the code and have verified that all of the required Node packages are installed you're ready to run the application! It's as easy as 1,2,3.
1. Using a command line interface (CLI) navigate to where to the `src` directory of Places.
<p align="center">
<img src="media/cli_root.png" />
</p>
2. Run the command:
```bash
npm start
```
<p align="center">
<img src="media/npm_start.png" />
</p>
3. Open a browser window and navigate to http://localhost:3000.
<p align="center">
<img src="media/get_started.png" />
</p>
## Support and Contribution <a name="support-contribution"></a>
Thanks so much for taking a look at the Flights app! As this is a very simple example, there's a lot of potential for customization!
If you have any questions, comments, or would like to contribute to this or future projects like this please reach out to us directly at developers@mariadb.com or on [Twitter](https://twitter.com/mariadb).

Plik binarny nie jest wyświetlany.

Po

Szerokość:  |  Wysokość:  |  Rozmiar: 152 KiB

Plik binarny nie jest wyświetlany.

Po

Szerokość:  |  Wysokość:  |  Rozmiar: 886 KiB

Plik binarny nie jest wyświetlany.

Po

Szerokość:  |  Wysokość:  |  Rozmiar: 140 KiB

Plik binarny nie jest wyświetlany.

Po

Szerokość:  |  Wysokość:  |  Rozmiar: 578 KiB

Plik binarny nie jest wyświetlany.

Po

Szerokość:  |  Wysokość:  |  Rozmiar: 233 KiB

61
Flights/src/.gitignore vendored 100644
Wyświetl plik

@ -0,0 +1,61 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
# nyc test coverage
.nyc_output
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# TypeScript v1 declaration files
typings/
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
# next.js build output
.next

23
Flights/src/client/.gitignore vendored 100644
Wyświetl plik

@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*

Wyświetl plik

@ -0,0 +1,68 @@
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.<br />
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.<br />
You will also see any lint errors in the console.
### `npm test`
Launches the test runner in the interactive watch mode.<br />
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `npm run build`
Builds the app for production to the `build` folder.<br />
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.<br />
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `npm run eject`
**Note: this is a one-way operation. Once you `eject`, you cant go back!**
If you arent satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point youre on your own.
You dont have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldnt feel obligated to use this feature. However we understand that this tool wouldnt be useful if you couldnt customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).
### Code Splitting
This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting
### Analyzing the Bundle Size
This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size
### Making a Progressive Web App
This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app
### Advanced Configuration
This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration
### Deployment
This section has moved here: https://facebook.github.io/create-react-app/docs/deployment
### `npm run build` fails to minify
This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify

14263
Flights/src/client/package-lock.json wygenerowano 100644

Plik diff jest za duży Load Diff

Wyświetl plik

@ -0,0 +1,44 @@
{
"name": "client",
"version": "0.1.0",
"private": true,
"dependencies": {
"@devexpress/dx-core": "^2.3.1",
"@devexpress/dx-grid-core": "^2.3.1",
"@devexpress/dx-react-core": "^2.3.1",
"@devexpress/dx-react-grid": "^2.3.1",
"@devexpress/dx-react-grid-bootstrap3": "^2.3.1",
"@devexpress/dx-react-grid-material-ui": "^2.3.1",
"@material-ui/core": "^4.7.2",
"@material-ui/icons": "^4.5.1",
"material-ui": "^0.20.2",
"prop-types": "^15.7.2",
"react": "^16.12.0",
"react-dom": "^16.12.0",
"react-scripts": "3.2.0",
"react-select": "^3.0.8",
"recharts": "^2.0.0-beta.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"proxy": "http://localhost:8080"
}

Plik binarny nie jest wyświetlany.

Po

Szerokość:  |  Wysokość:  |  Rozmiar: 15 KiB

Wyświetl plik

@ -0,0 +1,43 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>Flights</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>

Plik binarny nie jest wyświetlany.

Po

Szerokość:  |  Wysokość:  |  Rozmiar: 8.4 KiB

Plik binarny nie jest wyświetlany.

Po

Szerokość:  |  Wysokość:  |  Rozmiar: 22 KiB

Wyświetl plik

@ -0,0 +1,25 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}

Wyświetl plik

@ -0,0 +1,2 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *

Wyświetl plik

@ -0,0 +1,177 @@
.app {
text-align: center;
}
.app-logo {
height: 40vmin;
}
.app-header {
background-color: #003545;
min-height: 125px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
color: white;
}
.title-text {
margin: 0px;
font-size: 30px;
font-weight: bold;
}
.sub-title-text {
font-size: small;
}
.form-header {
background: #2F99A3;
color: white;
font-size: 20px;
border-top-left-radius: 5px;
border-top-right-radius: 5px;
}
.form-sub-header {
background: #2F99A3;
color: white;
font-size: 16px;
font-weight: bold;
border-top-left-radius: 5px;
border-top-right-radius: 5px;
padding: 8px;
}
.form-header > p {
margin: 0px;
padding: 10px;
}
.form-main {
width: 75%;
margin-left: auto;
margin-right: auto;
}
.form-main table {
width: 90%;
margin-left: auto;
margin-right: auto;
}
.form-content {
margin-left: auto;
margin-right: auto;
}
.form-section {
text-align: left;
}
.form-section p {
margin-bottom: 10px;;
}
.filter-background {
background: #E5E1E5;
border-radius: 5px;;
}
.airport-picker {
width: 400px;
}
button {
border-radius: 5px;
background: #003545;
border-color: #E5E1E5;
color: #ffffff;
font-weight: bold;
width: 350px;
height: 50px;
font-size: large;
}
button:hover {
cursor: pointer;
background: #96DDCF;
}
.float-left {
float: left;
}
.float-right {
float: right;
}
.margin-right-150 {
margin-right: 150px;
}
.charts-main {
margin-top: 20px;
margin-bottom: 20px;
padding-bottom: 30px;
border: 1px solid #c0c0c0;
border-radius: 10px;
}
.charts-title {
font-weight: bold;
margin: 25px;
}
.float-right > button {
margin-top: 40px;
}
.form-main > div {
margin-top: 25px;
}
.hidden {
display: none;
}
.select-month {
width: 165px;
margin-right: 10px;
}
.select-year {
width: 100px;
margin-right: 10px;
}
.select-day {
width: 100px;
}
.button-search {
margin: 20px;
}
.width-70 {
width: 70%;
}
.image-arrow {
width: 50px;
height: 50px;
}
.inline-div-50 {
width: 50%;
display: inline-block;
}
.margin-right-35 {
margin-right: 35px;
}
table.table-50 {
width: 40%;
}

Wyświetl plik

@ -0,0 +1,17 @@
import React from 'react';
import './App.css';
import Dashboard from './components/Dashboard';
function App() {
return (
<div className="app">
<header className="app-header">
<p className="title-text">Real-Time Flight Analytics</p>
<p className="sub-title-text">A MariaDB ColumnStore Demo</p>
</header>
<Dashboard />
</div>
);
}
export default App;

Wyświetl plik

@ -0,0 +1,9 @@
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(<App />, div);
ReactDOM.unmountComponentAtNode(div);
});

Wyświetl plik

@ -0,0 +1,139 @@
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {
PieChart, Pie, Legend, Tooltip, Cell,
BarChart, Bar, XAxis, YAxis, CartesianGrid
} from 'recharts';
export default class AirlineFlightsInfo extends Component {
colors = ["#003545","#2F99A3","#ABC74A","#96DDCF",'#0E6488','#424F62'];
state = {
airline_delays: [],
delays_comparison: []
};
componentDidMount() {
if (this.props !== null &&
this.props.origin !== null &&
this.props.destination !== null &&
this.props.airline !== null) {
this.load(this.props);
}
}
componentWillReceiveProps(nextProps) {
if (nextProps !== null &&
nextProps.origin !== null &&
nextProps.destination !== null &&
nextProps.airline !== null) {
this.load(nextProps);
}
}
async load(props) {
const origin = props.origin.code;
const dest = props.destination.code;
const airline = props.airline.code;
const yearFrom = props.yearFrom;
const yearTo = props.yearTo;
const month = props.month;
const day = props.day;
await this.getAirlineDelays(origin, dest, airline, yearFrom, yearTo, month, day)
.then(res => {
var other = 100 - (res.carrier_delay_pct + res.weather_delay_pct + res.security_delay_pct + res.late_aircraft_delay_pct + res.nas_delay_pct);
var airline_delays = [{name: 'Carrier', value: res.carrier_delay_pct},
{name: 'Late Aircraft', value: res.late_aircraft_delay_pct},
{name: 'NAS', value: res.nas_delay_pct},
{name: 'Security', value: res.security_delay_pct},
{name: 'Weather', value: res.weather_delay_pct},
{name: 'Other', value: other.toFixed(2)}];
this.setState({ airline_delays });
})
.catch(err => console.log(err));
await this.getDelaysComparison(origin, dest, airline, yearFrom, yearTo, month, day)
.then(res => {
var delays_comparison = [
{name: 'Carrier', Target: res[0].carrier, Average: res[1].carrier},
{name: 'Late Aircraft', Target: res[0].late_aircraft, Average: res[1].late_aircraft},
{name: 'NAS', Target: res[0].nas, Average: res[1].nas},
{name: 'Security', Target: res[0].sec, Average: res[1].sec},
{name: 'Weather', Target: res[0].weather, Average: res[1].weather}
];
this.setState({ delays_comparison })
})
.catch(err => console.log(err));
}
async getAirlineDelays(origin, dest, airline, yearFrom, yearTo, month, day) {
const response = await fetch('/api/flights/airline_delays?o=' + origin + "&dst=" + dest + "&a=" + airline +
"&yf=" + yearFrom + "&yt=" + yearTo + "&m=" + month + "&d=" + day);
const body = await response.json();
if (response.status !== 200) {
throw Error(body.message)
}
return body;
};
async getDelaysComparison(origin, dest, airline, yearFrom, yearTo, month, day) {
const response = await fetch('/api/flights/delays_comparison?o=' + origin + "&dst=" + dest + "&a=" + airline +
"&yf=" + yearFrom + "&yt=" + yearTo + "&m=" + month + "&d=" + day);
const body = await response.json();
if (response.status !== 200) {
throw Error(body.message)
}
return body;
};
render() {
const { airline_delays, delays_comparison } = this.state;
return (
<div className="charts-main">
<div className="form-sub-header">
{ !!(this.props.airline) ? this.props.airline.name : ''}
</div>
<div>
<div className="inline-div-50">
<p class="charts-title">Delay % By Type</p>
<PieChart className="form-content" width={400} height={300}>
<Pie isAnimationActive={false} data={airline_delays} cx={200} cy={125} outerRadius={80} fill="#8884d8" label>
{
airline_delays.map((entry, index) => (
<Cell key={`cell-${index}`} fill={this.colors[index]}/>
))
}
</Pie>
<Tooltip/>
<Legend align="center" />
</PieChart>
</div>
<div className="inline-div-50">
<p class="charts-title">Airline (avg minutes) delays vs. All (avg minutes) delays </p>
<BarChart className="Form-content" width={400} height={300} data={delays_comparison}>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="name" />
<YAxis />
<Tooltip />
<Legend align="center" />
<Bar dataKey="Target" fill="#96DDCF" />
<Bar dataKey="Average" fill="#0E6488" />
</BarChart>
</div>
</div>
</div>
);
}
}
AirlineFlightsInfo.propTypes = {
origin: PropTypes.object.isRequired,
destination: PropTypes.object.isRequired,
airline: PropTypes.string.isRequired,
yearFrom: PropTypes.number.isRequired,
yearTo: PropTypes.number.isRequired,
month: PropTypes.number,
day: PropTypes.number
};

Wyświetl plik

@ -0,0 +1,125 @@
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import Paper from '@material-ui/core/Paper';
import {
SelectionState,
SortingState,
IntegratedSorting,
} from '@devexpress/dx-react-grid';
import {
Grid,
Table,
TableHeaderRow,
TableSelection
} from '@devexpress/dx-react-grid-material-ui';
export default class AirlinesFlightsInfo extends Component {
state = {
data: [],
selection: [],
columns: [
{ name: 'airline', title: 'Airline' },
{ name: 'flight_count', title: 'Flights' },
{ name: 'market_share_pct', title: 'Market %' },
{ name: 'delayed_pct', title: 'Delayed %' },
{ name: 'diverted_pct', title: 'Diverted %' },
{ name: 'cancelled_pct', title: 'Cancelled %' }
]
};
constructor(props) {
super(props);
this.changeSelection = this.changeSelection.bind(this);
}
componentDidMount() {
if (this.props !== null &&
this.props.origin !== null &&
this.props.destination !== null) {
this.load(this.props.origin.code, this.props.destination.code,
this.props.yearFrom, this.props.yearTo, this.props.month, this.props.day);
}
}
componentWillReceiveProps(nextProps) {
if (nextProps !== null &&
nextProps.origin !== null &&
nextProps.destination !== null) {
this.load(nextProps.origin.code, nextProps.destination.code,
nextProps.yearFrom, nextProps.yearTo, nextProps.month, nextProps.day);
}
}
async load(origin, dest, yearFrom, yearTo, month, day) {
await this.getStats(origin, dest, yearFrom, yearTo, month, day)
.then(res => {
this.setState({ data: res })
})
.catch(err => console.log(err));
}
async getStats(origin, dest, yearFrom, yearTo, month, day) {
const response = await fetch('/api/flights/airlines_stats?o=' + origin + "&dst=" + dest + "&yf="
+ yearFrom + "&yt=" + yearTo + "&m=" + month + "&d=" + day);
const body = await response.json();
if (response.status !== 200) {
throw Error(body.message)
}
return body;
};
changeSelection(selection) {
const lastSelected = selection
.find(selected => this.state.selection.indexOf(selected) === -1);
if (lastSelected !== undefined) {
this.setState({ selection: [lastSelected] });
var d = this.state.data[lastSelected];
if (d !== undefined) {
this.props.airlineSelected({ code: d.carrier, name: d.airline});
}
} else {
// NOTE: Uncomment the next line in order to allow clear selection by double-click
//this.setState({ selection: [] });
//this.props.airlineSelected(null);
}
}
render() {
const { data, columns, selection } = this.state;
return (
<Paper>
<Grid
rows={data}
columns={columns}>
<SelectionState
selection={selection}
onSelectionChange={this.changeSelection}
/>
<SortingState defaultSorting={[{ columnName: 'cancelled_pct', direction: 'desc' }]} />
<IntegratedSorting />
<Table />
<TableHeaderRow showSortingControls />
<TableSelection
selectByRowClick
highlightRow
showSelectionColumn={false}
/>
</Grid>
</Paper>
);
}
}
AirlinesFlightsInfo.propTypes = {
airlineSelected: PropTypes.func.isRequired,
origin: PropTypes.object,
destination: PropTypes.object,
yearFrom: PropTypes.number,
yearTo: PropTypes.number,
month: PropTypes.number,
day: PropTypes.number
};

Wyświetl plik

@ -0,0 +1,60 @@
import React, {Component} from 'react';
import FlightsFilter from './FlightsFilter';
import FlightPlanHeader from './FlightPlanHeader';
import AirlineFlightsInfo from './AirlineFlightsInfo';
import AirlinesFlightsInfo from './AirlinesFlightsInfo';
export default class Dashboard extends Component {
state = {
origin: null,
destination: null,
airline: null,
yearFrom: null,
yearTo: null,
month: null,
day: null
};
executeSearch(params) {
this.setState({
origin: params.origin,
destination: params.destination,
airline: params.airline,
yearFrom: params.yearFrom,
yearTo: params.yearTo,
month: params.month,
day: params.day
});
}
airlineSelected(airline) {
if (airline !== null) {
this.setState({ airline });
}
}
render() {
const { origin, destination, airline,
yearFrom, yearTo, month, day } = this.state;
return (
<div className="form-main">
<div className="filter-background">
<FlightsFilter executeSearch={(params) => this.executeSearch(params)} />
</div>
<div>
<div className={origin !== null ? '' : 'hidden'}>
<FlightPlanHeader origin={origin} destination={destination} />
</div>
<AirlinesFlightsInfo origin={origin} destination={destination}
yearFrom={yearFrom} yearTo={yearTo} month={month} day={day}
airlineSelected={(airline) => this.airlineSelected(airline)} />
<div className={airline !== null ? '' : 'hidden'}>
<AirlineFlightsInfo origin={origin} destination={destination} airline={airline}
yearFrom={yearFrom} yearTo={yearTo} month={month} day={day} />
</div>
</div>
</div>
);
}
}

Wyświetl plik

@ -0,0 +1,29 @@
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import arrow from './../images/arrow-right.png';
export default class FlightPlanHeader extends Component {
render() {
if (this.props.origin !== null && this.props.destination !== null) {
return(
<div className="form-header">
<table className="table-50">
<tr>
<td><h2>{this.props.origin.code}</h2></td>
<td><img className="image-arrow" src={arrow} alt="->" /></td>
<td><h2>{this.props.destination.code}</h2></td>
</tr>
</table>
</div>
);
}
else {
return(<div />);
}
}
}
FlightPlanHeader.propTypes = {
origin: PropTypes.string.isRequired,
destination: PropTypes.string.isRequired
};

Wyświetl plik

@ -0,0 +1,259 @@
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import Select from 'react-select';
// TODO: Add validation checks on origin and destination
export default class FlightsFilter extends Component {
// TODO: Loop through to create years/days. Went with the quick and dirty instead. -RH
state = {
airlines: [],
airports: [],
selectedOriginOption: null,
selectedDestinationOption: null,
selectedAirlineOption: null,
years: [{ value: 1990, label: 1990},{ value: 1991, label: 1991},{ value: 1992, label: 1992},{ value: 1993, label: 1993},
{ value: 1994, label: 1994},{ value: 1995, label: 1995},{ value: 1996, label: 1996},{ value: 1997, label: 1997},
{ value: 1998, label: 1998},{ value: 1999, label: 1999},{ value: 2000, label: 2000},{ value: 2001, label: 2001},
{ value: 2002, label: 2002},{ value: 2003, label: 2003},{ value: 2004, label: 2004},{ value: 2005, label: 2005},
{ value: 2006, label: 2006},{ value: 2007, label: 2007},{ value: 2008, label: 2008},{ value: 2009, label: 2009},
{ value: 2010, label: 2010},{ value: 2011, label: 2011},{ value: 2012, label: 2012},{ value: 2013, label: 2013},
{ value: 2014, label: 2014},{ value: 2015, label: 2015},{ value: 2016, label: 2016},{ value: 2017, label: 2017},
{ value: 2018, label: 2018},{ value: 2019, label: 2019}],
selectedYearFromOption: { value: 1990, label: 1990},
selectedYearToOption: { value: 2019, label: 2019},
months: [{ value: 1, label: "January"}, { value: 2, label: "February"},
{ value: 3, label: "March"}, { value: 4, label: "April"},
{ value: 5, label: "May"}, { value: 6, label: "June"},
{ value: 7, label: "July"}, { value: 8, label: "August"},
{ value: 9, label: "September"}, { value: 10, label: "October"},
{ value: 11, label: "November"}, { value: 12, label: "December"}],
selectedMonthOption: null,
days: [{ value: 1, label: 1},{ value: 2, label: 2},{ value: 3, label: 3},{ value: 4, label: 4},
{ value: 5, label: 5},{ value: 6, label: 6},{ value: 7, label: 7},{ value: 8, label: 8},
{ value: 9, label: 9},{ value: 10, label: 10},{ value: 11, label: 11},{ value: 12, label: 12},
{ value: 13, label: 13},{ value: 14, label: 14},{ value: 15, label: 15},{ value: 16, label: 16},
{ value: 17, label: 17},{ value: 18, label: 18},{ value: 19, label: 19},{ value: 20, label: 20},
{ value: 21, label: 21},{ value: 22, label: 22},{ value: 23, label: 23},{ value: 24, label: 24},
{ value: 25, label: 25},{ value: 26, label: 26},{ value: 27, label: 27},{ value: 28, label: 28},
{ value: 29, label: 29},{ value: 30, label: 30},{ value: 30, label: 30}],
selectedDayOption: null
};
constructor(props) {
super(props);
this.executeSearch = this.executeSearch.bind(this);
}
componentDidMount() {
this.loadAirports();
this.loadAirlines();
}
async loadAirlines() {
await this.getAirlines()
.then(res => {
const airlineOptions = res.map(airline => ({
value: airline.iata_code,
label: airline.airline
}));
this.setState({ airlines: airlineOptions })
})
.catch(err => console.log(err));
}
async loadAirports() {
await this.getAirports()
.then(res => {
const airportOptions = res.map(airport => ({
value: airport.iata_code,
label: airport.airport
}));
this.setState({ airports: airportOptions })
})
.catch(err => console.log(err));
}
async getAirlines() {
const response = await fetch('/api/airlines');
const body = await response.json();
if (response.status !== 200) {
throw Error(body.message)
}
return body;
};
async getAirports() {
const response = await fetch('/api/airports');
const body = await response.json();
if (response.status !== 200) {
throw Error(body.message)
}
return body;
};
handleOriginChange = selectedOriginOption => {
this.setState({ selectedOriginOption });
};
handleDestinationChange = selectedDestinationOption => {
this.setState({ selectedDestinationOption });
};
handleAirlineChange = selectedAirlineOption => {
this.setState({ selectedAirlineOption });
};
handleYearFromChange = selectedYearFromOption => {
this.setState({ selectedYearFromOption });
};
handleYearToChange = selectedYearToOption => {
this.setState({ selectedYearToOption });
};
handleMonthChange = selectedMonthOption => {
this.setState({ selectedMonthOption });
};
handleDayChange = selectedDayOption => {
this.setState({ selectedDayOption });
};
async executeSearch() {
const { selectedOriginOption, selectedDestinationOption, selectedAirlineOption,
selectedYearFromOption, selectedYearToOption, selectedMonthOption, selectedDayOption } = this.state;
var params = {
origin: {
code: selectedOriginOption.value,
name: selectedOriginOption.label
},
destination: {
code: selectedDestinationOption.value,
name: selectedDestinationOption.label
},
yearFrom: selectedYearFromOption !== null ? selectedYearFromOption.value : null,
yearTo: selectedYearToOption !== null ? selectedYearToOption.value : null,
month: selectedMonthOption !== null ? selectedMonthOption.value : null,
day: selectedDayOption !== null ? selectedDayOption.value : null
};
if (selectedAirlineOption !== null) {
params.airline = {
code: selectedAirlineOption.value,
name: selectedAirlineOption.label
}
}
else {
params.airline = null
}
this.props.executeSearch(params);
}
renderAirportOptions(selectedOption, handleChange) {
return (
<Select
className="airport-picker"
value={selectedOption}
onChange={handleChange}
options={this.state.airports}
isClearable="true"
/>
);
}
renderAirlineOptions(selectedOption, handleChange) {
return (
<Select
className="airport-picker"
value={selectedOption}
onChange={handleChange}
options={this.state.airlines}
isClearable="true"
/>
);
}
render() {
return (
<div>
<table cellSpacing="10">
<tr>
<td>
<div className="form-section">
<p>Origin</p>
{this.renderAirportOptions(this.state.selectedOriginOption,this.handleOriginChange)}
</div>
</td>
<td>
<div className="form-section">
<p>Destination</p>
{this.renderAirportOptions(this.state.selectedDestinationOption,this.handleDestinationChange)}
</div>
</td>
</tr>
<tr>
<td>
<div className="form-section">
<p>Airline</p>
{this.renderAirlineOptions(this.state.selectedAirlineOption,this.handleAirlineChange)}
</div>
</td>
<td>
<div className="form-section">
<div className="float-left">
<p>From</p>
<Select
className="select-year"
value={this.state.selectedYearFromOption}
onChange={this.handleYearFromChange}
options={this.state.years}
/>
</div>
<div className="float-left">
<p>To</p>
<Select
className="select-year"
value={this.state.selectedYearToOption}
onChange={this.handleYearToChange}
options={this.state.years}
/>
</div>
<div className="float-left">
<p>Month</p>
<Select
className="select-month"
value={this.state.selectedMonthOption}
onChange={this.handleMonthChange}
options={this.state.months}
isClearable="true"
/>
</div>
<div className="float-left">
<p>Day</p>
<Select
className="select-day"
value={this.state.selectedDayOption}
onChange={this.handleDayChange}
options={this.state.days}
isClearable="true"
/>
</div>
</div>
</td>
</tr>
<tr>
<td colSpan="2">
<button className="button-search" onClick={this.executeSearch}>Search</button>
</td>
</tr>
</table>
</div>
);
}
}
FlightsFilter.propTypes = {
executeSearch: PropTypes.func.isRequired
};

Plik binarny nie jest wyświetlany.

Po

Szerokość:  |  Wysokość:  |  Rozmiar: 1.8 KiB

Wyświetl plik

@ -0,0 +1,13 @@
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
"Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New",
monospace;
}

Wyświetl plik

@ -0,0 +1,12 @@
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();

File diff suppressed because one or more lines are too long

Po

Szerokość:  |  Wysokość:  |  Rozmiar: 8.0 KiB

Wyświetl plik

@ -0,0 +1,135 @@
// This optional code is used to register a service worker.
// register() is not called by default.
// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on subsequent visits to a page, after all the
// existing tabs open on the page have been closed, since previously cached
// resources are updated in the background.
// To learn more about the benefits of this model and instructions on how to
// opt-in, read https://bit.ly/CRA-PWA
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.1/8 is considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
);
export function register(config) {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
return;
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (isLocalhost) {
// This is running on localhost. Let's check if a service worker still exists or not.
checkValidServiceWorker(swUrl, config);
// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service ' +
'worker. To learn more, visit https://bit.ly/CRA-PWA'
);
});
} else {
// Is not localhost. Just register service worker
registerValidSW(swUrl, config);
}
});
}
}
function registerValidSW(swUrl, config) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (installingWorker == null) {
return;
}
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older
// content until all client tabs are closed.
console.log(
'New content is available and will be used when all ' +
'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
);
// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration);
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration);
}
}
}
};
};
})
.catch(error => {
console.error('Error during service worker registration:', error);
});
}
function checkValidServiceWorker(swUrl, config) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl)
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
const contentType = response.headers.get('content-type');
if (
response.status === 404 ||
(contentType != null && contentType.indexOf('javascript') === -1)
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl, config);
}
})
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
);
});
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready.then(registration => {
registration.unregister();
});
}
}

36
Flights/src/db.js 100644
Wyświetl plik

@ -0,0 +1,36 @@
var fs = require("fs")
var mariadb = require('mariadb');
/*
const pool = mariadb.createPool({
host: 'localhost',
user:'dba',
port: 3307,
password: 'demo_password',
database: 'flights',
connectionLimit: 5
});
*/
//const serverCert = [fs.readFileSync("skysql_root.pem", "utf8")];
const pool = mariadb.createPool({
host: 'sky0001276.mdb0001390.db.skysql.net',
user:'DB00001323',
port: 5002,
password: "xqjvKYE6q7yE~J8X0N1,1i|6",
database: 'flights',
connectionLimit: 5
});
module.exports={
getConnection: function(){
return new Promise(function(resolve,reject){
pool.getConnection().then(function(connection){
resolve(connection);
}).catch(function(error){
reject(error);
});
});
}
}

1042
Flights/src/package-lock.json wygenerowano 100644

Plik diff jest za duży Load Diff

Wyświetl plik

@ -0,0 +1,19 @@
{
"name": "flights",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"start": "concurrently \"npm run server\" \"npm run client\"",
"server": "node server.js",
"client": "npm start --prefix client"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"concurrently": "^5.0.0",
"express": "^4.17.1",
"mariadb": "^2.1.3"
}
}

Wyświetl plik

@ -0,0 +1,22 @@
"use strict";
let express = require("express"),
router = express.Router(),
pool = require('../db');
// GET all airlines
router.get("/", async (req, res, next) => {
let conn;
try {
conn = await pool.getConnection();
var query = "select * from airlines order by airline";
var rows = await conn.query(query);
res.send(rows);
} catch (err) {
throw err;
} finally {
if (conn) return conn.release();
}
});
module.exports = router;

Wyświetl plik

@ -0,0 +1,22 @@
"use strict";
let express = require("express"),
router = express.Router(),
pool = require('../db');
// GET all airports
router.get("/", async (req, res, next) => {
let conn;
try {
conn = await pool.getConnection();
var query = "select iata_code, airport from airports group by airport, iata_code order by airport";
var rows = await conn.query(query);
res.send(rows);
} catch (err) {
throw err;
} finally {
if (conn) return conn.release();
}
});
module.exports = router;

Wyświetl plik

@ -0,0 +1,175 @@
"use strict";
let express = require("express"),
router = express.Router(),
pool = require('../db');
// GET search
router.get("/airlines_stats", async (req, res, next) => {
var origin = req.query.o;
var dest = req.query.dst;
var yearFrom = req.query.yf;
var yearTo = req.query.yt;
var month = req.query.m;
var day = req.query.d;
let conn;
try {
conn = await pool.getConnection();
var query = "select " +
"q.carrier, " +
"q.airline, " +
"q.volume flight_count, " +
"round(100 * q.volume / sum(q.volume) over " +
"(order by q.airline rows between unbounded preceding and unbounded following),2) market_share_pct, " +
"round(100 * (q.`delayed` / q.volume), 2) delayed_pct, " +
"round(100 * (q.cancelled / q.volume), 2) cancelled_pct, " +
"round(100 * (q.diverted / q.volume), 2) diverted_pct " +
"from ( " +
"select f.carrier, a.airline, count(*) volume, " +
"sum(case when dep_delay > 0 then 1 else 0 end) `delayed`, " +
"sum(diverted) diverted, sum(cancelled) cancelled " +
"from flights f join airlines a on f.carrier = a.iata_code " +
"where " +
"f.origin = ? and " +
"f.dest = ? and " +
"f.year >= ? and " +
"f.year <= ?";
if (month !== null && !isNaN(month)) {
query += " and f.month = " + month;
}
if (day !== null && !isNaN(day)) {
query += " and f.day = " + day;
}
query += " group by a.airline, f.carrier) q order by flight_count desc;";
var rows = await conn.query(query, [origin, dest, yearFrom, yearTo]);
res.send(rows);
} catch (err) {
throw err;
} finally {
if (conn) return conn.release();
}
});
router.get("/airline_delays", async (req, res, next) => {
var origin = req.query.o;
var dest = req.query.dst;
var airline = req.query.a;
var yearFrom = req.query.yf;
var yearTo = req.query.yt;
var month = req.query.m;
var day = req.query.d;
let conn;
try {
conn = await pool.getConnection();
var query = "select " +
"round(100 * (weather_delayed / total_delayed), 2) weather_delay_pct, " +
"round(100 * (carrier_delayed / total_delayed), 2) carrier_delay_pct, " +
"round(100 * (nas_delayed / total_delayed), 2) nas_delay_pct, " +
"round(100 * (security_delayed / total_delayed), 2) security_delay_pct, " +
"round(100 * (late_aircraft_delayed / total_delayed), 2) late_aircraft_delay_pct " +
"from (" +
"select " +
"carrier_delayed, nas_delayed, security_delayed, late_aircraft_delayed, weather_delayed, " +
"(carrier_delayed+nas_delayed+security_delayed+late_aircraft_delayed+weather_delayed) total_delayed " +
"from (" +
"select " +
"avg(carrier_delay) carrier_delayed, " +
"avg(nas_delay) nas_delayed, " +
"avg(security_delay) security_delayed, " +
"avg(late_aircraft_delay) late_aircraft_delayed, " +
"avg(weather_delay) weather_delayed " +
"from " +
"flights f join airlines a on f.carrier = a.iata_code " +
"where " +
"f.origin = ? and f.dest = ? and f.carrier = ? and f.year >= ? and f.year <= ?";
if (month !== null && !isNaN(month)) {
query += " and f.month = " + month;
}
if (day !== null && !isNaN(day)) {
query += " and f.day = " + day;
}
query += " group by a.airline, f.carrier) a) b";
var rows = await conn.query(query, [origin, dest, airline, yearFrom, yearTo]);
res.send(rows[0]);
} catch (err) {
throw err;
} finally {
if (conn) return conn.release();
}
});
router.get("/delays_comparison", async (req, res, next) => {
var origin = req.query.o;
var dest = req.query.dst;
var airline = req.query.a;
var yearFrom = req.query.yf;
var yearTo = req.query.yt;
var month = req.query.m;
var day = req.query.d;
let conn;
try {
conn = await pool.getConnection();
var query = "select " +
"avg(carrier_delay) carrier, " +
"avg(nas_delay) nas, " +
"avg(security_delay) sec, " +
"avg(late_aircraft_delay) late_aircraft, " +
"avg(weather_delay) weather " +
"from " +
"flights f " +
"where " +
"f.origin = ? " +
"and f.dest = ? " +
"and f.carrier = ? " +
"and f.year >= ? and f.year <= ?";
if (month !== null && !isNaN(month)) {
query += " and f.month = " + month;
}
if (day !== null && !isNaN(day)) {
query += " and f.day = " + day;
}
query += " union select " +
"avg(carrier_delay) carrier, " +
"avg(nas_delay) nas, " +
"avg(security_delay) sec, " +
"avg(late_aircraft_delay) late_aircraft, " +
"avg(weather_delay) weather " +
"from " +
"flights f " +
"where " +
"f.origin = ? " +
"and f.dest = ? " +
"and f.year >= ? and f.year <= ?";
if (month !== null && !isNaN(month)) {
query += " and f.month = " + month;
}
if (day !== null && !isNaN(day)) {
query += " and f.day = " + day;
}
var rows = await conn.query(query, [origin, dest, airline, yearFrom, yearTo, origin, dest, yearFrom, yearTo]);
res.send(rows);
} catch (err) {
throw err;
} finally {
if (conn) return conn.release();
}
});
module.exports = router;

Wyświetl plik

@ -0,0 +1,31 @@
const express = require('express');
const app = express();
const port = 8080;
const path = require('path');
const bodyParser = require("body-parser");
const airlinesRoutes = require("./routes/airlinesRoutes");
const airportsRoutes = require("./routes/airportsRoutes");
const flightsRoutes = require("./routes/flightsRoutes");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
if (process.env.NODE_ENV === 'production') {
app.use(express.static('client/build'));
}
app.use("/api/airlines", airlinesRoutes);
app.use("/api/airports", airportsRoutes);
app.use("/api/flights", flightsRoutes);
app.get("/*", (req, res) => {
res.sendFile(path.join(__dirname, "/client/build/index.html"));
});
app.use((err, req, res, next) => {
res.status(422).send({ error: err._message });
});
// console.log that your server is up and running
app.listen(port, () => console.log(`Listening on port ${port}`));