Learning with Python: Class Object, Inheritance and Comments

I’m going to start learning python as a side hobby. So with all upcoming python related topics will have the title “learning”. Anyways the syntax of python is fairly straight forward but there are some of those bits that is not “fairly” straight forward. Like declaring a class object.

In python  depending on the version , there is an old style class and new style class. Old style don’t have inheritance but new style do.

# old style
class myClass():
  pass
# new style
class myClass2(Object) # all class inherits Object
  pass
# inheritance
class myClass3(myClass, myClass2)
  pass

The new style class in here has “Object” as base class. All class inherits from Object.

Thats it for class.

By the way comments in python is # and multi-line comments is a little weird but like this

# One line comment
"""
 Im a multi-line comment, and please dont indent this block as it becomes an error.
"""

TTY – TeleTYpewriter on Linux

I came accross a tutorial talking about TTY command in linux. Basically its pertaining to terminals in the container. Lets drill down the terminology first.

– Terminal is just a term use pointing to a dumb machine connected to the main computer. Consist of a display and a keyboard.

– Console is use to describe a TERMINAL physically connected to the computer. Let say like a personal computer connected with a keyboard and monitor. Or like xbox console and ps4.

– TTY and PTY . TTY is technology that handles input and output to a display and the program it executes.It is a virtual console refer above to communicate with the host. Most terminal in linux is PTY pseudo-tty. Meaning a fake or technology that acts similar to tty.  Ssh terminal is type of PTY.

Using command tty, shows device name you are currently on. tty0 usually refers to your current terminal.

What are virtual terminals and when to use it?
“A Virtual Terminal is a full-screen terminal which doesn't run inside an X window (unlike the terminal window on your graphical desktop). Virtual terminals are found on all GNU/Linux systems, even on systems which don't have a desktop environment or graphical system installed.

Virtual terminals can be accessed on an Ubuntu system by pressing Ctrl+Alt+F1 till F6. To come back to the graphical session, press Ctrl+Alt+F7.“

So all in all my understanding is when you SSH to a server, you are using a pseudo-tty to the server giving you a virtual terminal to manage the machine. This also gives you a interactive shell. When you spawn a connection to sshd, it mounts a /dev/pts/* dynamically. Making it look like a real terminal is connected or physical device. And you can use this to refer to your connection, by using tty command on your terminal. Pseudo because you are emulating tty functionality, instead of actually connected to the server physically.

In the olden days terminal are real physical device connected to the pc. Linux didnt have a GUI before. To manage it, you remote to it and creates a “virtual terminal” or “virtual console”  like a real physical device terminal.

The tty 1-6 ctrl + alt + f1-6 are basically the same as a virtual console or terminal. The f7+ keys shortcut is when you have a gui terminal on the server. Gui terminal refers to let say, your ubuntu is your server. It can open a terminal in its window as you do. Then pressing keys above f(1-6) opens tty terminal without the gui as if you are back in a gui-less server and use your keyboard and monitor to manage it. Take note pressing these keys only works when you are physically logged-in on the console. But your terminal is still virtual, see below.

Additional info, when you are executing a command to connect to your server using ssh -t or -T flag remotely.

-t means to provide an interactive terminal or TTY terminal to execute commands.

-T to disable any interactivity.

Upon saying this. When you open a terminal connection via ssh. You most likely want tty/interactivity, that can execute commands etc. tty is just the technology that creates this connection between your remote pc keyboard to a server. A linux box by itself is a console. Connect a keyboard and a monitor to it and will generate a virtual console or terminal to administer it.

Taken from red-hat website

https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/6/html/installation_guide/sn-guimode-virtual-consoles-ppc

“A virtual console is a shell prompt in a non-graphical environment, accessed from the physical machine, not remotely. Multiple virtual consoles can be accessed simultaneously.”

BLOG: NodeJS – Server Side Rendering

Its a technique in the web development world most of your front end rendering(javascript) is rendered by the server, hence the title.

Basically what its saying is most front-end javascript processing happens in the browser. But with server side rendering, your javascript is pre-compiled and delivered with values pre-populated by the server stack. In this case NodeJS.

Im not sure how it works on Apache server yet. Or any other platform stack that does not use javascript. Here is a video about React – Server side scripting works using express/webpack combination.

YAML

Meet Uncle Yammy, or Yamel or Yamil?

I been using JSON and XML as my standard go to objects for as long as I can remember. They are both very capable. But I think I need to give YAML a try too as its good for storing very simple to very complex representation of your data.

The syntax? [ my_yaml.yml ]

PROPERTY_NAME: VALUE

Thats it. Yaml is also structured with indentation. Its actually pretty straight forward. Theres also parsers available already to use yml type files.

Please see video below by Giraffe Academy for more syntax specification

Docker & Docker-compose

So here we are in the DevOps world. Well not quite, so what is this docker thing here that will help us be productive as a developer?

Docker is like a virtual machine but is’nt. It is an image or an instance of an mini operating system that act as a host to your application and what not. This image or template creates a container that uses this template to create an environment.

You can either use Dockerfile or Docker Compose (yaml file) . Dockerfile lets you create your custom image. Docker compose manage multiple docker images to simplify the commands.

Here is a link to a cheat sheet for Dockerfile:

https://github.com/wsargent/docker-cheat-sheet

Basic Dockerfile configuration:
http://blog.flux7.com/blogs/docker/docker-tutorial-series-part-3-automation-is-the-word-using-dockerfile

ARG MY_VARIABLE=hello world (can be reference inside dockerfile by eg. FROM python:${MY_VARIABLE})
FROM: <imagename>[:<tag or version>] (You can have multiple from. Means multiple container. If you omit the tag , you get latest version)
MAINTAINER: <author name>RUN: <command to run for extra provisioning>
ADD: <source from build context local path> <destination in the container> (add can be used to extract files from path similar to COPY)
COPY: <source from local machine> <destination> Always use copy for copying from local machine(windows) relative to the build context to container
ENTRYPOINT: <command to run after container starts eg: ping>
CMD: <command to feed to entry point>
(Difference between CMD and ENTRYPOINT https://stackoverflow.com/questions/21553353/what-is-the-difference-between-cmd-and-entrypoint-in-a-dockerfile?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa )
WORKDIR: <working directory for RUN, ENTRYPOINT and CMD>
ENV: <key> <value> set environment variable in the container
VOLUME: [‘/var/www’]  or “docker create or run -v source:destination” (Lets  you mount a directory to the host machine, this persist even the container is removed.This volume can be used by the container to read and write to , when the container is stopped or removed the data volume in the host will still be there. The HOST(path):CONTAINER(path) only applies in the command line)

Volume is a bit confusing to wrap your head around at least for me , please see this link: https://www.digitalocean.com/community/tutorials/how-to-work-with-docker-data-volumes-on-ubuntu-14-04

Basic docker-compose yaml config
Full Reference:

https://docs.docker.com/v17.09/compose/compose-file/#compose-file-structure-and-examples

Start with:
VERSION: 3
SERVICES:
___[SERVICE NAME – 1]:
______image: (image name) If BUILD is not specify this will just download the image from the internet.
______build: [context or below]
________context: ./dir
________dockerfile: Dockerfile-alternate
________args:
___________buildno: 1 [accessible in your dockerfile as $buildno]
______command: [“bundle”, “exec”, “thin”, “-p”, “3000”] (overrides the CMD in your dockerfile)
______ports: (“host:container”)
________  – “3000:8000”
______links:
________ -[service-name] ( any service name that this service links to)
______depends_on:
________ -[service-name] ( any service this service depends on)
______expose: (exposes/open a port on a container , can be use for other application that is serve using this port)
________ – “3000” (port numbers)
______networks: (group it belongs)
________- Network1
networks: (list of networks/groups the image belong)
______- Network1
These are the basic simplification configurations for docker. See full reference above for more information. Take note there is also a DEPLOY option only for docker version 3. This deploy option is for deploying to docker swarm which is a little bit advanced for me at the moment.

Common mistakes setting up docker:


https://runnable.com/blog/9-common-dockerfile-mistakes

 

Programmer Code Guidelines

Been reading lots lately and never actually put into writing how I write my code. First thing first, variety of things and habits what you should keep in the back of mind.

Functions and Methods I’ve been writing functions and methods and never in my mind try to stop between the difference. Here is what I’ve learn about functions

  • Functions should be stateless and only cares about the argument being passed.  Can return a value or just do any work. Mostly use for utility helpers.
  • Methods are usually part of an object. When methods are called it should change a state or depends on the state the object belongs to.

Arguments pass as Copy or Reference When passing an argument to a method or function, should we consider passing a value or a reference? Passing a value means creating a copy of the argument that can increase memory usage, passing a reference avoid this. This is basically useful when passing a resource reference value.

Modularity Write codes in a modular way, this decreases headaches of debugging later on. Making it modular allows for add ons and modules to be added later on. Modularity is separation of functions and logic  in your code. If you can have separate files for each function is ideal.

Naming Convention make sure to adhere to a convention in declaring functions , objects and variables. I have decided to use this convention for general programming, although different conventions works for different  languages. For C# and windows related code, function name starts with capital letter. And private property starts with “_” underscore. For other things I use, “_” underscore for variables and camel casing for functions. Classes starts with capital letter.

.HTACCESS

We all know how .htaccess change the way you access a particular URL in your web server. Mainly use for apache web servers. When starting one always start with

RewriteEngine On 

Options +Indexes = Allows folder to be indexed.
ErrorDocument 404 /notfound.html = Allow to set error page.
401 – Authorization Required
400 – Bad request
403 – Forbidden
500 – Internal Server Error
404 – Wrong page

RewriteBase / = change the context as root folder
RewriteCond %{THE_REQUEST} !^[A-Z]{3,9}\ [a-zA-Z0-9\.\+_/\-\?\=\&]+\ HTTP/ [NC]  = Like an if statement if true continue below
RewriteRule .* – [F,NS,L] = L means stop, F causes forbidden access 403 page, NC not case sensitive, NS no sub request if page is included, R redirection. Rewrite rule only gets the page.

QSA allow to be included to query string

When the replacement URI contains a query string, the default behavior of RewriteRule is to discard the existing query string, and replace it with the newly generated one. Using the [QSA] flag causes the query strings to be combined.

Consider the following rule:

RewriteRule "/pages/(.+)" "/page.php?page=$1" [QSA]

With the [QSA] flag, a request for /pages/123?one=two will be mapped to /page.php?page=123&one=two. Without the [QSA] flag, that same request will be mapped to /page.php?page=123 – that is, the existing query string will be discarded.

Enter VS Code on Windows

Hi I have been a fan of sublime text for a while now. But also tried different IDE available in the community. Recently been trying ATOM, but it seems a little laggy at times. Anyways here are my top shortcuts I used for Visual Studio Code editor:

[ ctrl + , ] Open settings for configurations
[ctrl + `] Opening terminal console
[ctrl + d] Select next occurence [ctrl + u] deselect back
[ctrl + f2] Select all occurence
[ctrl + k ctrl + c] Add line comment
[alt + shift + down or up] Duplicate line down or up
[ctrl + p] Open command palette and find files quick
[ctrl +  “[” or “]” ] Moves your current line via tab
[ctrl + shift + f ] Find text in files
[ alt + arrow left or right ] Go back and forward
[ ctrl + shift + \ ] Go to matching bracket
[ F12 or CTRL + F2  or ALT F12 ] Go to definition and implementation, peek definition
[ F8 ] Go to the next error
[ Ctrl + W ] Close the current window
[ alt + shift + left or right ] Shrink or grow selection on brackets
[ ctrl + alt + up or down ] Add a cursor for multiple editions

2018 © Ideas, designs and algorithms