All posts by ernani

Learning 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-machine & 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

Docker command line reference.

https://docs.docker.com/engine/reference/commandline/docker/

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>
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 for eg: ENTRYPOINT [“ping”] >
CMD: <command to feed to entry point> So from above entry point of “ping”. If you have a command like this eg: CMD [“localhost”] then the executing command will be “ping localhost”

This is a good description over the difference between ENTRYPOINT and CMD: The ENTRYPOINT specifies a command that will always be executed when the container starts. The CMD specifies arguments that will be fed to the ENTRYPOINT

(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 )
You can also check the difference between RUN,ENTRYPOINT and CMD in here: http://goinbigdata.com/docker-run-vs-cmd-vs-entrypoint/

RUN: <cmd to call> Its normally used for installing packages.
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

To build the image, go to where your dockerfile folder is located. And type the command: “docker build .”  take note of the dot after the build word. This is specifying where your dockerfile is located. In our case we are in  that folder.

The basic command to start and run docker container by issuing:

docker start [docker container] This will start an already existing container. To create a new container you must build the image and do docker run etc.
docker exec [options] [docker container] [cmd]  This is when you already have a container and running and you need to execute a command within that container. Usually used for logging into the shell. eg: docker exec -it myalpinecontainer sh (sh for alpine containers otherwise bash)

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

Docker-machine

Docker machine is created so old mac and windows can use docker. The machine that is created (VM) will hold the docker engine that will power up our containers. I normally use docker-machine as I got a laptop that has Windows Home only.

Tips#1: If you like to specify where your docker-machine files will live. Create an environment variables called “MACHINE_STORAGE_PATH” and set it to the location you like.

Then try creating a new machine if you dont already have one. The default this is normally the default machine to use by typing “docker-machine create default“.

Tips#2: If you like to mount a (local) folder to your docker-machine.
Check link below:
http://support.divio.com/local-development/docker/how-to-use-a-directory-outside-cusers-with-docker-toolboxdocker-for-windows

Note: Tip#2 to persist the volume mounting of your OS to the HOST OS. In the boot2docker folder create a file named “bootlocal.sh” and add the commands:

mkdir /home/docker/projects
sudo mount -t vboxsf -o uid=1000,gid=50 share_name_from_virtualbox /home/docker/projects

Tips#3: When starting your “docker-machine start name” and the certificate is messed up. Just regenerate it by typing “docker-machine regenerate-certs“. Then restart your docker-machine

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 VSCode on Windows

* Updated (04/09/2019)

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:

Most Used shortcuts (Default)
[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 + a ] Adds a multi-line comment
[ctrl + p] Open command palette and find files quick
[ctrl + shift + f ] Find text in files
[ctrl + shift + \ ] Go to matching bracket
[alt + shift + down or up] Duplicate line down or up
[alt + shift + left or right ] Shrink or grow selection on brackets

Extra
If you use the keybindings below and disabled the closing of windows shortcut ctrl+w and ctrl+shift+w , another extra shortcut I used are:

 alt +  [    – Jumps to matching bracket “{}”
 alt + ]     – Jumps to matching tag “<tag></tag>”
 ctrl + w  – Selection grow inside brackets
 ctrl + shift + w – Selection grow inside tags.

Secondary Shortcuts
[ ctrl + , ] Open settings for configurations
[ctrl +  “[” or “]” ] Moves your current line via tab
[ alt + arrow left or right ] Go back and forward
[ F12 or CTRL + F2  or ALT F12 ] Go to definition and implementation, peek definition
[ F8 ] Go to the next error
[ ctrl + alt + up or down ] Add a cursor for multiple editions
[ctrl + k + s ] Open keyboard shortcut

Tips:
* Disable ctrl + w and ctrl + shift + w – these closes the current window and application which is really annoying and we can really use the shortcut combination.

Life quality plugins
Auto Rename Tag: Lets you rename your opening and closing tag simultaneously.

Bracket Pair Colorizer: Makes it easy to see where those bracket ends in your code.

Highlight Matching Tag: You can visually see the highlighted tag both open and closing tag.

Beautify by hookyqr: Nothing like easily format your JS/HTML/CSS in one fell swoop of the keyboard.

Technology Helpers
ReactJS Code Snippets: Easily create React code snippet for eg: rcc, gives you building boy of a react component. Redux snippet is also included.

Cordova Tools: If you are developing with Apache Cordova , this one is a must have.

WordPress Snippet: When working on snippets theres nothing like having a code hinter, snippets and auto-completion at hand.

Configuration Settings

Use this in your settings.json file.

{ “files.autoSave”: “off”, “editor.tabSize”: 2, “editor.detectIndentation”: false, “breadcrumbs.enabled”: true, “explorer.confirmDragAndDrop”: false, “explorer.confirmDelete”: false, “emmet.triggerExpansionOnTab”: true, “emmet.includeLanguages”: { “php”: “html” }, “emmet.showSuggestionsAsSnippets”: true, “editor.snippetSuggestions”: “top”, “window.zoomLevel”: 0, “typescript.tsserver.log”: “verbose”, “javascript.updateImportsOnFileMove.enabled”: “always”}

Use this in your keybinding.json file

[ { “key”: “ctrl+shift+u”, “command”: “editor.action.transformToUppercase”, “when”: “editorTextFocus” }, { “key”: “ctrl+shift+l”, “command”: “editor.action.transformToLowercase”, “when”: “editorTextFocus” }, { “key”: “ctrl+shift+alt+l”, “command”: “editor.action.selectHighlights”, “when”: “editorFocus” }, { “key”: “ctrl+shift+l”, “command”: “-editor.action.selectHighlights”, “when”: “editorFocus” }, { “key”: “shift+alt+right”, “command”: “-editor.action.smartSelect.grow”, “when”: “editorTextFocus” }, { “key”: “ctrl+w”, “command”: “editor.action.smartSelect.grow”, “when”: “editorTextFocus” }, { “key”: “ctrl+shift+w”, “command”: “editor.emmet.action.balanceOut” }, { “key”: “alt+]”, “command”: “editor.emmet.action.matchTag” }, { “key”: “alt+[“, “command”: “editor.action.jumpToBracket”, “when”: “editorTextFocus” }, { “key”: “ctrl+shift+\\”, “command”: “-editor.action.jumpToBracket”, “when”: “editorTextFocus” },]