Local MySQL connection refused

mysql -u root
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

Can be resolved with:

mysql -u root -h 127.0.0.1
Welcome to the MySQL monitor.  Commands end with ; or \g.

Postgres: How to add an extension to a certain database

If you get errors like this:

PG::InsufficientPrivilege: ERROR:  permission denied to create extension "btree_gist"
HINT:  Must be superuser to create this extension.

You need to install the extension as a user with sufficient rights.

  1. Open the postgres console as a priviledged user:
    sudo -u postgres psql
    
  2. Afterwards, switch to the databse which needs the extension to be installed:
    \connect my_database
    
  3. Then you can install the extension:
    CREATE EXTENSION IF NOT EXI...
    

How to analyze database statements in a Rails app

Marginalia is a gem that will help you to find out where in your code database queries are triggered.

After adding it to your Gemfile, add a config/initializers/marginalia.rb with the following contents:

Marginalia::Comment.components = [:line]
Marginalia::Comment.prepend_comment = true

And in your log you will see the file and line number before each database statement.
If you are only interested in writing statements, you can grep through your log like this:

tail -f log/te...

Easily compare performance of two implementations

Sometimes you have to decide between two or more ways on how to implement something. As developer, we make such decisions all day log. If you write code that has to be fast (e.g. because it runs often), comparing the performance of different implementations is key.
Ruby has a handy gem for that: benchmark-ips. Here's how to use it.

Gemfile:

gem "benchmark-ips"

Rails console or irb:

require 'benchmark/ips'

str = "gid://glibberish/Glib/12345"
Benchmark.ips do |x|
  x.report('r...

Make Postgres dump from Heroku human-readable

When dumping your Heroku Postgre database (with heroku pg:backups:capture --app my-app and heroku pg:backups:download --app my-app), it will result in a binary dump.
If you want your contents to be human-readable (e.g. for moving to a different database system like MariaDB or SQLite), you can transform the file with pg_restore:

pg_restore -f output.sql infile.dump

Note that there is also a flag to omit the schema and output only the data of the dump: --data-only. This may be useful if you can restore the schema otherwise, ...

Define multiple (similar) hosts with one ssh config entry

Instead of

Host host1
    HostName host1.namespace.com
    ForwardAgent yes
    Port 1234
    User judith
    IdentityFile /Path/to/file
    
Host host2
    HostName host2.namespace.com
    ForwardAgent yes
    Port 1234
    User judith
    IdentityFile /Path/to/file
    
Host host3
    HostName host3.namespace.com
    ForwardAgent yes
    Port 1234
    User judith
    IdentityFile /Path/to/file

You can just add one entry and work with a placeholder:

Host host1 host2 host3
    HostName %h.namespace.com
    ForwardAgent yes
   ...

List of free E-Books about Ruby

There is a whole list of e-books about ruby on rubyandrails.info! Some of them are even free and you can filter it. How nice is that?!

Some honorable mentions:

Ruby Science

The book consists of a collection of code smells and anti-patterns and how to refactor them. Very important for everyone working in a team on a l...

How to customize your Pry prompt to include your application name and Rails environment

Every developer loves to individualize prompts and play around with the cool features. Or at least... I do. Here's how to customize your Pry prompt, if you're using Pry in your rails console.

Then add the following to config/initializers/pry.rb:

if defined?(Pry)
  Pry::Prompt.add(:custom, 'Custom Prompt with app name and environment') do |context, nesting, pry, sep|
    formatter = Pry::Helpers::Text

    app_name = begin
      name ...

How to always load Pry in irb and Rails console

I really love using binding.pry as my debugger because of Pry's ls command.

If you want to always load pry in your irb and rails console, just add a .irbrc to your project root with the following lines:

begin
  require "pry"
  Pry.start
  exit
rescue LoadError
  warn "=> Unable to load pry"
end

And if you're using Rails and still want to be able to call reload! or helpers on the rails console, also add a config/initializers/pry.rb with these contents:

if defined?(Pry)
  require "rails/console/app"
  requi...

RSpec: Properly clean up your before(:context)` blocks

Using before(:context) is considered bad practice, because it's so easy to forget that you have to clean up all database changes done in the hook yourself. Usually RSpec uses transactions and just rolls back your changes after every block. This is really convenient, because each test just gets a blank slate of the database. However, this is not possible if your before block spans a whole context.
Having before(:context) blocks can lead to random failing of other tests - for example when the before(:context) creates objects in the dat...

Rubymine database explorer: How to stop a long running query after you lost connection

If you started a long running query that you want to abort, you can use the red "Cancel running queries"-stop button.

If you started a long running query and lost connection, the button may not be available any more. In this case (after reconnecting) you can use the SHOW PROCESSLIST; SQL-Statement get a list of the running processes you started.
If you identified your process, use the [kill statement](https://dev.mysql.com/doc/refman/5.7/en/kill.h...

Bash shell becomes inactive on Ctrl+S

tl;dr: The linked article describes what happens and how to bring your shell back to live:

you need to hit Ctrl+Q to resume output again.

Find where a javascript function is defined (Chrome)

On the developer console, run the function without (). Then right click on the function name and choose "show function definition":

Image

Linux command line: Search and replace in multiple files

The examples use ripgrep, which you probably have to install before you can use it. See the last example for how to do the same with grep.

rg -l <search-term> | xargs sed -i 's/<search-term>/<replace-term>/g'

e.g.

rg -l float-right | xargs sed -i 's/float-right/float-end/g'

rg -l will only print the file in which the search term is found.

Of course this also works with a regular grep instead of ripgrep:

grep l '<search-term>' | xargs sed -i 's/<search-term>/<replace-t...

Bookmarklet to increase playback speed on Audio Elements without a control for that

If websites use raw audio or video tags, you will see some basic controls for them, but usually, they do not include the control for changing the playback speed.

Since I usually want to playback audio or videos faster, I created a bookmarklet to change the playback speed for all elements.
This will open a small dialog where you can choose the speed:

Image

To use, it, just add a new bookmark, give it a speaking name and copy the following code into the URL field:

javascript:(() => {
  va...

Linux: Easily change screen orientation

My notebook is a convertible and also has a stylus as input. When using the pen, I like to use the laptop screen in portrait format instead of landscape. Then the screen format is more similar to A4 paper, which helps a lot if you're taking hand-written notes on PDFs. Here's how to easily change the screen orientation via script.

xrandr is a linux command line tool for managing screen output (e.g. size, orientation).

Set the screen direction with xrandr --orientation <normal, inverted, left or right>

e.g.

xrandr --orientation...

Dropbox download url for raw contents

Instead of

https://www.dropbox.com/s/e3f7geskg4byntn/my_file.txt?dl=0

use

https://dl.dropboxusercontent.com/s/e3f7geskg4byntn/my_file.txt

Therefore, replace www.dropbox.com with dl.dropboxusercontent.com.

How to include helpers in RSpec for different use cases

module FixtureHelper

  def fixture_base_path
    Pathname.new(File.expand_path('../../../fixtures', __FILE__))
  end

  def fixture_fake_repo_path
    Pathname.new(File.expand_path('../../../fixtures/fake_repo', __FILE__))
  end

end

RSpec.configure do |config|
  config.extend(FixtureHelper) # <--- make it available outside of an example (e.g. for `let`)
  config.include(FixtureHelper) # <--- make it available inside an example (e.g. `it` block)
end

require it in spec_helper.rb.


module SpecialHelper
  
  def ra...

Permission problems with single folders on a Synology NAS

I use my Synology NAS as a storage that is accessed from Windows and Linux.
On Linux, I mount it with this command:

sudo mount.cifs -v -o username=judith,uid=1000,gid=1000 //<IP address>/Subjektiv /media/judith/subjektiv/

and in general that works great, as expected.

I only encountered some strange behaviour for certain, very old folders. In the linux system, it seemed like the permissions on the folder are correct, yet I still could not change any files in that folder:

 06:45:17 /media/judith/subjektiv/Buntes/Web/ALT >stat ...

Upgrade Sprockets 3 to 4 in a Rails project

There's a update guide at https://github.com/rails/sprockets/blob/master/UPGRADING.md

In short, must replace Rails.application.config.assets.precompile entries with link statements in Sprockets' manifest.js file.

Example: app/assets/stylesheets/frontend/all.sass and app/assets/stylesheets/backend/all.sass should be precompiled.

Sprockets 3:

Rails.application.config.assets.precompile += %w[
  backend/all.css
  frontend/all.css
]

Sprockets 4 manifest.js:

//= link_tree ../images
//= link backend/all.css...

How to install fonts on Ubuntu 20.04

  1. Download the file(s) (OTF / TTF format)
  2. Move them to ~/.local/share/fonts/
  3. Run fc-cache -f -v to make them available
    -f: Force re-generation of apparently up-to-date cache files, overriding the timestamp checking.
    -v: Display status information while busy.

Bash Script to add bookmarks to PDFs

This uses pdftk.

#!/bin/bash

file=$1
text=$2

if [ -z "$file" ] | [ -z "$text" ]; then
  echo "Usage: sh script.sh file.pdf 'text for bookmark'"
  exit 1
fi

echo "File:    $file"
echo "Text:    $text"

outfile=$("basename" "$file" ".pdf")_mit_Inhaltsverzeichnis.pdf
echo "Outfile: $outfile"

data=$("pdftk" "$file" "dump_data")
#echo "$data"
#echo 

new_part=$(cat << EOF
BookmarkBegin
BookmarkTitle: $text 
BookmarkLevel: 1
BookmarkPageNumber: 1
EOF
)
#echo "$new_part"
#echo

new_data="$data""\n""$new_part"
echo "$new_data" > new_data....

How to extract JPG image from PDF on the linux command line

Prerequisite: sudo apt install poppler-utils (was already installed on my machine)

pdfimages -j input.pdf output_dir/

-j: Save as JPG

How to create PDF from JPG image on the linux command line

Prerequisite: sudo apt install img2pdf

img2pdf -o output.pdf --pagesize A4 image_1.jpg  image_2.jpg