Today I Solved

Add git branch name to bash prompt
Add the following lines to your ~/.bash_profile file

parse_git_branch () {
  git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}
export PS1="\u@\h \[\033[32m\]\w\[\033[33m\]\$(parse_git_branch)\[\033[00m\] $ "


It works by editing the PS1 (Prompt string 1) variable.
2016-9-9
bashgitlinux
Ammend a commit's author

$ git commit --amend --author="author <author@example.com>"

2016-09-25
git
Ansible register and show variables

- name: Register what groups I am in
  shell: groups
  register: usergroups

- name: Show what groups I am in
  debug: var=usergroups.stdout

2018-9-24
ansible
Use babel-eslint to support async syntax

$ npm install eslint@4.x babel-eslint@8 --save-dev

Markdown preview in Visual Studio Code
Open markdown preview to the side with Ctrl+K then press V
2017-11-16
vscodemarkdown
Copy only newer or nonexistent files

$ cp -u

2016-9-9
linux
performance.now()

t0 = performance.now();
// doSomething();
t1 = performance.now();
console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.");

2018-1-19
javascript
Validate nginx conf files before restarting

$ nginx -t

2016-9-16
javascript
Concurrently
Use concurrently to start both the frontend server and backend server.
In package.json:

"start": "concurrently \"command1 arg\" \"command2 arg\""

2018-1-31
javascriptnode.js
Write common characters in linux

`  shift + u + 60
‒  shift + u + 2012
✔  shift + u + 2714
á  shift + u + E1
é  shift + u + E9
í  shift + u + ED
ó  shift + u + F3
ú  shift + u + FA
ñ  shift + u + F1

2017-11-5
linux
Change the time in linux

# date -s "9:06:10"

2017-10-11
linux
Erase one word backwards in the linux shell
Press Ctrl+W
2016-9-4
linuxshell
List all event listeners
In the console, write:

getEventListeners(document)

2018-5-13
javascriptdom
Install only dependencies, not devDependencies

$ npm install --only=production

To install node_modules in a non-default location
With the command line, you can use the --prefix option

With ansible:

- name: APP Install node_modules on the parent directory for sharing
  become: yes
  become_user: "{{ userweb }}"
  become_method: sudo
  shell: npm install {{ appdir_build }} --prefix={{ appdir_build }} --home=/opt/kanban


With the shell:

$ sudo su -s /bin/bash app-web -c 'npm install /opt/kanban/build --prefix=/opt/kanban/build --home=/opt/kanban'

Change directory for a particular command only
Use parenthesis and the boolean "AND" operator (&&):

(cd /var/log && cp -- *.log ~/Desktop)

2016-9-7
linux
Disable chrome's "Translate this page" prompt

<meta name="google" content="notranslate">

2018-9-5
chromehtml
git diff between repo file and work directory file

$ git diff HEAD:full/path/to/foo full/path/to/bar

2016-9-14
git
panes vs subwindows vs modals
Subwindows: Float freely and the user can freely resize, position, maximize, restore and close them

Panes: Their position is preset, and the user can adjust their relative sizes by dragging the sash between them.
2017-9-18
ui
Prevent chrome from requesting your keyring password
Add the following parameter to your chrome launcher

"runtimeArgs": ["--password-store=basic"]

2018-9-5
chrome
"Can't upload zip modules to prestashop"

$ aptitude install php5-pclzip zip

2017-6-19
phpzip
Enable Ctrl-Arrow for moving word by word in bash
Add the following lines to ~/.inputrc

"\e[1;5C": forward-word
"\e[1;5D": backward-word

2017-6-19
linuxbash
Get the last segment of a url

new URL(window.location.href).pathname.split('/').pop()

2018-9-17
javascripturl
Print to screen all text files found

$ find . -ipath "*tasks/*.yml" -printf "\n\n\n\n%p\n" -exec cat {} \;

2016-9-4
linuxshellfind
Send json via post method with curl

$ curl -X POST -H "Content-Type: application/json" -d '{"key":"val"}'

2016-9-30
curl
Issuing a command as a user with no shell

$ sudo su -s /bin/bash -c 'psql < ~/kanban/ddl/001.0001.sql app' app-web

More examples:

$ sudo su labmin-web -c "(cd /home/labmin-web/labmin/server; psql labmin-db labmin-web < data.sql)" -s /bin/bash
$ su -s /bin/bash -c '/path/to/your/script' testuser
$ sudo su -s /bin/bash -c 'pm2 log' app-web
$ sudo -u apache whoami
$ sudo su -s /bin/bash -c 'psql app < /home/app-web/librusados/ddl/001.0001.sql' app-web

2016-9-30
linuxsu
Setting up a parser that understands dynamic imports
"dynamic import unexpected token"
In your vscode settings:

"standard.options": {
  "parser": "babel-eslint"
}

2018-1-31
vscodebabel-eslint
JSX DOM elements vs React elements
React treats JSX tags that start with a lowercase letter as DOM tags. Be especially careful when using object properties as JSX elements, if they start with a lowercase letter they will be treated as DOM tags regardless of the property name case.
2017-7-7
reactjsx
Make Babel ignore node_modules, output to a specified directory, copy files and watch

$ babel . --out-dir=../../build/dev/ --ignore='node_modules' --copy-files -w

2016-8-23
babelnpm
Cannot find java. Please use the --jdkhome switch
Edit netbeans/netbeans-8.2/etc/netbeans.conf and set the corresponding setting. For example:

netbeans_jdkhome="/usr/local/java/jdk1.8.0_131"

2017-6-29
errorjavanetbeans
Disable ansible's host key checking at the inventory level
In the corresponding server group in your inventory file:

ansible_ssh_common_args='-o StrictHostKeyChecking=no'

2016-9-14
ansible
Make ansible report task status changed = false

# this will never report 'changed' status
- shell: wall 'beep'
  changed_when: False

2016-9-9
ansible
Test a single file from npm test using jest
If npm test is an alias for "jest"

$ npm run test -- ./path/to/the/test/file.js

2017-11-1
npmjest
mkdir create parent directories
Doesn't fail if exists. Make parent directories as needed

$ mkdir -p

2017-9-27
linuxshell
"eslint block must not be padded by blank lines" vs "expected line before comment"
Change the rule so that it allow comments at the start of a block

"lines-around-comment": [
  "error", {
    "allowBlockStart": true
  }
]

2017-9-30
javascripteslint
Want to copy a project directory, except for node_modules, build and .vagrant?

$ rsync -rP ./origin/ ./destination/ --exclude=node_modules --exclude=build --exclude=.vagrant --exclude=.git

2018-9-20
linuxshellrsync
ENOSPC
Increase the maximum number of files that can be watched

$ echo fs.inotify.max_user_watches=524288 | tee -a /etc/sysctl.conf && sysctl -p

Validate with visudo before copying sudoer file with Ansible
Copy a new sudoers file into place, after passing validation with visudo

- template: src=/mine/sudoers dest=/etc/sudoers validate='visudo -cf %s'

2016-9-9
linuxansiblesudo
Match multiple strings at the same time with grep
Use the pipe operator

$ ps aux | grep postgres | grep collector

2018-2-19
linuxshelllgrep
Stage deleted files
To stage all manually deleted files you can use:

$ git rm $(git ls-files --deleted)

2016-9-21
linuxansiblesudo
Find and kill a process in one line using bash and regex

$ ps aux | awk '/fileops/' | awk '{print $2}' | xargs kill

2017-9-1
linux
Create a new ssh key pair
In  ~/.ssh

$ ssh-keygen -t ed25519 -f ./vagrant_key -C "Key for all vagrant development machines"

2018-2-18
ssh
Handy static print function for Java

public static<T> void print (T arg) {
  System.out.println(arg);
}

2017-10-13
java
Make the tree command ignore node_modules

$ tree --dirsfirst -aFI "node_modules|.git|.vagrant"

Additionally, you can make an alias in .bashrc

alias tree='/usr/bin/tree --dirsfirst -aFI "node_modules|.git|.vagrant"'

2016-9-16
linuxshelltree
Sample PM2 processes.json file for an express app

{
  "apps" : [{
    "name"            : "appname",
    "script"          : "bin/www",
    "watch"           : "./",
    "ignore_watch"    : ["node_modules"],
    "log_date_format" : "YYYY-MM-DD HH:mm Z"
  }]
}


Start PM2 with:

$ pm2 start processes.json

2016-9-14
node.jspm2express
Show the desktop with Win+D in XFCE
Add the following lines to the file ~/.config/xfce4/xfconf/xfce-perchannel-xml/xfce4-keyboard-shortcuts.xml:

<property name="&lt;Super&gt;d" type="string" value="show_desktop_key"/>

2018-2-5
linuxxfce
Show the taskbar in XFCE
XFCE started without the taskbar. Press Alt+F2 and execute:

xfce4-panel --preferences

2020-2-13
linuxxfce
Disable default shared folder in Vagrant

Vagrant.configure('2') do |config|
  config.vm.synced_folder '.', '/vagrant', disabled: true
    # ...
end

2016-10-4
vagrant
Change the password of a PostgreSQL user
You'd have to use peer auth first:

postgres=# ALTER USER postgres PASSWORD 'myPassword';

2016-11-8
linuxansiblesudo
Using PM2 with Vagrant
If you set up PM2 to watch files, enable usePolling in your ecosystem.config.js:

usePolling: true

2016-9-19
vagrantpm2
Postman may change from a GET to a POST
Cuando hay una redireccion, asi como las redirecciones permanentes 301 que cambian al protocolo https. Entonces puede haber un cambio de POST a GET usando postman, eso se arregla escribiendo la direccion final para que no haya redireccion.
2016-9-30
postman
mkdir and cd all in one
$_ is a special parameter that holds the last argument of the previous command. The quote around $_ make sure it works even if the folder name contains spaces.

$ mkdir foo && cd "$_"

2017-9-6
linuxshell
example sudo config lines explained
The root user can execute in all terminals as all users, all commands

root ALL = (ALL) ALL

The wheel group can execute in all terminals as all users, all commands and doesn't need a password prompt to do that

%wheel ALL=(ALL) NOPASSWD: ALL

2016-9-7
linuxsudo
Minutes to "Hour and minutes" in Java
If your time is in a variable called t

int hours = t / 60; //since both are ints, you get an int
int minutes = t % 60;
System.out.printf("%d:%02d", hours, minutes);

2017-10-20
javatime
List tables in a PostgreSQL schema
In the current schema

\dt

In all schemas

\dt *.*

In a particular schema

\dt public.*

2017-6-8
postgresql
Copy a public key to a remote server
You will need root's password.

ssh-copy-id -i ~/.ssh/mykey root@192.168.10.2

If you'd wish not to be asked for root's password, use vagrant's account to copy the key using sudo.

cat ~/.ssh/mykey.pub | ssh vagrant@192.168.10.2 'cat | sudo tee -a /root/.ssh/authorized_keys && echo "Key copied"'

2019-2-23
sshvagrant
OpenSSL certificate file types.
.csr
- This is a Certificate Signing Request
.pem
(privacy-enhanced mail)
.key
- This is a PEM formatted file containing just the private-key of a specific certificate
.cert .cer .crt
- A
.pem
(or rarely
.der
) formatted file with a different extension, one that is recognized by Windows Explorer as a certificate, which
.pem
is not.
2018-7-1
opensslhttps
Telling webpack where to find node_modules in case it's not in the same folder
In my case my node_modules folder is in a different location, and only modifying resolve.modules didn't work well with webpack-dev-server. This worked for me:

resolveLoader: {
  modules: ['/path/to/node_modules'],
},
resolve: {
  modules: ['/path/to/node_modules'],
}

2018-2-6
webpacknpm
Example of a sequelize where with and

if (req.query.filtertext) {
   config.where = Sequelize.and(
    Sequelize.where(Sequelize.fn('unaccent', Sequelize.col('nombre')), {
      [Sequelize.Op.iLike]: Sequelize.fn('unaccent', `%${req.query.filtertext}%`)
    }),
    Sequelize.where(Sequelize.fn('unaccent', Sequelize.col('nombre')), {
      [Sequelize.Op.iLike]: Sequelize.fn('unaccent', `%f%`)
    })
  );
}

2017-7-31
node.jssequelize
Clone from github with Ansible

- name: SUDO Create and configure /etc/sudoers.d/{{ useradmin }} file
  lineinfile: dest=/etc/sudoers.d/{{ useradmin }} line="Defaults env_keep+=SSH_AUTH_SOCK" state=present create=yes owner=root group=root mode="u+rw,g-rwx,o-rwx"

- name: APP Checkout git repo
  become: no
  git: repo=git@github.com:oscbco/kanban.git dest=/home/app-admin/kanban update=no


~/.ssh/config

ForwardAgent yes

2019-2-24
ansiblegitgithub
Reading from an existing Dexie Database example

let db = new Dexie('fileops');
db.open().then(function () {
  let windows = db.table('windows');
  windows.toCollection().first().then(function (window) {
    console.log(window.id);
  });
});

async count () {
 let count = await
 appdb.count('windows');
 console.log('count', count);
}

Fetch Example

import 'whatwg-fetch';
const API_URL = '/api';
const API_HEADERS = {
  'Content-Type': 'application/json'
};

window.fetch(API_URL + '/cards/', API_HEADERS)
.then((response) => response.json()) // Takes a Response stream and reads it to completion
  // It returns a promise that resolves with a JSON object
  .then((responseData) => {
    this.setState({
    cards: responseData
  });
}).catch((error) => {
  console.log('Error fetching and parsing data', error);
});

Changing a parameter properties

console.log("\nScenario 1: Modifying a referenced value (in this case an object's property):");
const obj1 = {a: "a", b: "b"}
function changeObj1 (obj) {
  obj.newPropertyC = "newPropertyC";
}
changeObj1(obj1);
console.log(JSON.stringify(obj1, null, 2));
// {
//   "a": "a",
//   "b": "b",
//   "c": "c"
// }

console.log("\nScenario 2: Replacing the referenced value with a new one:");
const obj2 = {a: "a", b: "b"}
function changeObj2 (obj) {
  obj = "new string";
}
changeObj2(obj2);
console.log(JSON.stringify(obj2, null, 2));
// {
//   "a": "a",
//   "b": "b"
// }

2017-9-5
javascript
Failed to mount folders in Linux guest. This is usually because the "vboxsf" file system is not available. Please verify that the guest additions are properly installed in the guest and can work properly.
The command attempted was:

mount -t vboxsf -o uid=`id -u vagrant`,gid=`getent group vagrant | cut -d: -f3` home_app-web_kanban /home/app-web/kanban
mount -t vboxsf -o uid=`id -u vagrant`,gid=`id -g vagrant` home_app-web_kanban /home/app-web/kanban

The error output from the last command was:

stdin: is not a tty
/sbin/mount.vboxsf: mounting failed with the error: No such device

Solved by:

install vagrant vbguest plugin

Reference Exceptions
Trying to read an undeclared object throws a Reference Error
Trying to read an undeclared property returns undefined
Trying to read an non-existing position at an array returns undefined

try {
  elem = {
    filename: newFiles[keypath[i]].filename,
    hasChild: newFiles[keypath[i]].child !== null,
    hasSibling: newFiles[keypath[i] + 1] !== undefined
  };
  newFiles = newFiles[keypath[i]].child;
} catch (e) {
  elem = undefined;
  break;
}

Here trying to access newFiles[keypath[i]] can return undefined, and if one tries to read a property from undefined an exception will be thrown
2017-7-20
javascript
Update package versions in package.json
Install npm-check-updates

$ npm install -g npm-check-updates

To print installed and available versions

$ ncu

To update your package.json

$ ncu -u

Ansible Command Warnings
By default since Ansible 1.8, Ansible will issue a warning when the shell or command module is used and the command appears to be similar to an existing Ansible module. For example, this can include reminders to use the ‘git’ module instead of shell commands to execute ‘git’. Using modules when possible over arbitrary shell commands can lead to more reliable and consistent playbook runs, and also easier to maintain playbooks:

command_warnings = false

These warnings can be silenced by adjusting the following setting or adding warn=yes or warn=no to the end of the command line parameter string, like so:

- name: usage of git that could be replaced with the git module
  shell: git update foo warn=no

2016-9-13
ansibleshell
Sequelize soft delete and unique indexes
PostgreSQL doesn't consider two null values equal
postgresql.org/docs/9.0/static/indexes-unique
So an index including name, and deletedAt wouldn't behave as expected

The solution is to add a default value to deletedAt so it's never null.

name: {
  type: DataTypes.TEXT,
  allowNull: false,
  unique: 'name_cod_del'
},
deletedAt: {
  allowNull: false,
  type: DataTypes.DATE,
  unique: 'name_cod_del',
  defaultValue: new Date(0)
}

Sequelize considers deletedAt default value as the default value by which the paranoid option picks up deleted fields.

So even though new Date (0) *is* in the past. Rows with it in the deletedAt field wouldn't be considered deleted.

Now however, restoration of soft deleted fields becomes problematic.
2018-8-16
postman
Example of a three vm vagrant file

# -*- mode: ruby -*-
# vi: set ft=ruby :

Vagrant.configure("2") do |config|
  config.ssh.insert_key = false

  config.vm.provider "virtualbox" do |vb|
    vb.gui = false
    vb.memory = "256"
  end


  # Application Server 1
  config.vm.define "app1" do |app|
    app.vm.box = "debian/jessie64"
    app.vm.hostname = "orc-app1.dev"
    app.vm.network "private_network", ip: "192.168.60.4"
  end

  # Application Server 2
  config.vm.define "app2" do |app|
    app.vm.box = "debian/jessie64"
    app.vm.hostname = "orc-app2.dev"
    app.vm.network "private_network", ip: "192.168.60.5"
  end

  # Database Server
  config.vm.define "db" do |db|
    db.vm.box = "debian/jessie64"
    db.vm.hostname = "orc-db.dev"
    db.vm.network "private_network", ip: "192.168.60.6"
  end
end

2016-7-10
vagrant
Generating a certificate with OpenSSL
Generate private key

$ openssl genpkey -algorithm RSA -out private_key.key -pkeyopt rsa_keygen_bits:2048

Viewing the generated key file

openssl rsa -text -in private_key.key

Alternative:
  Generate a CSR (Certificate signing request) File

openssl req -new -key fd.key -out fd.csr

  Generate the 2048 rsa key and the certficate signing request all in one go (Interactive)

openssl req -new -newkey rsa:2048 -nodes -keyout oscbco.key -out oscbco.csr


Check the Certificate Signing Request

openssl req -text -in fd.csr -noout


Step 1: Write Conf File: fd.conf

[req]
default_bits        = 2048
default_keyfile     = privkey.pem  
prompt              = no
encrypt_key         = no
distinguished_name  = dn
req_extensions      = ext

[dn]
countryName         = "SV"                    # C=
stateOrProvinceName = "San Salvador           # ST=
localityName        = "Soyapango"             # L=
commonName          = "www.example.com"       # CN=
emailAddress        = "webmaster@example.com" # CN/emailAddress=

Step 2: Issue the following command

openssl req -new -config fd.conf -out oscbco.csr
req:
  The req command primarily creates and processes certificate requests in PKCS#10 format. It can additionally create self-signed certificates for use as root CAs for example
-new
  this option generates a new certificate request. It will prompt the user for the relevant field values. The actual fields prompted for and their maximum and minimum sizes are specified in the configuration file and any requested extensions.
  If the -key option is not used it will generate a new RSA private key using information specified in the configuration file.
-config filename
  this allows an alternative configuration file to be specified, this overrides the compile time filename or any
  specified in the OPENSSL_CONF environment variable.

Generate a certificate instead of a csr

openssl req -new -config fd.conf -x509 -days 365 -out oscbco.crt

Generate a csr from a crt

openssl x509 -x509toreq -in oscbco.crt -out oscbco.csr -signkey privkey.pem

View the csr

openssl req -text -in oscbco.csr -noout

~/.inputrc example

"\e[A": history-search-backward
"\e[B": history-search-forward
set show-all-if-ambiguous on
set completion-ignore-case on
"\e[1;5C": forward-word
"\e[1;5D": backward-word

2017-7-9
linuxshell
Embed a base64 encoded svg in a stylesheet

background: transparent url("data:image/svg+xml;base64,BASE64DATA") no-repeat;

2019-3-2
svgcss
&& operator
An idiom for accessing a property, only if its parent object exists. Avoiding a TypeError exception in the process.

obj.person && obj.person.name

2018-3-4
javascript
Webpack externals example:
Explicitly declaring React as an external dependency.

externals: {
  react: {
    root: 'React',
    commonjs2: 'react',
    commonjs: 'react',
    amd: 'react'
  }
}

2018-12-23
webpackjavascript
Sample function for retrieving a query param

export let getSearchParam = function (param) {
  let url = new URL(window.location);
  let params = new URLSearchParams(url.search);

  return params.get(param);
};

Form Submit
Calling the submit() method of a form does not trigger the "onsubmit" handler or html validations

<button type=button> does not submit the form.

Node.js Module Caching
Modules are cached after the first time they are loaded and the code inside them is only executed once.
This is useful for modules that connect to databases, since they won't try to connect to the database everytime the module is imported.
Instead such modules return the same db connection. This is where module internal variables come into play because they behave just like private variables. The user of the module can only modify them through the module's API.
Simple demo: repl.it/@oscbco/node-module-caching
2016-3-3
javascriptnodejs
exports vs module.exports
Like "require", exports is a special variable available to modules. It points to module.exports, this is the reason why you can not set anything to it as that would erase that reference
You are only supposed to define its properties with values you wish to export.
In the end it's module.exports that is exported, and is perfectly valid to ignore exports.
2016-3-3
javascriptnodejs
Simple Node.js static server
Start a static server in less than 10 seconds

Step 1: Copy the following code to a index.js file
Step 2: $ node index.js
Step 3: Visit the server on http://127.0.0.1:8125

var http = require('http');
var fs = require('fs');
var path = require('path');
http.createServer(function (request, response) {
  console.log('request ', request.url);
  var filePath = '.' + request.url;
  if (filePath == './') {
    filePath = './index.html';
  }
  var extname = String(path.extname(filePath)).toLowerCase();
  var mimeTypes = {'.html': 'text/html','.js': 'text/javascript','.css': 'text/css','.json': 'application/json','.png': 'image/png','.jpg': 'image/jpg','.gif': 'image/gif','.wav': 'audio/wav','.mp4': 'video/mp4','.woff': 'application/font-woff','.ttf': 'application/font-ttf','.eot': 'application/vnd.ms-fontobject','.otf': 'application/font-otf','.svg': 'application/image/svg+xml'};
  var contentType = mimeTypes[extname] || 'application/octet-stream';
  fs.readFile(filePath, function(error, content) {
    if (error) {
      if(error.code == 'ENOENT') {
        fs.readFile('./404.html', function(error, content) {
          response.writeHead(200, { 'Content-Type': contentType });
          response.end(content, 'utf-8');
        });
      }
      else {
        response.writeHead(500);
        response.end('Sorry, check with the site admin for error: '+error.code+' ..\n');
        response.end();
      }
    }
    else {
      response.writeHead(200, { 'Content-Type': contentType });
      response.end(content, 'utf-8');
    }
  });

}).listen(8125);
console.log('Server running at http://127.0.0.1:8125/');

2019-3-10
javascriptnodejs
XFCE starts with no desktop

$ xfdesktop

2019-3-11
errorlinuxxfce
Change screen brightness in XFCE
Install xfce4-power-manager-plugins. Then add the Power Manager Plugin to the task panel
2019-3-11
errorlinuxxfce
Render the page not zoomed in and with the the current device's width.

<meta name="viewport" content="width=device-width, initial-scale=1">

Block select in Linux

ctrl + alt + mouse drag

2016-10-6
linuxshell
Why redux reducers are called that
They are called reducers because they take an action and the old state and return a new state.
They "reduce" the amount of items from 2 (action and old state) to 1 (new state)
Think of the Array.reduce() function which takes as its first parameter a function.
This function receives the acummulator and currentValue parameters and is run through the whole array returning a single value.
Show which website you downloaded a file from
On Debian (Install the attr package first):  $ getfattr -d file
On Windows:  > notepad file:Zone.Identifier
2018-3-15
linux
clear vs tput reset
After using clear, if you scroll the screen up you realize it only moved the prompt to the top of the screen. This is troublesome when you need to inspect long lists such as logs, directory listings, search results or compilation messages.
If you really want to clear the screen, you can use $ tput reset

To reduce typing time you may add the $ cls alias to your bash shell, like this:

alias cls="tput reset"

2019-3-17
linuxbash
Preventing commands from littering your bash history
Edit this line in your ~/.bashrc and add the commands you are not interested in seeing there.

export HISTIGNORE="ls:pwd:exit:htop:su:clear:fb:cls:SU:reading:mve:reset:cmd"

2019-3-17
linuxbash
currentColor with SVGs
You can use currentColor variable with the stroke property in svg paths:

<path d='m0.61405 290.96 3.6193 3.6193' stroke='currentColor' />

2019-3-22
htmlcsssvg
Screen locker for X
You can inkove as is. But you'll most likely create a launcher to use it from your task bar

$ i3lock -c 000000

2018-1-21
linuxxgui
Vagrant compatible keys
The private key you're attempting to use with this Vagrant box uses an unsupported encryption type. The SSH library Vagrant uses does not support this key type. Please use `ssh-rsa` or `ssh-dss` instead. Note that sometimes keys in your ssh-agent can interfere with this as well, so verify the keys are valid there in addition to standard
2019-2-31
vagrantssh
Trim whitespace on save in Sublime Text
Add this to your settings:

"trim_trailing_white_space_on_save": true

2019-2-31
sublime
Unstage all files

git reset

2019-4-18
git
Viewing live error logs for PM2, which is run by a service account with no shell

sudo su service-user -c "pm2 logs" -s /bin/bash

2019-4-20
linuxnodejspm2
Determine why a package was installed

$ sudo aptitude why libjs-jquery

i task-xfce-desktop Recommends quodlibet
i A quodlibet Depends exfalso (= 3.2.2-1)
i A exfalso Depends libjs-sphinxdoc (>= 1.0)
i A libjs-sphinxdoc Depends libjs-jquery (>= 1.4)

2019-5-10
linuxdebianapt
nano

Exit insert mode: Esc
Go to end of file: Ctrl + _ then Ctrl + v | Alt + \
Go to beginning of file: Alt + \

2019-5-12
linuxnano
Bash starting directory
Normally bash sessions start at your home directory, you can change that by cd-ing there in your ~/.bashrc file:

cd ~/Projects/sites/@vm

Caveat: This is not advisable if you use integrated terminals like VSCode's where you expect your starting directory to be your currently opened folder. This will break that behavior.
2019-5-22
linuxbash
Bash "bookmarks"
Put directory paths in environment variables, like this:
In your ~/.bashrc file:

export vm=~/Projects/sites/@vm

Then in your console, you can type:

cd $vm

2019-5-22
linuxbash
Make VS Code integrated terminal start in a user-defined folder

"terminal.integrated.cwd": "./source/server"

You'll want to change this in your workspace settings rather than in your user settings, since not all projects are the same.
2019-5-23
vs code
Error: Failed to set permissions on the temporary files Ansible needs to create when becoming an unprivileged user
Use pipelining:

In your ansible.cfg file:

[ssh_connection]
pipelining=True

or in your inventory:

192.168.10.4 ansible_ssh_pipelining='yes'

2019-5-29
linuxansibleerror
PostgreSQL's DROP DATABASE NOT WORKING?
You probably forgot the semicolon at the end
2019-5-29
postgresqlerror
PostgreSQL ansible modules' login_unix_socket parameter
When using ansible's PostgreSQL modules is not necessary to use the "login_unix_socket" parameter if your "login_host" is "/var/run/postgresql"
2019-5-30
postgresql
Trim whitespace from ansible variables
For example:

{{ variable.stdout | trim }}

2019-5-30
ansibleyaml
Sample ~/.gitconfig

[user]
  name = Name Surname
  email = nsurname@example.com
[push]
  followTags = true

2019-6-3
git
Replance new line escape sequences with proper new lines in ansible error messages
Add these lines to your ansible.cfg
(Global ansible.cfg is in /etc/ansible/ansible.cfg)

[defaults]

stdout_callback=debug
stderr_callback=debug

Change errors to a more readable color

[colors]

error = white

2019-6-21
ansible
PostgreSQL - List all tables in all schemas

\dt *.*

2019-6-21
postgresql
Push commits and tags simultaneously

git config --global push.followTags true

2019-6-22
git
Emojis in your console
Install the fonts-symbola package
Download from https://packages.debian.org/sid/all/fonts-symbola/download

sudo dpkg -i fonts-symbola_2.60-1_all.deb

2019-7-29
debianutf8emoji
Webpack won't process dependencies inside css modules :global rule
Move those dependencies to a global css file instead
2019-10-24
webpackcss modules
PostgreSQL listen_addresses format
Don't mix "localhost" with ip addresses in postgresql.conf. If you need it use 127.0.0.1 instead.
2019-10-25
postgresql
Gthumb shows video in an external window
Install

gstreamer1.0-gtk3

2019-10-26
gthumb
Control screen brightness without laptop special keys in linux

sudo apt-get install xbacklight xbacklight -set 60

2019-10-26
linuxbrightness
Install PostgreSQL debugger plugin

Debugger installation:

Install compilation dependenies and execute make and make install with USE_PGXS

$ sudo apt-get install build-essential postgresql-server-dev-12 libssl-dev libkrb5-dev
$ sudo git clone git://git.postgresql.org/git/pldebugger.git -C /usr/local/src/
$ cd /usr/local/src/pldebugger/
$ sudo USE_PGXS=1 make
$ sudo USE_PGXS=1 make install


Edit postgresql.conf. Find it with:

# SHOW config_file;

Inside of postgresql.conf, Search for 'preload' (Ctrl + W in nano), Set "shared_preload_libraries" to:

shared_preload_libraries = 'plugin_debugger'


Install the extension in your database

$ sudo su - postgres
$ psql database_name
database_name=# CREATE EXTENSION pldbgapi;


Restart the server

sudo service postgresql restart

2019-11-6
postgresql
Handle missing mouseup

@-moz-document url-prefix() {
  .class {
    rule: value;
  }
}

2020-2-6
browsercss
Reduce js events by using data attributes
Let's say you have a parent element with an event attached, next are its direct descendants with the data attribute you are using to differentiate them.

The problem lies in that the children of those second-level elements have to have a data attribute too, otherwise we won't be able to distinguish them.
e.g. menu items with svg icons with multiple paths

To access the corresponding data attribute, without adding it to the descendants directly, you can use Element.closest.

This searches up the document tree using a selector, and since the second level elements are guaranteed to have a data attribute, you can use this result and pass it to your function.
2020-2-10
browserjsdom
Get file permissions in octal and decimal

$ ls README.md -hal


Returns:

-rwSr-Sr-T 1 user user 0 Feb 14 17:52 2A2A

$ stat --printf "%a " README.md && stat -c "%a" README.md | xargs -I PERM echo "obase=2; ibase=8; PERM" | bc


Returns:

7644 111110100100

2020-2-24
linux
Linux file group
Linux users can only set the group of a file to groups they belong to
2020-2-26
linux
From string octal to string binary
"0400" to "100000000"

parseInt(`0${value}`, 8).toString(2)

2019-2-26
js
Use xclip to put a file in the clipboard
Replace copy with cut if you want to move it

$ echo -ne 'copy\nfile:///path/to/file.txt' '\0' | xclip -i -selection clipboard -t x-special/gnome-copied-files

2019-4-9
linuxclipboard
imagemagik vs sharp for creating thumbnails
Imagemagick:

$ time ./magick mogrify -path thumbnails_magick -thumbnail 100x100 originals/* -quality 50
  real 1m26.212s
  user 1m5.203s
  sys  0m20.560s


Sharp:

$ time node thumbnails.js
  real 0m1.716s
  user 0m3.858s
  sys  0m0.434s

2019-4-13
jsimages
margin: auto
Your margin auto may not be working because you are using it inside a inline element
2020-4-21
css
clip-path and shadows
Use a drop-shadow filter and a non-transparent background in the parent element
2020-4-22
css
Marking variables as global in eslintrc.json

"globals": {
  "expect": "readonly",
  "it": "readonly",
  "afterEach": "readonly",
  "describe": "readonly"
}

2019-4-25
javascripteslint
Install Java

sudo apt update
sudo apt upgrade
# Locate the latest java version
sudo apt search openjdk
sudo apt-get install openjdk-11-jdk
update-alternatives --config java
sudo sh -c 'echo "export JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64/" > /etc/profile.d/java.sh'
# Make it readable
sudo chmod og+r /etc/profile.d/java.sh
# Add this line to ~/bashrc
source /etc/profile.d/java.sh
# Verify it exists
echo $JAVA_HOME
# Output: /usr/lib/jvm/java-11-openjdk-amd64/

2019-4-25
java
Chrome screenshot
Ctrl + Shift + I  ->  Open developer tools
Ctrl + Shift + P  ->  Show run command prompt
Write "screenshot"
Select one the commands available
It's buggy, so be prepared to try several times. (Maybe try scrolling)
2019-4-25
javascripteslint
Find out your NICs addresses. (ifconfig is deprecated)

$ ip address show

2019-5-2
linuxnetwork