Solidity - Ethereum, Blockchain, Smart Contracts, and EVM
1 hour 30 min tutorial on Solidity. Currently, 1 Ether = 233.83.
Blockchain is "an open, distributed ledger that can record transactions between two parties efficiently and in a verifiable and permanent way". There are 3 pillars:
- Decentralization
- Transparency
- Immutability
Blocks = growing list of records
Distributed ledger technology (DLT) that allows data to be stored globally on thousands of servers.
"Gas requirements of this function is infinite" can be dismissed.
Fallback function not working.
pragma solidity ^0.5.1;
contract ERC20Token {
string public name;
mapping(address => uint256) public balances;
function mint() public {
balances[tx.origin] ++;
}
}contract MyContract {
address payable wallet;
address public token;
constructor(address payable _wallet, address _token) public {
wallet = _wallet;
token = _token;
}
function() external payable {
buyToken();
}
function buyToken() public payable {
ERC20Token(address(token)).mint();
wallet.transfer(msg.value);
}
}
Inheritance
Game Development - Tetris in React
First game development. Starter files can be found here.
Troubleshooting:
1. Solution to the absence of src folder in react app:
npm rm -g create-react-app
npm install -g create-react-app
npx create-react-app my-app
2. forEach is not a function in hooks>useStage.js
So I changed line 28 and 29 from
player.tetromino.forEach((row, y) => {
row.forEach((value, x) => {
to:
[...player.tetromino].forEach(function(row, y) {
Array.from(row).forEach((value, x) => {
3. It turns out the Start button isn't working.It shows a blank gaming screen with no tetrominoes. The console shows:
[HMR] Waiting for update signal from WDS
The suggested solution is to create projects with:
npx create-react-app project-name --scripts-version 3.2.0
Soon I found out it has to do with StartButton.js. I leftout a chunk of code in styled components. What was I thinking?
const StyledStartButton = styled.button`
box-sizing: border-box;
margin: 0 0 20px 0;
padding: 20px;
min-height: 30px;
width: 100%;
border-radius: 20px;
border: none;
color: white;
background: #333;
font-family: Pixel, Arial, Helvetica, sans-serif;
font-size: 1rem;
outline: none;
cursor: pointer;
`;
And the game worked after inserting the code :)
Coding my first game was fun, especially Tetraminos.js and usePlayer.js:
Responsive Bootstrap Website
Building Responsive Website with Bootstrap 4.1.2, HTML5 & CSS3
Bootstrap - Copy CSS and JS
Fontawesome - Icons
<script src="https://kit.fontawesome.com/00dacea898.js" crossorigin="anonymous"></script>
Outline Button and Red Button
<input type="button" value="Detail" class="btn btn-outline-info">
<input type="button" value="Show me" class="btn btn-danger">
Flexible row
<div class="d-flex flex-row">
Three equal column cards
<div class="col-md-4">
<div class="card">
Divide into sections for style.css
<div class="section-1">
<div class="section-2">
Social Media Icons
<i class="fab fa-twitter m-2"></i>
<i class="fab fa-instagram m-2"></i>
<i class="fab fa-youtube m-2"></i>
Lightbox Gallery
Responsive Image Gallery using HTML, CSS and Javascript. It shows up nicely in preview, but when I try to upload in blogger it become something entirely different...
https://lokeshdhakar.com/projects/lightbox2/
Hosting CSS and Scripts in Google drive:
Upload to Scripts folder in Google Drive, set file view to public.
Right click "Create Sharable Link"
Change file extension from https://docs.google.com/file/d/your-file-code/ to https://googledrive.com/host/your-file-code
Node.js, Express, MongoDB Book Project
Preparation
MongoDB (64 bit)
MongoDB Atlas: https://www.mongodb.com/cloud/atlas
GitHub - SSH key. Find in id_rsa.pub
Deploy images at separate server, not heroku. Heroku Filepond CDN
<link href="https://unpkg.com/filepond/dist/filepond.css" rel="stylesheet">
<script src="https://unpkg.com/filepond/dist/filepond.js"></script>
Code can be found at GitHub - WebDevSimplified/Mybrary at v1.2
Insomnia - Rest API (REpresentational State Transfer) to develop web service. Use HTTP requests to GET, PUT, POST, DELETE
React Project - E commerce store
Fixed: Line 14 in ProductList.js
<div className="row">
NOT <div className="row" />
Now it's displaying in four rows instead of one.
Resume Project
cd desktop
cd store
code .
npm start
Ctrl + C - stop and start server
Structure
-Create components in src - Navbar.js, Product.js, ProductList.js, Default.js, Details.js, Button.js, Title.js
- Create img in public - product-1.png... product-8.png (400 x 400)
- Create context.js in src
- Place logo.svg in src
Preparation
Font Awesome Code
<link rel="stylesheet"
href="https://use.fontawesome.com/releases/v5.6.1/css/all.css"
integrity="sha384-gfdkjb5BdAXd+lj+gudLWI+BXq4IuLW5IT+brZEZsLFm++aCMlF1V92rMkPaX4PP"
crossorigin="anonymous"
/>
App.css
:root {
--mainBlue: #2a2a72;
--lightBlue: #009ffd;
--mainWhite: #f3f3f3;
--mainDark: #232528;
--mainYellow: #ffa400;
transition: all 1s linear;
}
body {
font-family: "Oswald", sans-serif !important;
background: var(--mainWhite) !important;
color: var(--mainDark) !important;
}
.text-title {
font-family: "Ubuntu";
letter-spacing: 0.3rem;
text-transform: uppercase;
}
.text-blue {
color: var(--mainBlue);
}
.text-bright {
color: var(--lightBlue);
}
Install React-router-dom
npm install -g create-react-app
create-react-app demo-app
- Fragment component allows a component to return a set of children without a wrapper DOM element.
Install Styled Components
npm installed --save styled-components
App.js
import React, { Component } from "react";
import { Switch, Route } from "react-router-dom";
import logo from "./logo.svg";
import "./App.css";
import "bootstrap/dist/css/bootstrap.min.css";
import Navbar from "./components/Navbar";
import ProductList from "./components/ProductList";
import Details from "./components/Details";
import Cart from "./components/Cart";
import Default from "./components/Default";class App extends Component {
render() {
return (
<React.Fragment>
<Navbar />
<Switch>
<Route exact path="/" component={ProductList} />
<Route path="/details" component={Details} />
<Route path="/cart" component={Cart} />
<Route component={Default} />
</Switch>
</React.Fragment>
);
}
}
export default App;
Button.js
Building the yellow hover button (3:13:54)
border-color: ${props =>
props.cart ? "var(--mainYellow)" : "var(--lightBlue)"};
Bootstrap Shorthand
Using the format {property}{sides}-{size} for xs and {property}{sides}-{breakpoint}-{size} for sm, md, lg, and xl.
- m = margin, p = padding
- tblr = top, bottom, left, right; x= left and right; y = top and bottom
- 0-5 = 0 eliminate margin or padding, 1 = *0.25, 2= *0.5, 3 default, 4 = *1.5, 5 = *3, auto
- rgba = red, green, blue, alpha ---> rgba (0,0,255,.1)
- container-fluid takes up the whole screen
<div className="row">
<div className="col-10 mx-auto col-md-6 my-3 text-capitalize">
<img src={img} className="img-fluid" alt="product" />
</div>
Modal.js
4:06:30 - Your Cart Page
Create cart folder - Cart.js, package.json, CartColumns.js, CartItem.js, EmptyCart.js, CartTotals.js
Tip: to move file, write package.json
{
"main": "Cart.js"
}
5:13:29 - Total and tax computations at Context.js
addTotals = () => {
let subTotal = 0;
this.state.cart.map(item => (subTotal += item.total));
const tempTax = subTotal * 0.1;
const tax = parseFloat(tempTax.toFixed(2));
const total = subTotal + tax;
this.setState(() => {
return {
cartSubTotal: subTotal,
cartTax: tax,
cartTotal: total
};
});
5:16:56 - Clear Cart
5:28:41 - Incremention and Decrementation
5:40:50 - 404 Default Page
<div className="container">
<div className="row">
<div className="col-10 mx-auto text-center text-title text-uppercase pt-5">
<h1 className="display-3">404</h1>
<h2>page not found</h2>
<h3>
the requested URL
<span className="text-danger">
{this.props.location.pathname}
</span>{" "}
was not found
</h3>
</div>
</div>
</div>
5:47:15 - Deploy on Netlify
https://jewellery-store.netlify.com/
6:00:11 - Paypal APM Package
- Accounts: faciliator and buyer email address
- My Apps & Credentials > REST API apps > Create app
Login Sandbox Paypal with faciliator and buyer email address to verify payment
Notification occur when there's error
6:11:00 - Create env.development in root
Prevent API keys from being seen
Include .env.development in .gitignore #dependencies
Copy API key from PayPalButton to .env file
REACT_APP_APP_ID={insert API key}
Access environment variable. Replace line 33 PayPalButton.js with
sandbox: process.env.REACT_APP_APP_ID,
Stop and restart server
Copy dependent key to netlify
6:50:03 - Github
Create new repository
git init
git add .
git commit -m "first commit"
git remote add origin https://github.com/account-name/repository-name.git (not required for amendments)
git push -u origin master
Domain setting in Netlify
Upon making changes in github, Netlify have hook in github and will deploy again
JavaScript Project - Search Filter Page
2019/06/01/125814
Overall site still very buggy
Followup: Need to resize images, 72 dpi
- hero-bcg: 1000 x 700 (52k)
- product-1... product-8: 1280 x 720 (80k)
Followup: Deploy contentful
Contentful.js
import { createClient } from "contentful";
export default createClient({
space: "xxxxxxxxxxx",
accessToken: "XXXXXXXXXXXXXXXXXXXXXXXX"
});
Followup: Study React Code
Search Filter Page Completed
context.js
import React, { Component } from "react";
import items from "./data";
// import Client from "./Contentful";
// import { all } from "q";
// import { taggedTemplateExpression } from "@babel/types";const RoomContext = React.createContext();
class RoomProvider extends Component {
state = {
rooms: ,
sortedRooms: ,
featuredRooms: [],
loading: true,
type: "all",
capacity: 1,
price: 0,
minPrice: 0,
maxPrice: 0,
minSize: 0,
maxSize: 0,
breakfast: false,
pets: false
};
// getDatacomponentDidMount() {
// this.getData();
let rooms = this.formatData(items);
let featuredRooms = rooms.filter(room => room.featured === true);
let maxPrice = Math.max(...rooms.map(item => item.price));
let maxSize = Math.max(...rooms.map(item => item.size));this.setState({
rooms,
featuredRooms,
sortedRooms: rooms,
loading: false,
price: maxPrice,
maxPrice,
maxSize
});
}formatData(items) {
let tempItems = items.map(item => {
let id = item.sys.id;
let images = item.fields.images.map(image => image.fields.file.url);
let room = { ...item.fields, images, id };
return room;
});
return tempItems;
}
getRoom = slug => {
let tempRooms = [...this.state.rooms];
const room = tempRooms.find(room => room.slug === slug);
return room;
};
handleChange = event => {
const target = event.target;
const value = target.type === "checkbox" ? target.checked : target.value;
const name = event.target.name;
this.setState(
{
[name]: value
},
this.filterRooms
);
};
filterRooms = () => {
let {
rooms,
type,
capacity,
price,
minSize,
maxSize,
breakfast,
pets
} = this.state;
// all the rooms
let tempRooms = [...rooms];
// transform value
capacity = parseInt(capacity);// filter by type
if (type !== "all") {
tempRooms = tempRooms.filter(room => room.type === type);
}// filter by capacity
if (capacity !== 1) {
tempRooms = tempRooms.filter(room => room.capacity >= capacity);
}// filter by price
tempRooms = tempRooms.filter(room => room.price <= price);
// filter by size
tempRooms = tempRooms.filter(
room => room.size >= minSize && room.size <= maxSize
);
// filter by breakfast
if (breakfast) {
tempRooms = tempRooms.filter(room => room.breakfast === true);
}
// filter by pets
if (pets) {
tempRooms = tempRooms.filter(room => room.pets === true);
}
// change state
this.setState({
sortedRooms: tempRooms
});
};
render() {
return (
<RoomContext.Provider
value={{
...this.state,
getRoom: this.getRoom,
handleChange: this.handleChange
}}
>
{this.props.children}
</RoomContext.Provider>
);
}
}const RoomConsumer = RoomContext.Consumer;
export function withRoomConsumer(Component) {
return function ConsumerWrapper(props) {
return (
<RoomConsumer>
{value => <Component {...props} context={value} />}
</RoomConsumer>
);
};
}
export { RoomProvider, RoomConsumer, RoomContext };
https://weekend-trip.netlify.com/
Javascript Project - Beach Resort
1:01:27 - Finished App.js and Navbar.js
npx create-react-app resort
npm install react-icons
npm i react-router-dom --save
npm start
React Router DOM Documentation
App.js
import React from "react";
import "./App.css";import Home from "./pages/Home";
import Rooms from "./pages/Rooms";
import SingleRoom from "./pages/SingleRoom";
import Error from "./pages/Error";import { Route, Switch } from "react-router-dom";
function App() {
return (
<>
<Switch>
<Route exact path="/" component={Home} />
<Route exact path="/rooms/" component={Rooms} />
<Route exact path="/rooms/:slug" component={SingleRoom} />
<Route component={Error} />
</Switch>
</>
);
}export default App;
Navbar.js
import React, { Component } from "react";
import logo from "../images/logo.svg";
import { FaAlignRight } from "react-icons/fa";
import { Link } from "react-router-dom";export default class Navbar extends Component {
state = {
isOpen: false
};
handleToggle = () => {
this.setState({ isOpen: !this.state.isOpen });
};
render() {
return (
<nav className="navbar">
<div className="nav-center">
<div className="nav-header">
<Link to="/">
<img src={logo} alt="Beach Resort" />
</Link>
<button
type="button"
className="nav-btn"
onClick={this.handleToggle}
>
<FaAlignRight className="nav-icon" />
</button>
</div>
<ul
className={this.state.isOpen ? "nav-links show-nav" : "nav-links"}
>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/rooms">Rooms</Link>
</li>
</ul>
</div>
</nav>
);
}
}
Banner.js
import React from "react";
export default function Banner({ children, title, subtitle }) {
return (
<div className="banner">
<h1>{title}</h1>
<div />
<p>{subtitle}</p>
{children}
</div>
);
}
Hero.js
import React from "react";
export default function Hero({ children, hero }) {
return <header className={hero}>{children}</header>;
}Hero.defaultProps = {
hero: "defaultHero"
};
Loading.js
import React from "react";
import loadingGif from "../images/gif/loading-arrow.gif";
export default function Loading() {
return (
<div className="loading">
<h4>Getting data...</h4>
<img src={loadingGif} alt="" />
</div>
);
}
2:01:32 - Created Context.js
2:29:30 - Starting SingleRoom.js
2:51:44 - Creating StyledHero.js
Styled Components
npm install --save styled-components
To test the installation, in Home.js:
import Button from "../components/StyledHero";
<Button>Hello</Button>
Create new file StyledHero.js:
import styled from "styled-components";
const orange = "#f15025";
const SimpleButton = styled.button`
color: ${orange};
background: green;
font-size: 3rem;
`;export default SimpleButton;
If successful, orange button should appear at bottom of homepage:
Stock market forecasting with prophet
fb
Open Anaconda Prompt and install fbprophet
conda install -c conda-forge fbprophet
If kernel error occured in jupyter notebook, open Anaconda prompt and view location. Open kernal.json, see if python editor have the same path
jupyter kernelspec list
If not, reinstall
python -m ipykernel install --user
Restart jupyter notebook
- Revision: For variables with space, use bracket notation:
ax1.plot(two_years.Adj Close) WRONG
ax1.plot(two_years['Adj Close'])
Stock market forecasting with prophet - Python Data
1. Import libraries
import numpy as np
import pandas as pd
import pandas_datareader as pdr
import matplotlib.pyplot as plt
%matplotlib inline
import datetime as datetime#Prophet
from fbprophet import Prophetfrom sklearn import metrics
2. Fetch data from yahoo
start = datetime.datetime(2015,1,5)
df_0012 = pdr.DataReader('0012.HK', 'yahoo', start=start)
df_0012.head()
3. Plot graph
plt.style.use('ggplot')
df_0012['Adj Close'].plot(figsize=(12, 8))
4. Transform data by log
- Facebook prophet's example use log-transform as a way to remove anomolies and outliers. It is not best way, but taking log of a number is easily reversible to see your original data
df = df_0012.reset_index().rename(columns={'Date':'ds', 'Adj Close':'y'})
df['y'] = np.log(df['y'])
5. Apply forecast model
- The black dots stops at today, blue line is predicted value. The pale blue area is uncertainty surrounding the prediction
model = Prophet()
model.fit(df)
future = model.make_future_dataframe(periods=365) #forecasting for 1 year from now.
forecast = model.predict(future)figure=model.plot(forecast)
6. Create two years forecast model
- Only the last 800 data are selected. The red line is actual value, blue line is prediction. From the diagram it is pretty close
two_years = forecast.set_index('ds').join(df_0012)
two_years = two_years'Adj Close', 'yhat', 'yhat_upper', 'yhat_lower' .dropna().tail(800)
two_years['yhat']=np.exp(two_years.yhat)
two_years['yhat_upper']=np.exp(two_years.yhat_upper)
two_years['yhat_lower']=np.exp(two_years.yhat_lower)
two_years'Adj Close', 'yhat'.plot()
7. Find out about descriptive data (std, mean, 25%, 50%....)
- To calculate the deviation between actual and predicted values, largest is 2.72, smallest is -3.32, mean is -0.04
two_years_AE = (two_years.yhat - two_years['Adj Close'])
two_years_AE.describe()
8. MSE
- Mean squared error: the closer to zero is better, if you are trying to predict exact changes and movements up/down. Take y coordinate (black dot) and subtract y coordinate value, calculate square, take all values and divide by n to give the mean. The goal is to minimize the mean, to provide (blue) line that goes through all the points to minimize squared distance
- From the dataset, MSE: 0.9696
print ("MSE:",metrics.mean_squared_error(two_years.yhat, two_years['Adj Close']))
9. MAE
- Mean absolute error: Measurement of absolute error between two continuous variables
- From the dataset, MAE: 0.764158903862
print ("MAE:",metrics.mean_absolute_error(two_years.yhat, two_years['Adj Close']))
10. Actual vs Forecasted Price with Upper & Lower Confidence
- The diagram shows the range of 47.5 to 52.5
- According to the Bollinger bands, lower and upper values are: 47 - 49.3
fig, ax1 = plt.subplots(figsize=(10, 8))
ax1.plot(two_years['Adj Close'])
ax1.plot(two_years.yhat)
ax1.plot(two_years.yhat_upper, color='black', linestyle=':', alpha=0.5)
ax1.plot(two_years.yhat_lower, color='black', linestyle=':', alpha=0.5)
ax1.set_title('Actual Price (Orange) vs Forecasted Upper & Lower Confidence (Black)')
ax1.set_ylabel('Price')
ax1.set_xlabel('Date')
React.js, Angular and Vue
React.js
- Lightweight, popular front-end framework, interactive user interface
- Virtual DOM, update blog post (instead of reload whole page)
- JSX is similar to HTML
- Reusable functionable components, familarize with ES6
Install node.js
Install React Developer Tool in chrome browser
Setup React.js
Open new folder React, RUN
npm install create-react-app -g
create-react-app my-app
cd my-app
npm start
Organizational Structure (DOM Tree)
|--- index.html
|--- index.js
+-- components ---- myinfo.js, footer.js, navbar.js.....
index.html
<body>
<div id="root"></div>
<script src="index.pack.js"></script>
</body>
index.js
- Boilerplate code
- ./ means local directory, can emit ; except in for loop, like for(let i =0;)
- 1st parameter what you want to render, 2nd is where to put that
import React from "react"
import ReactDOM from "react-dom"import MyInfo from "./components/MyInfo"
ReactDOM.render<MyInfo />, document.getElementById("root"))
MyInfo.js
- Can move entire function component to new MyInfo.js. By default, it's a .js file
- Element is regular HTML. Component created like <MyInfo /> has capital
- Can nest deeply with <Header />, <NavBar />, <Footer />... Need to wrap element in <div>
- className access DOM property, not class. Can only apply attribute to react element, but not component created like Header or Maincontent
- In JSX, any text inside {} is Javascript, {`${firstName} ${lastName}`}
- const App = () => { return (
<h1>Hello World</h1>
)}
can be simplified as:
const App = () => <h1>Hello World</h1>
import React from "react"
function MyInfo() {
return (
<div>
<h1>Hello World!</h1>
<p>This is a paragraph about me.</p>
<input type="checkbox" /><p>Place text here</p>
</div>
)
}export default MyInfo
Setting javascript to tell what time of day in index.js
- Inside Javascript cannot have tag inside name, e.g. background-color. Need to make it camel case
- <h1 style={{color: "FF8C00", backgroundColor: "#FF2D00"}}>Good {timeOfDay}</h1>
ContactCard.js
- Using Props: Properties in HTML modify how components act
- props: function parameter receive an object with property with imgUrl, each being name of property passed in, ie. props.name, props.imgUrl.... Replace hardcoded values with { }
- Use console.log(props) to see what is receiving
import React from "react"
function ContactCard(props) {
console.log(props)
return (
<div className="contact-card">
<img src= {props.imgUrl} />
h3>{props.name}</h3>
<p>Phone: {props.phone}</p>
<p>Email: {props.email}</p>
</div>
)
}export default ContactCard
App.js
- Passing separate props: name, imgUrl, phone, email
import React from "react"
import ContactCard from "./ContactCard"
function App() {return (
<div className="contacts">
<ContactCard
name= "Mr. Whiskerson"
imgUrl=""http://kitten.com/8795"
phone= "(222) 555-123"
email="whiskaz@catnap.meow"
/>
<ContactCard
name= "Fluffy King"
imgUrl=""http://kitten.com/8908"
phone= "(212) 455-123"
email="fluff@catnap.meow"
/>
</div>
)}
Props can be simplified to single property:
- Later stored as json file
- contact: with properties name, imgUrl, phone, email
<ContactCard
contact= {{ name: "Mr. Whiskerson",
imgUrl: "http:////kitten.com/8795", phone= "(222) 555-123", email="whiskaz@catnap.meow"}}
/>
Update ContactCard.js to:
{img src="{props.contact.imgUrl} />
{img src="{props.contact.name} />
Conditional rendering
- Only answer, but no question in some
- Ternary operator. Inside object props.question, a thing is it truthy? If not block, otherwise display none
<h3 style={display: props.question ? "block" : "none" }}> Question: {props.question}</h3>
or
If there isn't a... !, then we want to display... &&, otherwise ignore this rule completely
<h3 style={display: !props.question && "none" }}> Question: {props.question}</h3>
Higher Order Methods
- map, filter, reduce. Map returns new array. Render other components
- Arrow function component => has return implied
const nums = [1,2,3,4,5]
const doubled = nums.map(function(num){
return num * 2
)}
jokesData.map(joke => <Joke key={sthunique.id} question={joke.question} punchLine={joke.punchLine} /> )
return (
<div>
{jokeComponents}
</div>
)}
To Do List: Turning array to elements
Step 1: Go to App.js
import TodoItem from "./TodoItem"
import todoData from "./todosData"
function App() {
create const todoItems = todoData.map(item => <todoitem key={item.id} item={item} />)
return(
<div className="todo-list">
{todoItems}
</div>)}
export default App
Step 2: Go to TodoItem.js
- But cannot uncheck yet!
- todoData.js has
const todoData = [{ id: 1, text: "Grocery shopping", completed: true}]
function todoItem(props) {
return(
<div className="todo-item">
<input type="checkbox" checked={props.item.completed} />
<p>{props.item.text}</p>
</div> )}
export default todoItem
Class based Components
- State and lifecycle method
- Display things after render, but before return, like styles
class App() extends React.Component {
render() {
// styling goes here
return (
<div>JSX</div>
)
}}
2:03:48