Showing preview only (224K chars total). Download the full file or copy to clipboard to get everything.
Repository: lackovic/notes
Branch: master
Commit: 31612edfe3bd
Files: 56
Total size: 209.0 KB
Directory structure:
gitextract_9j5taalu/
├── Android/
│ └── uninstall-s21-bloatware
├── Chrome/
│ ├── README.md
│ ├── export.js
│ ├── import.js
│ └── marco_search_engines.json
├── Docker/
│ ├── .bashrc
│ ├── Dockerfile
│ └── README.md
├── ExifTool/
│ └── README.md
├── Git/
│ ├── .gitconfig
│ ├── README-template.md
│ └── README.md
├── Go/
│ └── README.md
├── Google Docs/
│ └── README.md
├── GraphQL/
│ └── README.md
├── Java/
│ ├── Country.java
│ ├── FixturesBuilder.java
│ └── README.md
├── Javascript/
│ └── README.md
├── Kubernetes/
│ └── README.md
├── Linux/
│ ├── .bash_profile
│ ├── .bashrc
│ ├── .vimrc
│ ├── README.md
│ └── powerlevel10k_rainbow_java.omp.json
├── PostgreSQL/
│ ├── README.md
│ └── postgresql-to-dbdiagram.sql
├── README.md
├── Redis/
│ └── README.md
├── Ruby on Rails/
│ └── README.md
├── Rust/
│ └── README.md
├── Visual Studio Code/
│ └── README.md
├── Windows/
│ ├── AutoHotkey.ahk
│ ├── AutoHotkey2.ahk
│ ├── Chocolatey/
│ │ ├── Profile.ps1
│ │ ├── README.md
│ │ ├── cdeps.ps1
│ │ └── packages.config
│ ├── PowerShell/
│ │ └── README.md
│ ├── README.md
│ ├── Scripts/
│ │ ├── DeleteOldWinDirs.ps1
│ │ ├── DisableWake-on-LAN.ps1
│ │ ├── DisableWakeupTimers.ps1
│ │ ├── ReduceOneHour.js
│ │ ├── ReduceOneHour.ps1
│ │ ├── SetupApps.ps1
│ │ ├── SetupConfig.ps1
│ │ ├── UninstallBloatware.ps1
│ │ └── WhatsAppMoveAndRename.ps1
│ ├── Windows Subsystem for Linux/
│ │ ├── README.md
│ │ └── config.xlaunch
│ └── Windows Terminal/
│ ├── README.md
│ └── settings.json
├── ffmpeg/
│ └── README.md
└── graphviz/
├── README.md
└── diagram.dot
================================================
FILE CONTENTS
================================================
================================================
FILE: Android/uninstall-s21-bloatware
================================================
# Install Android Debug Bridge (adb) https://developer.android.com/studio/command-line/adb
# Install the Universal ADB Drivers https://adb.clockworkmod.com/
# Run in PowerShell: Get-Content .\uninstall-s21-bloatware | adb shell
# Bixby
pm uninstall --user 0 com.samsung.android.bixby.service
pm uninstall --user 0 com.samsung.android.app.routines
pm uninstall --user 0 com.samsung.android.visionintelligence
pm uninstall --user 0 com.samsung.android.bixby.agent
pm uninstall --user 0 com.samsung.android.bixby.agent.dummy
pm uninstall --user 0 com.samsung.android.bixbyvision.framework
pm uninstall --user 0 com.samsung.android.bixby.wakeup
# AR Zone
pm uninstall --user 0 com.samsung.android.ardrawing
pm uninstall --user 0 com.samsung.android.aremoji
pm uninstall --user 0 com.samsung.android.aremojieditor
pm uninstall --user 0 com.sec.android.mimage.avatarstickers
pm uninstall --user 0 com.samsung.android.arzone
pm uninstall --user 0 com.samsung.android.livestickers
# Samsung Calendar: redundant, use Google Calendar
pm uninstall --user 0 com.samsung.android.calendar
# Samsung Contacts: redundant, use Google Contacts
pm uninstall --user 0 com.samsung.android.app.contacts
# Samsung Pass Autofill and Framework
pm uninstall --user 0 com.samsung.android.samsungpassautofill
pm uninstall --user 0 com.samsung.android.samsungpass
# Samsung Group Sharing
pm uninstall --user 0 com.samsung.android.mobileservice
# Samsung Kids
pm uninstall --user 0 com.samsung.android.kidsinstaller
# Samsung Cloud
pm uninstall --user 0 com.samsung.android.scloud
# Dictionary
pm uninstall --user 0 com.diotek.sec.lookup.dictionary
# upday
pm uninstall --user 0 de.axelspringer.yana.zeropage
# Android Auto
pm uninstall --user 0 com.google.android.projection.gearhead
# Microsoft OneDrive
pm uninstall --user 0 com.microsoft.skydrive
# Netflix
pm uninstall --user 0 com.netflix.mediaclient
# Talkback
pm uninstall --user 0 com.samsung.android.accessibility.talkback
# Voice Assistant
# Samsung Gallery
# Clock
# Game Launcher
# Samsung Keyboard
# Samsung Checkout
# Samsung Capture
# Samsung Visit In
# Samsung Create movie
# Samsung Video Editor
# Samsung GameOptimizingService
# Samsung Game Booster
# Samsung Customizaion Service
# Samsung Link to Windows Service
# Samsung Sticker Center
# Samsung Media and Devices
# Samsung Keyboard Content Center
# Samsung SmartThings Framework
# Samsung Private Share
# Samsung Link sharing
# Samsung TTS
================================================
FILE: Chrome/README.md
================================================
# Chrome
_Table of Contents_
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
<!-- generated with [DocToc](https://github.com/thlorenz/doctoc)* -->
- [Export/import search engines](#exportimport-search-engines)
- [Disable notifications from all sites](#disable-notifications-from-all-sites)
- [Change Google Chrome cache folder](#change-google-chrome-cache-folder)
- [Install Chrome in Ubuntu](#install-chrome-in-ubuntu)
- [Set the Material You theme](#set-the-material-you-theme)
- [Must have extensions](#must-have-extensions)
- [YouTube extensions](#youtube-extensions)
- [Other useful extensions](#other-useful-extensions)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
## Make a Chrome shortcut open the default profile in Windows
Append `--profile-directory="Default"` to the target of the shortcut
## Export/import search engines
1. Enter [`chrome://settings/searchEngines`](chrome://settings/searchEngines) in the address bar of Chrome to
1. Run the code in the following files in your DevTools console:
- to export to a JSON file: [`export.js`](export.js)
- to import from a JSON file: [`import.js`](import.js)
* [Source](https://superuser.com/a/1458616/54747)
## Disable notifications from all sites
Settings > Site Settings > Notifications > Sites can ask to send notifications = OFF
## Change Google Chrome cache folder
```powershell
$Path = "Registry::HKEY_LOCAL_MACHINE\Software\Policies\Google\Chrome"
if (-not (Test-Path $Path)) { New-item -Path $Path -Force }
Set-ItemProperty -Path $Path -Name 'DiskCacheDir' -Value 'C:\Temp\Chrome'
```
This will move Chrome cache folder to `C:\Temp\Chrome` system-wide, for every user and regardless where Chrome is started from (shortcut or command line).
Default value: `%LOCALAPPDATA%\Google\Chrome\User Data\Default\Cache`
- [Source](http://www.chromium.org/administrators/policy-list-3#DiskCacheDir)
## Install Chrome in Ubuntu
```sh
wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | sudo apt-key add -
sudo sh -c 'echo "deb https://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list'
sudo apt-get update
sudo apt-get install google-chrome-stable
```
## Set the Material You theme
1. three-dot menu in the top-right corner > _Help_ > _About Google Chrome_;
1. verify you have at version 116.0.5845.179/.180 or higher;
1. paste `chrome://flags` in the address bar and press Enter;
1. search for _Chrome Refresh_
1. enable both the following flags:
```
chrome://flags/#chrome-refresh-2023
chrome://flags/#chrome-webui-refresh-2023
```
1. click on _Relaunch_ at the bottom.
See also:
- [Chrome gets a fresh look and new features for its 15th birthday](https://blog.google/products/chrome/google-chrome-new-features-redesign-2023/)
## Must have extensions
- [I don't care about cookies](https://chrome.google.com/webstore/detail/i-dont-care-about-cookies/fihnjjcciajhdojfnbdddfaoknhalnja)
- [Don't add custom search engines](https://chrome.google.com/webstore/detail/dont-add-custom-search-en/dnodlcololidkjgbpeoleabmkocdhacc?hl=en)
- [History Blocker by Site](https://chromewebstore.google.com/detail/history-blocker-by-site/keamekimefemnbgegbfkdkmbomaahfai?pli=1) (see [this](https://superuser.com/questions/1684345/delete-translate-google-com-from-chrome-history))
- [Pop up blocker for Chrome - Poper Blocker](https://chrome.google.com/webstore/detail/pop-up-blocker-for-chrome/bkkbcggnhapdmkeljlodobbkopceiche?hl=en)
- [uBlacklist](https://chrome.google.com/webstore/detail/ublacklist/pncfbmialoiaghdehhbnbhkkgmjanfhe) in conjuction with [ublacklist-stackoverflow-translation](https://github.com/arosh/ublacklist-stackoverflow-translation)
- [Ghostery – Privacy Ad Blocker](https://chrome.google.com/webstore/detail/ghostery-%E2%80%93-privacy-ad-blo/mlomiejdfkolichcflejclcbmpeaniij)
## YouTube extensions
- [Return YouTube Dislike](https://chromewebstore.google.com/detail/return-youtube-dislike/gebbhagfogifgggkldgodflihgfeippi)
- [SponsorBlock](https://chromewebstore.google.com/detail/sponsorblock-for-youtube/mnjggcdmjocbbbhaepdhchncahnbgone): skips sponsorships, intros, and reminders.
- [PocketTube](https://chromewebstore.google.com/detail/pockettube-youtube-subscr/kdmnjgijlmjgmimahnillepgcgeemffb): groups subscriptions into collections.
- [Ad Auto-skipper](https://chromewebstore.google.com/detail/youtube-ad-auto-skipper/lokpenepehfdekijkebhpnpcjjpngpnd)
## Other useful extensions
- [Privacy Badger](https://chrome.google.com/webstore/detail/privacy-badger/pkehgijcmpdhfbdbbnkijodmdjhbjlgp)
- [Keepa - Amazon Price Tracker](https://chrome.google.com/webstore/detail/keepa-amazon-price-tracke/neebplgakaahbhdphmkckjjcegoiijjo?hl=en)
- [Save to Pocket](https://chrome.google.com/webstore/detail/save-to-pocket/niloccemoadcdkdjlinkgdfekeahmflj?hl=en)
- [Rememberry](https://chromewebstore.google.com/detail/rememberry-translate-and/dipiagiiohfljcicegpgffpbnjmgjcnf): translates selected text to any language.
- [Disable keyboard shortcuts](https://chromewebstore.google.com/detail/disable-keyboard-shortcut/aidbmcboeighgdnilpdljbedbbiocphj) (used to disable `Ctrl+D` to bookmark the current page, which is often pressed accidentally)
================================================
FILE: Chrome/export.js
================================================
(function exportSEs() {
/* Auxiliary function to download a file with the exported data */
function downloadData(filename, data) {
const file = new File([data], { type: "text/json" });
const elem = document.createElement("a");
elem.href = URL.createObjectURL(file);
elem.download = filename;
elem.click();
}
/* Actual search engine export magic */
settings.SearchEnginesBrowserProxyImpl.prototype
.getSearchEnginesList()
.then(searchEngines => {
downloadData("search_engines.json", JSON.stringify(searchEngines.others));
});
})();
================================================
FILE: Chrome/import.js
================================================
(async function importSEs() {
/* Auxiliary function to open a file selection dialog */
function selectFileToRead() {
return new Promise(resolve => {
const input = document.createElement("input");
input.setAttribute("type", "file");
input.addEventListener(
"change",
e => {
resolve(e.target.files[0]);
},
false
);
input.click();
});
}
/* Auxiliary function to read data from a file */
function readFile(file) {
return new Promise(resolve => {
const reader = new FileReader();
reader.addEventListener("load", e => {
resolve(e.target.result);
});
reader.readAsText(file);
});
}
const file = await selectFileToRead();
const content = await readFile(file);
const searchEngines = JSON.parse(content);
searchEngines.forEach(({ name, keyword, url }) => {
/* Actual search engine import magic */
chrome.send("searchEngineEditStarted", [-1]);
chrome.send("searchEngineEditCompleted", [name, keyword, url]);
});
})();
================================================
FILE: Chrome/marco_search_engines.json
================================================
[
{
"canBeDefault": true,
"canBeEdited": true,
"canBeRemoved": true,
"default": false,
"displayName": "YouTube",
"iconURL": "https://s.ytimg.com/yts/img/favicon_32-vflOogEID.png",
"id": 31,
"isOmniboxExtension": false,
"keyword": "y",
"modelIndex": 2,
"name": "Search YouTube",
"url": "https://www.youtube.com/results?search_query=%s",
"urlLocked": false
},
{
"canBeDefault": true,
"canBeEdited": true,
"canBeRemoved": true,
"default": false,
"displayName": "Stack Overflow",
"iconURL": "https://cdn.sstatic.net/Sites/stackoverflow/img/favicon.ico?v=4f32ecc8f43d",
"id": 75,
"isOmniboxExtension": false,
"keyword": "so",
"modelIndex": 4,
"name": "Stack Overflow",
"url": "http://stackoverflow.com/search?q=%s",
"urlLocked": false
},
{
"canBeDefault": true,
"canBeEdited": true,
"canBeRemoved": true,
"default": false,
"displayName": "Google Images",
"iconURL": "https://www.google.com/favicon.ico",
"id": 79,
"isOmniboxExtension": false,
"keyword": "gi",
"modelIndex": 5,
"name": "Search Google Images",
"url": "https://www.google.com/search?site=&tbm=isch&source=hp&biw=1678&bih=899&q=%s&=&=&oq=&gs_l=",
"urlLocked": false
},
{
"canBeDefault": true,
"canBeEdited": true,
"canBeRemoved": true,
"default": false,
"displayName": "Google Maps",
"id": 95,
"isOmniboxExtension": false,
"keyword": "m",
"modelIndex": 6,
"name": "Search Google Maps",
"url": "http://maps.google.com/maps?q=%s",
"urlLocked": false
},
{
"canBeDefault": true,
"canBeEdited": true,
"canBeRemoved": true,
"default": false,
"displayName": "Wikipedia (en)",
"iconURL": "https://en.wikipedia.org/static/favicon/wikipedia.ico",
"id": 98,
"isOmniboxExtension": false,
"keyword": "wen",
"modelIndex": 7,
"name": "Wikipedia (en)",
"url": "https://en.wikipedia.org/w/index.php?title=Special%3ASearch&search=%s",
"urlLocked": false
},
{
"canBeDefault": true,
"canBeEdited": true,
"canBeRemoved": true,
"default": false,
"displayName": "Thesaurus",
"iconURL": "https://www.thesaurus.com/assets/favicon-54545f5303fccb956af394ac10f1655d.png",
"id": 100,
"isOmniboxExtension": false,
"keyword": "th",
"modelIndex": 8,
"name": "Thesaurus",
"url": "http://www.thesaurus.com/browse/%s?s=t",
"urlLocked": false
},
{
"canBeDefault": true,
"canBeEdited": true,
"canBeRemoved": true,
"default": false,
"displayName": "Urban Dictionary",
"iconURL": "https://www.urbandictionary.com/favicon.ico",
"id": 142,
"isOmniboxExtension": false,
"keyword": "ud",
"modelIndex": 9,
"name": "Urban Dictionary",
"url": "http://www.urbandictionary.com/define.php?term=%s",
"urlLocked": false
},
{
"canBeDefault": true,
"canBeEdited": true,
"canBeRemoved": true,
"default": false,
"displayName": "amazon.com",
"iconURL": "https://www.amazon.com/favicon.ico",
"id": 159,
"isOmniboxExtension": false,
"keyword": "acom",
"modelIndex": 10,
"name": "amazon.com",
"url": "https://www.amazon.com/s/ref=nb_sb_noss_2?url=search-alias%3Daps&field-keywords=%s",
"urlLocked": false
},
{
"canBeDefault": true,
"canBeEdited": true,
"canBeRemoved": true,
"default": false,
"displayName": "thingiverse.com",
"iconURL": "https://cdn.thingiverse.com/site/img/favicons/favicon-32x32.png",
"id": 170,
"isOmniboxExtension": false,
"keyword": "tv",
"modelIndex": 12,
"name": "thingiverse.com",
"url": "https://www.thingiverse.com/search?q=%s",
"urlLocked": false
},
{
"canBeDefault": true,
"canBeEdited": true,
"canBeRemoved": true,
"default": false,
"displayName": "Super User",
"iconURL": "https://cdn.sstatic.net/Sites/superuser/img/favicon.ico?v=29b26120d2c5",
"id": 176,
"isOmniboxExtension": false,
"keyword": "su",
"modelIndex": 13,
"name": "Super User",
"url": "http://superuser.com/search?q=%s",
"urlLocked": false
},
{
"canBeDefault": true,
"canBeEdited": true,
"canBeRemoved": true,
"default": false,
"displayName": "AlternativeTo",
"iconURL": "http://alternativeto.net/favicon.ico",
"id": 184,
"isOmniboxExtension": false,
"keyword": "alt",
"modelIndex": 15,
"name": "AlternativeTo Software",
"url": "http://alternativeto.net/browse/search/?q=%s",
"urlLocked": false
},
{
"canBeDefault": true,
"canBeEdited": true,
"canBeRemoved": true,
"default": false,
"displayName": "Google Drive",
"iconURL": "https://ssl.gstatic.com/docs/doclist/images/infinite_arrow_favicon_5.ico",
"id": 185,
"isOmniboxExtension": false,
"keyword": "d",
"modelIndex": 16,
"name": "Google Drive",
"url": "https://drive.google.com/drive/search?q=%s",
"urlLocked": false
},
{
"canBeDefault": true,
"canBeEdited": true,
"canBeRemoved": true,
"default": false,
"displayName": "GitHub",
"iconURL": "https://github.githubassets.com/favicon.ico",
"id": 195,
"isOmniboxExtension": false,
"keyword": "gh",
"modelIndex": 17,
"name": "GitHub",
"url": "https://github.com/search?q=%s&ref=opensearch",
"urlLocked": false
},
{
"canBeDefault": true,
"canBeEdited": true,
"canBeRemoved": true,
"default": false,
"displayName": "Aliexpress",
"iconURL": "https://ae01.alicdn.com/images/eng/wholesale/icon/aliexpress.ico",
"id": 220,
"isOmniboxExtension": false,
"keyword": "ali",
"modelIndex": 18,
"name": "Aliexpress Shopping",
"url": "http://www.aliexpress.com/wholesale?SearchText=%s&opensearch=true",
"urlLocked": false
},
{
"canBeDefault": true,
"canBeEdited": true,
"canBeRemoved": true,
"default": false,
"displayName": "Gist",
"iconURL": "https://github.githubassets.com/favicon.ico",
"id": 224,
"isOmniboxExtension": false,
"keyword": "gist",
"modelIndex": 19,
"name": "Gist",
"url": "https://gist.github.com/search?q=%s&ref=opensearch",
"urlLocked": false
},
{
"canBeDefault": true,
"canBeEdited": true,
"canBeRemoved": true,
"default": false,
"displayName": "IMDb",
"iconURL": "https://m.media-amazon.com/images/G/01/imdb/images/desktop-favicon-2165806970._CB484110913_.ico",
"id": 228,
"isOmniboxExtension": false,
"keyword": "im",
"modelIndex": 20,
"name": "IMDb",
"url": "http://www.imdb.com/find?s=all&q=%s",
"urlLocked": false
},
{
"canBeDefault": true,
"canBeEdited": true,
"canBeRemoved": true,
"default": false,
"displayName": "amazon.co.uk",
"iconURL": "https://www.amazon.co.uk/favicon.ico",
"id": 247,
"isOmniboxExtension": false,
"keyword": "auk",
"modelIndex": 21,
"name": "amazon.co.uk",
"url": "https://www.amazon.co.uk/s/ref=nb_sb_noss/260-3973365-6318214?url=search-alias%3Daps&field-keywords=%s",
"urlLocked": false
},
{
"canBeDefault": true,
"canBeEdited": true,
"canBeRemoved": true,
"default": false,
"displayName": "Chocolatey",
"iconURL": "https://chocolatey.org/favicon.ico",
"id": 251,
"isOmniboxExtension": false,
"keyword": "cho",
"modelIndex": 22,
"name": "Chocolatey",
"url": "https://chocolatey.org/packages?q=%s",
"urlLocked": false
},
{
"canBeDefault": true,
"canBeEdited": true,
"canBeRemoved": true,
"default": false,
"displayName": "Vikipeedia (et)",
"iconURL": "https://et.wikipedia.org/static/favicon/wikipedia.ico",
"id": 256,
"isOmniboxExtension": false,
"keyword": "wet",
"modelIndex": 24,
"name": "Vikipeedia (et)",
"url": "https://et.wikipedia.org/w/index.php?title=Eri:Otsimine&search=%s",
"urlLocked": false
},
{
"canBeDefault": true,
"canBeEdited": true,
"canBeRemoved": true,
"default": false,
"displayName": "Steam",
"iconURL": "https://store.steampowered.com/favicon.ico",
"id": 264,
"isOmniboxExtension": false,
"keyword": "steam",
"modelIndex": 26,
"name": "store.steampowered.com",
"url": "https://store.steampowered.com/search/?snr=1_4_4__12&term=%s",
"urlLocked": false
},
{
"canBeDefault": true,
"canBeEdited": true,
"canBeRemoved": true,
"default": false,
"displayName": "amazon.de",
"iconURL": "https://www.amazon.de/favicon.ico",
"id": 284,
"isOmniboxExtension": false,
"keyword": "ade",
"modelIndex": 27,
"name": "amazon.de",
"url": "https://www.amazon.de/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords=%s",
"urlLocked": false
},
{
"canBeDefault": true,
"canBeEdited": true,
"canBeRemoved": true,
"default": false,
"displayName": "ebay.co.uk",
"iconURL": "https://www.ebay.co.uk/favicon.ico",
"id": 285,
"isOmniboxExtension": false,
"keyword": "euk",
"modelIndex": 28,
"name": "ebay.co.uk",
"url": "https://www.ebay.co.uk/sch/i.html?_from=R40&_trksid=m570.l1313&_nkw=%s&_sacat=0",
"urlLocked": false
},
{
"canBeDefault": true,
"canBeEdited": true,
"canBeRemoved": true,
"default": false,
"displayName": "Music-Map",
"iconURL": "https://www.music-map.com/favicon.ico",
"id": 287,
"isOmniboxExtension": false,
"keyword": "mumap",
"modelIndex": 29,
"name": "music-map.com",
"url": "https://www.music-map.com/map-search.php?f=%s",
"urlLocked": false
},
{
"canBeDefault": true,
"canBeEdited": true,
"canBeRemoved": true,
"default": false,
"displayName": "Google Play Store",
"iconURL": "https://www.gstatic.com/android/market_images/web/favicon_v2.ico",
"id": 294,
"isOmniboxExtension": false,
"keyword": "app",
"modelIndex": 30,
"name": "Google Play Store",
"url": "https://play.google.com/store/search?q=%s&c=apps",
"urlLocked": false
},
{
"canBeDefault": true,
"canBeEdited": true,
"canBeRemoved": true,
"default": false,
"displayName": "amazon.it",
"iconURL": "https://www.amazon.it/favicon.ico",
"id": 24,
"isOmniboxExtension": false,
"keyword": "ait",
"modelIndex": 1,
"name": "amazon.it",
"url": "http://www.amazon.it/s/ref=nb_sb_noss?__mk_it_IT=%C5M%C5%u017D%D5%D1&url=search-alias%3Daps&field-keywords=%s",
"urlLocked": false
},
{
"canBeDefault": true,
"canBeEdited": true,
"canBeRemoved": true,
"default": false,
"displayName": "ebay.it",
"iconURL": "https://www.ebay.it/favicon.ico",
"id": 263,
"isOmniboxExtension": false,
"keyword": "eit",
"modelIndex": 25,
"name": "ebay.it",
"url": "https://www.ebay.it/sch/i.html?_from=R40&_trksid=m570.l1313&_nkw=%s&_sacat=0",
"urlLocked": false
},
{
"canBeDefault": true,
"canBeEdited": true,
"canBeRemoved": true,
"default": false,
"displayName": "Trovaprezzi",
"iconURL": "https://a3.trovaprezzi.it/assets/assets/it/favicon_32x32-342b3e6a49cc618f396e167f687360be2ab61d7cdaf82579e4758bf47a2c178a.ico",
"id": 168,
"isOmniboxExtension": false,
"keyword": "tp",
"modelIndex": 11,
"name": "trovaprezzi.it",
"url": "https://www.trovaprezzi.it/categoria.aspx?id=-1&libera=%s",
"urlLocked": false
},
{
"canBeDefault": true,
"canBeEdited": true,
"canBeRemoved": true,
"default": false,
"displayName": "Wikipedia (it)",
"id": 68,
"isOmniboxExtension": false,
"keyword": "wit",
"modelIndex": 3,
"name": "Wikipedia (it)",
"url": "http://it.wikipedia.org/w/index.php?search=%s&title=Speciale%3ARicerca",
"urlLocked": false
}
]
================================================
FILE: Docker/.bashrc
================================================
# Docker
alias d-clean='docker system prune'
alias d-list='docker container ls -a --format "table {{.ID}}\t{{.Image}}\t{{.Names}}\t{{.Status}}"'
alias d-stop-all='docker stop $(docker container ls -q)'
# Docker Compose
alias dc-start='docker-compose up -d'
alias dc-build='docker-compose build'
alias dc-stop='docker-compose down --remove-orphans'
alias dc-restart='docker-compose up -d --force-recreate'
alias dc-rebuild='docker-compose down --remove-orphans && docker-compose build && docker-compose up -d'
================================================
FILE: Docker/Dockerfile
================================================
FROM alpine:latest
RUN set -xe \
# Install build tools, libraries and utilities
&& apk add --no-cache --virtual .build-deps \
gnupg \
wget \
# Contain file system pollution
&& TMP="$(mktemp -d)" && cd "$TMP" \
# Check integrity of the signature by signing the public key
# retrieved from a key server imported using the key fingerprint
&& gpg --keyserver pgp.mit.edu --recv-keyserver B0F4253373F8F6F510D42178520A9993A1C052F8 \
# Download, verify and unpack artifacts
&& wget --show-progress http://download/file.tar.gz \
&& wget --show-progress http://download/file.tar.gz.asc \
&& gpg --verify file.tar.gz.asc \
&& tar -xf file.tar.gz \
# Build and install
# Clean up
&& cd / && rm -rf "$TMP" \
&& apk del .build-deps \
# Forward logs to Docker logs cli
&& ln -sf /dev/stdout ...logs/output.log \
ln -sf /dev/stderr ...logs/error.log
# Copy static content and configuration from host to container
COPY from to
# Stop the container gracefully
STOPSIGNAL SIGQUIT
# Expose port
EXPOSE 1234
# Define entrypoint and default parameters
ENTRYPOINT [""]
CMD ["",""]
================================================
FILE: Docker/README.md
================================================
# Docker
_Table of Contents_
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
<!-- generated with [DocToc](https://github.com/thlorenz/doctoc) -->
- [Basic operations](#basic-operations)
- [Customize containers list](#customize-containers-list)
- [Check if Docker Engine is running](#check-if-docker-engine-is-running)
- [Docker compose](#docker-compose)
- [Basic operations](#basic-operations-1)
- [Useful links](#useful-links)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
## Basic operations
```sh
## List running containers (formerly "docker ps")
docker container ls
# List all containers, running and stopped
docker container ls -a
# Check whether one specific container is running
docker container ls -a | grep container_name
# Stop all running containers
docker stop $(docker ps -q)
# List images
docker image ls
# List dangling images
docker images -f dangling=true
# Remove dangling images
docker image prune
# Remove dangling and unused images
docker image prune -a
# Follow the logs of a running container
docker logs -f <container_name>
# Enter and open a shell in a running container
docker exec -it <container_name> bash
# Print a list of the environment variables of a running container
docker exec -it <container_name> env
# Run a SQL query in a Postgres container
docker exec container-name bash -c 'psql -d database-name -U username --command "select * from users;"'
# Inspect an image (use /bin/sh for alpine images)
docker image pull <image_name>
docker run -t -i <image_id> /bin/bash
```
## Customize containers list
```sh
# Show id, image, name and status of all containers
docker container ls -a --format "table {{ .ID }}\t{{ .Image }}\t{{ .Names }}\t{{ .Status }}"
# Show name, status and ports of all containers
docker container ls -a --format "table {{ .Names }}\t{{ .Status }}\t{{ .Ports }}"
# Filter containers by name
docker container ls -f name=container-name
```
Set a format to use it as a default in your `~/.docker/config.json`:
```js
{ "psFormat": "table {{ .Names }}\t{{ .Status }}\t{{ .Ports }}" }
```
- [Source](https://github.com/moby/moby/issues/7477)
## Check if Docker Engine is running
Run:
```sh
docker version
```
If docker **is running** you will see:
```sh
Client: Docker Engine - Community
Version: ...
[omitted]
Server: Docker Engine - Community
Engine:
Version: ...
[omitted]
```
If docker **is not running** you will see:
```sh
Client: Docker Engine - Community
Version: ...
[omitted]
Error response from daemon: Bad response from Docker engine
```
## Docker compose
Docker Compose is a way to configure docker containers together as a logical unit, define resources they all share and run containers together.
Some of the advantages include:
- it keeps track of the container it starts (via labels). If you re-run `docker-compose up -d` without changes it won’t try to recreate any containers. If on the other hand you change a service a `docker-compose up -d` will recreate only that service and any service that depends on it.
- with `logs` you can look at outputs of all involved containers merged together
- `ls` covers just the containers stemming from the given compose-file.
### Basic operations
```sh
# build
docker-compose build
# start
docker-compose up -d
# stop
docker-compose down --remove-orphans
# restart
docker-compose up -d --force-recreate
# rebuild
docker-compose down --remove-orphans && docker-compose build && docker-compose up -d
# clean up stale images
docker system prune
# prevent containers to start automatically
docker update --restart=no $(docker container ls -a -q)
# make one container start automatically
docker update --restart=always container_name
```
- [Restart policies (--restart)](https://docs.docker.com/engine/reference/run/#restart-policies---restart)
## Useful links
- [Slim](https://github.com/slimtoolkit/slim)
================================================
FILE: ExifTool/README.md
================================================
# ExifTool
[ExifTool](https://exiftool.org/) is a library and a command-line application for reading, writing and editing meta information.
_Table of Contents_
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
<!-- generated with [DocToc](https://github.com/thlorenz/doctoc) -->
- [Shift 2 hours earlier the time of the photos in the current folder](#shift-2-hours-earlier-the-time-of-the-photos-in-the-current-folder)
- [Set a specific date for all photos in the current folder, without changing the time](#set-a-specific-date-for-all-photos-in-the-current-folder-without-changing-the-time)
- [Rename image and video files by date and time](#rename-image-and-video-files-by-date-and-time)
- [Move or copy image files into folders by year and month](#move-or-copy-image-files-into-folders-by-year-and-month)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
## Shift 2 hours earlier the time of the photos in the current folder
```powershell
exiftool "-DateTimeOriginal-=0:0:0 2:0:0" .
```
## Set a specific date for all photos in the current folder, without changing the time
In powershell:
```powershell
Get-ChildItem *.jpg | ForEach-Object {
$currentDateTime = exiftool -s -s -s -DateTimeOriginal $_.Name
$timePart = $currentDateTime.Split(' ')[1]
exiftool -DateTimeOriginal="2006:10:16 $timePart" $_.Name
Write-Host "Updated: $($_.Name)"
}
```
## Rename image and video files by date and time
Rename image and video files according to their EXIF capture date, using `YYYY-MM-DD HH.MM.SS.ext` format. Files shot within the same second get copy number added (`-1`, `-2`, etc.). Some MOV files require a different date, so we run exiftool 3 times.
```powershell
# Exclude MOV files and rename the image files with <CreateDate>
exiftool --ext MOV '-filename<CreateDate' -d '%Y-%m-%d %H.%M.%S%%-c.%%le' .
# Target MOV files and rename them with MediaCreateDate (for iPhone videos)
exiftool -ext MOV '-filename<ContentCreateDate' -d '%Y-%m-%d %H.%M.%S%%-c.%%le' .
# Target MOV files and rename them with DateTimeOriginal (for Fuji camera videos)
exiftool -ext MOV '-filename<DateTimeOriginal' -d '%Y-%m-%d %H.%M.%S%%-c.%%le' .
```
`--ext` EXCLUDES files with the extension.
`-ext` INCLUDES files with that extension.
See:
- [Rename image files according to their creation date](https://ninedegreesbelow.com/photography/exiftool-commands.html#rename)
- [Common Date Format Codes](https://exiftool.org/filename.html)
- [Exiftool Canonize](https://gist.github.com/jmuspratt/3680d45b0c12f8b32093)
## Move or copy image files into folders by year and month
```powershell
# Move
exiftool '-Directory<CreateDate' -d './destination/folder/%Y/%m %B' -r ./source/folder
# Copy
exiftool -o . '-Directory<CreateDate' -d './destination/folder/%Y/%m %B' -r ./source/folder
```
See [Writing "FileName" and "Directory" tags](https://exiftool.org/filename.html).
================================================
FILE: Git/.gitconfig
================================================
[alias]
delete-last-commit = reset --hard HEAD~1
undo-last-commit = reset HEAD~1
stage-all-and-commit = add . && git commit -m
reset-and-clean = reset --hard && git clean -f -d
stash-keep = "!git stash store $(git stash create)"
list-local-branches = branch
delete-local-branch = branch -d
new-branch = checkout master && git pull && checkout -b
prune-branches = "!git branch --merged | grep -v "\\*" | xargs -n 1 git branch -d"
update = pull --rebase
log-pretty = log --oneline --graph --decorate
go-to-master = checkout master && git pull
================================================
FILE: Git/README-template.md
================================================
# `<project_name>`
<project_name> is a <utility/tool/service/application> that allows <target_audience> to do <action/task>.
_Additional line of information text about what the project does, should be up to 3 sentences._
_Table of Contents_
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
<!-- Generated with [DocToc](https://github.com/thlorenz/doctoc) -->
- [Tech stack](#tech-stack)
- [Prerequisites](#prerequisites)
- [Setup](#setup)
- [Running](#running)
- [Testing](#testing)
- [Contributing](#contributing)
- [Deploying](#deploying)
- [Monitoring](#monitoring)
- [Troubleshooting](#troubleshooting)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
## Tech stack
_List all the frameworks, libraries and tools used by this project_
## Prerequisites
_List all the software tools and their versions required to set up and run this project_
## Setup
_Explain how to set up this project locally for the first time_
## Running
_Explain how to run this project locally each time_
## Testing
_Explain how the tests are structured, which ones should be run locally and how_
## Contributing
_Explain how to contribute to this repository, conventions, guidelines and code review process_
## Deploying
_Explain how to deploy to staging and to production_
## Monitoring
_List the possible ways to monitor the health status of this project_
## Troubleshooting
_List here all the problems found by any developer while working on this project and their solutions, each one in a different subsection_
================================================
FILE: Git/README.md
================================================
# git
Table of Contents
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
<!-- Generated with [DocToc](https://github.com/thlorenz/doctoc) -->
- [First setup](#first-setup)
- [Branch operations](#branch-operations)
- [Merge remote changes to your local changes](#merge-remote-changes-to-your-local-changes)
- [Commits operations](#commits-operations)
- [Stash operations](#stash-operations)
- [Remove/delete local untracked files](#removedelete-local-untracked-files)
- [Revert a PR merge and delete its commits from master history](#revert-a-pr-merge-and-delete-its-commits-from-master-history)
- [Revert a PR merge to master](#revert-a-pr-merge-to-master)
- [Revert / undo / delete a pushed tag](#revert--undo--delete-a-pushed-tag)
- [Revision history](#revision-history)
- [Find who added and subtracted the most lines in a repository](#find-who-added-and-subtracted-the-most-lines-in-a-repository)
- [Display the history of changes of the lines containing a specific string](#display-the-history-of-changes-of-the-lines-containing-a-specific-string)
- [Display a compact list of commits](#display-a-compact-list-of-commits)
- [Search for a term in the commit history](#search-for-a-term-in-the-commit-history)
- [Enable git bash aliases auto completion](#enable-git-bash-aliases-auto-completion)
- [Persist the passphrase through restarts](#persist-the-passphrase-through-restarts)
- [On *nix systems](#on-nix-systems)
- [On Windows](#on-windows)
- [Resources](#resources)
- [Tools](#tools)
- [GitHub](#github)
- [Find the most active forks of a repository](#find-the-most-active-forks-of-a-repository)
- [Merging an upstream repository into your fork](#merging-an-upstream-repository-into-your-fork)
- [Navigate to the first commit in a GitHub repository](#navigate-to-the-first-commit-in-a-github-repository)
- [Change base branch](#change-base-branch)
- [Resurrect a PR displaying unknown repository after the fork was deleted](#resurrect-a-pr-displaying-unknown-repository-after-the-fork-was-deleted)
- [Tools](#tools-1)
- [Show commits between two dates](#show-commits-between-two-dates)
- [GitHub Learning Lab](#github-learning-lab)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
## First setup
```powershell
git config --global user.name "Your name here"
git config --global user.email "your_email@example.com"
git config --global core.editor code
ssh-keygen -t rsa -C "your_email@example.com"
# Copy the content of the public key to your clipboard, for example in PowerShell:
Get-Content C:\Users\user\.ssh\id_rsa.pub | Set-Clipboard
```
1. [GitHub Account Settings > SSH Keys](https://github.com/settings/ssh)
1. Press `New SSH Key`
1. Title = your computer name
1. Key = paste the clipboard content
Test the connection with:
```sh
ssh -T git@github.com
```
## Branch operations
```sh
# List local branches
git branch
# Get the current branch name
git rev-parse --abbrev-ref HEAD
# Delete local branch
git branch -d local-branch-name
# Delete all local branches except master or main
git branch | grep -v "master" | grep -v "main" | xargs git branch -D
# Reset your local branch
git fetch origin && git reset --hard && git clean -f -d
# Clone remote branch locally
# with modern Git (>= 1.6.6)
git fetch && git checkout remote-branch-name
# with old Git (< 1.6.6)
git fetch && git checkout -b remote-branch-name HEAD
# Merge master into the current branch
git pull origin master
```
### Merge remote changes to your local changes
When working in a busy branch, with more than one contributor, you usually synchronize your code by pulling after every commit or so, possibly several times a day. By using simply `git pull` you are actually issuing `git fetch` + `git merge` commands, which will result with an extra merge commit in your history.
To keep the repository clean use _rebase_:
- terminal: `git pull --rebase`
- Visual Studio Code > : Source Control Manager (SCM) > _Pull (Rebase)_
- IntelliJ IDEA > _Rebase current onto selected_ (master)
or add an alias to your `~/.gitconfig`, for example:
```sh
[alias]
update = pull --rebase
```
or set rebase as the default using:
```sh
git config branch.autosetuprebase always
```
using `git pull --no-rebase` when you want to use merge instead.
## Commits operations
```sh
# Undo the last local (not pushed) commit, keeping the changes
git reset HEAD~1
# Delete the last local (not pushed) commit and all uncommited changes
git reset --hard HEAD~1
# Undo an old commit, keeping all commits that came after that one
git revert <COMMIT_SHA>
# Restore your project to an old commit, undoing/deleting all the commits that came afterwards
git reset --hard <COMMIT_SHA>
# Commit all changes
git commit -a
```
## Stash operations
```sh
# Stash your changes and untracked files
git stash -u
# View a summary of your last stash
git stash show
# Pass the -p option (or --patch) to view the full diff
git stash show -p
# View your untracked files in your last stash
git show stash^3
# Copy your last stash to a file
git stash show -p > modifiedfile
git show stash^3 > untrackedfile
# Put a patch file to the stash
git apply modifiedfile
git apply untrackedfile
# Stash without removing the changes
git stash store $(git stash create) -m "Stash commit message"
# Stash a single file
git stash push path/to/file --keep-index
```
## Remove/delete local untracked files
```bash
# Run this command first to check which files will be removed:
git clean -n
# When you are sure you want to remove then run:
git clean -f -d
```
## Revert a PR merge and delete its commits from master history
Warning! This operation is potentially harmful, it will delete also all the merges of other PRs done in between:
```shell
git reset --hard <COMMIT_SHA>
git status
git push -f origin master
```
## Revert a PR merge to master
After reverting a PR on master (i.e., it was mistakenly merged the first time), to produce a clean history for the second attempt at a PR:
1. Temporarily move master (so that subsequent rebase commits are not dropped by Git)
```bash
git checkout master
git revert --mainline 1 <PR_SHA>
```
1. Rebase to reattach old commits to latest master
```bash
git checkout <BRANCH>
git rebase --onto master <FIRST_COMMIT_SHA>~
git checkout -b <NEW_BRANCH> # This will require you to create a new PR. You should no longer use <BRANCH> but instead use <NEW_BRANCH> going forward.
```
1. Restore master (as it was temporarily move to help with rebase)
```bash
git checkout master
git reset --hard origin/master
```
## Revert / undo / delete a pushed tag
```bash
# delete local tag '1.2.3'
git tag -d 1.2.3
# delete remote tag '1.2.3'
git push origin :refs/tags/1.2.3
```
## Revision history
### Find who added and subtracted the most lines in a repository
With [git-guilt](https://bitbucket.org/tpettersen/git-guilt/src/master/):
```
git-guilt `git log --until="3 years ago" --format="%H" -n 1` HEAD
```
### Display the history of changes of the lines containing a specific string
```
git log -S "specific string" --patch --reverse
```
### Display a compact list of commits
```
git log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit
```
Or add it as `lg` alias:
```
git config --global alias.lg "log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit"
```
## Search for a term in the commit history
```sh
git log -G"search term"
```
To see the changes in the commits:
```sh
git log -G"search term" --patch
```
## Enable git bash aliases auto completion
On most distributions, git completion script is installed when you install git. You just need to add this line to your `~/.bashrc`:
```sh
source /etc/bash_completion.d/git
# or (in ArchLinux for example)
source /usr/share/bash-completion/completions/git
```
## Persist the passphrase through restarts
### On *nix systems
```sh
# Append to ~/.bashrc
eval `ssh-agent -s`
# Run
source ~/.bashrc
# Store the passphrase in your keychain with the `-K` option (`-k` for Ubuntu):
ssh-add -K ~/.ssh/id_rsa
```
### On Windows
```sh
# 1. Install OpenSSH Client:
Get-WindowsCapability -Online | Where-Object { $_.Name -like "OpenSSH.Client*" } | Add-WindowsCapability -Online | Out-Null
# 2. Set the service "OpenSSH Authentication Agent" to start automatically:
Get-Service ssh-agent | Set-Service -StartupType Automatic -PassThru | Start-Service
# 3. Add the private key
ssh-add C:\Users\YourUsername\.ssh\id_rsa
```
## Resources
- [git-tips](https://github.com/git-tips/tips)
- [Githug](https://github.com/Gazler/githug)
- [How to Write a Git Commit Message](https://chris.beams.io/posts/git-commit/)
- [Semantic Commit Messages](https://gist.github.com/joshbuchea/6f47e86d2510bce28f8e7f42ae84c716)
## Tools
- [git for Windows](https://chocolatey.org/packages/git)
- [TortoiseGit](https://chocolatey.org/packages/TortoiseGit)
## GitHub
### Find the most active forks of a repository
- [active-forks](https://techgaun.github.io/active-forks/index.html)
### Merging an upstream repository into your fork
```powershell
git pull https://github.com/ORIGINAL_OWNER/ORIGINAL_REPOSITORY.git BRANCH_NAME
```
- [Source](https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/merging-an-upstream-repository-into-your-fork)
### Navigate to the first commit in a GitHub repository
1. take a note of the number of commits in the repository (say N)
1. calculate X = N-36
1. go to the list of commits
1. click on the "Older" button at the bottom of the page
1. replace +Y suffix in the URL with +X
### Change base branch
- [Changing the base branch of a pull request](https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/changing-the-base-branch-of-a-pull-request)
### Resurrect a PR displaying unknown repository after the fork was deleted
```sh
git fetch origin refs/pull/123/head:foo
```
Substitute (if necessary) `origin` for the remote pointing at the target repo, `123` for the PR number, and `foo` for the name of the local branch you want created to point to the head of the PR.
Then you can simply `git checkout foo`, close the stale PR, and resubmit a new one which supersedes it.
Sources: [this](https://github.com/isaacs/github/issues/168#issuecomment-374201226) and [this](https://gist.github.com/piscisaureus/3342247).
### Tools
- [Octo Mate](https://chrome.google.com/webstore/detail/octo-mate/baggcehellihkglakjnmnhpnjmkbmpkf)
### Show commits between two dates
Append `?since=2018-05-31&until=2018-07-01`.
Example:
```
https://github.com/github/linguist/commits/master?since=2018-05-31&until=2018-07-01
```
Source: [this](https://stackoverflow.com/a/42472394/1422096).
### GitHub Learning Lab
Learn how to use GitHub with interactive courses designed for beginners and experts:
- https://skills.github.com/
================================================
FILE: Go/README.md
================================================
# Go
Created by a small team at Google in 2007, composed by Robert Griesemer, Rob Pike, and Ken Thompson. Ken Thomson is the creator of the B programming language, which was the direct predecessor of the C programming language. He also created the Unix operating system, and the UTF-8 character encoding. Rob Pike is the creator of the Plan 9 operating system, and the Limbo programming language. Robert Griesemer is the creator of the Java HotSpot virtual machine, and the Java programming language.
Go was created to resolve the problems of the existing languages, such as the slow build time of C++, the verbosity of Java and complexity of its type system, the slow performance of Python and JavaScript and the lack of good concurrency support in all of them. These languages where invented at a time when computers didn't have a lot of memory, and the programs typically ran on a single core. Go is a strong and statically typed, compiled language in the tradition of C, with the added benefits of memory safety, garbage collection, structural typing, and CSP-style concurrency.
CSP-style concurrency (Communicating Sequential Processes) is a concurrency model that was developed by Tony Hoare in the 1970s. It is based on the idea of having concurrent processes communicate with each other by sending and receiving messages. This is in contrast to the shared memory model of concurrency, where concurrent processes communicate with each other by reading and writing to shared memory. The shared memory model of concurrency is the model used by C, C++, and Java. The CSP-style concurrency model is the model used by Go, Erlang, and Clojure.
The key features of Go are:
- Fast compilation
- Garbage collection
- Built-in concurrency
- Static typing
- Simplicity
- Safety
- Built-in tooling
Go has a built-in library (called "standard library") full of features like a testing framework, JSON and CSV encoding/decoding, html templating, http server and router, time operations and manipulation, regular expressions, cryptographic operations such as hashing and encryption, images encoding/decoding for formats like JPEG, PNG, GIF, file compression and decompression, and many more. Having such a rich standard library means that you don't have to rely on third-party libraries for many common tasks.
Go is used by many companies, including Google, Facebook, Twitter, Dropbox, Docker, Kubernetes, and many more. Many popular projects are written in Go, including Docker, Kubernetes, Hugo, InfluxDB, Terraform, and many more.
Go doesn't have a built-in dependency injection framework. This is because Go has a built-in dependency injection mechanism called "interfaces". An interface is a type that specifies a set of methods. A type that implements all the methods of an interface implements that interface. This means that you can use a type that implements an interface anywhere that interface is used. This is called "implicit implementation". This is in contrast to "explicit implementation", where you have to explicitly declare that a type implements an interface. Implicit implementation is a form of dependency injection, because it allows you to inject a type that implements an interface into a function or method that expects that interface.
The following notes are based on the current version of Go, which is [1.20.4](https://tip.golang.org/doc/go1.20), as of May 2023.
*Table of contents*
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
<!-- generated with [DocToc](https://github.com/thlorenz/doctoc) -->
- [Installation](#installation)
- [Setup](#setup)
- [Running and compiling](#running-and-compiling)
- [Type inference](#type-inference)
- [Initial values](#initial-values)
- [Arrays](#arrays)
- [Slices](#slices)
- [Maps](#maps)
- [Loops](#loops)
- [Functions](#functions)
- [Structs](#structs)
- [Generics (WIP)](#generics-wip)
- [Fuzzing (WIP)](#fuzzing-wip)
- [Testing (WIP)](#testing-wip)
- [Naming conventions](#naming-conventions)
- [IDEs](#ides)
- [Resources](#resources)
- [YouTube channels and playlists](#youtube-channels-and-playlists)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
## Installation
Go can be installed on Windows, macOS, and Linux. The installation instructions for each operating system can be found at https://golang.org/doc/install.
On Windows can be installed with winget:
```powershell
winget install --id GoLang.Go
```
## Setup
All your projects are in the same directory called the "workspace", located in the user's home directory, which by default is called "go". You can see its location by running `go env GOPATH`. The workspace contains three subdirectories:
- `src`, which contains the source files of your projects;
- `pkg`, which contains the compiled packages;
- `bin`, which contains the compiled binaries.
## Running and compiling
```sh
# Run a Go program
go run <filename>
# Compile a Go program and place the compiled binary in the current directory
go build <filename>
# Compile a Go program and place the compiled binary in the bin directory of the workspace
go install <filename>
```
## Type inference
In Go the compiler can infer the type of a variable from its value. This is called "type inference". Type inference is useful because it allows you to omit the type of a variable when you declare it. This makes the code shorter and easier to read.
```go
// Standard declaration
var x int = 1
// Shorthand declaration with type inference
x := 1
```
## Initial values
Every type has an initial value. The initial value of a numeric type is 0, the initial value of a string type is "", and the initial value of a boolean type is false.
```go
// Initial values
var x int // 0
var y string // ""
var z bool // false
```
## Arrays
An array is a fixed-length sequence of elements of a single type. Once an array is created, its length is fixed. The length of an array is part of its type. This means that arrays of different lengths are of different types, and you cannot assign an array of one length to an array of a different length.
```go
// Standard declaration of an array
var x [3]int = [3]int{1, 2, 3}
// Shorthand declaration of an array
x := [3]int{1, 2, 3}
```
## Slices
A slice is a variable-length sequence of elements of a single type. A slice is a reference type, which means that when you assign a slice to a variable or pass a slice to a function, a copy of the slice header is created and assigned or passed. The slice header contains a pointer to the underlying array, the length of the slice, and the capacity of the slice. The capacity of a slice is the maximum number of elements that the slice can hold. The length of a slice is the number of elements that the slice currently holds. The length of a slice can be changed by re-slicing the slice. The capacity of a slice cannot be changed.
```go
// Standard declaration of a slice
var x []int = []int{1, 2, 3}
// Shorthand declaration of a slice
x := []int{1, 2, 3}
```
## Maps
Maps are unordered collections of key-value pairs. The keys of a map must be of a type that can be compared with the `==` operator. The values of a map can be of any type. The keys of a map must be unique. The values of a map can be duplicated.
```go
// Standard declaration of a map
var x map[string]int = map[string]int{"one": 1, "two": 2, "three": 3}
// Shorthand declaration of a map
x := map[string]int{"one": 1, "two": 2, "three": 3}
// Add a key-value pair to a map
x["four"] = 4
// Remove a key-value pair from a map
delete(x, "four")
```
## Loops
The `for` loop is the only loop statement in Go. It can be used to iterate over the elements of an array, slice, or map.
```go
// Iterate over the elements of an array or slice
for i := 0; i < len(x); i++ {
fmt.Println(x[i])
}
// While loop equivalent
i := 0
for i < 10 {
fmt.Println(i)
i++
}
// Iterate over the elements of an array or slice with range
for i, value := range x {
fmt.Println(i, value)
}
// Iterate over the elements of a map
for key, value := range x {
fmt.Println(key, value)
}
```
## Functions
Functions in Go are first-class values. This means that you can assign a function to a variable, pass a function to a function, and return a function from a function.
Functions can return multiple values. The type of each return value is specified after the list of parameters. If a function returns multiple values, the return statement must specify the values to return.
```go
// Standard declaration of a function
func add(x int, y int) int {
return x + y
}
// Return multiple values
func addAndSubtract(x int, y int) (int, int) {
return x + y, x - y
}
// Assign variables returned from a function that returns multiple values
sum, difference := addAndSubtract(42, 13)
// Return multiple values, one of which is an error
func addPositives(x int, y int) (int, error) {
if x < 0 || y < 0 {
return 0, errors.New("x and y must be greater than 0")
}
return x + y, nil
}
// Assign a function to a variable
var f func(int, int) int = addPositives
// Pass a function to a function
func apply(f func(int, int) int, x, y int) int {
return f(x, y)
}
// Return a function from a function
func add(x int) func(int) int {
return func(y int) int {
return x + y
}
}
```
## Structs
A struct is a collection of fields. The fields of a struct can be of any type. The fields of a struct can be accessed using dot notation.
```go
// Standard declaration of a struct
type Person struct {
Name string
Age int
}
// Shorthand declaration of a struct
type Person struct {
Name, Age string
}
// Create a struct
p := Person{"John Doe", 42}
// Access a field of a struct
fmt.Println(p.Name)
```
## Generics (WIP)
Go supports generics since version 1.18. Generics allow you to write functions and data structures that can be used with any type. Generics are implemented using type parameters. Type parameters are specified in square brackets after the name of the function or data structure. Type parameters are specified using the `type` keyword. Type parameters can be used as types in the function or data structure.
```go
// Generic function
func add[T any](x, y T) T {
return x + y
}
// Generic data structure
type Stack[T any] struct {
values []T
}
// Generic method
func (s *Stack[T]) Push(value T) {
s.values = append(s.values, value)
}
// Create a stack of ints
var s Stack[int]
// Create a stack of strings
var s Stack[string]
```
## Fuzzing (WIP)
Fuzzing is a technique for finding bugs in software by providing random input to the software. Go has built-in support for fuzzing. To use fuzzing, you need to create a function that takes a byte slice as input and returns an integer. The function should return 1 if the input is valid and 0 if the input is invalid. The function should panic if the input is invalid. The function should not return an error. The function should not print anything to the console.
```go
// Fuzzing function
func Fuzz(data []byte) int {
// Do something with the input
return 1
}
```
## Testing (WIP)
Go has built-in support for testing. To write a test, you need to create a function that takes a pointer to a testing.T as input. The function should call the testing.T.Error or testing.T.ErrorF function if the test fails. The function should call the testing.T.Fatal or testing.T.FatalF function if the test fails and the test should not continue. Tests are run using the `go test` command.
```go
// Test function
func TestSomething(t *testing.T) {
// Do something
if something != somethingElse {
t.Error("something is not equal to somethingElse")
}
}
```
## Naming conventions
- The name of a variable or function should be in camel case. The first letter of the name should be lowercase, e.g. `person`, `addPerson`, `getPerson`, etc.
- The name of a boolean variable should be a question, e.g. `isPerson`, `hasPerson`, `canPerson`, `shouldPerson`, etc.
- The name of a constant should be all uppercase, using underscores to separate words, e.g. `MAX_INT`.
- The name of a type should be in camel case. The first letter of the name should be uppercase, e.g. `Person`.
- The name of a package should be in lowercase, using underscores to separate words, e.g. `person_utils`.
## IDEs
According to [Go Developer Survey 2022 Q2 Results](https://go.dev/blog/survey2022-q2-results), the 3 most popular IDEs for Go are:
1. [Visual Studio Code]{https://code.visualstudio.com/docs/languages/go} (used by 45% of respondents)
2. GoLand (used by 34% of respondents)
3. Vim/Neovim (used by 14% of respondents)
## Resources
- [Go by Example](https://gobyexample.com/)
- [A Tour of Go](https://tour.golang.org/welcome/1)
- [Effective Go](https://golang.org/doc/effective_go.html)
- [Go Documentation](https://golang.org/doc/)
- [Go Standard Library](https://golang.org/pkg/)
- [Go Playground](https://play.golang.org/)
- [Go tutorial on TutorialEdge](https://tutorialedge.net/course/golang/)
- [All About GoLang](https://golangdocs.com/)
- [Go tutorial on GoLangTutorial](https://golangtutorial.dev/)
- [Go tutorial on GoLangByExample](https://golangbyexample.com/)
- [The Go Blog](https://go.dev/blog/)
- [Go on Twitter](https://twitter.com/golang)
- [Go Proverbs](https://go-proverbs.github.io/)
- [Practical Go Lessons](https://www.practical-go-lessons.com/)
### YouTube channels and playlists
- [Go Class, by Matt Holiday](https://www.youtube.com/playlist?list=PLoILbKo9rG3skRCj37Kn5Zj803hhiuRK6)
- [Gopher Academy](https://www.youtube.com/channel/UCx9QVEApa5BKLw9r8cnOFEA)
- [Anthony GG](https://www.youtube.com/@anthonygg_/videos)
- [Building Microservices with Go, by Nic Jackson](https://youtube.com/playlist?list=PLmD8u-IFdreyh6EUfevBcbiuCKzFk0EW_)
- [Mario Carrion](https://www.youtube.com/@MarioCarrion/videos)
- [Rob Pike's talks](https://www.youtube.com/results?search_query=Rob+Pike%27s+talks)
- [Golang University 101 - Learn Golang](https://www.youtube.com/watch?v=rFejpH_tAHM&list=PLEcwzBXTPUE9V1o8mZdC9tNnRZaTgI-1P&index=1)
- [Golang University 201 - Intermediate Golang](https://www.youtube.com/watch?v=yeetIgNeIkc&list=PLEcwzBXTPUE_5m_JaMXmGEFgduH8EsuTs)
- [Golang University 301 - Master Golang](https://www.youtube.com/playlist?list=PLEcwzBXTPUE8KvXRFmmfPEUmKoy9LfmAf)
- [The Go Programming Language](https://www.youtube.com/@golang/videos)
- [TutorialEdge](https://www.youtube.com/@Tutorialedge/videos)
- [Ardan Labs](https://www.youtube.com/@ardanlabs/video)
================================================
FILE: Google Docs/README.md
================================================
# Google Docs
## Format text as code
### Use an add-on
- [Code Blocks](https://gsuite.google.com/marketplace/app/code_blocks/100740430168)
### Add a style
1. Create a new script (`Tools > Script Editor`)
1. Copy the following code into the editor:
```js
// Add new menu item
function onOpen() {
DocumentApp.getUi()
.createMenu('Styles')
.addItem('Format Code', 'formatCode')
.addToUi();
}
// Define code styling
var style = {};
style[DocumentApp.Attribute.FONT_FAMILY] = DocumentApp.FontFamily.CONSOLAS;
style[DocumentApp.Attribute.FONT_SIZE] = 10;
style[DocumentApp.Attribute.BACKGROUND_COLOR] = "#DDDDDD";
style[DocumentApp.Attribute.FOREGROUND_COLOR] = "#333333";
style[DocumentApp.Attribute.BOLD] = false;
// Apply code formatting
function formatCode() {
var selection = DocumentApp.getActiveDocument().getSelection();
if (selection) {
var elements = selection.getRangeElements();
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
// Only modify elements that can be edited as text; skip images and other non-text elements.
if (element.getElement().editAsText) {
var text = element.getElement().editAsText();
// Style the selected part of the element, or the full element if it's completely selected.
if (element.isPartial()) {
text.setAttributes(element.getStartOffset(), element.getEndOffsetInclusive(), style);
} else {
text.setAttributes(style);
}
}
}
}
}
```
1. Assign a trigger to run the onOpen function "On open" (`Edit > Current Project's Triggers`)
1. After authorizing the script, reload the original document
1. Use the new menu item to format selected text (`Styles > Format Code`)
[Source](https://webapps.stackexchange.com/a/117682/56505)
================================================
FILE: GraphQL/README.md
================================================
# GraphQL
## Learning resources
- [GraphQL: A success story for PayPal Checkout](https://medium.com/paypal-engineering/graphql-a-success-story-for-paypal-checkout-3482f724fb53)
- [Scaling GraphQL at PayPal](https://medium.com/paypal-engineering/scaling-graphql-at-paypal-b5b5ac098810)
- [REST vs. GraphQL: A Critical Review](https://goodapi.co/blog/rest-vs-graphql)
### Videos
- [Ben Awad GraphQL playlists](https://www.youtube.com/user/99baddawg/playlists)
- [How to Move a Mountain? GraphQL Best Practices — Kewei Qu @ GraphQL Conf 2019](https://youtu.be/YCmtNB61BS8)
- [Refactoring Your Mind From REST — Lachlan Young @ GraphQL Conf 2019](https://youtu.be/xHLzguFd8Ug?t=206)
### Podcasts
- [{CodingBlocks}.NET 3factor app – Realtime GraphQL](https://podcasts.google.com/?feed=aHR0cDovL3d3dy5jb2RpbmdibG9ja3MubmV0L2ZlZWQv&episode=aHR0cHM6Ly93d3cuY29kaW5nYmxvY2tzLm5ldC8_cD04Mzky)
## Projects which can be used as reference
- [Spectrum](https://github.com/withspectrum/spectrum)
## Tools
- [GraphiQL](https://github.com/graphql/graphiql)
- [Public GraphQL APIs](http://apis.guru/graphql-apis/)
- [TypeGraphQL](https://typegraphql.ml)
- [PostGraphile](https://www.graphile.org/postgraphile/)
- [GraphQL Code Generator](https://graphql-code-generator.com)
#### [Apollo Client Developer Tools](https://chrome.google.com/webstore/detail/apollo-client-developer-t/jdkknkkbebbapilgoeccciglkfbmbnfm)
GraphiQL Explorer got integrated into DevTools in April 2019:
- [Integrate GraphiQL Explorer into devtools #199](https://github.com/apollographql/apollo-client-devtools/pull/199).
Besides the newly introduced Explorer, it gives a great summary of all the queries, mutations and caching done for a page.
Here you can see all its features:
- [GraphiQL Explorer 2.0: A power-user release!](https://www.onegraph.com/blog/2019/05/30/GraphiQL_Explorer_2_0_A_Power_User_Release.html)
================================================
FILE: Java/Country.java
================================================
public enum Country {
Austria("Austria", "AT", "AUT", 40, "+43"),
Albania("Albania", "AL", "AUB", 8, "+355"),
Belgium("Belgium", "BE", "BEL", 56, "+32"),
BosniaAndHerzegovina("Bosnia and Herzegovina", "BA", "BIH", 70, "+387"),
Bulgaria("Bulgaria", "BG", "BGR", 100, "+359"),
Croatia("Croatia", "HR", "HRV", 191, "+385"),
Cyprus("Cyprus", "CY", "CYP", 196, "+357"),
Czechia("Czechia", "CZ", "CZE", 203, "+420"),
Denmark("Denmark", "DK", "DNK", 208, "+45"),
Estonia("Estonia", "EE", "EST", 233, "+372"),
FaroeIslands("Faroe Islands", "FO", "FRO", 234, "+298"),
Finland("Finland", "FI", "FIN", 246, "+358"),
France("France", "FR", "FRA", 250, "+33"),
Germany("Germany", "DE", "DEU", 276, "+49"),
Greece("Greece", "GR", "GRC", 300, "+30"),
Hungary("Hungary", "HU", "HUN", 384, "+36"),
Iceland("Iceland", "IS", "ISL", 352, "+354"),
Ireland("Ireland", "IE", "IRL", 372, "+353"),
Italy("Italy", "IT", "ITA", 380, "+39"),
Latvia("Latvia", "LV", "LVA", 428, "+371"),
Lithuania("Lithuania", "LT", "LTU", 440, "+370"),
Luxembourg("Luxembourg", "LU", "LUX", 442, "+352"),
Macedonia("Macedonia", "MK", "MKD", 807, "+389"),
Malta("Malta", "MT", "MLT", 470, "+356"),
Moldova("Moldova", "MD", "LUX", 498, "+373"),
Montenegro("Montenegro", "ME", "MNE", 499, "+382"),
Netherlands("Netherlands", "NL", "NLD", 528, "+31"),
Norway("Norway", "NO", "NOR", 578, "+47"),
Poland("Poland", "PL", "POL", 616, "+48"),
Portugal("Portugal", "PT", "PRT", 620, "+351"),
Romania("Romania", "RO", "ROU", 642, "+40"),
Serbia("Serbia", "RS", "SRB", 688, "+381"),
Slovakia("Slovakia", "SK", "SVK", 703, "+421"),
Slovenia("Slovenia", "SI", "SVN", 705, "+386"),
Spain("Spain", "ES", "ESP", 724, "+34"),
Sweden("Sweden", "SE", "SWE", 752, "+46"),
Switzerland("Switzerland", "CH", "CHE", 756, "+41"),
Ukraine("Ukraine", "UA", "UKR", 804, "+380"),
UnitedKingdom("United Kingdom", "GB", "GBR", 826, "+44");
// Short name in English
public String name;
// http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2
public String alpha2;
// http://en.wikipedia.org/wiki/ISO_3166-1_alpha-3
public String alpha3;
// http://en.wikipedia.org/wiki/ISO_3166-1_numeric
public int numeric;
// https://en.wikipedia.org/wiki/List_of_country_calling_codes
public String callingCode;
Country(String name, String alpha2, String alpha3, int numeric, String callingCode) {
this.name = name;
this.alpha2 = alpha2;
this.alpha3 = alpha3;
this.numeric = numeric;
this.callingCode = callingCode;
}
}
================================================
FILE: Java/FixturesBuilder.java
================================================
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class FixturesBuilder {
public static final String COUNTRY_CODE = "EE";
public static final String EMAIL = "gabriel@reliikvia.ee";
public static final String PHONE_NUMBER = "+37212341234";
public static final String NAME = "Gabriel";
// Assumes Person is annotated with Lombok @Builder
public static Person.PersonBuilder aPerson() {
return Person.builder()
.name(NAME)
.countryCode(COUNTRY_CODE)
.email(EMAIL)
.phoneNumber(PHONE_NUMBER);
}
public static Person.PersonBuilder aMan() {
return aPerson().gender(1);
}
}
================================================
FILE: Java/README.md
================================================
# Java
_Table of Contents_
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
<!-- generated with [DocToc](https://github.com/thlorenz/doctoc) -->
- [Spring](#spring)
- [Lombok](#lombok)
- [Create private constructor](#create-private-constructor)
- [Maven](#maven)
- [Basic commands](#basic-commands)
- [Gradle](#gradle)
- [Basic commands](#basic-commands-1)
- [Plugins](#plugins)
- [Set console=rich by default](#set-consolerich-by-default)
- [Print the full stacktrace when logging tests exceptions](#print-the-full-stacktrace-when-logging-tests-exceptions)
- [Upgrade all dependencies to their latest version](#upgrade-all-dependencies-to-their-latest-version)
- [SDKMAN](#sdkman)
- [Set up a specific Java version for a project](#set-up-a-specific-java-version-for-a-project)
- [Switch Java version automatically when you cd into a directory](#switch-java-version-automatically-when-you-cd-into-a-directory)
- [Flyway](#flyway)
- [NeoVim for Java](#neovim-for-java)
- [Groovy](#groovy)
- [Google Java Format](#google-java-format)
- [Lombok](#lombok-1)
- [IntelliJ IDEA](#intellij-idea)
- [Install on Linux](#install-on-linux)
- [Find in files regexes](#find-in-files-regexes)
- [Object to JSON in debugger](#object-to-json-in-debugger)
- [Favorite plugins](#favorite-plugins)
- [Settings](#settings)
- [Navigate back and forward using mouse buttons clicks](#navigate-back-and-forward-using-mouse-buttons-clicks)
- [Enable changing the font size with the mouse wheel](#enable-changing-the-font-size-with-the-mouse-wheel)
- [Prevent IDEA from automatically close opened files](#prevent-idea-from-automatically-close-opened-files)
- [Shortcuts](#shortcuts)
- [Useful links](#useful-links)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
## Spring
- [Write parameterized tests with autowiring dependency injection in Spring Boot 1](https://stackoverflow.com/a/63168806/334569)
- [Setting a TTL for @Cacheable](https://stackoverflow.com/a/44203099/334569)
## Lombok
### Create private constructor
```java
@NoArgsConstructor(access = AccessLevel.PRIVATE)
```
## Maven
### Basic commands
```sh
# Display available updates
mvn versions:display-dependency-updates
# Execute only the tests in SomeTestClass
mvn test -Dtest=SomeTestClass
# Stop immediately after the first failing test
mvn test -Dsurefire.skipAfterFailureCount=1
```
## Gradle
### Basic commands
```sh
# Tasks runnable from root project
gradle tasks
# Build displaying more logging information
gradle -i build
# Executes only the tests in SomeTestClass
gradle test --tests SomeTestClass
# Executes only one specific test method
gradle test --tests SomeTestClass.specificMethod
# Stop immediately after the first failing test
gradle test --fail-fast
```
### Plugins
Since Gradle version 3 plugins can be specified through the plugins DSL:
```groovy
plugins {
id 'java'
}
```
The `plugins {}` block must be a top level statement in the buildscript and cannot be nested inside another construct.
### Set console=rich by default
Both in _Gradle_ and _Gradle Wrapper_, add the following line to your `./gradle.properties`:
```
org.gradle.console=rich
```
### Print the full stacktrace when logging tests exceptions
Add the following block to your `./build.gradle`:
```groovy
test {
testLogging.exceptionFormat = 'full'
}
```
### Upgrade all dependencies to their latest version
Use [Gradle Use Latest Versions Plugin ](https://github.com/patrikerdes/gradle-use-latest-versions-plugin).
## SDKMAN
SDKMAN allows to install multiple versions of Java and conveniently switch between them.
### Set up a specific Java version for a project
1. cd into the base directory of your project
1. use SDKMAN to switch to the desired Java version
1. run `sdk env init` (this will generate a `.sdkmanrc` file in the current directory, pre-populated with the Java version in use)
From now on when you enter your project base directory you can switch to the chosen Java version by simply running:
```sh
$ sdk env
```
### Switch Java version automatically when you cd into a directory
Set the folling in your `~/.sdkman/etc/config`:
```sh
sdkman_auto_env=true
```
## Flyway
_Flyway_ is an open-source database migration tool: it is based around just 7 basic commands: `migrate`, `clean`, `info`, `validate`, `undo`, `baseline` and `repair`.
Migrations files names must comply with [Flyway naming pattern](https://flywaydb.org/documentation/concepts/migrations.html#naming).
To check that flyway is configured correctly and to see the list of pending migrations run:
```sh
flyway info
```
To run the pending migrations run:
```sh
flyway migrate
```
Rolling back/undo migrations is availble only for _Flyway Pro_ or _Enterprise Edition_. To roll back with the _Community Edition_ you need to:
- locally:
1. run `flyway clean`
1. move the migrations you want to roll back out of `flyway.locations`
1. run `flyway migrate`
1. move the migrations you rolled back in `flyway.locations`
- staging/production:
1. write migrations which revert the changes made in the migrations you want to roll back
1. commit, push and deploy the migrations
For furthern info check the [Flyway documentation](https://flywaydb.org/documentation/).
## NeoVim for Java
The following steps outline a basic setup for working with Java in NeoVim, enabling these key features: syntax highlighting, code navigation, code refactoring, code completion, formatting, debugging, diagnostics (errors, warnings, etc.), hover information, auto imports.
1. Install SDKMAN with `curl -s "https://get.sdkman.io" | bash`
1. Install the latest stable version of Java with `sdk install java`
1. Install [NeoVim](../Linux/README.md#install-the-latest-version-on-ubuntu)
1. Install [LazyVim](../Linux/README.md#lazyvim)
1. Create `~/.config/nvim/lua/plugins/treesitter.lua` and paste in the following:
```lua
return {
"nvim-treesitter/nvim-treesitter",
opts = {
ensure_installed = {
"java",
},
},
}
```
1. Run `:Mason`, select `jdtls` and press `i` to install it, go up to the top and wait until you see it is installed.
1. Create `~/.config/nvim/lua/plugins/jdtls.lua` and paste in the following:
```lua
return {
{
"mfussenegger/nvim-jdtls",
ft = "java",
}
}
```
### Groovy
Support to _Groovy_ might be needed for example if you are using the [Spock](https://github.com/spockframework/spock) test framework.
1. Append `"groovy",` to the `ensure_installed` object in the `treesitter.lua` file mentioned above.
1. To be continued...
### Google Java Format
[google-java-format](https://github.com/google/google-java-format) is not supported by [eclipse.jdt.ls](https://github.com/eclipse-jdtls/eclipse.jdt.ls) (see [redhat-developer/vscode-java#663](https://github.com/redhat-developer/vscode-java/issues/663) & [redhat-developer/vscode-java#419](https://github.com/redhat-developer/vscode-java/issues/419)) but given that it's an executable you should be able to use it with formatprg, see `:help formatprg`.
### Lombok
To be continued...
## IntelliJ IDEA
### Install on Linux
[Install as a snap package](https://www.jetbrains.com/help/idea/installation-guide.html#snap) to have your installation always up to date.
Alternatively, install manually with the following steps:
1. Download [IntelliJ IDEA](https://www.jetbrains.com/idea/download/#section=linux)
1. Unpack the `tar.gz` file to an empty directory using the following command:
```sh
tar -xzf idea-2020.2.1.tar.gz
```
1. Run `bin/idea.sh`
### Find in files regexes
```sh
# Find files which contain two strings on any line
(string1)[\s\S]*(string2)|\2[\s\S]*\1
# Find files which contain two strings on the same line
\Qstring1\E.*\Qstring2\E
# Find in files excluding packages and imports statements
^(?!import|package).*wordToSearch
```
### Object to JSON in debugger
- [Get object as JSON in IntelliJ Idea from debugger](https://stackoverflow.com/a/60189764/334569)
### Favorite plugins
- [Lombok plugin](https://plugins.jetbrains.com/plugin/6317)
- [Visual Studio Code Dark Plus Theme](https://plugins.jetbrains.com/plugin/12255-visual-studio-code-dark-plus-theme)
### Settings
#### Navigate back and forward using mouse buttons clicks
Keymap > Navigate > Back | Forward > right click > Add mouse shortcut
#### Enable changing the font size with the mouse wheel
Editor > General > Change font size with Ctrl+Mouse Wheel
#### Prevent IDEA from automatically close opened files
Editor > General > Editor Tabs > Tab limit = 100
### Shortcuts
Key|Command|Notes
---|-------|----------
`Ctrl+Shift+A` | Find action | *Enables you to search for commands and settings across all menus and tools (similarly to VsCode "Show all commands" - Ctrl+Shift+P)*
`Shift Shift` | Search for a target by name (Search everywhere) | *Find any item in the project or outside of it by its name: files, actions, classes, symbols, settings, and UI elements. (similar - but more powerful - than VsCode "Go to File..., Quick Open" - Ctrl+P)*
`Ctrl+Shift+F` | Find in path | *Search for a text string within a project*
`Ctrl+E` | Open Recent files |
`Ctrl+Shift+E` | Open Recent Edited files |
`Ctrl+F12` | Locate a code element | *Open the structure view popup allowing to jump to the desired element*
`Ctrl+N` | Navigate to class |
`Ctrl+Shift+N` | Navigate to file by file name |
`Ctrl+Alt+Shift+N` | Navigate to symbol in project (class, method, etc) |
### Useful links
- [KAFKA explained in a children’s book](https://www.gentlydownthe.stream/)
================================================
FILE: Javascript/README.md
================================================
# Javascript
_Table of Contents_
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
<!-- generated with [DocToc](https://github.com/thlorenz/doctoc) -->
- [Promises](#promises)
- [Frameworks and Libraries](#frameworks-and-libraries)
- [AngularJS](#angularjs)
- [NodeJS](#nodejs)
- [Installation](#installation)
- [Fast Node Manager (fnm)](#fast-node-manager-fnm)
- [Windows setup](#windows-setup)
- [Fix node version not being changed automatically on directory change](#fix-node-version-not-being-changed-automatically-on-directory-change)
- [Fix the "Can't create the symlink for multishells" error](#fix-the-cant-create-the-symlink-for-multishells-error)
- [Node Version Manager (nvm)](#node-version-manager-nvm)
- [The Event Loop](#the-event-loop)
- [The Worker Pool (aka the Thread Pool)](#the-worker-pool-aka-the-thread-pool)
- [Scaling](#scaling)
- [REPL](#repl)
- [Conferences videos](#conferences-videos)
- [Node Package Manager (npm)](#node-package-manager-npm)
- [Remove modules not listed in package.json](#remove-modules-not-listed-in-packagejson)
- [Upgrade your dependencies to the latest versions](#upgrade-your-dependencies-to-the-latest-versions)
- [How to keep your dependencies up to date](#how-to-keep-your-dependencies-up-to-date)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
## Promises
A promise is an object that may produce a single value some time in the future: either a resolved value, or a reason that it’s not resolved (e.g., a network error occurred). A promise may be in one of 3 possible states:
- fulfilled
- rejected
- pending
Promise users can attach callbacks to handle the fulfilled value or the reason for rejection. Promises are eager, meaning that a promise will start doing whatever task you give it as soon as the promise constructor is invoked.
A chain of promises without a catch at the end can potentially hide an issue by making errors failing silently. If you have to debug a big codebase, you can use the `unhandledRejection` hook to find all unhandled Promise rejections:
```js
process.on('unhandledRejection', (err) => {
console.log(err)
})
```
## Frameworks and Libraries
A framework owns the main() function, it performs some function like managing a collection of windows on the screen, it can run even without customization. The framework defines the overall nature of the program, while your code provides specific customizations.
A library is a box of tools used by your code. Your code owns main() and provides the overall structure of the program. The library does some specific task, like sending traffic over the network, computing bessel functions, etc. A library can do big things, like draw a view of a three-dimensional space full of objects, but only after you tell it about the objects.
- [Source](https://qr.ae/pNt5QI)
### AngularJS
A framework mainly maintained by Google, was superseded by [Angular](https://en.wikipedia.org/wiki/Angular_(web_framework)) in 2016.
* [Angular 1 Style Guide](https://github.com/johnpapa/angular-styleguide/tree/master/a1) by John Papa
* [AngularJS styleguide (ES2015)](https://github.com/toddmotto/angularjs-styleguide) by Todd Motto
* [AngularJS with Gulp Step by Step](https://youtu.be/p9ZngMW80-k) by Mark Winterbottom
* [Designing and Building Component-based AngularJS Applications](https://app.pluralsight.com/library/courses/component-based-angularjs-applications) by Miguel Castro
* [Ultimate AngularJS Component Oriented Design Guide](http://gautierdelorme.com/2016/04/20/ultimate-angularjs-component-oriented-design-guide.html) by Gautier Delorme
## NodeJS
Node.js is a JavaScript runtime or platform which is built on Google Chrome’s JavaScript v8 engine. This runtime allows executing the JavaScript code on any machine outside a browser (this means that it is the server that executes the Javascript and not the browser).
Node.js is single-threaded and employs a concurrency model based on an event loop. It doesn’t block the execution instead registers a callback which allows the application to continue: that means Node.js can handle concurrent operations without creating multiple threads of execution thus can scale pretty well.
The areas where it’s perfect to use Node.js are:
- I/O bound Applications
- Data Streaming Applications
- Data Intensive Real-time Applications (DIRT)
- JSON APIs based Applications
- Single Page Applications
Node.js is not suitable for heavy applications involving more of CPU usage.
Node.js uses an _event-driven architecture_: it has an _Event Loop_ for orchestration and a _Worker Pool_ for expensive tasks.
### Installation
The best way to install Node.js is through a node version manager: it is especially useful when working on various projects that have different Node.js versions requirements by making it easy to upgrade to new versions or to automatically switch between existing versions of Node.js when changing directory.
#### Fast Node Manager (fnm)
The best node version manager is [fnm (Fast Node Manager)](https://github.com/Schniz/fnm). When compared to `nvm`, `fnm` is much faster, has a smaller footprint and it's cross-platform.
##### Windows setup
Run as Administrator:
```powershell
Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Unrestricted
```
Add the following to the end of your profile file:
```powershell
fnm env --use-on-cd --shell powershell | Out-String | Invoke-Expression
```
##### Fix node version not being changed automatically on directory change
In your .bashrc, replace:
```sh
eval "$(fnm env)"
```
with:
```sh
eval "$(fnm env --use-on-cd)"
```
##### Fix the "Can't create the symlink for multishells" error
When you open a shell you get the following error:
```sh
error: Can't create the symlink for multishells at "/run/user/1000/fnm_multishells/2354_1691420468557". Maybe there are some issues with permissions for the directory? Permission denied (os error 13)
```
As a workaround, until the issue will be fixed by fnm developers, add to your `~/.bashrc` the following line just before the eval for fnm:
```sh
export XDG_RUNTIME_DIR="$HOME/.cache/xdgr"
```
Thumb up https://github.com/Schniz/fnm/issues/938 to raise the visibility of the issue.
#### Node Version Manager (nvm)
An alternative way to install Node.js is through [nvm (Node Version Manager)](https://github.com/nvm-sh/nvm).
On Linux:
1. follow [these instructions](https://github.com/nvm-sh/nvm#install--update-script)
1. [automatically call `nvm use` in a directory with a `.nvmrc` file](https://github.com/nvm-sh/nvm#automatically-call-nvm-use)
On Windows, [install it with Chocolatey](https://chocolatey.org/packages/nvm).
Some useful commands:
```sh
# List installed versions
nvm ls
# List remote versions available for install, only show LTS (long-term support) versions
nvm ls-remote --lts
# Download and install a <version>, uses .nvmrc if available
nvm install <version>
# Modify PATH to use <version>, uses .nvmrc if available
nvm use <version>
# Display currently activated version of Node
nvm current
# Generate a .nvmrc file with the Node version currently used
node -v > .nvmrc
# Upgrade to the latest working npm on the given node version
nvm install-latest-npm
```
### The Event Loop
Node.js processes incoming requests in the event loop: it's what allows Node.js to perform non-blocking operations despite the fact that JavaScript is single-threaded.
The Event Loop notices each new client connection and orchestrates the generation of a response. All incoming requests and outgoing responses pass through the Event Loop. This means that if the Event Loop spends too long at any point, all current and new clients will not get a turn. You should make sure you never block the Event Loop. In other words, each of your JavaScript callbacks should complete quickly.
A good way to ensure this is to reason about the "computational complexity" of your callbacks. If your callback takes a constant number of steps no matter what its arguments are, then you'll always give every pending client a fair turn. If your callback takes a different number of steps depending on its arguments, then you should think about how long the arguments might be.
Two common ways to block the Event Loop are (1) using a _vulnerable_ regular expression or (2) using `JSON.parse` and `JSON.stringify`.
If you want to do complex calculations in JavaScript without blocking the Event Loop, you have two options: partitioning or offloading.
- [What the heck is the event loop anyway? | Philip Roberts | JSConf EU](https://youtu.be/8aGhZQkoFbQ)
### The Worker Pool (aka the Thread Pool)
Node.js runs JavaScript code in the Event Loop (initialization and callbacks), and offers a Worker Pool to handle expensive tasks like file I/O. Node.js scales well, sometimes better than more heavyweight approaches like Apache. The secret to the scalability of Node.js is that it uses a small number of threads to handle many clients. If Node.js can run with fewer threads, then it can spend more of your system's time and memory working on clients rather than on paying space and time overheads for threads (memory, context-switching). But because Node.js has only a few threads, you must structure your application to use them wisely. A good rule of thumb for keeping your Node.js server speedy is: Node.js is fast when the work associated with each client at any given time is "small".
Node.js uses the Worker Pool to handle "expensive" tasks. This includes I/O for which an operating system does not provide a non-blocking version, as well as particularly CPU-intensive tasks. The Node.js module APIs that make use of this Worker Pool are:
- I/O-intensive: DNS, File System
- CPU-intensive: Crypto, Zlib
- [Don't Block the Event Loop (or the Worker Pool)](https://nodejs.org/uk/docs/guides/dont-block-the-event-loop/)
### Scaling
It can handle concurrent operations without creating multiple threads of execution (low resource cost per connection).
In a one-thread-per-client system like Apache, each pending client is assigned its own thread. If a thread handling one client blocks, the operating system will interrupt it and give another client a turn. The operating system thus ensures that clients that require a small amount of work are not penalized by clients that require more work.
Because Node.js handles many clients with few threads, if a thread blocks handling one client's request, then pending client requests may not get a turn until the thread finishes its callback or task. The fair treatment of clients is thus the responsibility of your application. This means that you shouldn't do too much work for any client in any single callback or task.
This is part of why Node.js can scale well, but it also means that you are responsible for ensuring fair scheduling.
### REPL
The REPL stands for _Read Eval Print Loop__: it is a simple program that accepts the commands, evaluates them, and finally prints the results. REPL provides an environment similar to that of Unix/Linux shell or a window console, in which we can enter the command and the system, in turn, responds with the output. REPL performs the following tasks.
- READ: it Reads the input from the user, parses it into JavaScript data structure and then stores it in the memory.
- EVAL: it Executes the data structure.
- PRINT: it Prints the result obtained after evaluating the command.
- LOOP: it Loops the above command until the user presses Ctrl+C two times.
### Conferences videos
- [Node+JS Interactive 2015](https://www.youtube.com/watch?v=O28Knn00qYo&list=PLfMzBWSH11xYjL8oFumSfzOf6-kr8_t-o)
- [Node+JS Interactive 2016 - Europe](https://www.youtube.com/watch?v=GD-Fw6VNtUc&list=PLfMzBWSH11xZKfC2b-XWJRMtl9y-jtQBN)
- [Node+JS Interactive 2016 - North America](https://www.youtube.com/watch?v=HxGt_3F0ULg&list=PLfMzBWSH11xYaaHMalNKqcEurBH8LstB8)
- [Node.js Live Events 2016 - Paris & London](https://www.youtube.com/watch?v=czbfOM6DY1Q&list=PLfMzBWSH11xZWvE3iuTw6tdzp90gnODdp)
- [Node+JS Interactive 2017 - Vancouver](https://www.youtube.com/watch?v=zphcsoSJMvM&list=PLfMzBWSH11xa-iNnQG2555lgi4574nZOh)
- [Node+JS Interactive 2018](https://www.youtube.com/watch?v=7-tcLvyaEBM&list=PLfMzBWSH11xaZvhv1X5Fq1H-oMdnAtG6k)
- [Node+JS Interactive 2019](https://www.youtube.com/watch?v=3JNYBdS-uXU&list=PLfMzBWSH11xZPfWcC0DqFqKo_reMP58mw)
### Node Package Manager (npm)
The _Node Package Manager_ provides the following two main functionalities:
- online repository for node.js packages/modules which are present at <nodejs.org>.
- command line utility to install packages, do version management and dependency management of Node.js packages.
NPM comes bundled along with Node.js installable.
#### Remove modules not listed in package.json
```powershell
npm prune
```
#### Upgrade your dependencies to the latest versions
```powershell
npm install -g npm-check-updates
ncu
ncu -u
```
See:
- [npm-check-updates](https://www.npmjs.com/package/npm-check-updates)
#### How to keep your dependencies up to date
- [npm-outdated](https://docs.npmjs.com/cli/outdated.html)
- [npm-update](https://docs.npmjs.com/cli/update.html)
- [npm-check](https://www.npmjs.com/package/npm-check)
- [Validating dependencies in the project with npm-check and depcheck](https://medium.com/@wlodarczyk_j/validating-dependencies-in-the-project-with-npm-check-and-depcheck-20e83345fc1f)
- [Semantic versioning](https://semver.org/)
================================================
FILE: Kubernetes/README.md
================================================
# Kubernetes (k8s)
## Basic operations
```sh
# Delete all failed pods with a specific name
kubectl get pods --field-selector 'status.phase=Failed' -o name | grep podname | xargs kubectl delete
```
## Cluster management GUIs
- [Lens](https://k8slens.dev/)
- [k9s](https://k9scli.io/)
================================================
FILE: Linux/.bash_profile
================================================
# Enable reverse-i-search forward with Ctrl+S
stty -ixon
================================================
FILE: Linux/.bashrc
================================================
# Colorize your cat output
alias dog='pygmentize -O console256 -g'
# Human readable files list in terminal
# -l = use a long listing format
# -h = print sizes like 1K, 234M, 2G, etc.
# -p = append `/` indicator to directories
# -a = hidden files/directories
alias dir='ls -lhpA --color --group-directories-first'
# Make grep ignore case and highlight matching string
alias grep="grep --ignore-case --color"
# Identify a zombie process
alias zombie="ps axo stat,ppid,pid,comm | grep -w defunct"
# Avoid duplicates
HISTCONTROL=ignoredups:erasedups
# When the shell exits, append to the history file instead of overwriting it
shopt -s histappend
# After each command, append to the history file and reread it
PROMPT_COMMAND="${PROMPT_COMMAND:+$PROMPT_COMMAND$'\n'}history -a; history -c; history -r"
# >>> Prompt renderers
# Option 1: like posh-git
# https://askubuntu.com/questions/730754/how-do-i-show-the-git-branch-with-colours-in-bash-prompt
force_color_prompt=yes
color_prompt=yes
parse_git_branch() {
git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/'
}
if [ "$color_prompt" = yes ]; then
PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[01;31m\]$(parse_git_branch)\[\033[00m\]\$ '
else
PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w$(parse_git_branch)\$ '
fi
unset color_prompt force_color_prompt
# Enable git aliases auto completion
source /usr/share/bash-completion/completions/git
# Option 2: oh-my-posh
# 1. curl -s https://ohmyposh.dev/install.sh | bash -s
# 2. oh-my-posh font install Inconsolata
# 3. wget https://raw.githubusercontent.com/JanDeDobbeleer/oh-my-posh/refs/heads/main/themes/powerlevel10k_rainbow.omp.json -P .config/
# 4. echo 'eval "$(oh-my-posh init bash --config ~/.config/powerlevel10k_rainbow.omp.json)"' >> ~/.profile
# For enabling language versions display in your theme see https://github.com/JanDeDobbeleer/oh-my-posh/discussions/5902#discussioncomment-11284862
# Install updates, set Docker containers to not autorestart
alias update='sudo apt update; sudo apt upgrade -y; sudo apt autoremove -y; sdk update; sudo snap refresh; docker update --restart=no $(docker container ls -a -q)'
# Colorize ip output
alias ip='ip -c'
================================================
FILE: Linux/.vimrc
================================================
" Place yanked text into the global clipboard
set clipboard=unnamedplus
" Display line numbers
set number
" Enable syntax highlighting
syntax on
" Enable mousewheel scrolling
" (press Alt+Shift while selecting to copy without line numbers)
set mouse=a
================================================
FILE: Linux/README.md
================================================
# Linux
_Table of Contents_
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
<!-- generated with [DocToc](https://github.com/thlorenz/doctoc) -->
- [First things to do after installation](#first-things-to-do-after-installation)
- [Get your operating system information](#get-your-operating-system-information)
- [Get your hardware information](#get-your-hardware-information)
- [Remove the green background color from the directory listing](#remove-the-green-background-color-from-the-directory-listing)
- [Display line numbers in your cat output](#display-line-numbers-in-your-cat-output)
- [Print a file from line to line](#print-a-file-from-line-to-line)
- [Copy files from Linux to Windows](#copy-files-from-linux-to-windows)
- [Find files by name and show all their properties](#find-files-by-name-and-show-all-their-properties)
- [Find the differences between two files](#find-the-differences-between-two-files)
- [Find all files containing a string](#find-all-files-containing-a-string)
- [List running processes](#list-running-processes)
- [Set an empty password for a user](#set-an-empty-password-for-a-user)
- [Services commands](#services-commands)
- [CLI Tools](#cli-tools)
- [Shell scripts](#shell-scripts)
- [Validation](#validation)
- [Debugging](#debugging)
- [Presentations from command line](#presentations-from-command-line)
- [Set your terminal default editor](#set-your-terminal-default-editor)
- [cd to the previous directory](#cd-to-the-previous-directory)
- [Troubleshoot network issues](#troubleshoot-network-issues)
- [Neovim](#neovim)
- [Install the latest version on Ubuntu](#install-the-latest-version-on-ubuntu)
- [Setup](#setup)
- [LazyVim](#lazyvim)
- [Using NvChad](#using-nvchad)
- [NvChad useful commands](#nvchad-useful-commands)
- [Using kickstart](#using-kickstart)
- [Vim usesul commands](#vim-usesul-commands)
- [Learning resources](#learning-resources)
- [Troubleshooting](#troubleshooting)
- [Must have plugins](#must-have-plugins)
- [Arch Linux](#arch-linux)
- [Update the system](#update-the-system)
- [Search for a package](#search-for-a-package)
- [Install AUR (Arch User Repository) packages](#install-aur-arch-user-repository-packages)
- [Install Java through SDKMAN](#install-java-through-sdkman)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
## First things to do after installation
1. Update the system packages:
```sh
sudo apt update; sudo apt upgrade -y; sudo apt autoremove -y
```
1. Copy the content of [`.bashrc`](.bashrc) to your `~/.bashrc`
## Get your operating system information
```sh
cat /etc/os-release
# or
lsb_release -a
```
## Get your hardware information
```sh
lshw -short
```
## Remove the green background color from the directory listing
```sh
dircolors -p > ~/.dircolors
vim ~/.dircolors
# Remove ;41 ;42 ;43 ;44 from the lines beginning with
# SETUID, SETGID, CAPABILITY, STICKY_OTHER_WRITABLE, OTHER_WRITABLE and STICKY
vim ~/.bashrc
# Append the following line
eval 'dircolors ~/.dircolors' > /dev/null
```
- [Source](https://unix.stackexchange.com/questions/94498/what-causes-this-green-background-in-ls-output)
## Display line numbers in your cat output
```sh
cat -n <file-path>
```
## Print a file from line to line
```sh
sed -n 10,20p <file-path>
```
## Copy files from Linux to Windows
- Install `openssh-server` and `net-tools` on Linux
- Intall `Putty` on Windows (with [Chocolatey](https://chocolatey.org/packages/putty))
```sh
# Assuming 192.168.10.12 is your Linux IP address,
# write the following command in a shell on Windows:
pscp user@192.168.10.12:/source/path/on/linux/* c:\Destination\Path\On\Windows
```
## Find files by name and show all their properties
```sh
find . -name <file_name_or_pattern> | xargs ls -lhpa --color --group-directories-first
```
## Find the differences between two files
```sh
comm -3 old.csv new.csv
# or
diff --suppress-common-lines --side-by-side old.csv new.csv
```
## Find all files containing a string
```sh
grep -Rin "string" .
```
`R` = recursive
`i` = ignore case
`n` = show the line number and content
`.` = starting from the current directory
Use `l` instead of `n` to show the file name only.
## List running processes
```sh
ps aux | grep procName
pgrep -f procName
top
htop
```
## Set an empty password for a user
```sh
sudo passwd -d username
```
## Services commands
```sh
# List running services
ls /etc/init.d
# Start/stop a service
sudo -u root bash
/etc/init.d/<my-service> start/stop
# if you don't find there, check
/var/spool/cron/*
# if not there, check:
/etc/monit.d/*
# List services listening to ports
sudo netstat -tulpn | grep LISTEN
```
## CLI Tools
- [Witowski Favorite CLI Tools](https://switowski.com/blog/favorite-cli-tools)
## Shell scripts
### Validation
- [ShellCheck](https://www.shellcheck.net/)
### Debugging
Prepend the following to your script:
```sh
# Exit immediately if a command exits with a non-zero status
set -e
# Print the last failed command, line number and exit code
trap 'prev_cmd=$curr_cmd; prev_ln=$curr_ln; curr_cmd=$BASH_COMMAND; curr_ln=${LINENO}' DEBUG
trap 'echo -e $"\n ERROR in ${BASH_SOURCE}:$prev_ln >>> $prev_cmd <<< FAILED with EXIT CODE $?\n"' EXIT
```
## Presentations from command line
- [mdp](https://github.com/visit1985/mdp)
- [tpp](https://synflood.at/tpp.html)
- [sent](https://tools.suckless.org/sent/)
## Set your terminal default editor
```sh
sudo update-alternatives --config editor
```
## cd to the previous directory
```sh
cd -
```
## Troubleshoot network issues
```sh
openssl s_client -connect <host>:443 -servername <host>
```
## Neovim
Neovim is a cross-platform fork of Vim with code highlighting, syntax checking, code completion, inlay hints, type hints, a built-in debugger, a terminal emulator, a file manager, a markdown previewer, a git client and much more. It has better defaults than Vim, for example `autoindent` and `hlsearch` (highlight all matches). It has been the most loved editor in the Stack Overflow Developer Survey for the last 2 years ([source](https://survey.stackoverflow.co/2022#integrated-development-environment)).
### Install the latest version on Ubuntu
Use [bob](https://github.com/MordechaiHadad/bob/releases). Example:
```sh
wget https://github.com/MordechaiHadad/bob/releases/download/<latest_version>/bob-linux-x86_64.zip
unzip bob-linux-x86_64.zip
cd bob-linux-x86_64/
chmod +x bob
echo "export PATH=\"~/.local/share/bob/nvim-bin:\$PATH\"" >> ~/.bashrc
source ~/.bashrc
./bob install stable
./bob use stable
```
### Setup
#### LazyVim
LazyVim is a popular Neovim configuration framework designed to provide users with a pre-configured, feature-rich setup for Neovim. It offers a curated set of plugins (for syntax highlighting, code completion, file navigation, git integration, etc.), sensible defaults, and optimized settings to enhance productivity and ease of use. At its core, LazyVim leverages the `lazy.nvim` plugin manager, which allows for efficient and lazy-loading of plugins, resulting in faster startup times and improved performance.
1. Install a [Nerd font](https://www.nerdfonts.com/font-downloads) of your choice (e.g. Inconsolata):
```sh
wget https://github.com/ryanoasis/nerd-fonts/releases/download/v3.2.1/Inconsolata.zip
unzip Inconsolata.zip -d ~/.local/share/fonts
fc-cache -fv
```
If you are using WSL, you need to install the font on Windows and set it in the terminal settings.
1. Install LazyVim prerequisites: `sudo apt install luarocks ripgrep xclip`
1. Install LazyVim following [these instructions](https://www.lazyvim.org/installation)
1. Start Neovim and wait for the plugins to be installed
1. Append the following lines to `~/.config/nvim/init.lua`:
```lua
-- place yanked text into the global clipboard
vim.opt.clipboard = "unnamedplus"
```
1. Inside Neovim run `:checkhealth` and fix any issues.
#### Using NvChad
Set one of the [Nerd Fonts](https://www.nerdfonts.com/font-downloads) as your terminal font, then run:
```sh
rm -rf ~/.local/share/nvim/
rm -rf ~/.config/nvim
git clone https://github.com/NvChad/NvChad ~/.config/nvim --depth 1 && nvim
```
##### NvChad useful commands
- Change theme with `space t h`
- Install a syntax highlighter with `:TSInstall <language>`
- Display the file tree with `Ctrl`+`n`
- Mark a file with `m`
- Create, rename, copy and paste a file with `a`, `r`, `c` and `p` (creating a folder is done by following the name with the slash `/`)
- Open the find file meny with `space f f`
- Search in the opened files names with `space f b`
- Search in the current file with `space s`
- Toggle the line numbers with `space n`
- Toggle the relative line numbers with `space r n`
- Cycle through the tabs (aka buffers) with `tab` and `shift tab`
- Close the current tab with `space x`
#### Using kickstart
```sh
sudo apt install gcc
mkdir -p ~/.config/nvim
git clone https://github.com/nvim-lua/kickstart.nvim.git ~/.config/nvim
echo "vim.wo.relativenumber = true" >> ~/.config/nvim/init.lua
nvim
```
### Vim usesul commands
- Jump back to previous location `Ctrl`+`o`
- Jump forward to next location `Ctrl`+`i`
- Undo/Redo `u`/`Ctrl`+`r`
- Copy current line `yy`
- Paste line from clipboard `p`
- Delete current line `dd`
- Jump the next/previous word `w`/`b`
- Select text (Visual) `v`
- Format current selected text `gq` (comes from plugin?)
- Change current word `cw`
- Copy the entire file to the clipboard `ggyG`
- Search for a word `/<word>`
- Search for the next/previous word `n`/`N`
### Learning resources
- Type `vimtutor` in your terminal and follow the instructions.
- [Vim Adventures](https://vim-adventures.com/)
- [Vim Cheat Sheet](https://devhints.io/vim)
- [The Primeagen: Vim As Your Editor](https://www.youtube.com/watch?v=X6AR2RMB5tE&list=PLm323Lc7iSW_wuxqmKx_xxNtJC_hJbQ7R&pp=iAQB)
- [The Primeagen: Vim Life](https://www.youtube.com/watch?v=y6VJBeZEDZU&list=PLm323Lc7iSW9CtibHhhQErDh167XfL4EU&pp=iAQB)
### Troubleshooting
When running `:checkhealth` I get a lot of errors like:
```
invalid node type at position 242 for language arduino
```
See [this gist](https://gist.github.com/lackovic/1916b5cc0ca22496ea3061f4ae3b5aff).
If you run `:echo nvim_get_runtime_file('parser', v:true)` and you get two parsers then you need to remove one of the two
### Must have plugins
- [tpope/vim-surround](https://github.com/tpope/vim-surround)
- [phaazon/hop.nvim](https://github.com/phaazon/hop.nvim)
## Arch Linux
### Update the system
```sh
sudo pacman -Syu
```
- `S` = Synchronize packages. Packages are installed directly from the remote repositories, including all dependencies required to run the packages
- `y` = Download a fresh copy of the master package database from the server(s) defined in pacman.conf
- `u` = Upgrades all packages that are out-of-date
### Search for a package
To search for example for _OpenJDK_, run:
```sh
sudo pacman -Ss OpenJDK
```
- `S` = Synchronize packages. Packages are installed directly from the remote repositories, including all dependencies required to run the packages
- `s` = Search each package in the sync databases for names or descriptions that match regexp
### Install AUR (Arch User Repository) packages
For WSL2 see [this issue](https://github.com/yuk7/ArchWSL/issues/142).
1. Install the prerequisites:
```sh
pacman -S --needed base-devel
```
1. Install Yay as AUR helper:
```sh
git clone https://aur.archlinux.org/yay.git
cd yay/
makepkg -si
```
1. Install the package of your choice with:
```sh
yay -S <package-name>
```
Resources:
- [AUR packages search](https://aur.archlinux.org/packages/)
- [AUR wiki](https://wiki.archlinux.org/index.php/Arch_User_Repository)
- [AUR helpers](https://wiki.archlinux.org/index.php/AUR_helpers)
### Install Java through SDKMAN
1. Install the prerequisites:
```sh
sudo pacman -Sy which unzip zip
```
1. Follow the [installation instructions](https://sdkman.io/install).
1. To see the list of available Java versions: it
```sh
sdk list java
```
1. To install a particular version of Java run:
```sh
sdk install java <identifier>
```
================================================
FILE: Linux/powerlevel10k_rainbow_java.omp.json
================================================
{
"$schema": "https://raw.githubusercontent.com/JanDeDobbeleer/oh-my-posh/main/themes/schema.json",
"blocks": [
{
"alignment": "left",
"segments": [
{
"background": "#d3d7cf",
"foreground": "#000000",
"leading_diamond": "\u256d\u2500\ue0b2",
"style": "diamond",
"template": " {{ if .WSL }}WSL at {{ end }}{{.Icon}} ",
"type": "os"
},
{
"background": "#3465a4",
"foreground": "#e4e4e4",
"powerline_symbol": "\ue0b0",
"properties": {
"home_icon": "~",
"style": "full"
},
"style": "powerline",
"template": " \uf07c {{ .Path }} ",
"type": "path"
},
{
"background": "#4e9a06",
"background_templates": [
"{{ if or (.Working.Changed) (.Staging.Changed) }}#c4a000{{ end }}",
"{{ if and (gt .Ahead 0) (gt .Behind 0) }}#f26d50{{ end }}",
"{{ if gt .Ahead 0 }}#89d1dc{{ end }}",
"{{ if gt .Behind 0 }}#4e9a06{{ end }}"
],
"foreground": "#000000",
"powerline_symbol": "\ue0b0",
"properties": {
"branch_icon": "\uf126 ",
"fetch_stash_count": true,
"fetch_status": true,
"fetch_upstream_icon": true
},
"style": "powerline",
"template": " {{ .UpstreamIcon }}{{ .HEAD }}{{if .BranchStatus }} {{ .BranchStatus }}{{ end }}{{ if .Working.Changed }} \uf044 {{ .Working.String }}{{ end }}{{ if and (.Working.Changed) (.Staging.Changed) }} |{{ end }}{{ if .Staging.Changed }} \uf046 {{ .Staging.String }}{{ end }}{{ if gt .StashCount 0 }} \ueb4b {{ .StashCount }}{{ end }} ",
"type": "git"
}
],
"type": "prompt"
},
{
"alignment": "right",
"segments": [
{
"background": "#689f63",
"foreground": "#ffffff",
"invert_powerline": true,
"powerline_symbol": "\ue0b2",
"properties": {
"fetch_version": true,
"home_enabled": true,
"display_mode": "always"
},
"style": "powerline",
"template": " {{ if .PackageManagerIcon }}{{ .PackageManagerIcon }} {{ end }}{{ .Full }} \ue718 ",
"type": "node"
},
{
"type": "java",
"style": "powerline",
"powerline_symbol": "",
"properties": {
"fetch_version": true,
"home_enabled": true,
"display_mode": "always"
},
"foreground": "#ffffff",
"background": "#4063D8",
"template": " {{ .Full }}"
},
{
"background": "#00acd7",
"foreground": "#111111",
"invert_powerline": true,
"powerline_symbol": "\ue0b2",
"properties": {
"fetch_version": true
},
"style": "powerline",
"template": " {{ if .Error }}{{ .Error }}{{ else }}{{ .Full }}{{ end }} \ue627 ",
"type": "go"
},
{
"background": "#4063D8",
"foreground": "#111111",
"invert_powerline": true,
"powerline_symbol": "\ue0b2",
"properties": {
"fetch_version": true
},
"style": "powerline",
"template": " {{ if .Error }}{{ .Error }}{{ else }}{{ .Full }}{{ end }} \ue624 ",
"type": "julia"
},
{
"background": "#FFDE57",
"foreground": "#111111",
"invert_powerline": true,
"powerline_symbol": "\ue0b2",
"properties": {
"display_mode": "files",
"fetch_virtual_env": false
},
"style": "powerline",
"template": " {{ if .Error }}{{ .Error }}{{ else }}{{ .Full }}{{ end }} \ue235 ",
"type": "python"
},
{
"background": "#AE1401",
"foreground": "#ffffff",
"invert_powerline": true,
"powerline_symbol": "\ue0b2",
"properties": {
"display_mode": "files",
"fetch_version": true
},
"style": "powerline",
"template": " {{ if .Error }}{{ .Error }}{{ else }}{{ .Full }}{{ end }} \ue791 ",
"type": "ruby"
},
{
"background": "#FEAC19",
"foreground": "#ffffff",
"invert_powerline": true,
"powerline_symbol": "\ue0b2",
"properties": {
"display_mode": "files",
"fetch_version": false
},
"style": "powerline",
"template": " {{ if .Error }}{{ .Error }}{{ else }}{{ .Full }}{{ end }} \uf0e7",
"type": "azfunc"
},
{
"background_templates": [
"{{if contains \"default\" .Profile}}#FFA400{{end}}",
"{{if contains \"jan\" .Profile}}#f1184c{{end}}"
],
"foreground": "#ffffff",
"invert_powerline": true,
"powerline_symbol": "\ue0b2",
"properties": {
"display_default": false
},
"style": "powerline",
"template": " {{ .Profile }}{{ if .Region }}@{{ .Region }}{{ end }} \ue7ad ",
"type": "aws"
},
{
"background": "#ffff66",
"foreground": "#111111",
"invert_powerline": true,
"powerline_symbol": "\ue0b2",
"style": "powerline",
"template": " \uf0ad ",
"type": "root"
},
{
"background": "#c4a000",
"foreground": "#000000",
"invert_powerline": true,
"powerline_symbol": "\ue0b2",
"style": "powerline",
"template": " {{ .FormattedMs }} \uf252 ",
"type": "executiontime"
},
{
"background": "#000000",
"background_templates": [
"{{ if gt .Code 0 }}#cc2222{{ end }}"
],
"foreground": "#d3d7cf",
"invert_powerline": true,
"powerline_symbol": "\ue0b2",
"properties": {
"always_enabled": true
},
"style": "powerline",
"template": " {{ if gt .Code 0 }}{{ reason .Code }}{{ else }}\uf42e{{ end }} ",
"type": "status"
},
{
"background": "#d3d7cf",
"foreground": "#000000",
"invert_powerline": true,
"style": "diamond",
"template": " {{ .CurrentDate | date .Format }} \uf017 ",
"trailing_diamond": "\ue0b0\u2500\u256e",
"type": "time"
}
],
"type": "prompt"
},
{
"alignment": "left",
"newline": true,
"segments": [
{
"foreground": "#d3d7cf",
"style": "plain",
"template": "\u2570\u2500",
"type": "text"
}
],
"type": "prompt"
},
{
"segments": [
{
"foreground": "#d3d7cf",
"style": "plain",
"template": "\u2500\u256f",
"type": "text"
}
],
"type": "rprompt"
}
],
"console_title_template": "{{ .Shell }} in {{ .Folder }}",
"final_space": true,
"version": 3
}
================================================
FILE: PostgreSQL/README.md
================================================
# PostgreSQL CLI notes
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
**Contents**
- [Basic psql commands](#basic-psql-commands)
- [Basic commands for psql interactive terminal](#basic-commands-for-psql-interactive-terminal)
- [Basic SQL queries](#basic-sql-queries)
- [Use empty password for postgres user on Windows](#use-empty-password-for-postgres-user-on-windows)
- [Dump data from a specific user of specific tables from a database](#dump-data-from-a-specific-user-of-specific-tables-from-a-database)
- [See your database schema in dbdiagram.io](#see-your-database-schema-in-dbdiagramio)
- [Set a default database to connect to](#set-a-default-database-to-connect-to)
- [Restart PostgresQL](#restart-postgresql)
- [External resources](#external-resources)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
## Basic psql commands
```sh
# Output version information
psql -V
# Connect to a host database as user
psql -h <host> -d <db_name> -U <user>
# default host = /var/run/postgresql
```
## Basic commands for psql interactive terminal
```sh
# List of databases
\l
# Connect to a database
\c database_name
# List all tables in the current database
\dt
# List the columns details of a table
\d+ table_name
# List all users
\du
## Change the password for a user
\password username
## Exit from PostgreSQL CLI
\q
```
## Basic SQL queries
```sql
-- List just the columns names of a table
SELECT * FROM table_name WHERE FALSE;
-- Specify a number of records to return
SELECT * FROM table_name LIMIT <number>;
-- Clear all the data from a database
DROP DATABASE "db_name";
CREATE DATABASE "db_name";
-- List columns with indexes for a table
SELECT * FROM pg_indexes WHERE tablename = 'mytable';
-- List columns names, types and nullability for a table
SELECT column_name, data_type, is_nullable
FROM information_schema.columns
WHERE table_name = 'mytable';
```
## Use empty password for postgres user on Windows
Edit your `C:\Program Files\PostgreSQL\10\data\pg_hba.conf` and
replace the IPv4 and IPv6 local connections with:
```sh
# TYPE DATABASE USER ADDRESS METHOD
# IPv4 local connections:
host all all 127.0.0.1/32 trust
# IPv6 local connections:
host all all ::1/128 trust
```
## Dump data from a specific user of specific tables from a database
```sh
pg_dump -U username -t table1 -t table2 -t table3 -O --column-inserts --data-only database_name
```
## See your database schema in dbdiagram.io
You have two options:
* Run [this query](https://github.com/matthewoldham/dbdiagram.io-ddl-queries/blob/master/sql/postgresql.sql) to generate the DDL
* Run one of the following and import it in dbdiagram.io:
```
pg_dump -F t -f dump.bin database-name
pg_dump -F t -p dump.sql database-name
```
## Set a default database to connect to
In your `~/.bashrc` or similar:
```sh
export PGDATABASE=my-database
```
## Restart PostgresQL
```sh
/etc/init.d/postgresql restart
```
## External resources
* [PostgreSQL cheatsheet](https://gist.github.com/Kartones/dd3ff5ec5ea238d4c546)
================================================
FILE: PostgreSQL/postgresql-to-dbdiagram.sql
================================================
-- Backup copy of the query to generate dbdiagram.io DDL, copied from:
-- https://github.com/matthewoldham/dbdiagram.io-ddl-queries/blob/master/sql/postgresql.sql
WITH tableKeys AS (
SELECT t.constraint_schema,
t.table_name,
c.column_name,
'PK' AS column_key
FROM information_schema.table_constraints t
JOIN information_schema.constraint_column_usage c
ON c.constraint_schema = t.constraint_schema
AND c.table_name = t.table_name
AND c.constraint_name = t.constraint_name
WHERE t.constraint_type = 'PRIMARY KEY'
),
tableColumns AS (
SELECT t.table_schema,
t.table_name,
c.column_name,
COALESCE(tk.column_key::TEXT,'') AS column_pk,
CASE
WHEN data_type IN ('USER-DEFINED',
'timestamp without time zone',
'timestamp with time zone',
'character varying') THEN udt_name
ELSE data_type
END AS column_type
FROM information_schema.columns c
JOIN information_schema.tables t
ON c.table_schema = t.table_schema
AND c.table_name = t.table_name
LEFT JOIN tableKeys tk
ON tk.constraint_schema = t.table_schema
AND tk.table_name = t.table_name
AND tk.column_name = c.column_name
WHERE t.table_type = 'BASE TABLE'
ORDER BY t.table_name, c.ordinal_position
),
tableDefs AS(
SELECT table_schema,
CONCAT_WS(' ','Table',table_name,'{',CHR(10)) AS table_prefix,
ARRAY_TO_STRING(ARRAY_AGG(CONCAT_WS(' ',' ',QUOTE_IDENT(column_name),column_type,column_pk)),CHR(10)) AS column_list,
CONCAT(CHR(10),'}',CHR(10)) AS table_suffix
FROM tableColumns
GROUP BY 1,2,4
ORDER BY 2
),
relDefs AS (
SELECT tc.table_schema,
CONCAT('Ref: ',tc.table_name,'.',kcu.column_name,' > ',ccu.table_name,'.',ccu.column_name,CHR(10)) AS relationships
FROM information_schema.table_constraints AS tc
JOIN information_schema.key_column_usage AS kcu
ON tc.constraint_name = kcu.constraint_name
AND tc.table_schema = kcu.table_schema
JOIN information_schema.constraint_column_usage AS ccu
ON ccu.constraint_name = tc.constraint_name
AND ccu.table_schema = tc.table_schema
WHERE tc.constraint_type = 'FOREIGN KEY'
ORDER BY tc.table_name,
kcu.column_name,
ccu.table_name,
ccu.column_name
)
SELECT CONCAT(table_prefix,column_list,table_suffix) AS ddl
FROM tableDefs
WHERE table_schema = 'public'
UNION ALL
SELECT relationships AS ddl
FROM relDefs
WHERE table_schema = 'public'
================================================
FILE: README.md
================================================
# Notes
A collection of personal notes about programming, operating systems and tools.
Pull requests for wrong, suboptimal or incomplete information are very welcome!
================================================
FILE: Redis/README.md
================================================
# Redis
## Basic commands
```sh
# Set a key and assign it a value
redis-cli SET <key> <value>
# Get a value associated to a key
redis-cli GET <key>
# List all keys
redis-cli KEYS '*'
# Delete all keys of all databases
redis-cli FLUSHALL
# Delete all keys of the currently selected database
redis-cli FLUSHDB
# Delete all keys of the specified database
redis-cli -n <database_number> FLUSHDB
```
## Troubleshooting
1. check the configuration file of the app (e.g. `/opt/<appname>/config/redis.yaml`) for hostnames, ports and sentinels
1. verify that Redis is running with `redis-cli ping` (you should get `PONG` back)
1. check the connection with the sentinels with (you should get `PONG` back):
```
nc sentinel.hostname.net 6388
ping
```
1. check the local network ports `netstat -an | grep :6379`
1. check whether Redis is running in a Docker container `docker container ls`
1. check the app that is using Redis log with `tail /var/log/<appname>/<servicename> -F`
================================================
FILE: Ruby on Rails/README.md
================================================
# Ruby on Rails
*Contents*
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
<!-- generated with [DocToc](https://github.com/thlorenz/doctoc) -->
- [Introduction](#introduction)
- [Debugging](#debugging)
- [Testing](#testing)
- [Generate your database diagram from Rails schema](#generate-your-database-diagram-from-rails-schema)
- [Gems management](#gems-management)
- [List installed gems](#list-installed-gems)
- [Know the version of an installed gem](#know-the-version-of-an-installed-gem)
- [Clean up unused gems in your bundler directory](#clean-up-unused-gems-in-your-bundler-directory)
- [Uninstall all Ruby gems](#uninstall-all-ruby-gems)
- [Display information about the RubyGems environment](#display-information-about-the-rubygems-environment)
- [Change version of an installed gem](#change-version-of-an-installed-gem)
- [Rails console](#rails-console)
- [Enter Rails console](#enter-rails-console)
- [Enable syntax highlighting](#enable-syntax-highlighting)
- [CRUD database operations](#crud-database-operations)
- [Migrations data types](#migrations-data-types)
- [Resources](#resources)
- [Visual Studio Code](#visual-studio-code)
- [Recommended extensions](#recommended-extensions)
- [Format .erb files in VsCode](#format-erb-files-in-vscode)
- [RubyMine](#rubymine)
- [Windows](#windows)
- [Installation](#installation)
- [Setup](#setup)
- [Find in path regex](#find-in-path-regex)
- [Favorite plugins](#favorite-plugins)
- [Install a theme from a jar file](#install-a-theme-from-a-jar-file)
- [Select a theme](#select-a-theme)
- [Navigate back and forward using mouse buttons clicks](#navigate-back-and-forward-using-mouse-buttons-clicks)
- [Enable mouse scroll zooming](#enable-mouse-scroll-zooming)
- [Shortcuts](#shortcuts)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
## Introduction
**Ruby** is an interpreted scripting object-oriented programming language. **Ruby on Rails** ("RoR") is an open-source framework, written in Ruby, for implementing web applications.
## Debugging
1. Insert `binding.pry` before the line you want the execution to be paused
1. Run your app or test
1. The execution will pause where you inserted the binding and will give you a rails console.
- See [Debugging With Pry](https://learn.co/lessons/debugging-with-pry)
## Testing
```shell
# Run (focus on) one test only out of a suite of tests
bundle exec rspec path/file_spec.rb:32
```
## Generate your database diagram from Rails schema
1. Open [dbdiagram.io](https://dbdiagram.io/)
1. Click Import → From Rails (schema.rb)
1. Paste (or upload) your schema.rb
## Gems management
### List installed gems
```sh
gem list --local
```
### Know the version of an installed gem
```sh
gem list --local | grep your-gem-name
```
### Clean up unused gems in your bundler directory
```sh
# Print the changes, but do not clean the unused gems.
bundle clean --dry-run
# Force a clean even if --path is not set.
bundle clean --force
```
- [Docs](https://bundler.io/man/bundle-clean.1.html)
### Uninstall all Ruby gems
```sh
# Make sure you upgrade your Rubygems:
gem update --system
# Uninstall all gems:
gem uninstall --all
```
### Display information about the RubyGems environment
```sh
gem env
```
### Change version of an installed gem
1. Install the new version (e.g. `1.17.3`) with:
```sh
gem install bundler:1.17.3
```
1. uninstall the previously existing version with:
```sh
gem uninstall bundler
```
## Rails console
### Enter Rails console
```shell
# Using your global version of Rails:
rails c
# Testing out some code without changing any data:
# (modifications will be rolled back on exit)
rails c --sandbox
# Using the local version of Rails defined in your Gemfile:
bundle exec rails c
```
### Enable syntax highlighting
Use [pry](https://github.com/pry/pry)
### CRUD database operations
```ruby
# Create
User.create(name: "Douglas")
# Read by ID (returns only one object if found, if not raises an exception):
User.find(42)
# Read by name (returns only one object if found, if not returns nil):
User.find_by(name: "Douglas")
# Read by name (returns an array of objects if found, if not returns an empty array):
User.where(gender: "Male")
# Update
User.find(42).update_attribute(:name, "Douglas")
# Delete only the current object record:
User.delete(42)
User.delete_all(age: 49)
# Delete the current object record and all its descendants records:
User.destroy(42)
User.destroy_all(age: 49)
```
- [Docs](https://www.rubydoc.info/docs/rails/4.1.7/ActiveRecord/Relation)
## Migrations data types
```rb
create_table 'example' do |t|
t.integer :int # int (4 bytes, max 2,147,483,647)
t.integer :int1, limit: 1 # tinyint (1 byte, -128 to 127)
t.integer :int2, limit: 2 # smallint (2 bytes, max 32,767)
t.integer :int3, limit: 3 # mediumint (3 bytes, max 8,388,607)
t.integer :int4, limit: 4 # int (4 bytes)
t.integer :int5, limit: 5 # bigint (8 bytes, max 9,223,372,036,854,775,807)
t.integer :int8, limit: 8 # bigint (8 bytes)
t.integer :int11, limit: 11 # int (4 bytes)
t.timestamp :my_date # timestamp without time zone
t.timestamptz :my_other_date # timestamp with time zone
t.string :str, # character varying(255)
t.string :str, length: 255 # character varying(512)
t.string :str, length: 1024 # character varying(1024)
end
```
- [Source](https://gist.github.com/icyleaf/9089250)
## Resources
- [The Ruby Style Guide](https://github.com/rubocop-hq/ruby-style-guide)
- [Ruby Style Guide](https://github.com/github/rubocop-github/blob/master/STYLEGUIDE.md)
## Visual Studio Code
### Recommended extensions
- [endwise](https://marketplace.visualstudio.com/items?itemName=kaiwood.endwise)
- [Ruby Solargraph](https://marketplace.visualstudio.com/items?itemName=castwide.solargraph) (`gem install solargraph` required)
- [Gem Lens](https://marketplace.visualstudio.com/items?itemName=ninoseki.vscode-gem-lens)
### Format .erb files in VsCode
This is not a good solution but it is the best I could find.
Add to your workspace settings:
```json
"files.associations": {
"*.html.erb": "html"
}
```
- [Prettier .erb support request](https://github.com/prettier/plugin-ruby/issues/371)
## RubyMine
### Windows
#### Installation
The easiest way to install it is with Chocolatey:
```powershell
choco install rubymine -y
```
#### Setup
1. Install Ruby with Chocolatey, choosing from the [available versions](https://chocolatey.org/packages/ruby#versionhistory)
1. Run `ridk install` and choose options 1, 2 and 3 when asked
1. Run `bundle install` in your project directory (if some of the gems installation fails, try commenting them out from your `Gemfile`)
================================================
FILE: Rust/README.md
================================================
# Rust
To create an API service in Rust on Windows, install Rust with:
```powershell
winget install -e --id Rustlang.Rustup
rustup toolchain install stable-x86_64-pc-windows-gnu
rustup default stable-x86_64-pc-windows-gnu
```
Follow Rocket [Getting Started](https://rocket.rs/v0.4/guide/getting-started/) guide.
As IDE use Visual Studio Code with the [rust-analyzer](https://marketplace.visualstudio.com/items?itemName=rust-lang.rust-analyzer) extesion.
================================================
FILE: Visual Studio Code/README.md
================================================
# Visual Studio Code
_Table of Contents_
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
<!-- generated with [DocToc](https://github.com/thlorenz/doctoc) -->
- [Useful workspace settings](#useful-workspace-settings)
- [Favorite shortcuts](#favorite-shortcuts)
- [Favorite user settings](#favorite-user-settings)
- [Prevent the Java Platform extension from creating files in the bin directory](#prevent-the-java-platform-extension-from-creating-files-in-the-bin-directory)
- [Top Extensions](#top-extensions)
- [Useful Extensions](#useful-extensions)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
## Useful workspace settings
```js
// Hide VsCode configuration files from sidebar explorer
"files.exclude": { ".vscode": true },
// Use relative path for Typescript auto-imports
"typescript.preferences.importModuleSpecifier": "relative"
// Use single quotes in Typescript auto-imports
"typescript.preferences.quoteStyle": "single"
// Automatically update TypeScript import paths on file rename/move
"typescript.updateImportsOnFileMove.enabled": "always"
```
## Favorite shortcuts
| Key | Command |
| ------------------------- | --------------------------------- |
| `Ctrl+Shift+P` | Show all commands |
| `Ctrl+P` | Go to file..., quick open |
| `Ctrl+Shift+O` | Go to symbol in the current file |
| `Ctrl+T` | Go to symbol in the whole project |
| `Ctrl+K M` | Change language mode |
| `Ctrl+K O` | Show opened file in new window |
| `Ctrl+Shift+P dupl Enter` | Duplicate workspace in new window |
| `Shift+Alt+Down` | Copy line down / Duplicate line |
| `Ctrl+Shift+N` | New window |
| `Ctrl+R` | Open recent folder |
| `Ctrl+.` | Show the quickfix menu |
| `Ctrl+,` | Open settings |
| `Ctrl+Shift+.` | Focus and select breadcrumbs |
| `Ctrl+Shift+G G` | Show source control |
| `Ctrl+Shift+E` | Show and focus explorer |
| `Ctrl+B` | Toggle sidebar visibility |
| `Ctrl+0` | Focus into sidebar |
| `Ctrl+1` | Focus into editor |
| `Ctrl+/` | Toggle comment on selected lines |
[All shortcuts](https://code.visualstudio.com/docs/getstarted/keybindings)
## Favorite user settings
```js
{
"breadcrumbs.enabled": true,
"diffEditor.ignoreTrimWhitespace": true,
"editor.cursorSurroundingLines": 5,
"editor.fontFamily": "Inconsolata, 'Input Mono Light', 'Fira Code', Consolas, 'Courier New', monospace",
"editor.fontSize": 16,
"editor.minimap.enabled": true,
"editor.minimap.scale": 3,
"editor.mouseWheelZoom": true,
"explorer.confirmDelete": false,
"explorer.confirmDragAndDrop": false,
"files.autoSave": "onWindowChange",
"window.title": "${rootName}",
"window.zoomLevel": 0,
"workbench.editor.wrapTabs": true,
"workbench.settings.useSplitJSON": true,
"workbench.settings.editor": "json",
"java.autobuild.enabled": false,
}
```
## Prevent the Java Platform extension from creating files in the bin directory
Set `java.autobuild.enabled` to false in your settings.
[Source](https://github.com/redhat-developer/vscode-java/issues/634#issuecomment-2485241295)
## Top Extensions
- [Better Comments](https://marketplace.visualstudio.com/items?itemName=aaron-bond.better-comments)
- [Bracket Pair Colorizer](https://marketplace.visualstudio.com/items?itemName=CoenraadS.bracket-pair-colorizer)
- [Debugger for Chrome](https://marketplace.visualstudio.com/items?itemName=msjsdiag.debugger-for-chrome)
- [GitLens](https://marketplace.visualstudio.com/items?itemName=eamodio.gitlens)
- [markdownlint](https://marketplace.visualstudio.com/items?itemName=DavidAnson.vscode-markdownlint)
- [Partial Diff](https://marketplace.visualstudio.com/items?itemName=ryu1kn.partial-diff)
- [Prettier - Code formatter](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode)
- [Sort lines](https://marketplace.visualstudio.com/items?itemName=Tyriar.sort-lines)
- [Surround](https://marketplace.visualstudio.com/items?itemName=yatki.vscode-surround)
- [Text Marker (Highlighter)](https://marketplace.visualstudio.com/items?itemName=ryu1kn.text-marker)
- [Selected Lines Count](https://marketplace.visualstudio.com/items?itemName=gurumukhi.selected-lines-count)
- [Rewrap](https://marketplace.visualstudio.com/items?itemName=stkb.rewrap)
## Useful Extensions
- [Bookmarks](https://marketplace.visualstudio.com/items?itemName=alefragnani.Bookmarks)
- [EditorConfig](https://marketplace.visualstudio.com/items?itemName=EditorConfig.EditorConfig)
- [GraphQL for VSCode](https://marketplace.visualstudio.com/items?itemName=kumar-harsh.graphql-for-vscode)
- [jumpy](https://marketplace.visualstudio.com/items?itemName=wmaurer.vscode-jumpy)
- [Log File Highlighter](https://marketplace.visualstudio.com/items?itemName=emilast.LogFileHighlighter)
- [Markdown Preview Enhanced](https://marketplace.visualstudio.com/items?itemName=shd101wyy.markdown-preview-enhanced)
- [Paste JSON as Code](https://marketplace.visualstudio.com/items?itemName=quicktype.quicktype)
- [PowerShell](https://marketplace.visualstudio.com/items?itemName=ms-vscode.PowerShell)
- [Project Snippets](https://marketplace.visualstudio.com/items?itemName=rebornix.project-snippets)
- [Subtitles Editor](https://marketplace.visualstudio.com/items?itemName=pepri.subtitles-editor)
- [VS Live Share](https://marketplace.visualstudio.com/items?itemName=MS-vsliveshare.vsliveshare)
================================================
FILE: Windows/AutoHotkey.ahk
================================================
; AutoHotkey is a scripting language for Microsoft Windows which provides
; keyboard shortcuts that allows users to automate repetitive tasks.
;
; Hotkey Modifier Symbols
; https://www.autohotkey.com/docs/Hotkeys.htm#Symbols
;
; 1. Install it with Chocolatey: cinst autohotkey -y
; 2. Copy this file (AutoHotkey.ahk) to %UserProfile%\Documents
; 3. Create a shortcut to AutoHotkey in shell:startup
; 4. Run AutoHotkey
;
; --- Web pages ---------------------------------------------------------------
; Ctrl+Alt+C = opens Google Calendar in a new window of Chrome
; Ctrl+Alt+D = opens Google Drive in a new window of Chrome
; Ctrl+Alt+G = opens Gmail in a new window of Chrome
; Ctrl+Alt+M = opens Google Maps in a new window of Chrome
; Ctrl+Alt+T = opens Google Translate in a new window of Chrome
^!c::Run Chrome.exe "https://calendar.google.com/" " --new-window "
^!d::Run Chrome.exe "https://drive.google.com/" " --new-window "
^!g::Run Chrome.exe "https://mail.google.com/" " --new-window "
^!m::Run Chrome.exe "https://www.google.ee/maps/" " --new-window "
^!j::Run Chrome.exe "https://keep.google.com/" " --new-window "
^!t::Run Chrome.exe "https://translate.google.com/" " --new-window "
; --- Local apps --------------------------------------------------------------
; Ctrl+Alt+K = launches or brings to front KeePass
^!k::
IfWinExist, KeePass
WinActivate
else
Run "C:\Program Files\KeePass Password Safe 2\KeePass.exe"
return
; --- File Explorer -----------------------------------------------------------
; F4 = sets view to details and all columns to fit width
F4::
send,{LCtrl down}{LShift down}6{LCtrl up}{LShift up}
send,{LCtrl down}{NumpadAdd}{LCtrl up}
return
; --- Acronyms ----------------------------------------------------------------
::bbl::be back later
::brb::be right back
::btw::by the way
; --- SQL ---------------------------------------------------------------------
::sfr::SELECT * FROM
:o:slk::LIKE '%%'{Left 2}
; --- Markdown --------------------------------------------------------------------
:o:mkc::````{Left 1}
:o:mkbc::```````n`n`````` {Up 1}
; --- System ------------------------------------------------------------------
; Win+F12 = Puts the computer to sleep
^#F12::
; Sleep/Suspend:
DllCall("PowrProf\SetSuspendState", "int", 0, "int", 0, "int", 0)
; Hibernate:
;DllCall("PowrProf\SetSuspendState", "int", 1, "int", 0, "int", 0)
Return
; --- Typography ------------------------------------------------------------------
<^>!,:: Send, {Text}~ ; , VK=BC SC=033 ~={U+223C}
<^>!.:: Send, {Text}`` ; . VK=BE SC=034 `={U+0060}
<^>!-:: Send, {Text}— ; , VK=BD SC=035 —={U+2014}
================================================
FILE: Windows/AutoHotkey2.ahk
================================================
; AutoHotkey is a scripting language for Microsoft Windows which provides
; keyboard shortcuts that allows users to automate repetitive tasks.
;
; Hotkey Modifier Symbols
; https://www.autohotkey.com/docs/Hotkeys.htm#Symbols
;
; 1. Install it with winget: winget install -e --id AutoHotkey.AutoHotkey
; 2. Copy this file to shell:startup
; 3. Run AutoHotkey
; --- Legendd -----------------------------------------------------------------
; ^ = ctrl
; ! = alt
; + = shift
; # = lwin|rwin
; ^!+# = Hyper = (lwin|rwin)+ctrl+alt+shift
; --- Disable Windows hotkeys -------------------------------------------------
#w::return ; news feed
^!+#i::return ; system settings
^!+#+::return ; zoom
^!+#f::return ; feedback hub
^!+#,::return ; show open windows transparent
^!+#o::return ; outlook
^!+#d::return ; OneDrive
^!+#n::return ; OneNote
^!+#y::return ; Yammer Viva Engage
!r::return ; Nvidia overlay
; ^!+#w::return ; pen settings (commented because reassigned below)
; ^!+#c::return ; cortana/copilot (commented because reassigned below)
; ^!+#g::return ; Game Bar Xbox (commented because reassigned below)
; ^!+#k::return ; Connect (commented because reassigned below)
; #v::return ; Clipboard history
; #p::return ; monitor settings
; #a::return ; notification sidebar
; #r::return ; run dialog
; #l::return ; sign out
; #.::return ; Emojis
; --- Web pages ---------------------------------------------------------------
; Hyper+C = opens Google Calendar in a new window of Chrome
; Hyper+D = opens Google Drive in a new window of Chrome
; Hyper+G = opens Gmail in a new window of Chrome
; Hyper+M = opens Google Maps in a new window of Chrome
; Hyper+T = opens Google Translate in a new window of Chrome
^!+#c::Run("Chrome.exe `"https://calendar.google.com/`" `" --new-window `"")
^!+#g::Run("Chrome.exe `"https://mail.google.com/`" `" --new-window `"")
^!+#m::Run("Chrome.exe `"https://www.google.ee/maps/`" `" --new-window `"")
^!+#j::Run("Chrome.exe `"https://keep.google.com/`" `" --new-window `"")
^!+#t::Run("Chrome.exe `"https://translate.google.com/`" `" --new-window `"")
^!+#w::Run("Chrome.exe `"https://web.whatsapp.com/`" `" --new-window `"")
^!+#b::Run("C:\Program Files\Bambu Studio\bambu-studio.exe")
^!+#s::Run("ms-settings:sound")
^!+#x::
{
if WinExist("Telegram")
WinActivate()
else
Run("`"C:\Users\marco\AppData\Roaming\Telegram Desktop\Telegram.exe`"")
return
}
; --- Local apps --------------------------------------------------------------
; Hyper+K = launches or brings to front KeePass
^+#!k::
{
if WinExist("KeePass")
WinActivate()
else
Run("`"C:\Program Files\KeePass Password Safe 2\KeePass.exe`"")
return
}
; --- File Explorer -----------------------------------------------------------
; F4 = sets view to details and all columns to fit width
F4::
{
Send("{LCtrl down}{LShift down}6{LCtrl up}{LShift up}")
Send("{LCtrl down}{NumpadAdd}{LCtrl up}")
return
}
; --- Acronyms ----------------------------------------------------------------
::bbl::be back later
::brb::be right back
::btw::by the way
; --- SQL ---------------------------------------------------------------------
::sfr::SELECT * FROM
:o:slk::LIKE '%%'{Left 2}
; --- Markdown ----------------------------------------------------------------
:o:mkc::````{Left 1}
:o:mkbc::```````n`n`````` {Up 1}
; --- System ------------------------------------------------------------------
; Win+F12 = Puts the computer to sleep
; ^#F12::
; {
; ; Sleep/Suspend:
; DllCall("PowrProf\SetSuspendState", "int", 0, "int", 0, "int", 0)
; ; Hibernate:
; ;DllCall("PowrProf\SetSuspendState", "int", 1, "int", 0, "int", 0)
; return
; }
; --- Typography --------------------------------------------------------------
; Associates Alt Gr + , with ~ (, VK=BC SC=033 ~={U+223C})
;<^>!,::Send("{Text}~")
; Associates Alt Gr + . with ` (. VK=BE SC=034 `={U+0060})
;<^>!.::Send("{Text}``")
; Associates Alt Gr + - with — (- VK=BD SC=035 —={U+2014})
;<^>!-::Send("{Text}—")
; Replaces § with ~
;+SC02B::~
; Replaces ç with `
;+SC027::`
================================================
FILE: Windows/Chocolatey/Profile.ps1
================================================
# Include it in your PowerShell profile to publish Chocolatey packages
$ChocolateyProfile = "$env:ChocolateyInstall\helpers\chocolateyProfile.psm1"
if (Test-Path($ChocolateyProfile)) {
Import-Module "$ChocolateyProfile"
}
================================================
FILE: Windows/Chocolatey/README.md
================================================
# Chocolatey
[Chocolatey](https://chocolatey.org/) is a package manager for Windows.
## Install a list of packages in bulk
```powershell
cinst .\packages.config -y
```
See [`.\packages.config`](packages.config) for reference.
## Update all installed software
```powershell
cup all -y
```
## List installed software
```powershell
clist -l
```
## Install a specific version
```powershell
choco install bulkrenameutility --version=3.4.0.0 -y
```
## Pin a package to suppress upgrades
```powershell
choco pin add -n=ruby
```
- [Source](https://superuser.com/a/972614/54747)
================================================
FILE: Windows/Chocolatey/cdeps.ps1
================================================
$packages = Get-ChildItem C:\ProgramData\chocolatey\lib\ -Recurse *.nuspec | select fullname,name
foreach($p in $packages){
[XML]$xml=get-content $p.fullname
$dependencies = $xml.package.metadata.dependencies.dependency
foreach($d in $dependencies){
$obj = New-Object -TypeName psobject
$obj | Add-Member -MemberType NoteProperty -name package -Value $xml.package.metadata.id
$obj | Add-Member -MemberType NoteProperty -name packageversion -Value $xml.package.metadata.version
$obj | Add-Member -MemberType NoteProperty -name dependency -Value $d.id
$obj | Add-Member -MemberType NoteProperty -name dependencyversion -Value $d.version
$obj
}
}
================================================
FILE: Windows/Chocolatey/packages.config
================================================
<?xml version="1.0" encoding="utf-8"?>
<packages>
<!-- common -->
<package id="7zip" />
<package id="adobereader" />
<package id="dropbox" />
<package id="emule" />
<package id="fsviewer" />
<package id="googlechrome" />
<package id="libreoffice-fresh" />
<package id="qbittorrent" />
<package id="shutup10" />
<package id="teamviewer" />
<package id="telegram" />
<!-- development -->
<package id="docker-desktop" />
<package id="inconsolata" />
<package id="jetbrainsmono" />
<package id="poshgit" />
<package id="tortoisegit" />
<package id="vscode" />
<!-- command line tools -->
<package id="exiftool" />
<package id="ffmpeg" />
<package id="git" />
<package id="grep" />
<package id="microsoft-windows-terminal" />
<package id="nvm" />
<package id="wget" />
<!-- images & video editors -->
<package id="audacity" />
<package id="avidemux" />
<package id="gimp" />
<package id="inkscape" />
<package id="shotcut" />
<!-- gaming -->
<package id="discord" />
<package id="epicgameslauncher" />
<package id="nvidia-display-driver" />
<package id="origin" />
<package id="steam" />
<package id="uplay" />
<!-- multimedia -->
<package id="aimp" />
<package id="k-litecodecpackmega" />
<package id="spotify" />
<!-- productivity -->
<package id="autohotkey" />
<package id="bulkrenameutility" />
<package id="ccleaner" />
<package id="freefilesync" />
<package id="keepass" />
<package id="keepass-plugin-favicon" />
<package id="linkshellextension" />
<package id="nordvpn" />
<package id="openvpn" />
<package id="partitionwizard" />
<package id="pasteintofile" />
<package id="patchcleaner" /> <!-- Windows Installer directory cleaner -->
<package id="powertoys" />
<package id="procexp" /> <!-- Shows handles and DLLs opened or loaded by processes -->
<package id="rufus" /> <!-- Creates bootable USB flash drives -->
<package id="sizer" /> <!-- Resizes windows to exact sizes -->
<package id="treesizefree" />
</packages>
================================================
FILE: Windows/PowerShell/README.md
================================================
# PowerShell
Table of Contents
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
<!-- generated with [DocToc](https://github.com/thlorenz/doctoc) -->
- [Installation](#installation)
- [Know PowerShell version](#know-powershell-version)
- [Registry keys CRUD operations](#registry-keys-crud-operations)
- [Get hardware info](#get-hardware-info)
- [Add a timestamp to your prompt](#add-a-timestamp-to-your-prompt)
- [Shortcuts](#shortcuts)
- [Quickly open PowerShell as Administrator](#quickly-open-powershell-as-administrator)
- [Use CTRL + D to exit PowerShell console](#use-ctrl--d-to-exit-powershell-console)
- [List only files and folders names in the current directory](#list-only-files-and-folders-names-in-the-current-directory)
- [Add git integration](#add-git-integration)
- [Set the default starting directory](#set-the-default-starting-directory)
- [Enable partial matching of a command with up and down keys](#enable-partial-matching-of-a-command-with-up-and-down-keys)
- [Have syntax highlighting](#have-syntax-highlighting)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
## Installation
PowerShell 7 is a modern, cross-platform version of PowerShell that can run on Windows, Linux, and macOS, unlike version 5 which is limited to Windows. It offers improved performance, new features and better error handling. PowerShell 7 is actively developed and maintained, while version 5 only receives security updates. PowerShell 7 installs to a new directory and runs side-by-side with Windows PowerShell 5.
To install it run:
```powershell
winget install -h --id Microsoft.PowerShell
```
For a better experience, install also the [PowerShell Toys](https://github.com/lackovic/PSToys).
## Know PowerShell version
```powershell
$PSVersionTable
```
## Registry keys CRUD operations
```powershell
# To read a registry key:
Get-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\Test\One\Two\Three
# To create or update a registry key default value:
Set-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\Test\One\Two\Three -Name '(Default)' -Value 'NewValue'
# To append something to an existing registry key default value:
$MyRegKey = Get-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\Test\One\Two\Three
$NewValue = $MyRegKey.'(Default)' + 'Something'
Set-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\Test\One\Two\Three -Name '(Default)' -Value $NewValue
# To delete a registry key and all its subkeys:
Remove-ItemProperty -Path Registry::HKEY_CLASSES_ROOT\Test\One\Two\Three -Recurse
```
## Get hardware info
```powershell
# Computer brand and model
Get-CimInstance Win32_ComputerSystem | Format-List Manufacturer, Model
# Motherboard
Get-CimInstance Win32_Baseboard | Format-List Manufacturer, SerialNumber, Version, Product
# BIOS
Get-CimInstance Win32_BIOS | Format-List Manufacturer, Version, ReleaseDate, SMBIOSBIOSVersion, SMBIOSMajorVersion, SMBIOSMinorVersion, SystemBiosMajorVersion, SystemBiosMinorVersion
# CPU
Get-CimInstance Win32_Processor | Format-List DeviceID, LoadPercentage, MaxClockSpeed, ProcessorType, SocketDesignation, Description, Name, CurrentClockSpeed, Manufacturer, NumberOfCores, NumberOfEnabledCore, NumberOfLogicalProcessors, ProcessorId, ThreadCount
# Graphic card
Get-CimInstance Win32_VideoController | Format-List AdapterCompatibility, Caption, Description, Name, PNPDeviceID, VideoModeDescription, VideoProcessor
# Drives / storage
Get-WmiObject Win32_DiskDrive | Select Model, SerialNumber, Size, MediaType
# RAM
Get-CimInstance Win32_PhysicalMemory | Format-List Manufacturer, PartNumber, SerialNumber, Tag, BankLabel, Capacity, Speed, ConfiguredClockSpeed, DeviceLocator
# Operating System
Get-CimInstance Win32_OperatingSystem | Format-List Name, InstallDate, LastBootUpTime, NumberOfUsers, Version, BuildNumber, SerialNumber
```
## Add a timestamp to your prompt
See prompt renderers posh-git in [./Microsoft.PowerShell_profile.ps1](./Microsoft.PowerShell_profile.ps1)
## Shortcuts
### Quickly open PowerShell as Administrator
`Ctrl`+`X` `A`
### Use CTRL + D to exit PowerShell console
See [./Microsoft.PowerShell_profile.ps1](./Microsoft.PowerShell_profile.ps1)
## List only files and folders names in the current directory
```powershell
dir | Select-Object Name
```
## Add git integration
See prompt renderers in [./Microsoft.PowerShell_profile.ps1](./Microsoft.PowerShell_profile.ps1)
## Set the default starting directory
See [./Microsoft.PowerShell_profile.ps1](./Microsoft.PowerShell_profile.ps1)
## Enable partial matching of a command with up and down keys
Add to your profile (e.g. - `~\Documents\PowerShell\Microsoft.PowerShell_profile.ps1`):
```powershell
Set-PSReadlineKeyHandler -Key UpArrow -Function HistorySearchBackward
Set-PSReadlineKeyHandler -Key DownArrow -Function HistorySearchForward
```
## Have syntax highlighting
See color highlighting in [./Microsoft.PowerShell_profile.ps1](./Microsoft.PowerShell_profile.ps1)
================================================
FILE: Windows/README.md
================================================
# Windows
*Table of contents*
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
<!-- generated with [DocToc](https://github.com/thlorenz/doctoc) -->
- [Installation](#installation)
- [Install the latest Windows release with all the latest updates included](#install-the-latest-windows-release-with-all-the-latest-updates-included)
- [Install Windows without 3rd party bloatware](#install-windows-without-3rd-party-bloatware)
- [Things to do right after a Windows 11 installation](#things-to-do-right-after-a-windows-11-installation)
- [Windows Update](#windows-update)
- [Run Windows Update from terminal](#run-windows-update-from-terminal)
- [Get the Windows Update log](#get-the-windows-update-log)
- [Miscellaneous how-tos](#miscellaneous-how-tos)
- [Favorite shortcuts](#favorite-shortcuts)
- [Know the version and build](#know-the-version-and-build)
- [Know the domain](#know-the-domain)
- [Know whether a service is running on a port number](#know-whether-a-service-is-running-on-a-port-number)
- [Change the screenshots default save location](#change-the-screenshots-default-save-location)
- [Create your own custom keyboard layout](#create-your-own-custom-keyboard-layout)
- [Wipe all the deleted data / free space on a drive](#wipe-all-the-deleted-data--free-space-on-a-drive)
- [See the command history across all PowerShell sessions](#see-the-command-history-across-all-powershell-sessions)
- [BitLocker](#bitlocker)
- [Lock a BitLocker encrypted drive from the command line](#lock-a-bitlocker-encrypted-drive-from-the-command-line)
- [Find out if your drive is running BitLocker software based encryption](#find-out-if-your-drive-is-running-bitlocker-software-based-encryption)
- [Disable BitLocker encryption for a drive](#disable-bitlocker-encryption-for-a-drive)
- [Find a file or directory being used by another process](#find-a-file-or-directory-being-used-by-another-process)
- [Autostarting programs locations](#autostarting-programs-locations)
- [Get rid of US language in Windows 11](#get-rid-of-us-language-in-windows-11)
- [Automation and bloatware removal](#automation-and-bloatware-removal)
- [Customize File Explorer (permanently disable files grouping)](#customize-file-explorer-permanently-disable-files-grouping)
- [Disable magnifier](#disable-magnifier)
- [Scripts for automation of routine tasks and bloatware removal](#scripts-for-automation-of-routine-tasks-and-bloatware-removal)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
## Installation
1. Visit [Download Windows 11](https://www.microsoft.com/en-gb/software-download/windows11).
1. **Create Windows 11 Installation Media** > Download now.
1. Run the downloaded `MediaCreationToolW11.exe`.
1. Follow the instructions to create a bootable USB drive.
### Install the latest Windows release with all the latest updates included
1. Download the image creation script from [UUP dump](https://uupdump.net/)
1. Set `CustomList=1` in `ConvertConfig.ini` in order to avoid including Windows bloatware (like Outlook, Teams, Xbox, etc) in the installation image.
1. Run `uup_download_windows.cmd`
The process will take a while: it takes 35 minutes on a beafy desktop computer with a 150 Mbps bandwidth. Once it's done, you'll find the ISO image (~6 GB) in the folder where you ran the script. You can use it to create a bootable USB drive with [Rufus](https://rufus.ie/).
### Install Windows without 3rd party bloatware
1. At the initial install, select "_English (World)_" as the _Time & Currency format_.
1. After installation, open Windows Settings > _Time & Language & Region_ > _Country or region_: set the country you actually are located in.
[Source](https://twitter.com/thiojoe/status/1686565269907636224).
### Things to do right after a Windows 11 installation
1. Run Windows Update and reboot until there are no more updates available
1. Run [SetupConfig.ps1](./Scripts/SetupConfig.ps1) to apply various configuration tweaks using the following command:
```powershell
powershell.exe -ExecutionPolicy Bypass -File .\SetupConfig.ps1
```
1. Download [Incosolata Nerd Font](https://www.nerdfonts.com/font-downloads), extract and install all TTF files
1. Set it as default font in Windows Terminal
1. Install [PowerShell Toys](https://github.com/lackovic/PSToys) for a better PowerShell experience
1. Run [SetupApps.ps1](./Scripts/SetupApps.ps1) to install commonly used applications via Winget
1. Install your motherboard drivers (chipset, audio, LAN, etc.)
1. Install your GPU drivers
## Windows Update
### Run Windows Update from terminal
```powershell
Install-Module PSWindowsUpdate
Get-WindowsUpdate
Install-WindowsUpdate
```
### Get the Windows Update log
Running the following command will create a `WindowsUpdate.log` file in your Desktop folder:
```powershell
Get-WindowsUpdateLog
```
## Miscellaneous how-tos
See [SetupConfig.ps1](./Scripts/SetupConfig.ps1).
## Favorite shortcuts
| Key | Command |
| ------------------------- | --------------------------------------------------- |
| `Win+E` | Open File Explorer |
| `Win+X` | Open the Quick Link menu. |
| `Win+R` | Open the Run dialog box. |
| `Win+Tab` | Open Task view. |
| `Win+V` | Open the clipboard history. |
| `Win+B` | Set focus to the first icon in the Taskbar corner. |
| `Win+number` | Start/switch to the n-th app pinned to the taskbar. |
| `Win+Ctrl+V` | Open the sound output device selector |
[All shortcuts](https://support.microsoft.com/en-us/windows/keyboard-shortcuts-in-windows-dcc61a57-8ff0-cffe-9796-cb9706c75eec)
## Know the version and build
Run in PowerShell:
```powershell
# Displays the version in a window
winver
# Displays the version in the terminal
systeminfo | findstr /B /C:"OS Name" /C:"OS Version"
```
## Know the domain
Run in PowerShell either of the two:
```powershell
systeminfo | findstr /B /C:"Domain"
wmic computersystem get domain
```
## Know whether a service is running on a port number
Run in PowerShell:
```powershell
netstat -an -b | grep <port_number>
```
## Change the screenshots default save location
1. Right click on `%USERPROFILE%\Pictures\Screenshots\`
1. Properties > Location
## Create your own custom keyboard layout
- [Microsoft Keyboard Layout Creator](https://www.microsoft.com/en-us/download/details.aspx?id=102134)
## Wipe all the deleted data / free space on a drive
```powershell
# Overwrites the deallocated space on drive C:
cipher /w:C
```
Cipher goes through the following steps:
1. creates the folder `C:\EFSTMPWP`
1. creates a first file in that folder filled with `0`, making it grow until the hard drive fills up
1. deletes that file and creates a second one filled with `255`, making it grow until the hard drive fills up
1. deletes the second file, creates a third file filled with random numbers, making it grow until the hard drive fills up again
1. deletes the third file and returns you to the prompt
## See the command history across all PowerShell sessions
```powershell
cat (Get-PSReadlineOption).HistorySavePath
```
## BitLocker
### Lock a BitLocker encrypted drive from the command line
```powershell
manage-bde.exe -lock e:
```
### Find out if your drive is running BitLocker software based encryption
```powershell
manage-bde -status
```
### Disable BitLocker encryption for a drive
```powershell
manage-bde -off e:
```
This will take a while, depending on the size of the drive and the amount of data stored on it. You can monitor the decryption progress with:
```powershell
manage-bde -status
```
and then look at the _Conversion Status_ field and the _Percentage Encrypted_ field.
## Find a file or directory being used by another process
1. Open "Resource Monitor" (`resmon.exe`)
1. Go to the "CPU" tab
1. In the "Associated Handles" section, type part of the file or directory name in the search box
## Autostarting programs locations
- Task Manager > Startup apps
- Registry Editor:
- `Computer\HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run`
- `Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run`
- Task Scheduler > Task Scheduler Library
## Get rid of US language in Windows 11
In Windows 11 settings (`Win`+`i`), select _Time & language_ > _Language & region_:
1. Open the Language options of any listed language, press _Add a keyboard_, select _US Qwerty_ to add it, then click on the triple dots next to _US Qwerty_ and select _Remove_ to remove it.
1. _Related settings_ section, _Administrative language settings_ option, _Administrative_ tab, _Language for non-Unicode programs_ > press the _Change system locale..._ button, replace _US English_ with the layout of your main language.
1. Reboot.
[Source](https://superuser.com/questions/1680608/how-to-get-rid-of-us-language-in-windows-11/1749153)
## Automation and bloatware removal
### Customize File Explorer (permanently disable files grouping)
Use [WinSetView](https://lesferch.github.io/WinSetView/) to apply the following changes:
Options:
- Show file extensions
- Classic context menu in Windows 11
- No Internet in Windows search
- Make All Folders Generic (Advanced interface)
Global (details) columns:
- Name
- Size
- Date created
- Date modified
- Type
- Group by: (None)
### Disable magnifier
(The following steps are currently not working and are left here for reference until a working solution is found).
In an elevated PowerShell console run the following command:
```powershell
takeown /f C:\Windows\System32\Magnify.exe
```
- type Y and press Enter
- Right-click on `C:\Windows\System32\Magnify.exe` and rename it to `Magnify.exe.bak`
### Scripts for automation of routine tasks and bloatware removal
- [topics/windows-11-debloat](https://github.com/topics/windows-11-debloat)
- [builtbybel/BloatyNosy](https://github.com/builtbybel/BloatyNosy)
- [W4RH4WK/Debloat-Windows-10](https://github.com/W4RH4WK/Debloat-Windows-10)
- [LeDragoX/Win-Debloat-Tools](https://github.com/LeDragoX/Win-Debloat-Tools)
- [Tron fights for the User](https://www.reddit.com/r/TronScript/wiki/index)
- [farag2/Windows-10-Sophia-Script](https://github.com/farag2/Windows-10-Sophia-Script)
- [Disassembler0/Win10-Initial-Setup-Script](https://github.com/Disassembler0/Win10-Initial-Setup-Script) (discontinued since May 28, 2021)
- [Sycnex/Windows10Debloater](https://github.com/Sycnex/Windows10Debloater) (discontinued since Sep 21, 2023)
- [ChrisTitusTech/win10script](https://github.com/ChrisTitusTech/win10script) (discontinued since Sep 8, 2022)
================================================
FILE: Windows/Scripts/DeleteOldWinDirs.ps1
================================================
<#
.SYNOPSIS
Removes old Windows directories from a previous Windows installation.
.DESCRIPTION
Based on: https://superuser.com/a/1028115/54747
.PARAMETER TargetDrive
The drive letter where the old Windows installation is located
.PARAMETER Force
Skip confirmation prompts and proceed with deletion
.EXAMPLE
.\DeleteOldWinDirs.ps1 -TargetDrive "D:" -Force
#>
#Requires -RunAsAdministrator
Write-Host "Warning: This script will permanently delete old Windows directories from the specified drive.`n Ensure you have selected the correct drive and have backups if necessary.`n Press c to continue or any other key to cancel." -ForegroundColor Red
$key = [System.Console]::ReadKey($true)
if ($key.Key -ne "C") {
Write-Host "Operation cancelled by user." -ForegroundColor Yellow
exit
}
Write-Host "Continuing with deletion..." -ForegroundColor Green
param(
[Parameter(Mandatory = $true)]
[ValidatePattern("^[A-Za-z]:$")]
[string]$TargetDrive,
[switch]$Force
)
$ErrorActionPreference = "Stop"
function Write-ColoredOutput {
param([string]$Message, [string]$Color = "White")
Write-Host $Message -ForegroundColor $Color
}
function Get-FolderSize {
param([string]$Path)
if (-not (Test-Path $Path)) { return 0 }
try {
$size = (Get-ChildItem $Path -Recurse -File -ErrorAction SilentlyContinue | Measure-Object Length -Sum).Sum
return [math]::Round($size / 1GB, 2)
}
catch { return 0 }
}
function Remove-WindowsDirectory {
param([string]$Path, [string]$Name)
if (-not (Test-Path $Path)) {
Write-ColoredOutput " $Name not found - skipping" "Yellow"
return 0
}
$size = Get-FolderSize $Path
Write-ColoredOutput " Removing $Name ($size GB)..." "Cyan"
try {
# Take ownership and set permissions
& takeown.exe /F $Path /A /R /D Y 2>&1 | Out-Null
& icacls.exe $Path /T /grant "Administrators:F" 2>&1 | Out-Null
# Remove directory
Remove-Item $Path -Recurse -Force
Write-ColoredOutput " ✓ Removed $Name ($size GB)" "Green"
return $size
}
catch {
Write-ColoredOutput " ✗ Failed to remove $Name`: $_" "Red"
return 0
}
}
# Main execution
try {
Write-ColoredOutput "`n=== Delete Old Windows Directories ===" "White"
Write-ColoredOutput "Target Drive: $TargetDrive" "Cyan"
# Check if running as administrator
if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
throw "This script requires Administrator privileges."
}
# Check if target drive exists
if (-not (Test-Path $TargetDrive)) {
throw "Target drive $TargetDrive does not exist."
}
# Define directories to remove
$directories = @(
@{ Path = "$TargetDrive\Program Files"; Name = "Program Files" }
@{ Path = "$TargetDrive\Program Files (x86)"; Name = "Program Files (x86)" }
@{ Path = "$TargetDrive\ProgramData"; Name = "ProgramData" }
@{ Path = "$TargetDrive\Users"; Name = "Users" }
@{ Path = "$TargetDrive\Windows"; Name = "Windows" }
)
# Calculate total size
$totalSize = ($directories | ForEach-Object { Get-FolderSize $_.Path } | Measure-Object -Sum).Sum
Write-ColoredOutput "Total size to delete: $totalSize GB`n" "Yellow"
# Show confirmation unless -Force is used
if (-not $Force) {
Write-ColoredOutput "WARNING: This will permanently delete:" "Red"
foreach ($dir in $directories) {
if (Test-Path $dir.Path) {
$size = Get-FolderSize $dir.Path
Write-ColoredOutput " - $($dir.Path) ($size GB)" "Yellow"
}
}
$response = Read-Host "`nContinue? (yes/no)"
if ($response -ne "yes") {
Write-ColoredOutput "Operation cancelled." "Yellow"
exit 0
}
}
# Remove directories
Write-ColoredOutput "`nRemoving directories..." "White"
$totalRemoved = 0
foreach ($dir in $directories) {
$totalRemoved += Remove-WindowsDirectory $dir.Path $dir.Name
}
Write-ColoredOutput "`n=== Completed Successfully ===" "Green"
Write-ColoredOutput "Total space freed: $totalRemoved GB" "Green"
}
catch {
Write-ColoredOutput "`nError: $_" "Red"
exit 1
}
================================================
FILE: Windows/Scripts/DisableWake-on-LAN.ps1
================================================
# Get the specific Realtek adapter
$nic = Get-NetAdapter | Where-Object { $_.InterfaceDescription -match "Realtek" }
if ($nic) {
Write-Host "Found: $($nic.InterfaceDescription)" -ForegroundColor Cyan
# Disable the standard Power Management features
# We use -ErrorAction SilentlyContinue because some drivers don't support all flags
Set-NetAdapterPowerManagement -InterfaceDescription $nic.InterfaceDescription `
-WakeOnMagicPacket Disabled `
-WakeOnPattern Disabled `
-ErrorAction SilentlyContinue
# Now we disable the "Magic Packet" and "Pattern Match" at the driver-specific level
# This is often where the 'Ghost' wakes live for Realtek cards
Write-Host "Disabling hardware-level Advanced properties..." -ForegroundColor Yellow
Set-NetAdapterAdvancedProperty -InterfaceDescription $nic.InterfaceDescription -DisplayName "Wake on Magic Packet" -DisplayValue "Disabled" -ErrorAction SilentlyContinue
Set-NetAdapterAdvancedProperty -InterfaceDescription $nic.InterfaceDescription -DisplayName "Wake on pattern match" -DisplayValue "Disabled" -ErrorAction SilentlyContinue
Set-NetAdapterAdvancedProperty -InterfaceDescription $nic.InterfaceDescription -DisplayName "Shutdown Wake-On-Lan" -DisplayValue "Disabled" -ErrorAction SilentlyContinue
Write-Host "Network wake features have been neutralized." -ForegroundColor Green
} else {
Write-Warning "Realtek adapter not found via PowerShell."
}
================================================
FILE: Windows/Scripts/DisableWakeupTimers.ps1
================================================
# 1. Disable Wake Timers in the Active Power Plan using Aliases
# This works even if the GUIDs are non-standard.
$activeScheme = (powercfg /getactivescheme | ForEach-Object { $_.split(' ')[3] })
Write-Host "--- Power Plan Security ---" -ForegroundColor Cyan
try {
# 0 = Disabled, 1 = Enabled, 2 = Important Only
powercfg /setacvalueindex $activeScheme SUB_SLEEP RTCWAKE 0
powercfg /setdcvalueindex $activeScheme SUB_SLEEP RTCWAKE 0
powercfg /setactive $activeScheme
Write-Host "[OK] Global Wake Timers disabled for active scheme: $activeScheme" -ForegroundColor Green
} catch {
Write-Warning "Failed to set Power Plan via Aliases."
}
# 2. Neutralize 'WakeToRun' Scheduled Tasks
Write-Host "`n--- Scanning Scheduled Tasks ---" -ForegroundColor Cyan
Import-Module ScheduledTasks
$tasks = Get-ScheduledTask | Where-Object {$_.Settings.WakeToRun}
if ($tasks) {
foreach ($task in $tasks) {
try {
$settings = $task.Settings
$settings.WakeToRun = $false
Set-ScheduledTask -TaskName $task.TaskName -TaskPath $task.TaskPath -Settings $settings -ErrorAction Stop
Write-Host "[FIXED] Disabled wake trigger for: $($task.TaskName)" -ForegroundColor Yellow
} catch {
Write-Warning "[LOCKED] Could not modify $($task.TaskName) - Likely Protected by System."
}
}
} else {
Write-Host "[OK] No rogue wake-up tasks found." -ForegroundColor Green
}
# 3. Final Verification
Write-Host "`n--- Current Wake Status ---" -ForegroundColor Cyan
powercfg /waketimers
================================================
FILE: Windows/Scripts/ReduceOneHour.js
================================================
// BulkRenameUtility script to reduce the hour of a date by one hour of filenames in the format "YYYY-MM-DD HH.MM.SS"
// Example: 2021-01-01 23.59.59 -> 2021-01-01 22.59.59
// Assumes that the hour is never 00
function reduceOneHour(dateString) {
const parts = dateString.split("\\");
const lastPart = parts.pop();
const hour = Number(lastPart.substring(11, 13));
var newHour = (hour - 1);
newHour = newHour < 10 ? "0" + newHour : "" + newHour;
const newLastPart = lastPart.substring(0, 11) + newHour + lastPart.substring(13);
return parts.length ? parts.join("\\") + "\\" + newLastPart : newLastPart;
}
newName = reduceOneHour(name);
================================================
FILE: Windows/Scripts/ReduceOneHour.ps1
================================================
<#
.SYNOPSIS
Reduce the hour of date-based filenames by one hour.
.NOTES
Processes files in the current directory with filenames in the format "YYYY-MM-DD HH.MM.SS".
Pattern matches the date/time portion but allows any file extension.
.EXAMPLE
"2024-01-01 23.59.59.txt" -> "2024-01-01 22.59.59.txt"
"2024-01-01 00.00.00.jpg" -> "2023-12-31 23.00.00.jpg"
"2024-03-01 00.30.15.mp4" -> "2024-02-29 23.30.15.mp4"
#>
$pattern = "^\d{4}-\d{2}-\d{2} \d{2}\.\d{2}\.\d{2}"
$files = Get-ChildItem | Where-Object { $_.BaseName -match $pattern }
foreach ($file in $files) {
try {
# Extract the date components from the filename
$dateParts = $file.BaseName -split " "
if ($dateParts.Length -ne 2) {
Write-Warning "Skipping '$($file.Name)': Invalid format"
continue
}
$date = $dateParts[0]
$time = $dateParts[1]
# Validate date format
if ($date -notmatch '^\d{4}-\d{2}-\d{2}$') {
Write-Warning "Skipping '$($file.Name)': Invalid date format"
continue
}
# Validate time format
if ($time -notmatch '^\d{2}\.\d{2}\.\d{2}$') {
Write-Warning "Skipping '$($file.Name)': Invalid time format"
continue
}
# Convert the date string to DateTime object
$dateTime = [DateTime]::ParseExact("$date $($time.Replace('.', ':'))", "yyyy-MM-dd HH:mm:ss", $null)
# Subtract one hour
$newDateTime = $dateTime.AddHours(-1)
# Format the new date and time
$newDate = $newDateTime.ToString("yyyy-MM-dd")
$newTime = $newDateTime.ToString("HH.mm.ss")
# Construct new filename with original extension
$newName = "$newDate $newTime$($file.Extension)"
# Check if target file already exists
if (Test-Path $newName) {
Write-Warning "Cannot rename '$($file.Name)': Target file '$newName' already exists"
continue
}
# Rename the file
Rename-Item -Path $file.FullName -NewName $newName -ErrorAction Stop
# Output the change
Write-Host "Renamed: $($file.Name) -> $newName"
}
catch {
Write-Error "Error processing '$($file.Name)': $_"
}
}
# Output summary of any files in the directory that weren't processed
$unprocessedFiles = Get-ChildItem | Where-Object { $_.BaseName -notmatch $pattern }
if ($unprocessedFiles) {
Write-Host "`nFiles not matching the required format:"
$unprocessedFiles | ForEach-Object { Write-Host " - $($_.Name)" }
}
================================================
FILE: Windows/Scripts/SetupApps.ps1
================================================
<#
.SYNOPSIS
Install commonly used applications via Winget.
.NOTES
Comment out any applications you do not wish to install.
#>
#Requires -RunAsAdministrator
# Verify Winget is installed
if (-not (Get-Command winget -ErrorAction SilentlyContinue)) {
Invoke-WebRequest -Uri https://aka.ms/getwinget -OutFile winget.msixbundle
Add-AppxPackage winget.msixbundle
Remove-Item winget.msixbundle
}
winget source update
# General Apps
winget install -h --id Microsoft.WindowsTerminal
winget install -h --id Google.Chrome
winget install -h --id Telegram.TelegramDesktop
# Needs to be installed from a non-elevated PowerShell
winget install -h --id Mega.MEGASync --ignore-security-hash
winget install -h --id DominikReichl.KeePass
winget install -h --id AutoHotkey.AutoHotkey
winget install -h --id Microsoft.PowerShell
winget install -h --id HermannSchinagl.LinkShellExtension
winget install -h --id Microsoft.VisualStudioCode
winget install -h --id Git.Git
winget install -h --id FastStone.Viewer
winget install -h --id LocalSend.LocalSend
winget install -h --id TGRMNSoftware.BulkRenameUtility
winget install -h --id SumatraPDF.SumatraPDF
winget install -h --id Spotify.Spotify
winget install -h --id GIMP.GIMP.3
winget install -h --id RIA.eIDsoftware
winget install -h --id CodecGuide.K-LiteCodecPack.Mega
winget install -h --id Avidemux.Avidemux
winget install -h --id JAMSoftware.TreeSize.Frees
winget install -h --id Microsoft.VCRedist.2015+.x64
winget install -h --id Deskflow.Deskflow
# Gaming Apps
winget install -h --id Discord.Discord
winget install -h --id Valve.Steam
winget install -h --id Amazon.Games
winget install -h --id GOG.Galaxy
winget install -h --id EpicGames.EpicGamesLauncher
# Work Apps
winget install -h --id JetBrains.IntelliJIDEA.Ultimate
winget install -h --id SlackTechnologies.Slack
winget install -h --id DBeaver.DBeaver.Community
winget install -h --id Docker.DockerDesktop
winget install -h --id Schniz.fnm
winget install -h --id Bruno.Bruno
winget install -h --id Gravitational.Teleport
winget install -h --id Google.GoogleDrive
# Windows Subsystem for Linux
wsl --install
================================================
FILE: Windows/Scripts/SetupConfig.ps1
================================================
<#
.SYNOPSIS
Configure various Windows settings for improved usability and performance.
.EXAMPLE
WARNING! This script must be executed in this specific way to avoid execution policy errors:
powershell.exe -ExecutionPolicy Bypass -File .\SetupConfig.ps1
.NOTES
Comment out any settings you do not wish to apply.
#>
#Requires -RunAsAdministrator
# >>> Taskbar >>>
# Disable Taskbar Search box
Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Search" -Name "SearchboxTaskbarMode" -Type DWord -Value 0
# Disable Taskbar Task View button
Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced" -Name "ShowTaskViewButton" -Type DWord -Value 0
# Disable Taskbar Widgets (News and Interests)
Write-Host "*** Warning *** Disabling Taskbar Widgets (News and Interests) is not automated yet, please do it manually." -ForegroundColor Yellow
# Disable Taskbar Chat button
Write-Host "*** Warning *** Disabling Taskbar Chat button is not automated yet, please do it manually." -ForegroundColor Yellow
# Set Taskbar alignment to Left (0 = Left, 1 = Center)
Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced" -Name "TaskbarAl" -Type DWord -Value 0
# >>> Explorer >>>
# Hide desktop icons
Set-ItemProperty -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced' -Name HideIcons -Value 1
# Enable showing hidden files and file extensions in Windows Explorer
Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced" -Name "HideFileExt" -Value 0
# Enable classic context menu
reg add "HKCU\Software\Classes\CLSID\{86ca1aa0-34aa-4e8b-a509-50c905bae2a2}\InprocServer32" /f /ve
# Enable "Expand to open folder" in Navigation pane
Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced" -Name "NavPaneExpandToCurrentFolder" -Value 1 -Type DWord
# >>> Notification >>>
# Disable Notifications
Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\PushNotifications" -Name "ToastEnabled" -Type DWord -Value 0 -Force
# Enable Notifications > Do not disturb
Write-Host "*** Warning *** Enabling Notifications > Do not disturb is not automated yet, please do it manually." -ForegroundColor Yellow
# Disable Notifications > Additional settings > "Show the Windows welcome experience..."
Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\ContentDeliveryManager" -Name "SubscribedContent-310093Enabled" -Value 0 -Type DWord
# Disable Notifications > Additional settings > "Suggest ways to get the most out of Windows..."
New-Item -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\UserProfileEngagement" -Force | Out-Null
Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\UserProfileEngagement" -Name "ScoobeSystemSettingEnabled" -Type DWord -Value 0
# Disable Notifications > Additional settings > "Get tips and suggestions when I use Windows"
Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\ContentDeliveryManager" -Name "SubscribedContent-338389Enabled" -Value 0 -Type DWord
# >>> Power >>>
# Set lid close action to "Do Nothing" for both battery and plugged in
powercfg /setdcvalueindex SCHEME_CURRENT 4f971e89-eebd-4455-a8de-9e59040e7347 5ca83367-6e45-459f-a27b-476b1d01c936 0
powercfg /setacvalueindex SCHEME_CURRENT 4f971e89-eebd-4455-a8de-9e59040e7347 5ca83367-6e45-459f-a27b-476b1d01c936 0
powercfg /setactive SCHEME_CURRENT
# Enable hibernate option in power menu
powercfg /hibernate on
Set-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\Power' -Name HibernateEnabled -Value 1
Set-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\FlyoutMenuSettings' -Name ShowHibernateOption -Value 1 -Force
# Control panel > Power options > Choose what the power buttons do > Turn on fast startup
Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Power" -Name "HiberbootEnabled" -Value 1 -Type DWord
# Disable computer wake up on key press or mouse movement
# You might have to run this command again after a plugging in a new mouse or keyboard, or after a major Windows update
powercfg /DEVICEQUERY wake_programmable | Select-String -Pattern "mouse|keyboard" | ForEach-Object { $_.ToString() } | ForEach-Object { powercfg /DEVICEDISABLEWAKE $_ }
# >>> Visual and audio >>>
# Set Sounds > More sounds settings > Sounds > Sound Scheme to "No Sounds"
Set-ItemProperty -Path "HKCU:\AppEvents\Schemes" -Name "(Default)" -Value ".None" -Type String
Get-ChildItem -Path "HKCU:\AppEvents\Schemes\Apps" -Recurse |
Where-Object { $_.PSChildName -eq ".Current" } |
ForEach-Object { Set-ItemProperty -Path $_.PSPath -Name "(Default)" -Value "" -Type String }
# Disable Accessibility > Visual effects > Transparency effects
Set-ItemProperty -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize' -Name EnableTransparency -Type DWord -Value 0
# Disable Accessibility > Visual effects > Animation effects
# https://github.com/Raphire/Win11Debloat/issues/120
Write-Host "*** Warning *** Disabling Accessibility > Visual effects > Animation effects is not automated yet, please do it manually." -ForegroundColor Yellow
# >>> Other Settings >>>
# Disable Personalization > Start "Show recommended files in Start, recent files in File Explorer, and items in Jump Lists"
Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced" -Name "Start_TrackDocs" -Value 0 -Type DWord
# Disable Personalization > Start "Show recommendetions for tips, shortcuts, new apps, and more"
Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced" -Name "Start_IrisRecommendations" -Value 0 -Type DWord
# Disable file search integration in Start Menu
Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced" -Name "Start_SearchFiles" -Value 0 -Type DWord
# Enable Windows Update "Get the latest updates as soon as they're available"
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\WindowsUpdate\UX\Settings" -Name "IsContinuousInnovationOptedIn" -Value 1 -Type DWord
# Enable System > Clipboard > Clipboard history
Set-ItemProperty -Path "HKCU:\Software\Microsoft\Clipboard" -Name "EnableClipboardHistory" -Value 1 -Type DWORD -Force
# Disable Cortana and web search integration in Windows Search
reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Search" /v BingSearchEnabled /t REG_DWORD /d 00000000 /f
reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Search" /v AllowSearchToUseLocation /t REG_DWORD /d 00000000 /f
reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Search" /v CortanaConsent /t REG_DWORD /d 00000000 /f
# Disable hyper key (Win+Alt+Ctrl+Shift) opening Microsoft Office
REG ADD HKCU\Software\Classes\ms-officeapp\Shell\Open\Command /t REG_SZ /d rundll32 /f
# Enable Windows Security > App & browser control > Reputation-based protection
Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\AppHost" -Name "EnableWebContentEvaluation" -Type DWord -Value 1
# Restart Explorer to apply Start Menu changes
Stop-Process -Name explorer -Force
================================================
FILE: Windows/Scripts/UninstallBloatware.ps1
================================================
<#
.SYNOPSIS
Uninstall common bloatware applications from Windows.
.EXAMPLE
WARNING! This script must be executed in this specific way to avoid execution policy errors:
powershell.exe -ExecutionPolicy Bypass -File .\UninstallBloatware.ps1
.NOTES
Comment out any applications you do not wish to remove.
#>
#Requires -RunAsAdministrator
# >>> Bloatware Removal >>>
$apps = @(
"*Clipchamp.Clipchamp*",
"*LinkedIn*",
"*Microsoft.BingNews*",
"*Microsoft.BingWeather*",
"*Microsoft.GamingApp*",
"*Microsoft.Microsoft3DViewer*",
"*Microsoft.MicrosoftSolitaireCollection*",
"*Microsoft.MicrosoftStickyNotes*",
"*Microsoft.MicrosoftOfficeHub*",
"*Microsoft.MixedReality.Portal*",
"*Microsoft.Office.OneNote*",
"*Microsoft.OutlookForWindows*",
"*Microsoft.Paint*",
"*Microsoft.Teams*",
"*Microsoft.Todos*",
"*Microsoft.Whiteboard*",
"*Microsoft.Windows.Photos*",
"*microsoft.windowscommunicationsapps*", # Mail & Calendar
"*Microsoft.Xbox*",
"*Microsoft.YourPhone*",
"*Microsoft.ZuneMusic*", # Media Player
"*Microsoft.ZuneVideo*", # Movies & TV
"*MicrosoftTeams*",
"*MSPaint*",
"*MSTeams*",
"*SkypeApp*"
)
foreach ($app in $apps) {
Get-AppxPackage -Name $app -AllUsers | Remove-AppxPackage -ErrorAction SilentlyContinue
# Remove provisioned packages to prevent reinstallation for new users
Get-ProvisionedAppxPackage -Online | Where-Object { $_.PackageName -like $app } | ForEach-Object { Remove-ProvisionedAppxPackage -Online -AllUsers -PackageName $_.PackageName }
}
# Microsoft Copilot
winget uninstall -h --id 9WZDNCRD29V9
# OneDrive
winget uninstall -h --id Microsoft.OneDrive
# Microsoft Teams Machine-Wide Installer
$uninstallKeys = @("HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall", "HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall")
foreach ($key in $uninstallKeys) {
Get-ChildItem $key -ErrorAction SilentlyContinue | Get-ItemProperty | Where-Object { $_.DisplayName -eq "Teams Machine-Wide Installer" } | ForEach-Object {
Start-Process msiexec.exe -ArgumentList "/x $($_.PSChildName) /qn" -Wait
}
}
# Microsoft Office 365 Suite
winget uninstall -h --id Microsoft.Office.365
winget uninstall -h --id Microsoft.Office.Desktop
# Force remove Office/Outlook (MSI & Click-To-Run Registry lookup)
Write-Host "Forcing removal of remaining Office/Outlook installations, the operation may take several minutes..."
$officeKeys = @("HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall", "HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall")
foreach ($key in $officeKeys) {
Get-ChildItem $key -ErrorAction SilentlyContinue | Get-ItemProperty | Where-Object { $_.DisplayName -match "Microsoft Office|Microsoft 365|Outlook" } | ForEach-Object {
if ($_.UninstallString -match "msiexec") {
Write-Host "Removing MSI: $($_.DisplayName)"
Start-Process msiexec.exe -ArgumentList "/x $($_.PSChildName) /qn" -Wait
} elseif ($_.UninstallString -match "OfficeClickToRun.exe") {
Write-Host "Removing C2R: $($_.DisplayName)"
# Extract arguments and force silent display level
if ($_.UninstallString -match 'scenario=.*') {
$args = $matches[0] + " DisplayLevel=False"
Start-Process "C:\Program Files\Common Files\Microsoft Shared\ClickToRun\OfficeClickToRun.exe" -ArgumentList $args -Wait
}
}
}
}
================================================
FILE: Windows/Scripts/WhatsAppMoveAndRename.ps1
================================================
<#
.SYNOPSIS
Move and rename WhatsApp media files into organized folders by date.
.DESCRIPTION
Processes WhatsApp media files in the current directory, moving and renaming them into a structured folder hierarchy based on the date embedded in the filenames.
.EXAMPLE
IMG-20150527-WA0002.jpg -> .\2015\05\2015-05-27 WA0002.jpg
VID-20130509-WA0006.mp4 -> .\2013\05\2013-05-09 WA0006.mp4
#>
function Test-IsWhatsAppImage($file) {
return $file.BaseName.StartsWith("IMG-") -and $file.Extension.equals(".jpg")
}
function Test-IsWhatsAppVideo($file) {
return $file.BaseName.StartsWith("VID-") -and ($file.Extension.equals(".mp4") -or $file.Extension.equals(".mov") -or $file.Extension.equals(".3gp"))
}
function Test-IsWhatsAppMediaFile($file) {
return $file.BaseName.length.equals(19) -and $file.BaseName.substring(12, 3).equals("-WA") -and ((Test-IsWhatsAppImage($file)) -or (Test-IsWhatsAppVideo($file)))
}
Get-ChildItem | ForEach-Object {
if (Test-IsWhatsAppMediaFile($_)) {
$BaseName = $_.BaseName
$Extension = $_.Extension
$Year = $BaseName.substring(4, 4)
$Month = $BaseName.substring(8, 2)
$Day = $BaseName.substring(10, 2)
$WhatsAppId = $BaseName.substring(13, 6)
$NewName = "$Year-$Month-$Day $WhatsAppId$Extension"
$Directory = ".\$Year\$Month"
if (!(Test-Path $Directory)) {
New-Item -Path $Directory -ItemType Directory -Force | Out-Null
}
Move-Item $_ -Force -Destination ".\$Directory\$NewName"
}
}
================================================
FILE: Windows/Windows Subsystem for Linux/README.md
================================================
# Windows Subsystem for Linux (WSL2)
WSL2 compared to WSL1 brings increased file system performance, full system call compatibility, virtualization technology (based on Hyper-V), a lightweight utility VM on a real Linux kernel allowing Docker containers to run natively without emulation. The Linux filesystem in WSL2 uses EXT4 directly over a virtual pmem device, thus achieving very close to native Linux performance. In order to benefit from WSL2 performance boost you need to run your applications in WSL2's local filesystem (e.g. `/home/user/src/`) and not in the mounted NTFS filesystem (e.g. `/mnt/c/`).
## Contents
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
<!-- generated with [DocToc](https://github.com/thlorenz/doctoc) -->
- [Installation](#installation)
- [Configuration](#configuration)
- [Basic Commands](#basic-commands)
- [Docker](#docker)
- [How to Import a Docker Image as a WSL Distribution](#how-to-import-a-docker-image-as-a-wsl-distribution)
- [Run Linux GUI applications](#run-linux-gui-applications)
- [Setup XLaunch (legacy)](#setup-xlaunch-legacy)
- [Install IntelliJ IDEA](#install-intellij-idea)
- [Windows 11](#windows-11)
- [Windows 10](#windows-10)
- [On ArchWSL](#on-archwsl)
- [Backup - export/import distributions](#backup---exportimport-distributions)
- [Manage multiple distributions](#manage-multiple-distributions)
- [Use your Windows browser from WSL](#use-your-windows-browser-from-wsl)
- [Useful links](#useful-links)
- [Troubleshooting](#troubleshooting)
- [Time not synced](#time-not-synced)
- [WSL2 requires an update to its kernel component](#wsl2-requires-an-update-to-its-kernel-component)
- [Docker asking for a password](#docker-asking-for-a-password)
- [The computer gets stuck at booting](#the-computer-gets-stuck-at-booting)
- [WSL2 with NTFS is slow](#wsl2-with-ntfs-is-slow)
- [Known issues](#known-issues)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
## Installation
1. Run:
```powershell
wsl --install
```
1. Reboot
1. Run:
```powershell
# Get the list of available Linux distributions
wsl.exe --list --online
# Install your favorite Linux distribution, e.g. Ubuntu 24.04
wsl.exe --install Ubuntu-24.04
```
1. In **Turn Windows features on or off** ensure that the following are:
- enabled: Virtual Machine Platform, Windows Subsystem for Linux
- disabled: Hyper-V, Windows Hypervisor Platform
## Configuration
1. if Linux has been installed with only the `root` user then in WSL run:
```sh
sudo adduser <username>
```
1. set an empty password for your WSL user with the following command:
```sh
sudo passwd -d <username>
```
(secure access to your WSL shell is already protected by your Windows password)
1. install all the updates:
```sh
sudo apt update; sudo apt upgrade -y; sudo apt autoremove -y; sudo snap refresh
```
1. set your favorite editor as default editor:
```sh
sudo update-alternatives --config editor
```
1. grant root privileges to your user:
```sh
sudo visudo
```
Append after `#User privilege specification`, right below `root`:
```sh
<username> ALL=(ALL:ALL)ALL
```
1. if Linux was installed with only the `root` user then in PowerShell run:
```powershell
ubuntu2204.exe config --default-user <username>
```
(secure access to your WSL shell is already protected by your Windows password)
## Basic Commands
In PowerShell:
```powershell
# Switch WSL version
wsl --set-version <distro> <version>
# List your distributions and their WSL versions
wsl --list -v
# Update WSL to its latest version (https://github.com/microsoft/WSL/releases)
wsl --update
```
## Docker
- [Docker Desktop WSL 2 backend](https://docs.docker.com/docker-for-windows/wsl/)
- [Using Remote Containers in WSL 2](https://code.visualstudio.com/blogs/2020/07/01/containers-wsl)
#### How to Import a Docker Image as a WSL Distribution
This guide shows how to replicate a Docker image as a WSL distribution. [amazoncorretto:21.0.8-al2023](https://hub.docker.com/layers/library/amazoncorretto/21.0.8-al2023/images/sha256-f3187c24c8a9e06d6cb49e378b397af4ff68e095588573e71aded97db0337249) is used as an example.
Step 1: Pull the Docker Image
```powershell
docker pull amazoncorretto:21.0.8-al2023
```
Step 2: Verify Image Download
```powershell
docker images | findstr amazoncorretto
```
You should see the image with size around 730MB.
Step 3: Create Container from Image
```powershell
docker create --name temp-corretto amazoncorretto:21.0.8-al2023
```
Step 4: Export Container to Tar File
```powershell
docker export temp-corretto -o corretto-al2023.tar
```
This will take several minutes and create a ~940MB tar file.
Step 5: Verify Tar File Creation
```powershell
dir .\corretto-al2023.tar
```
Check that the file size is around 900MB+.
Step 6: Create WSL Directory
```powershell
mkdir "$env:USERPROFILE\WSL\CorrettoAL2023"
```
Step 7: Import to WSL
```powershell
wsl --import CorrettoAL2023 "$env:USERPROFILE\WSL\CorrettoAL2023" ".\corretto-al2023.tar"
```
Step 8: Verify WSL Distribution
```powershell
wsl -l -v
```
You should see `CorrettoAL2023` in the list.
Step 9: Clean Up
```powershell
docker rm temp-corretto
del .\corretto-al2023.tar
```
Step 10: Launch Your New Environment
```powershell
wsl -d CorrettoAL2023
```
Key Notes:
- **PowerShell Syntax:** Use `$env:USERPROFILE` in PowerShell, not `%USERPROFILE%`
- **Export Method:** Always use `docker export -o filename.tar`, never `docker export > filename.tar`
- **File Verification:** A proper tar file should show binary byte patterns, not UTF-16 encoding markers
- **Naming:** You can replace `CorrettoAL2023` with any name you prefer for your WSL distribution
Your new WSL distribution will have the exact same environment, packages, and Java version as the original Docker image.
## Run Linux GUI applications
The newest versions of WSL2 have built-in support for GUI applications through the [WSLg](https://github.com/microsoft/wslg): it can run Linux GUI applications directly on Windows, without the need for a third-party X server. It comes enabled by default in Windows 11 and works out of the box. Linux GUI applications get automatically integrated into the Windows Start menu.
### Setup XLaunch (legacy)
The following steps are kept for legacy purposes and for those who prefer to use XLaunch instead of WSLg.
Setup:
1. On Windows:
1. [Install _VcXsrv_ with winget](https://winget.run/pkg/marha/VcXsrv)
2. In the folder `%PROGRAMFILES%\VcXsrv`:
- right click on `vcxsrv.exe`
- Properties > Compatibility > Change high DPI settings
- Check _Override high DPI scaling behavior_
- Select _Application_
3. Control Panel\System and Security\Windows Defender Firewall\Allowed apps
- Select _VcXsrv windows xserver_
- Check both Private and Public checkboxes
- Press _OK_ at the bottom of the window
4. Download [`config.xlaunch`](./config.xlaunch) to your file system (save it in `%AppData%\Microsoft\Windows\Start Menu\Programs\Startup` if you want to make XLaunch automatically run at startup) and double click on it to run XLaunch
The _XLaunch_ configuration should be:
- Multiple Windows
- Display number = 0
- Start no client
- Disable access control
When you want to run a GUI application in WSL2 you need to:
1. On Windows: run _XLaunch_ with the shortcut created above
1. On WSL: run the command to start your GUI application.
Some applications may require a desktop environment (like _Xfce_, _Gnome_ or _KDE_) or a window manager (like _Blackbox_ or _Fluxbox_) to run properly.
If you are getting the error `xrdb: Can't open display` try other solutions on [this issue](https://github.com/QMonkey/wsl-tutorial/issues/11#issuecomment-650833026).
Sources:
- [wsl2-tutorial](https://github.com/QMonkey/wsl-tutorial/blob/master/README.wsl2.md)
- [What's the easiest way to run GUI apps on Windows Subsystem for Linux as of 2018?](https://askubuntu.com/questions/993225/whats-the-easiest-way-to-run-gui-apps-on-windows-subsystem-for-linux-as-of-2018)
- [Developing "in" Windows Subsystem for Linux](https://intellij-support.jetbrains.com/hc/en-us/community/posts/360004275400-Developing-in-Windows-Subsystem-for-Linux)
## Install IntelliJ IDEA
### Windows 11
1. install the latest Java LTS version with [SDKMAN](https://sdkman.io/
```sh
sdk install java
```
1. Install IntelliJ IDEA with `sudo snap install intellij-idea-ultimate --classic`
1. Run IntelliJ IDEA from the Windows Start menu or with `intellij-idea-ultimate`
### Windows 10
In WSL:
1. Download the [`tar.gz` file for Linux](https://www.jetbrains.com/idea/download/#section=linux) and extract it in your home directory `~`
1. Run `~/intellij/bin/idea.sh`
### On ArchWSL
Install [yay](../../Linux/README.md#install-aur-arch-user-repository-packages) and then run:
```sh
yay -S snapd genie-systemd
genie -s
sudo systemctl enable --now snapd.socket
sudo ln -s /var/lib/snapd/snap /snap
# log out and back in again to ensure snap's paths are updated correctly
genie -s
sudo snap install intellij-idea-ultimate --classic
```
Run with:
```sh
genie -s
intellij-idea-ultimate
```
## Backup - export/import distributions
Very good for keeping a backup copy and recover it in case you mess up your distribution, but also for occasions like formatting the computer or moving to a new one! Once stripped off private credentials it can even passed over to a new colleague who has just joined your project to speed up the onboarding.
```sh
# List your distributions
wsl --list -v
# Save your distribution to a local file (this operation can take several minutes)
wsl --export Ubuntu-20.04 ./Ubuntu-20.04.tar
# Import a distribution from a local file
mkdir ~/AppData/Local/Ubuntu-20.04
wsl --import Ubuntu-20.04 ~/AppData/Local/Ubuntu-20.04 ./Ubuntu-20.04.ta
gitextract_9j5taalu/
├── Android/
│ └── uninstall-s21-bloatware
├── Chrome/
│ ├── README.md
│ ├── export.js
│ ├── import.js
│ └── marco_search_engines.json
├── Docker/
│ ├── .bashrc
│ ├── Dockerfile
│ └── README.md
├── ExifTool/
│ └── README.md
├── Git/
│ ├── .gitconfig
│ ├── README-template.md
│ └── README.md
├── Go/
│ └── README.md
├── Google Docs/
│ └── README.md
├── GraphQL/
│ └── README.md
├── Java/
│ ├── Country.java
│ ├── FixturesBuilder.java
│ └── README.md
├── Javascript/
│ └── README.md
├── Kubernetes/
│ └── README.md
├── Linux/
│ ├── .bash_profile
│ ├── .bashrc
│ ├── .vimrc
│ ├── README.md
│ └── powerlevel10k_rainbow_java.omp.json
├── PostgreSQL/
│ ├── README.md
│ └── postgresql-to-dbdiagram.sql
├── README.md
├── Redis/
│ └── README.md
├── Ruby on Rails/
│ └── README.md
├── Rust/
│ └── README.md
├── Visual Studio Code/
│ └── README.md
├── Windows/
│ ├── AutoHotkey.ahk
│ ├── AutoHotkey2.ahk
│ ├── Chocolatey/
│ │ ├── Profile.ps1
│ │ ├── README.md
│ │ ├── cdeps.ps1
│ │ └── packages.config
│ ├── PowerShell/
│ │ └── README.md
│ ├── README.md
│ ├── Scripts/
│ │ ├── DeleteOldWinDirs.ps1
│ │ ├── DisableWake-on-LAN.ps1
│ │ ├── DisableWakeupTimers.ps1
│ │ ├── ReduceOneHour.js
│ │ ├── ReduceOneHour.ps1
│ │ ├── SetupApps.ps1
│ │ ├── SetupConfig.ps1
│ │ ├── UninstallBloatware.ps1
│ │ └── WhatsAppMoveAndRename.ps1
│ ├── Windows Subsystem for Linux/
│ │ ├── README.md
│ │ └── config.xlaunch
│ └── Windows Terminal/
│ ├── README.md
│ └── settings.json
├── ffmpeg/
│ └── README.md
└── graphviz/
├── README.md
└── diagram.dot
SYMBOL INDEX (9 symbols across 5 files)
FILE: Chrome/export.js
function downloadData (line 3) | function downloadData(filename, data) {
FILE: Chrome/import.js
function selectFileToRead (line 3) | function selectFileToRead() {
function readFile (line 19) | function readFile(file) {
FILE: Java/Country.java
type Country (line 1) | public enum Country {
method Country (line 58) | Country(String name, String alpha2, String alpha3, int numeric, String...
FILE: Java/FixturesBuilder.java
class FixturesBuilder (line 4) | @NoArgsConstructor(access = AccessLevel.PRIVATE)
method aPerson (line 13) | public static Person.PersonBuilder aPerson() {
method aMan (line 21) | public static Person.PersonBuilder aMan() {
FILE: Windows/Scripts/ReduceOneHour.js
function reduceOneHour (line 5) | function reduceOneHour(dateString) {
Condensed preview — 56 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (227K chars).
[
{
"path": "Android/uninstall-s21-bloatware",
"chars": 2450,
"preview": "# Install Android Debug Bridge (adb) https://developer.android.com/studio/command-line/adb\n# Install the Universal ADB D"
},
{
"path": "Chrome/README.md",
"chars": 5357,
"preview": "# Chrome\n\n_Table of Contents_\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON"
},
{
"path": "Chrome/export.js",
"chars": 580,
"preview": "(function exportSEs() {\n /* Auxiliary function to download a file with the exported data */\n function downloadData(fil"
},
{
"path": "Chrome/import.js",
"chars": 1063,
"preview": "(async function importSEs() {\n /* Auxiliary function to open a file selection dialog */\n function selectFileToRead() {"
},
{
"path": "Chrome/marco_search_engines.json",
"chars": 11879,
"preview": "[\n {\n \"canBeDefault\": true,\n \"canBeEdited\": true,\n \"canBeRemoved\": true,\n \"default\": false,\n \"displayNam"
},
{
"path": "Docker/.bashrc",
"chars": 510,
"preview": "# Docker\nalias d-clean='docker system prune'\nalias d-list='docker container ls -a --format \"table {{.ID}}\\t{{.Image}}\\t{"
},
{
"path": "Docker/Dockerfile",
"chars": 1149,
"preview": "FROM alpine:latest\n\nRUN set -xe \\\n # Install build tools, libraries and utilities\n && apk add --no-cache --virtual"
},
{
"path": "Docker/README.md",
"chars": 4034,
"preview": "# Docker\n\n_Table of Contents_\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DO"
},
{
"path": "ExifTool/README.md",
"chars": 3009,
"preview": "# ExifTool\n\n[ExifTool](https://exiftool.org/) is a library and a command-line application for reading, writing and editi"
},
{
"path": "Git/.gitconfig",
"chars": 591,
"preview": "[alias]\n delete-last-commit = reset --hard HEAD~1\n undo-last-commit = reset HEAD~1\n stage-all-and-commit = add "
},
{
"path": "Git/README-template.md",
"chars": 1644,
"preview": "# `<project_name>`\n\n<project_name> is a <utility/tool/service/application> that allows <target_audience> to do <action/t"
},
{
"path": "Git/README.md",
"chars": 11153,
"preview": "# git\n\nTable of Contents\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T ED"
},
{
"path": "Go/README.md",
"chars": 14611,
"preview": "# Go\n\nCreated by a small team at Google in 2007, composed by Robert Griesemer, Rob Pike, and Ken Thompson. Ken Thomson i"
},
{
"path": "Google Docs/README.md",
"chars": 1922,
"preview": "# Google Docs\n\n## Format text as code\n\n### Use an add-on\n\n- [Code Blocks](https://gsuite.google.com/marketplace/app/code"
},
{
"path": "GraphQL/README.md",
"chars": 1887,
"preview": "# GraphQL\n\n## Learning resources\n\n- [GraphQL: A success story for PayPal Checkout](https://medium.com/paypal-engineering"
},
{
"path": "Java/Country.java",
"chars": 2674,
"preview": "public enum Country {\n\n Austria(\"Austria\", \"AT\", \"AUT\", 40, \"+43\"),\n Albania(\"Albania\", \"AL\", \"AUB\", 8, \"+355\"),\n "
},
{
"path": "Java/FixturesBuilder.java",
"chars": 752,
"preview": "import lombok.AccessLevel;\nimport lombok.NoArgsConstructor;\n\n@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic cla"
},
{
"path": "Java/README.md",
"chars": 9780,
"preview": "# Java\n\n_Table of Contents_\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T"
},
{
"path": "Javascript/README.md",
"chars": 13611,
"preview": "# Javascript\n\n_Table of Contents_\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!--"
},
{
"path": "Kubernetes/README.md",
"chars": 288,
"preview": "# Kubernetes (k8s)\n\n## Basic operations\n\n```sh\n# Delete all failed pods with a specific name\nkubectl get pods --field-se"
},
{
"path": "Linux/.bash_profile",
"chars": 57,
"preview": "# Enable reverse-i-search forward with Ctrl+S\nstty -ixon\n"
},
{
"path": "Linux/.bashrc",
"chars": 2248,
"preview": "# Colorize your cat output\nalias dog='pygmentize -O console256 -g'\n\n# Human readable files list in terminal\n# -l = use a"
},
{
"path": "Linux/.vimrc",
"chars": 255,
"preview": "\" Place yanked text into the global clipboard\nset clipboard=unnamedplus\n\n\" Display line numbers\nset number\n\n\" Enable syn"
},
{
"path": "Linux/README.md",
"chars": 12330,
"preview": "# Linux\n\n_Table of Contents_\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON"
},
{
"path": "Linux/powerlevel10k_rainbow_java.omp.json",
"chars": 7279,
"preview": "{\n \"$schema\": \"https://raw.githubusercontent.com/JanDeDobbeleer/oh-my-posh/main/themes/schema.json\",\n \"blocks\": [\n "
},
{
"path": "PostgreSQL/README.md",
"chars": 3257,
"preview": "# PostgreSQL CLI notes\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDI"
},
{
"path": "PostgreSQL/postgresql-to-dbdiagram.sql",
"chars": 2700,
"preview": "-- Backup copy of the query to generate dbdiagram.io DDL, copied from:\n-- https://github.com/matthewoldham/dbdiagram.io-"
},
{
"path": "README.md",
"chars": 169,
"preview": "# Notes\n\nA collection of personal notes about programming, operating systems and tools.\n\nPull requests for wrong, subopt"
},
{
"path": "Redis/README.md",
"chars": 992,
"preview": "# Redis\n\n## Basic commands\n\n```sh\n# Set a key and assign it a value\nredis-cli SET <key> <value>\n\n# Get a value associate"
},
{
"path": "Ruby on Rails/README.md",
"chars": 6931,
"preview": "# Ruby on Rails\n\n*Contents*\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T"
},
{
"path": "Rust/README.md",
"chars": 457,
"preview": "# Rust\n\nTo create an API service in Rust on Windows, install Rust with:\n\n```powershell\nwinget install -e --id Rustlang.R"
},
{
"path": "Visual Studio Code/README.md",
"chars": 5904,
"preview": "# Visual Studio Code\n\n_Table of Contents_\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update"
},
{
"path": "Windows/AutoHotkey.ahk",
"chars": 2656,
"preview": "; AutoHotkey is a scripting language for Microsoft Windows which provides\n; keyboard shortcuts that allows users to aut"
},
{
"path": "Windows/AutoHotkey2.ahk",
"chars": 4114,
"preview": "; AutoHotkey is a scripting language for Microsoft Windows which provides\n; keyboard shortcuts that allows users to aut"
},
{
"path": "Windows/Chocolatey/Profile.ps1",
"chars": 225,
"preview": "# Include it in your PowerShell profile to publish Chocolatey packages\n\n$ChocolateyProfile = \"$env:ChocolateyInstall\\hel"
},
{
"path": "Windows/Chocolatey/README.md",
"chars": 583,
"preview": "# Chocolatey\n\n[Chocolatey](https://chocolatey.org/) is a package manager for Windows.\n\n## Install a list of packages in "
},
{
"path": "Windows/Chocolatey/cdeps.ps1",
"chars": 737,
"preview": "$packages = Get-ChildItem C:\\ProgramData\\chocolatey\\lib\\ -Recurse *.nuspec | select fullname,name \nforeach($p in $packa"
},
{
"path": "Windows/Chocolatey/packages.config",
"chars": 2181,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<packages>\n\n <!-- common -->\n <package id=\"7zip\" />\n <package id=\"adober"
},
{
"path": "Windows/PowerShell/README.md",
"chars": 5059,
"preview": "# PowerShell \n\nTable of Contents\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- "
},
{
"path": "Windows/README.md",
"chars": 11010,
"preview": "# Windows\n\n*Table of contents*\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- D"
},
{
"path": "Windows/Scripts/DeleteOldWinDirs.ps1",
"chars": 4476,
"preview": "<#\n.SYNOPSIS\n Removes old Windows directories from a previous Windows installation.\n.DESCRIPTION\n Based on: https:"
},
{
"path": "Windows/Scripts/DisableWake-on-LAN.ps1",
"chars": 1477,
"preview": "# Get the specific Realtek adapter\n$nic = Get-NetAdapter | Where-Object { $_.InterfaceDescription -match \"Realtek\" }\n\nif"
},
{
"path": "Windows/Scripts/DisableWakeupTimers.ps1",
"chars": 1563,
"preview": "# 1. Disable Wake Timers in the Active Power Plan using Aliases\n# This works even if the GUIDs are non-standard.\n$active"
},
{
"path": "Windows/Scripts/ReduceOneHour.js",
"chars": 665,
"preview": "// BulkRenameUtility script to reduce the hour of a date by one hour of filenames in the format \"YYYY-MM-DD HH.MM.SS\"\n//"
},
{
"path": "Windows/Scripts/ReduceOneHour.ps1",
"chars": 2658,
"preview": "<#\n.SYNOPSIS\n Reduce the hour of date-based filenames by one hour.\n.NOTES\n Processes files in the current director"
},
{
"path": "Windows/Scripts/SetupApps.ps1",
"chars": 2130,
"preview": "<#\n.SYNOPSIS\n Install commonly used applications via Winget.\n.NOTES\n Comment out any applications you do not wish "
},
{
"path": "Windows/Scripts/SetupConfig.ps1",
"chars": 7238,
"preview": "<#\n.SYNOPSIS\n Configure various Windows settings for improved usability and performance.\n.EXAMPLE\n WARNING! This s"
},
{
"path": "Windows/Scripts/UninstallBloatware.ps1",
"chars": 3525,
"preview": "<#\n.SYNOPSIS\n Uninstall common bloatware applications from Windows.\n.EXAMPLE\n WARNING! This script must be execute"
},
{
"path": "Windows/Scripts/WhatsAppMoveAndRename.ps1",
"chars": 1546,
"preview": "<#\n.SYNOPSIS\n Move and rename WhatsApp media files into organized folders by date.\n.DESCRIPTION\n Processes WhatsAp"
},
{
"path": "Windows/Windows Subsystem for Linux/README.md",
"chars": 13609,
"preview": "# Windows Subsystem for Linux (WSL2)\n\nWSL2 compared to WSL1 brings increased file system performance, full system call c"
},
{
"path": "Windows/Windows Subsystem for Linux/config.xlaunch",
"chars": 356,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<XLaunch WindowMode=\"MultiWindow\" ClientMode=\"NoClient\" LocalClient=\"False\" Displ"
},
{
"path": "Windows/Windows Terminal/README.md",
"chars": 4449,
"preview": "\n# Windows Terminal\n\n[Windows Terminal](https://docs.microsoft.com/en-us/windows/terminal/) is a terminal application fo"
},
{
"path": "Windows/Windows Terminal/settings.json",
"chars": 6715,
"preview": "// This file was initially generated by Windows Terminal 0.11.1121.0\n// It should still be usable in newer versions, but"
},
{
"path": "ffmpeg/README.md",
"chars": 1874,
"preview": "# ffmpeg\n\n_Table of Contents_\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON"
},
{
"path": "graphviz/README.md",
"chars": 616,
"preview": "# graphviz\n\n[Graphviz](https://graphviz.org/) is open source graph visualization software: it takes the description of a"
},
{
"path": "graphviz/diagram.dot",
"chars": 3017,
"preview": "// https://www.graphviz.org/\n// dot -Tpng diagram.dot > diagram.png\n\ndigraph architecture {\n graph [ compound=true, n"
}
]
About this extraction
This page contains the full source code of the lackovic/notes GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 56 files (209.0 KB), approximately 58.5k tokens, and a symbol index with 9 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.