All articles

Glossary

Category:
Emacs term Term for normal people
A- C-x 8
Buffer An opened file or other thing like game, help, Messages, etc.
Copy as kill Copy.
Faces Fonts.
Frame Emacs window.
Fringes Margins on left, right or both sides of the window.
Kill Kill buffer = close buffer. Kill text = cut text.
Meta key Alt key.
Window Panel where buffers can be displayed.
Yank Paste (like copy and paste).

map vs pluck

Category:

Both methods return the same output (an array of strings).

Article.all.map{|a| a.title}
Article.pluck(:title)

But they do that in different ways.

SQL query generated by all:

SELECT "articles".* FROM "articles"

It fetches all atributes, then it converts the collection with map method.

SQL query generated by pluck (or .all.pluck):

SELECT "articles"."title" FROM "articles"

pluck is faster.

Depth First Search

Category:

The graph is given.

An image of graph

Graph as a hash:

graph = {
    0 => [1,9],
    1 => [0,8],
    2 => [3],
    3 => [2,4,5,7],
    4 => [3],
    5 => [3,6],
    6 => [5,7],
    7 => [3,6,11,10,8],
    8 => [1,7,9],
    9 => [0,8],
    10 => [7,11],
    11 => [7,10],
    12 => [],
}

Algorithm code with a loop instead of recursion

def dfs(graph, start_node)
  current_node = start_node
  stack = [start_node]
  visited = [start_node]
  loop do
    p "stack: #{stack}"
    p "visited: #{visited}"
    unvisited_neighbour = graph[current_node].find do |node|
      !visited.include?(node)
    end
    if unvisited_neighbour
      current_node = unvisited_neighbour
      visited << current_node
      stack << current_node
      next
    else
      stack.pop
      current_node = stack.last
      break unless current_node
    end
  end
end

dfs(graph, 0)

String vs Symbol

Category:

String

Is a sequence of bytes. The text is converted into those bytes usually by UTF-8 encoding.

String object are mutable.

Symbol

Symbol objects are immutable.

Same symbols, for example :book and :book, are in fact one object that is shared globally in all contexts for the duration of a program’s execution.

Thanks to that sharing symbols costs less memory than strings, but they cannot be collected by Garbage Collector once created.

Comparing symbols is quicker than comparing strings.

Datatypes in Postgresql and Rails

Category:
Postgresql type name in Rails Rails type
text text String
box box String
polygon polygon String
circle circle String
timestamp datetime ActiveSupport::TimeWithZone
time time ActiveSupport::TimeWithZone
date date Date
json json String
point point ActiveRecord::Point
boolean boolean TrueClass/FalseClass
path path String
xml xml String
jsonb jsonb String
bit bit String
inet inet IPAddr
float float Float
daterange daterange Date…Date
tsrange tsrange Time…Time
integer integer Integer
money money BigDecimal
uuid uuid String
numrange numrange BigDecimal..BigDecimal
decimal decimal BigDecimal

Directed graph by "has_many through"

Category:

My model will be called Node, and I want to connect them with other nodes in a way that is called “directed graph”.

an image of a directed graph

An example of a directed graph from Wikimedia Commons.

Each node can have zero, one or many children, and zero, one or many parents. To do this I need an another model which will represent connections between nodes. I assume that Node model already exists and I will create the NodeConnection model by generating a scaffold.

rails g scaffold NodeConnection child:references parent:references --no-stylesheets

Nodes will be connected with other nodes, but I can’t make two column with the same “node” name. Instead of that the names are “child” and “parent”. I think the same result can be achived by child_id:integer parent_id:integer instead of child:references parent:references.

An auto-generated migration is OK, I don’t need to add anything at this moment, so I can migrate.

rake db:migrate

The associations in the NodeConnection model file should have additional arguments.

class NodeConnection < ActiveRecord::Base
  belongs_to :parent, class_name: 'Node', foreign_key: 'parent_id'
  belongs_to :child, class_name: 'Node', foreign_key: 'child_id'
end

And an assiociation in the Node model file:

class Node < ActiveRecord::Base
  has_many :parent_connections, foreign_key: 'child_id', class_name: 'NodeConnection'
  has_many :parents, through: :parent_connections

  has_many :child_connections, foreign_key: 'parent_id', class_name: 'NodeConnection'
  has_many :children, through: :child_connections
end

For each node there are now methods parents and children avaliable.

Cron

Category:

Crontab commands

Edit user’s crontab

crontab -e

List user’s crontab

crontab -l

Delete user’s crontab

crontab -r

Crontab examples

On every minute

* * * * * /scripts/foo.sh

On every 5 minutes

*/5 * * * * /scripts/foo.sh

At midnight on first day of every month

0 0 1 * * /scripts/foo.sh

On every 30 seconds

* * * * * /scripts/foo.sh
* * * * * sleep 30; /scripts/foo.sh

At night on last day of every month

0 3 28-31 * * test $(date -d tomorrow +%d) -eq 1 && /scripts/foo.sh

Configuring Ubuntu server

Category:

Upgrade the system

apt update
apt upgrade

Show the current timezone ~~~timedatectl~~~

Change it to UTC

timedatectl set-timezone UTC

Change root password

passwd

Delete user ubuntu created by who knows

deluser --remove-home ubuntu

Add a new regular user

adduser yournickname

Add it to the sudo group.

usermod -aG sudo yournickname

Switch to that user

su yournickname

Install your favourite text editor

sudo apt install emacs-nox

Install htop

sudo apt install htop

Create a ssh key (with a passphrase) for pushing stuff to github

ssh-keygen -t rsa -b 4096 -C "user@host"

Add the public key to the SSH keys in github/bitbucket account settings.

Postgresql: Basic Workflow

Category:

Create a role

Login to psql

psql -U postgres

Check existing roles

SELECT * FROM pg_roles;

Create the role

CREATE ROLE name WITH CREATEDB LOGIN PASSWORD 'secret'

Create a database

createdb -E UTF8 -U rolename dbname_production

Delete a database

dropdb -U postgres dbname_production

Restore database from sql file

psql -U rolename -d dvname_production < /root/db_backups/dbname.sql

Save database to sql file

pg_dump -U rolename dbname > filename.sql