Sunday, September 22, 2019

CSS Course - 3: A bit deeper into CSS


  • The Box Model
  • Height & Width
  • The "display" Property
  • Properties worth to remember
  • Pseudo classes & elements
CSS Box Model

Margin
   border
      padding
         content


  • The Box Model
  • Height & Width
  • The "display" Property
  • Properties worth to remember
  • Pseudo classes & elements
CSS Box Model

Margin
   border
      padding
         content


Margin Collapsing - Bigger Margin “wins”

In general: Use either margin-top or margin-bottom

Shorthand Properties - Combine values of multiple properties in a single property (the shorthand property)

Example: 

border-width: 2px;
border-style: dashed | solid
border-color: orange

Shorthand property:
border: 2px dashed orange
margin: 5px 10px 5px 10px;  // top right bottom left
margin: 5px 10px; //top & bottom;  left & right
margin: 10px; //all sides

Height & Width properties

Block element default to 100% width

box-sizing: content-box (default) |border-box

Display Property

Display: none|block|inline|inline-block

Pseudo Classes & Pseudo Elements

Pseudo class - Defines the style of a special state of an element, eg: hover, active

Pseudo element - Defines the style of a specific part of an element, eg: ::after, ::selection, ::first-line

Check MDN standard pseudo-classes


Properties Worth to Remember

color:
background-color:
display:
padding:
border:
margin:
width:
height:




Saturday, September 21, 2019

CSS Course - 2: Understanding the Basic


  • How to add CSS to HTML
  • Setting up CSS rules
  • Selectors, Properties & Values
  • Conflicting Styles

How to add CSS to HTML, 3 approaches
1. Inline styling



<body>
    <main>
        <section style="background:#ff1b68">
            <h1>Welcome to shuyanonline.com</h1>
        </section>
    </main>
</body>





2. CSS rules

<
head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
section{
background:#ff1b68;
}
</style>
</head>
<body>
<main>
<section>
<h1>Welcome to shuyanonline.com</h1>
</section>
</main>
</body>


3. use external style sheets

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>CSS course</title>
<link rel="stylesheet" href="main.css">
</head>
<body>
<main>
<section>
<h1>Welcome to ShuyanOnline.com</h1>
</section>
<section>
<h1>Chose your course</h1>
</section>
</main>
</body>
</html>

main.css
section{
background: #ff1b68;
}

h1 {
color: white;
font-family: 'Anton', sans-serif;
}

More about selectors

Elements - Set equal style for these element

h1 {
color: white;
font-family: 'Anton', sans-serif;
}

Classes - Set equal style for elements within the same class

.post {
color: red;

}

Universal - Rarely use this one!

* {
color: red;
}

IDs - Set style to one specific element

#my-title {
color: red;
}

Attributes - Set equal styles to all elements with attributes
index.html
<button disabled>
Click
</button>
main.css
[disabled] {
color: red;
}



Notes: ID must be unique, classes can be reused.

Cascading Style Sheets & Specificity
Cascading - Multiple Rules can apply to the same element

Specificity - Resolve conflicts arising from multiple rules

priority from high to low:
Inline styles  》 #ID selectors 》 .class, :pseudo-class and [attribute] selectors 》 <tag> and ::pseudo-element selectors 

Inheritance

An element inheritance some styles from the parent element

font-family: inherit;

Combinators

  • Adjacent sibling (elements share the same parent; second element comes immediately after first element)
div + p {
}
  • General sibling (elements share the same parent; second element comes after first element)
div ~ p {
}
  • Child (second element is a direct child of first element)
div > p {
}
  • Descendant (second element is a descendant of the first element)
div p {
}

Summary:
  • CSS works with Rules
  • Different Types of Selectors
  • Properties & Values
    • Long list of available properties and values
    • Check MDN or comparable references
    • Different type of values, depending on properties
  • Selectors with Combinators
  • Inheritance & Specifity
    • Parent styles are generally inherited
    • Multiple rules can apply to one element
    • Specifity resolves "multiple rules" conflicts
    • Inheritance defaults can be changed




(Over.)



CSS Course - 1: Course overview

Course outline:


Basic:

Getting Started -> The Basics -> Diving Deeper -> Selectors & CSS Features -> Practicing the Basics -> Positioning


Advanced:

Backgrounds & Images -> Dimensions, Units & Sizes -> JavaScript & CSS -> Responsiveness -> Styling Forms -> Working with Text & Fonts


Expert: 

Flexbox -> CSS Grid -> Transformations -> Transitions & Animations -> Writing Future-Proof CSS->Sass Introduction


Course Prerequisites:

Basic Web Dev & HTML Knowledge

How to get the Most out of the course

  • Attend classes, lectures
  • Code along & do exercises
  • Debug errors

Tools used in this course

  • Visual Studio Code (download at code.visualstudio.com)
  • Chrome browser

React: Using Ref

class Person extends Component {
    constructor(props) {
        super(props);
        this.inputElementRef = React.createRef();
    }

}

componentDidMount() {
    this.inputElement.current.focus();
    //old approach
    // this.inputElement.focus();
}

render() {
    ...
    <input
      key="k1"
      // old approach
     // ref={(inputEl)=>{this.inputEleemnt=inputEl}}
      ref={this.inputElementRef}
      type="text"
    ...
}

Thursday, September 19, 2019

React: Best practice to setState when setting the value based on previous state

There is another interface to sue

this.setState( (prevState,props)=>{
    return {
        posts: posts,
        counter: prevState.counter + 1
    }
});

Sunday, September 15, 2019

How to obfuscate or minify react javascript source code?


First of all, what is obfuscation of javascript code?

Obfuscation is the deliberate act of creating obfuscated code, i.e. source or machine code that is difficult for humans to understand. It is something similar to encryption however machine can understand the code and able to execute the code.

For example -- Original code:

function hello(name) {
console.log('Hello, ' + name);
}
hello('New user');
After Obfuscation:
eval(function(p,a,c,k,e,d{e=function(c{returnc};if(!''.replace(/^/,String)){while(c--){d=k||c}k=[function(e){return d[e]}];e=function({return'\\w+'};c=1};while(c--){if(k{p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k)}}return p}('3 0(1{2.4(\'5,\'+1)}0(\'76\');',8,8,'hello|name|console|function|log|Hello|user|New'.split('|'),0,{}))
What is minifies source code?
Minification is performed after the code for a web application is written, but before the application is deployed. When a user requests a webpage, the minified version is sent instead of the full version, resulting in faster response times and lower bandwidth costs. Minification is used in websites ranging from small personal blogs to multi-million user services.

Minification also a type of obfuscation here empty spaces will be removed and variables will be renamed.
React minifies the code during the build and generates source maps. JS ends up being sort of obfuscated as a byproduct of minification, not because of secrecy (well, that too, to some extend). That way, the end users are able to load scripts faster than if they were not minified, and you (and everybody else) get to navigate around original code when you (or they) open Developer Tools.

If you take a look in build/static/js directory after the build, there are pairs of .js and .mapfiles. JS files are loaded with your website, and .map files are loaded on demand, when Developer Tools are opened.
To disable sourcemap generation, run your build with GENERATE_SOURCEMAP environment variable set to false.
GENERATE_SOURCEMAP=false npm run build
or
GENERATE_SOURCEMAP=false yarn build
or make it part of build script in package.json
  {
    
    "scripts": {
      
-     "build": "react-scripts build"
+     "build": "GENERATE_SOURCEMAP=false react-scripts build"
    }
  }
If you omit the SOURCEMAP generation, .map files will not end up in production, and your original source code will not be available for anyone (including you).

Friday, September 13, 2019

Useful online coding tools

1. codepen.io
2. jsbin.com 

https://www.creativebloq.com/netmag/top-20-online-coding-tools-10126010






How to self learn programming from youtube tutorial or online courses

We all know there are tons of online resources you can learn at your own pace, such as youtube videos (courses, tutorials, playlists, etc), online courses you purchase from Udemy, O'Reilly, etc; subscriptions like codeakid.com, apexlearning.com, etc, etc, etc...

How do you make good use of these online resources and learn at your own pace and get most out of these resources? I highly recommend you the following:


  1. Code along -- play the videos, code along as the videos, if you need more time, pause the videos and continue, if you miss some part, wind back and replay;
  2. Check source code -- Many of online courses, tutorials provide source code from the author, a lot of time you can download or find on the github, try to download it or fork it into your own repository (I also recommend you learn about the basic usage of github/git for source code control and management)
  3. Participate in Q&A -- Many of the online courses, tutorials (like on yourtube) has views' comment, or online forum for Q&A, participate there, ask your questions, answer others' questions if you know the answer. You learn from participation
  4. Practice, Practice, and Practice -- Think of your own project ideas, and implement these great ideas with the skills you just learned from the online resources, apply your knowledge into these projects

Thursday, September 5, 2019

How to create a WordCloud image with 20 lines of python code

Instruction for Mac OS, you can easily find the windows equivalence.

Pre-requsite:
1. Install python3

  • Follow this link to download the latest python3 OS X package
  • Run the package and follow the steps to install python3
  • Once the installation is done, on your Terminal, run the following to confirm python 3.7.4 is installed
       python3 --version


2. Install pip3

  • Securly download the get-pip.py file from this link
  • From the directory where the file was downloaded to, run the following command in the Terminal
      python3 get-pip.py

Setup:
Install the following package: 
   pip3 install wikipedia wordcloud matplotlib

Python code:
Create a python file name: generatewc.py, and paste the following 20 lines:

import wikipedia
from wordcloud import WordCloud, STOPWORDS
import os
from PIL import Image
import numpy as np
currdir = os.path.dirname( __file__ )
def get_wiki(query):
    title = wikipedia.search(query)[0]
    page = wikipedia.page(title)
    return page.content
def create_wordcloud(text):
    mask = np.array(Image.open(os.path.join(currdir, "cloud.png")))
    stopwords = set(STOPWORDS)
    wc = WordCloud(background_color="pink",
        mask = mask,
        max_words=200,
        stopwords=stopwords)
    wc.generate(text)
    wc.to_file(os.path.join(currdir, "wc.png"))
create_wordcloud(get_wiki("Sichuan cuisine"))

Explanation: What this code does is -
1. first function get_wiki(query) to generate the page content of a given query, for example: "Sichuan cuisine"
2. second function create_wordcloud(text) to generate the word cloud image of the most seen words in the wikipedia page retrieve from the first function
3. the image is saved in the same location of the generatewc.py as "wc.png"

Results:

Monday, September 2, 2019

How to wait for a few seconds then redirect to another page in React


It took me a bit of thinking to make the redirect work smoothly. This is the use case in my react app, users can look at the course details info, and attempt to register a course, if user doesn't log in yet, the registration page should redirect user to a login page, after display a message that user needs to login to register for 5 seconds. Here is what we need to do:

state = {
    redirect: false // add a redirect flag
};

componentDidMount() {
    // only change the redirect flag after 5 seconds if user is not logged in
    if (!auth) {
        this.timeout = setTimeout(() => this.setState({ redirect: true }), 5000);
    }
}

componentWillUnmount() {
    // clear the timeer just in case
    clearTimeout(this.timeout);
}

render() {
    // this is the key:
    // 1. when this is first invoked, redirect flag isn't set to true until 5 seconds later
    // 2. so it will step into the first else block
    // 3. display content based on auth status, NOT based on redirect flag
    // 4. 5 seconds later, redirect flag is set to true, this is invoked again
    // 5. this time, it will get into the redirect block to go to the sign in page
    if (this.state.redirect) {
        return <Redirect to="/signin" />;
    } else {
        if (!auth) {
            return (
                <div className="center">
                    <h5>You need to login first to register a course</h5>
                </div>
            );
        } else {
            return <div>Registration Page</div>;
        }
    }
}