4 TILS from the Epic React Basic React Hooks Workshop

What did I learn from the workshop Basic React Hooks by Kent C. Dodds? Previously, I wrote down my learnings from the React Fundamentals workshop. The second workshop introduces React hooks. Here are some insights that I found useful: Set Initial State Via Props Set an initial value by adding props to a component: <Greeting initialName="George"> Take that as an argument to the function and pass it down to useState:
Read more →

3 TILs from the Epic React Fundamentals Workshop

Kent C. Dodds released his Epic React training course with a big fanfare last week. I was on the fence of buying this, as the pro license is a premium training course that comes with a premium price tag. The course is expensive compared to other online courses. For example, a year-long-subscription to Frontend Masters costs roughly the same. But as a life-long learner, I’m dedicated to becoming a better programmer.
Read more →

TIL About Adding a New Line to “git commit -m”

For Git messages I use git commit -m to add a headline to a git commit. So far, I’ve never used the detailed summary which you can add to a commit message. It was tooMuch of a hassle to open a text editor and add a detailed explanation. Today I learned that you can write a multi-line commit message with git commit -m. For example, in Bash: git commit -m 'my headline Here goes the detailed explanation of the commit ' Source:
Read more →

TIL How to Assign Variables in Go

Declaration and Assignment Go is statically typed. Before you can bind a variable, you have to declare it: var age int This declares a new variable called age of type Integer. The variable is declared, but not initialized. If you want to assign something to a variable, you’ll do it like this: age = 35 There is a short-hand operator: :=: age := 35 The “walrus operator” is syntactic sugar for the two commands:
Read more →

TIL How to Execute an External Command in Vim and Reload the File

Or: How To Pipe The Current Vim Buffer Through Unix Commands In this post I will show you how to run a shell command from within Vim, and immediately reload that file. The Problem I write a Go file in (Neo)Vim. I want to use the command gofmt to format my file. Running gofmt will change the contents of my file, so I’ll need to reload my Vim buffer.
Read more →

TIL About Copying a Range in Vim

Today I learned about the copy command (alias t): :[range]co[py] {address} :co :copy Copy the lines given by [range] to below the line given by {address}.Let’s say we have a file like this: 1 line a 2 line b 3 line c 4 line d | You are on line d (symbolized with the | as the cursor). You want to copy from 1 to 3 (line a, line b, line c).
Read more →

TIL About Makefiles

Today I learned that you can use Makefiles to create simple task-runners. Stuart Feldman invented Make in 1976 to automate build processes for C programs. But you can use it for other languages, too. For example, Vladislav Supalov uses this Makefile for Docker commands: all: @echo "Usage: build or run" build: docker build -t test . run: docker run –rm -it test Now run the file with your terminal: make > Usage: build or run Build the Docker container via make build or run the container via make run.
Read more →

TIL About Array.prototype.fill (Javascript)

Today I learned about Array.prototype.fill and friends. You can use the method to fill an array with values, or create a new array filled with values. Pitfall: if you fill a new array with a value that is an object, each slot in the array will reference that object. const newArr = Array(4).fill([]) > [[], [], [], []] newArr[1].push(8) > 1 newArr > [[8], [8], [8], [8]] Further Reading MDN: Array.
Read more →

TIL About background-blend-mode

Read more →

TIL About CSS Attribute Selectors and Square Brackets in HTML

You can use CSS attribute selectors to target HTML elements. Let’s say you have this HTML snippet: <img alt="myPicName" src="/" /> <img alt="anotherPicName" src="/" /> You can style the first image by targeting the alt attribute and without changing the second image element. img[alt='myPicName'] { width: 100px; } When you use square brackets in HTML, it means something different: you group classes with square brackets. The brackets have no meaning, they are used for clarity.
Read more →

TIL About Git Pretty Log

Read more →

TIL About the i3 Scratchpad

Today I learned about the i3 scratchpad. The scatchpad is a special i3 window. You can use it as a window that opens your favorite program, e.g., a music player or editor. Examples:

Make the currently focused window a scratchpad bindsym $mod+Shift+minus move scratchpad # Show the first scratchpad window bindsym $mod+minus scratchpad show The first command moves the current window to the scratchpad and makes it invisible. With the second command you open the scratchpad and cycle through all windows.

Read more →

TIL About How To Create Ordered Lists in Vim Quickly

Today I found a cool trick on the Vim SubReddit: how to quickly create ordered lists. Here’s a screen-cast by rnevius: Steps Let’s say that you have a list: one item another item it’s an item Use <C-v> (CTRL + V), then I to select all lines at the start of the line and add a 0. in front of each: 0. one item 0. another item 0.
Read more →

TIL About React Native Expo

Today I learned about Expo, a toolkit/SDK for React Native development. Expo makes it easy to bootstrap a React Native code-base without having to install Android Studio or other tool-chains. Node.js and npm (or yarn) are the only requirements. Install via npm install expo-cli –global. Create a new project: expo init myProject && cd myProject expo start This will open up a browser window (“Expo Client”). Here you can open a new emulator, even a web emulator.
Read more →

TIL Copy With Clipboard in Vim Over Ssh

Today I tried using Vim over SSH on a remote machine. I needed to copy some configuration to the server. I opened Vim in the terminal (via SSH): vim config.txt I wanted to paste into the Vim buffer. I tried to use the "+p command in normal mode to paste from the system clipboard. Unfortunately, that didn’t work. Solution: The “clipboard” is a feature of X11, so you will need to enable “X11 forwarding” for the SSH connection in “trusted” mode:
Read more →

TIL Paste From System Clipboard Into Vim in Insert Mode

Today I learned how to paste into Vim in insert mode (and normal mode). When I write my blog posts, I often have to refer to material from the internet: other articles, blog posts, or books. That means that I will have to copy the title and URL from the web and paste it into my Vim editor. First of all, the "* and "+ registers are for the system clipboard.
Read more →

TIL About INSTALL_FAILED_INSUFFICIENT_STORAGE on Android

I’m working on a Flutter REST API. I type into the command-line: flutter run -v to start the application. But that doesn’t work: INSTALL_FAILED_INSUFFICIENT_STORAGE Why? There is still enough storage space on my local machine. The error is Android-specific. When you run the Android emulator, it creates an ADB device. When you develop your app, Flutter (or Android SDK) will install packages into ADB. It looks like that fills up the (virtual) storage space.
Read more →

TIL About Fish Abbreviations

Read more →

TIL How to Jump to Matching Bracket in Vim

I’ve started using Flutter, the mobile SDK for the Dart language. Dart reminds of Java and JavaScript. It’s quite verbose. If you have nested functions and classes, it’s hard to find the matching brackets and parentheses. Sometimes the start of a function or class is not on your screen, and it’s hard to get a quick visual overview. There are plugins that color the brackets differently, for example, Junegunn’s rainbow_parentheses.vim or luochen1990’s rainbow.
Read more →

TIL How to Revert Last Git Commit but Keep Changes

Read more →

TIL About Finding the Path Environment Variables With Fish Shell

The fish_user_paths are the alternative for $PATH in fish shell. But how do I find out, what’s in my fish path? echo $fish_user_paths | tr " " "\n" | nl This gives you an array of path environment variables. You can erase a path with set -e fish_user_paths[1]. Be aware that the array is mutable, so if you delete an item, another one will take its place. Further Reading How to remove a path from $PATH variable in fish?
Read more →

TIL About Text Search in MongoDB

Read more →

TIL How to Refactor Try Catch With Either Monad

Today I watched the course Hardcore Functional Programming in JavaScript, v2. The instructor, Brian Lonsdorf, shows you functional programming principles with JavaScript and introduces concepts like currying, functors and monads. One interesting application is the refactoring of a try-catch-block to the Either monad. const fs = require('fs') const getPort = () => { try { const str = fs.readFileSync('config.json') const config = JSON.parse(str) return config.port } catch (e) { return 3000 } } const result = getPort() const Right = (x) => ({ map: (f) => Right(f(x)), chain: (f) => f(x), fold: (f, g) => g(x), inspect: () => Right(${x}), }) const Left = (x) => ({ map: (f) => Left(x), chain: (f) => Left(x), fold: (f, g) => f(x), inspect: () => Left(${x}), }) const fromNullable = (x) => (x !
Read more →

TIL About Joining Tmux Panes

I love using Tmux for my terminal. I have a tiling window manager (i3) for my 15” notebook. On the left side I open a web browser. Now I can watch videos, read tutorials, develop React applications, etc. On the right side of my screen I use tmux with two or three panes. The major pane holds a NeoVim instance. That’s what I’m using as my text editor for coding.
Read more →

TIL: How to Use Curl(ie) With Bearer Tokens

I use curlie (for curl) and fish shell (for bash). Original post by Niel de Wet: Using cURL to authenticate with JWT Bearer tokens. Get The Bearer Token You must install jq for parsing json from the command line. The following command queries the authentication endpoint with the required credentials and stores the JWT bearer token in an environment variable. set -x AUTH_TOKEN (curlie post https://hostname/auth/signin username='your username' password='your password' | jq -r '.
Read more →

TIL About Streamlit’s Magic

Streamlit allows you to write Markdown within a Python file (.py): import streamlit as st st.title("Otto Group Product Classification Challenge 🛍") st.markdown("## 1. Problem Statement") st.markdown( "Given a dataset with 93 features, create a predictive model which is able to distinguish between the main product categories." ) st.markdown("### 1.2 Evaluation") st.markdown( "The evaluation for the competition is multi-class logarithm loss. See Kaggle: Evaluation." ) I like that I can write Markdown, but the syntax is cumbersome.
Read more →

TIL: Linux - Delete Files Older Than X Days

Today I learned that you can pass a date argument to find. I wanted to delete all files that were older than 10 days using the command line. We can use find which ships with every Linux distribution. find . -type f -mtime +20 Find all files that are older than 20 days in the current directory. Now let’s delete them: find . -type f -mtime +20 -exec rm -f {} ; I use fd as an alternative to find:
Read more →

TIL About Git Attributes

Today I learned that I can set up my own filters for doing substitutions on commit/checkout with Git. Why is that useful? GitHub restricts files to 100 MB. What if you want to push a file to your GitHub repository that’s bigger than 100 MB? You can use Clean and Smudge to compress your file. images are from https://git-scm.com/book/en/v2/Customizing-Git-Git-Attributes Clean and Smudge Decide which file types you want to compress and add them to .
Read more →

TIL About Feature Engineering

As I’m working through different data sets in my machine learning journey, it gets more obvious that you have to know about feature engineering. Feature engineering is an umbrella term for transforming your input data. A machine learning model can only be as efficient as the data you feed it. Features are the different input qualities you give the model. Often, these features are in the wrong format, or they are missing.
Read more →

TIL About Logistic Regression

Today I learned about logistic regression. Logistic Regression is a statistical model that we can use for classification problems in machine learning. You can easily confuse the term with linear regression. With linear regression, you model the probability of a quantitative value, for example a price. With logistic regression you can predict categories: yes/no, pass/fail, etc. Logistic regression is used to describe data and to explain the relationship between one dependent binary variable and one or more nominal, ordinal, interval or ratio-level independent variables.
Read more →

TIL: How to Reduce Feature Labels With PCA

Today I learned how to reduce feature labels in a data set with Principal Component Analysis. From Python Data Science Handbook: Principal component analysis is a fast and flexible unsupervised method for dimensionality reduction in data, […] You can use PCA to learn about the relationship between two values: In principal component analysis, this relationship is quantified by finding a list of the principal axes in the data, and using those axes to describe the dataset.
Read more →

TIL: Numpy Array Slices Return Views

Today I learned that if you slice a list in Python, the program returns a copy of the list. But NumPy returns a view, not a copy. That means, that slicing a NumPy array will modify it: This default behavior is actually quite useful: it means that when we work with large datasets, we can access and process pieces of these datasets without the need to copy the underlying data buffer.
Read more →

TIL: How to Search and Replace Text in All Files With rg and sed

Read more →

TIL: How to Plot a Confusion Matrix

Let’s say we made some predictions with a machine-learning model using scikit-learn. We want to evaluate how our model performs, and create a confusion matrix: from sklearn.metrics import confusion_matrix ## make predictions with the scikit-learn model on the test data set y_preds = model.predict(X_test) ## Create confusion matrix on test data and predictions cm = confusion_matrix(y_test, y_preds) cm You’ll get an array like this: array([[24, 5], [ 4, 28]]) We can visualize it with pandas:
Read more →

TIL: How to Run Your Scripts From Everywhere

I’ve been writing a few bash scripts and some Nim command line utilities. You can run a script from the folder which contains the script. Here’s an example file structure: ~/bin/ ├── git-reset-author.sh └── readme_template When I’m inside the ~/bin directory, I can type into the terminal: readme_template. But what if I want to navigate to a different folder on my machine and run the script from that location? fish: unknown command readme_template The shell doesn’t find the program.
Read more →

TIL: Docker Debugging and Exit Codes

Read more →

TIL: JupyterLab: Run All Cells

Read more →

TIL: Docker: chown Copies All Files

Docker builds containers via layers. All commands add another layer to the already existing image. What does that mean for changing file permissions via chown or chmod? Let’s say we build this image: FROMfrolvlad/alpine-miniconda3:python3.7 AS build## set working directoryWORKDIR/usr/src/app## copy codeCOPY ./code /codeCOPY ./notebooks /notebooks## add non-root userRUN addgroup –system user && \ adduser –system -G user user && \ chown -R user:user /usr/src/appAfter copying the code from the host machine to the container, we switch permissions for the working directory from root to user.
Read more →

TIL: kitty @ set-colors

kitty is the terminal emulator that I use in conjunction with fish. Kitty is fast, customizable, and has font ligatures. When I start a Vim session from the kitty terminal, Vim looks smooth (I use Victor Mono as my font). If you want to switch kitty’s color scheme, you can use kitty @ set-colors –all <path-to-colors-file> to interactively switch colors in your session. I wrote a fish function that uses kitty @ set-colors and sed to switch colors for both kitty and (Neo)Vim.
Read more →

About Docker DNS and Networking

Read more →

TIL About 3factor app

Read more →

TIL: PostgreSQL Insert ID Only Works With id as Primary Key

I’ve created a database table for my PostgreSQL database with Nim: import db_postgres, os ## some code proc setup*(database: Database) = database.db.exec(sql""" CREATE TABLE IF NOT EXISTS Url( shortcode SERIAL PRIMARY KEY, orig_url VARCHAR(255) NOT NULL ); """) ## more code My primary key is shortcode as a SERIAL data type. That means the shortcode column automatically increments. I want to insert data into the database and return the generated ID for the row.
Read more →

TIL: You Can’t Mount Host Volumes Into Docker During Build

Today I learned that you can’t bind-mount folders on your host machine into a Docker container during build. For local development, I bind-mount with docker-compose. Example: version: '2.4'services: url-shortener: build: context: ./services/url-shortener dockerfile: Dockerfile volumes: - './services/url-shortener:/usr/src/app:delegated' ports: - 5001:5000My goal was to use the language’s package manager to install the required dependencies. Here’s the Dockerfile:

base imageFROMnimlang/nim:1.0.4-regular AS build-image## set working directoryWORKDIR/usr/src/app## install dependenciesRUN nimble refresh && nimble install -y## run serverCMD nimble c -r src/urlShortenerHere is the problem: nimble can’t find the required files for installation.

Read more →

TIL: Objects in Nim

Objects in Nim use the type constructor:

Type Definition type MusicTrack = object index: int title: string ## (Mutable) Value var summer = MusicTrack(index: 1, title: "Summer in the City") That reminds me of Records in Reason:

/* Type definition */ type musicTrack = {index: int, title: string} /* Value */ let summerInTheCity = {index: 1, title: "Summer in the City"} In Nim, “An object is a value type, which means that when an object is assigned to a new variable all its components are copied as well.

Read more →

Learning Progress TIL: About Container Orchestration

Read more →

TIL: Replace Local Files With Remote Files With Git

Read more →

TIL: Typescript Still Coerces Types

Here’s a simple TypeScript function: function f() { const a = 2 const b = 'a string' return a + b } What I expected: TypeScript can infer types. It will recognize that a is of type number and b is of type string. I expected a type error, because I try to add a string to a number. You can also be more explicit and tell TypeScript the types. Like so:
Read more →

TIL: Bind Mounts

Read more →

TIL: ASGI for Python

Today I learned about the ASGI specification for Python frameworks: ASGI (Asynchronous Server Gateway Interface) is a spiritual successor to WSGI, intended to provide a standard interface between async-capable Python web servers, frameworks, and applications. Python didn’t have asynchronous execution until recently. Since Python 3.4 there’s asyncio in the standard library. asyncio is singl-threaded, single-process - like JavaScript’s event loop. ASGI is build on top of asyncio. So, basically, Python now has web servers and frameworks with async capacities.
Read more →

TIL: How to Use Both Gitlab and Github

There are several ways to mirror a repository both on GitLab and GitHub. Repository Mirroring The free GitLab plan allows you to pull from a remote repository. You could use a GitHub repository as the main repo, and the GitLab repo as the mirror. In theory, you can also push from GitLab to GitHub. But I couldn’t get it working on GitLab’s free plan. Remote Repositories and Overloading The alternative is to “overload” your remote repository address.
Read more →

Suspend Vim to the Background or What Is Linux Job Control

Vim has an inbuilt terminal, which you can start with :terminal. That means that you don’t have to leave your Vim editor to run commands in the shell. Sometimes, it’s still useful. If you quickly want to switch to your shell, suspend the Vim editor with Ctrl+z. That sends the process into the background (on Linux). Now you have access to your standard terminal and can run commands. Type jobs or jobs -l to see a list of the background processes.
Read more →

Vim Undo And Redo

Today I learned about Vim undo and redo. Undo changes: in normal mode: u to undo latest change, U to undo all changes in Ex mode (command mode): :u to undo latest change Use :u {N} to undo a number of changes. For example, :undo 5 reverts the latest 5 changes. Redo changes: in normal mode: Ctrl+r in Ex mode: :re or :redo In Vim, undo is a tree:
Read more →

Start Vim With Terminal Command

Today I learned that you can start Vim with a terminal command. Vim has the -c flag, which you can use for running an Ex command. The same is true for NeoVim, which also has an inbuilt terminal. So you can either start NeoVim inside the terminal like so: nvim +te or like that: nvim -c ':terminal' The second option allows you to run another command afterwards. Example: nvim -c ':terminal hugo server -D' Now NeoVim starts in terminal mode and runs my Hugo development server immediately.
Read more →

Run Macro On Multiple Lines in Vim

Modern editors like VS Code or Sublime Text can use multiple cursors to edit code on more than one line. Vim doesn’t offer this functionality out of the box. But you may not need it. Today I learned how to run a macro to edit several lines in Vim. The method is useful when you have a similar structure on several lines, for example: <li class="link">About</li> <li class="link">Blog</li> <li class="link">Works</li> Add the script visual-at.
Read more →

Reason Option Type

I’m interested in Reason and ReasonReact because it is a typed functional language for the frontend. Today I learned about the Option type. During my experiments with ReasonReact I’m stumbling over some hurdles. I have no experience with typed languages and it shows. Sparse documentation and React’s inherent complexity don’t help. I’m spoiled by bigger communities and more well-known languages, where it’s easy to find material. Still, it’s interesting to learn new concepts and to try to solve problems.
Read more →

TIL: Docker Python Connection Refused

Read more →

TIL: Jump to Next Paragraph in Vim

Read more →

VIM: Open a File In a Web Browser on Linux

Today I learned two neat tricks for Vim: Put your cursor on a link (in normal mode), and type gx. This will open the URL in a browser window. What if you want to open a file in a web browser? On Linux, you can type :!xdg-open % to open the current file in the default browser. (On a Mac, just type :!open %) If you want to make sure that your file is saved, you can first update the file and then pipe it through xdg-open:
Read more →

Learning a Little Thing Every Day

Read more →

Phoenix: Use Ecto to Recreate Your Database

Today I learned that it’s a bad idea to drop a PostgreSQL table directly with PGAdmin. Afterwards, I got tons of errors, because the table was missing. I you want to re-create your database from scratch, you should use Ecto. If you want to completely roll back your database and re-create it, use: mix ecto.reset From Codebase: reset is the equivalente of running the following commands: mix ecto.drop mix ecto.
Read more →

TIL: How to Pass Props to React Router

Just a short note: Today I learned that you shouldn’t pass props to React Router with the component attribute, but with render. From the Docs: When you use component (instead of render or children, below) the router uses React.createElement to create a new React element from the given component. That means if you provide an inline function to the component prop, you would create a new component every render. This results in the existing component unmounting and the new component mounting instead of just updating the existing component.
Read more →

Run PostgreSQL in a Docker Container

I try to learn something new every day, and I find it surprising what cool things you can do with technology. Today I learned that you could run a PostgreSQL database in a docker container. I was doing a Phoenix tutorial by Alvise Susmel. The article shows you how to create a Phoenix app which can handle user uploads and is an interesting piece in itself. But I also like the idea of running the database in Docker for local development.
Read more →

Powerful Keymaps in VS Code Vim

Today I learned that you can remap Vim keys with VS Code. In my NeoVim config I have some custom keybindings that I can now replicate with VS Code. The official VSCodeVim documentation has some examples: In this example, you bind jj to <esc> in insert mode: "vim.insertModeKeyBindings": [ { "before": ["j", "j"], "after": ["<Esc>"] } ] The docs also have some nifty VSCodeVim tricks that you might want to check out.
Read more →