Today I Learned

A Hashrocket project

66 posts about #workflow

Advanced Google Queries

You can use various techniques to narrow your Google queries:

To start, open a new tab, and google hashrocket.com. Compare those results to the following:

site:hashrocket.com This will only return resources that has a reference to this website.

site:hashrocket.com admin Same as above, but only containing resources that contain the word admin. In this case, it shows all of the TIL posts containing admin.

link:hashrocket.com Only pages that have links to hashrocket.com

related:hashrocket.com Sites that are similar to hashrocket.com (other dev shops).

source: ‘The Web Application Hackers Handbook 2’ - Dafydd Stuttard & Marcus Pinto

Fork A Heroku Project

The Heroku CLI has a useful command I recently learned about, called heroku fork. Here’s how it works:

$ heroku fork --from tilex-staging --to tilex

As the example suggests, I’ve used this tool to clone a tricky-to-set-up Heroku staging application as a production application. It’s great.

The bad news is that Heroku us sunsetting fork as a core CLI command. Use it while you can. After that, you can fork the Github repo and use it as CLI plugin.

Fingerpring of an ssh key in multiple formats

You might need to confirm which keys you have attached to your github account. Github provides a list of your keys with the associated fingerprints. If you have a public key on your machine you can see what fingerprint it has with:

> ssh-keygen -lf ~/.ssh/id_rsa.pub
4096 SHA256:/6Rat4zVZ0auHEwWtF4QG8NA0j4NAKWisFuXV0ZP5zk chris.erin@gmail.com (RSA)

Github displays an md5 fingerprint rather than a sha256 fingerprint. You can use the -E flag to choose a specific hash type.

> ssh-keygen -E md5 -lf ~/.ssh/id_rsa.pub
4096 MD5:e3:19:85:1c:8a:31:0f:4b:de:cb:6d:a7:64:b4:4e:e7 chris.erin@gmail.com (RSA)

Opening Gnome terminal emulator

In an attempt to get better with keyboard shortcuts on Ubuntu I’ve - for the time being - ditched the mouse. I generally only use two applications, Firefox and Terminal.

Opening a new terminal is as easy as:

Ctrl + Shift + T

It starts rather small but I resize it by using left or right with the Super (window/apple/command) key.

Super + Left
Super + Right

Then its resized to either the left half of the screen or the right half of the screen.

Add email to github account

You can have multiple emails associated with your github account so that if your commits have user_x@example.com or on another machine your commits have user_y@example.com they’ll both show up as you on the github system.

In my case, all commits on hashrocket workstations are dev+somebody@hashrocket.com and we change who that somebody is with the pear application. So when I’m working on a hashrocket workstation I commit as dev+chriserin@hashrocket.com.

When editing a profile on github there is a left hand menu labeled ‘personal settings’ and in that menu there is an emails link. When you click emails you have the opportunity to ‘Add email address’. There ya go! Happy committing!

H/T Matt Polito

Debug :hover selectors in CSS

When styling HTML you may need to define a hover style the css of which might look like this:

div.something:hover {
  background-color: red;
}

The div with class something will now have a red background when your mouse hovers over it.

This can be hard to debug however, if this were a regular style we could inspect it and change the style of the element in dev tools. With hovers, the style is only available in dev tools when the mouse is physically over the element.

Chrome has a facility to declare that a hover state should be on for an element. Simply open dev tools and in the “Elements” tab right click an element to get a context menu. The menu will have options :active, :hover, :focus, and :visited. Choose :hover and the hover state will be permenantly affixed to that element. You can now play with the hover style until it looks right.

Full page screenshots in Firefox

Firefox has an interesting feature called the Developer Toolbar. This toolbar is entirely separate from the JS console and provides a cli for custom commands for specific functionality. It can opened with shift-F2 or Tools > Developers > Developer Toolbar.

In that toolbar, type:

screenshot --fullpage my-page.png

A png file with the given name will be saved to the Downloads folder. The file format will always be png.

Source

More Developer Toolbar information can be found here.

Type help in the toolbar to see all the commands.

Images in markdown

Images in markdown are the same as links except for the bang (!) character preceding the syntax.

The syntax for links is squares-parens. I have a hard time remembering this, and I try parens-squares as often as not, but its squares-parens, like this:

[My text](https://mylink.com)

The syntax for images is also squares-parens but preceded by a bang (!), like this:

![My alt text](https://mylink.com/oh_my.png)

Understanding Github's Language Calculations

Ever noticed this at the top of a Github repo?

This filetype percentage is calculated by Github’s Linguist project.

There’s just one problem: ‘Today I Learned’ isn’t a JavaScript project; it’s a Rails application. I would expect the majority of the files to be Ruby files. Labeling ‘Today I Learned’ a JavaScript project misrepresents it to the Github community.

I found several techniques to correct the Linguist evaluation; this pull request explains one I tried in greater detail. TL;DR – once I moved some vendored JS files into a directory with a name that Linguist ignores (ace-builds/), the calculation started to look more like a Rails app.

Here’s the updated header:

Exclude Whitespace Changes From GitHub Diffs

If you run a tidy ship and use plugins like vim-spacejam, then whitespace changes cluttering up your git diffs probably isn’t much of an issue.

However, if you are working with other people or messier code bases, then you may not be so lucky. If there are a bunch of whitespace changes in a commit, then that is going to make the diff view of a commit on GitHub annoying, and perhaps hard, to read.

You can cut to the chase by excluding whitespace changes from GitHub’s diff view by adding w=1 to the diff URL.

Check out this view of the diff and then this view of the diff that excludes whitespace.

source

Simulating Various Connection Speeds In Chrome

I spend everyday building web apps from a machine that has a wired connection to the internet. Though I spend a lot of time loading various pages and experiencing the app like a user might, I end up having a pretty narrow perspective. What will this app be like for people on various qualities of mobile connections?

Chrome has a feature built in to its devtools that makes it easy to throttle your connection to simulate various speeds. Open up devtools with Cmd+Opt+J, navigate to the Network tab, and then open the throttling drop down.

From here we can select the connection speed we want to simulate. If we then reload the page, we will not only experience the page load at that speed, we will also see the numbers in that Network tab.

Map Caps Lock to Escape in macOS Sierra #seil

macOS Sierra was made available to the public yesterday and many of us early adopters rushed to install and test it out.

One of the things that broke and really affected my workflow was that Seil, the program I use to remap Caps Lock to ESC, no longer works. It’s sister application Karabiner also stopped working.

Fortunately there’s a solution available from the developer of Karabiner and Seil. It’s a little more complicated than usual:

  1. Download and install Karabiner-Elements:

    https://github.com/tekezo/Karabiner-Elements

  2. Karabiner Elements will install a virtual keyboard driver, and you probably want to disable the default capslock behavior for the new virtual driver:

    disable capslock

  3. Use your favorite editor and edit the following file (create it if does not exist):

    vim ~/.karabiner.d/configuration/karabiner.json

    And add the following to it:

    {
        "profiles": [
            {
                "name": "Default profile",
                "selected": true,
                "simple_modifications": {
                    "caps_lock": "escape"
                }
            }
        ]
    }

That’s it. Just make sure you have Karabiner Elements running.

Find Dead Code with Unused

Today I discovered a fascinating tool called Unused, written by Josh Clayton.

Unused leverages two of my favorite projects, Exhuberant Ctags and The Silver Searcher, to identify dead code. I installed it with homebrew.

Dead code is code that is never used by your application. It wastes electricity and mental bandwidth, and can hang around unnoticed for years. We need powerful tools to find and remove it.

Unused threw out a few false positives, as expected. Use with caution and a solid test suite.

The Unused website highlights several pull requests removing dead code from popular open source projects. I was able to use it on ‘Today I Learned’ itself. A small win:

https://github.com/hashrocket/hr-til/pull/101

Github Advanced Search Parameters

I really enjoy browsing Github. The search feature in particular is a fantastic way to stumble on interesting projects.

Search has an ‘advanced’ menu that lets you restrict your query. I’ve used it enough that I have some preferences that I enter directly into the search bar: is:issue is:open label:"help wanted" finds open issues actively seeking outside contributions. Not everybody uses labels, so removing that can yield even more results.

Add a language filter as a query parameter, and you’re on your way to some good open source contribution opportunities. Drill down further with a search term, such as ‘testing’ or ‘flicker’.

Toggle Mute in Hangouts (Mac)

During client calls, I mute and unmute my microphone dozens of times. Mute to listen and cut ambient office noises, unmute to speak.

Google Hangouts provides some shortcuts for this and other common activities. In particular, ⌘ + d toggles mute on a Mac.

Step your videoconferencing game up! 🖥

https://support.google.com/hangouts/answer/3112005

Drop connections with Nginx

You can ignore requests sent to nginx by responding with the status 444

server {
  listen 80;
  listen [::]:80;
  listen 443;
  listen [::]:443 ssl http2;

  server_name dillonhafer.com;
  location /no-response {
    return 444;
  }
}

The primary use for this is to prevent processing requests with undefined server names:

# block for requests with undefined server names
server {
  listen 80;
  listen [::]:80;

  return 444;
}

Loopback to different 127.*.*.* ips mac osx

You can’t bind to the loopback interface automatically on mac osx.

> rails -b 127.0.0.2
ERROR: Can't assign requested address - bind(2) for 127.0.0.2:3000 (Errno::EADDRNOTAVAIL)

Mac OSX will disable all loopback addresses other than 127.0.0.1 by default, but they can be enabled with ifconfig.

> sudo ifconfig lo0 alias 127.0.0.2 up

And now your server can bind to that address.

h/t Jack Christensen

Script for bootstrapping a new project #bash #git

Creating a new project and publishing it usually involves many repeatitive steps. As developers we like to automate the tedious repetitive tasks to allow our creative juices to flow freely.

I wrote the following script for boostrapping a new project. Feel free to modify and add to your zshrc or bashrc:

function initprj() {
  # create the directory and cd into it unless the user uses '.'
  # to indicate current directory
  if [[ "$1" != "." ]]; then
    mkdir $1
    cd $1
  fi

  # setup git
  git init

  # setup remote repo on github and add it to git remote
  hub create

  # setup base files (add your own if you'd like)
  touch README.md
  touch .gitignore

  # You must use tabs if you want to indent heredocs that use the <<- syntax
  cat <<-EOF > LICENSE
        Copyright (c) $(date +"%Y") Dorian Karter

        Permission is hereby granted, ...
        EOF
}

To run the script simply type initprj my-project and watch the magic happen.

Note: you must have hub installed to create the remote repo.

`CTRL` commands in Chrome's Address Bar

The Hashrocket Dotmatrix binds some of the UNIX CTRL- commands to commands in Chrome’s address bar. Here are a few examples:

  • CTRL-a to move cursor to the beginning of the line
  • CTRL-e to move cursor to the end of the line
  • CTRL-b to move the cursor one space backward
  • CTRL-f to move the cursor one space forward

There are more to try; some work the same as they do in the command line, and some work differently.

Here’s the code that makes this possible.

h/t Brian Dunn

Rust Array Access is Bound Checked at Runtime

Today I encountered a feature of Rust that I hadn’t seen before— uses of array subscript notation (‘array[n]’) are checked at runtime to ensure they fit into the bounds of the array.

Here’s a passing test I wrote to demonstrate:

// src/lib.rs
#[test]
#[should_panic(expected="index out of bounds: the len is 3 but the index is 5")]
fn array_access_is_bound_checked_at_runtime() {
    let elements = ["Wind", "Fire", "Water"];
    assert_eq!("Wind", elements[5]);
}

>’Such errant access is the source of many bugs in other systems programming languages.’ —The Rust Programming Language

More information:

https://doc.rust-lang.org/book/primitive-types.html#arrays

Trust Issues 🤔

Our computers trust a scary amount of Root Certificate Authorites, and sometimes I have trust issues with some of them. Most recently being the StartCom bug, which allowed anyone to get a certificate for any domain they wanted.

I can’t trust them. Period. And I don’t have to.

Here is how you can revoke trust for any Root CA in OSX:

  1. Open Keychain Access.
    open /Applications/Utilities/Keychain\ Access.app
  2. Click on System Roots from the left Keychains sidebar.
  3. Typestartcom in the search bar.
  4. Select all the root certificates and press ⌘i.
  5. Expand the Trust section
    and change the option
    When using this certificate
    to
    Never Trust.

Github Reactions and Merge Strategy

Recently Github has launched 2 new features:

Reactions to comments

Now users can add few reactions to Issues, Pull Requests or Comments. This will reduce a lot of noise on issues like the 👍 (:+1:) for new feature. Really cool.

Squash and rebase as a new merge strategy

Github always create a new commit merging a branch into another one (usually master).

So now we can choose to squash commits and merge. So all commits in a branch will become just one and this one will be rebased into the branch. Sounds cool for a few situations.

Check it out!

Add Emoji To GitHub Repository Description

GitHub restricts the set of unicode characters that can appear in the description field of a repository to anything up to 0xffff. Most emoji have unicode values above this. This means you will have limited success adding emoji via your system’s emoji keyboard.

Fortunately, GitHub allows you to add any recognized emoji to a repository description with its specialized emoji syntax (e.g. :memo:). You may have used this syntax in other parts of GitHub such as the issue tracker.

If you add an emoji like this:

it will show up like so:

Check out this Emoji Cheat Sheet for the names of all recognized emojis.

Put -L in your ssh config

If you’ve used ssh you’ve probably had to use local port forwarding before. If you use complex flags often, you will find remembering what you need is tiresome. Stop. Write it down so you can forget all about it. Save your memory.

Instead of doing this:

ssh -L 3000:localhost:3002 not_dillon@example.com

Add those flags to the ~/.ssh/config file instead:

# /home/dillon/.ssh/config

Host example
  User         not_dillon
  Hostname     example.com
  LocalForward 3000 localhost:3002

From now on, all you need to type is:

ssh example

Pretty Print Tabular Data

Looking at a bunch of data in the Chrome dev tools console isn’t great. It can be a bit difficult to read because of the way it is displayed. Fortunately, the Chrome dev tools come with a handy way of displaying tabular data, console.table(). If you give console.table an array of objects or array of arrays, it will format it in a table like so:

Reference The Selected Node

In the Chrome dev tools, if you’ve selected (highlighted) a node in the DOM, you can reference that node from the console with $0. This is handy if you are debugging or exploring certain parts of a page and need to run commands against that node. For instance, if you were to select the <html> node in the DOM, you could then programmatically check the lang attribute from the console like so:

> $0.lang
// "en-US"

If there is jQuery on the page and you’ve selected the node that contains all of the page’s content, you can do something like the following:

> $($0).html('<h1>Hello, World!</h1>')

Tutorial Better

When I’m going through an online video tutorial, I have to write all of the code shown to really solidify the concepts. As a result I spend a lot of time pressing CMD + TAB to toggle between the browser video and my Vim session. This method is inefficient.

Helium to the rescue. Helium is a floating browser window for OS X, with some nice features like transparency. Position it on top of your console session, watch the video, and hack away in realtime.

Helium Screenshot

http://heliumfloats.com/

h/t Dorian Karter

Twitter Media and Characters

Today while debugging, we realized something surprising about Twitter— attaching media to a tweet counts as characters and reduces the overall amount of characters available.

Try adding any picture to a tweet. You’ll see the available characters drop. We experienced a consistent drop of 24, from 140 to 116, although this seems to have varied at different points in Twitter’s history.

This can produce subtle failures in an API call; two-dozen (or so) phantom characters are subtracted just by adding an image and may push any tweet over the limit. Turning up our logs helped expose this issue.

Kill Other Connections To A tmux Session

One of the best features of tmux is the ability for multiple people to connect to the same session in order to pair. This can, however, sometimes result in a extra session hanging around if someone forgets to detach. This is no problem though because you can view and kill other connections.

Hit

<prefix>D

to open up an interactive list of all connections to the current session. Then navigate over the one you want to kill and hit enter. If you are viewing the connections but don’t want to kill one, you can hit q to back out.

h/t Josh Davey

The Case of the Default 🕵

In Apple’s Swift language switch statements must be what apple calls “exhaustive”. I’ve felt the term to be very literal. Literally exhaustive?

Example that does not work:

let count = 42

switch count {
case 1:
  print(1)
case 7:
  print(7)
}

The above statement does not work because it’s missing a default case. Why? What if I don’t want to do anything else? Why do I need to write something that won’t be used? Don’t worry, there is an amazing and less “exhaustive” way to handle these situations; simply default: ()

Correct example:

let count = 42

switch count {
case 1:
  print(1)
case 7:
  print(7)
default: ()
}

Enter the PHP REPL

Working in a language you’ve never worked in before can be challenging. We’ve been doing some PHP source-diving lately, and I find having a REPL very useful for decoding unfamiliar syntax.

If you have PHP installed, entering the REPL is easy; just type php -a. The flag stands for Run as interactive shell. I guess the -i flag was already taken.

Ternary shortcut in PHP

Sometimes, and hopefully sometimes is rarely, you have to read some PHP in order to rewrite that code in another language. In these cases you might run across this oddity.

$a = $a ?: 2; 

This is pretty much like var a = a || 2; in javascript but it comes out of the ternary operator and definitely doesn’t make sense when you first look at it. In every other language that’s a syntax error, but php, ya dig?

Get Chrome history from remote machine

Let’s say you need to get the url you visited Friday at the office, but its Sunday and you’re at home! First, ssh into the remote machine where you were browsing the internet. Second, locate the history file, on OSX its at:

~/Library/Application Support/Google/Chrome/Default/History

Third, try to open the file with a text editor. DOH! Its a sqlite file! Fortunately you have sqlite on your machine so you can use sqlite3 History at the command line. Fourth, type .table to see what tables are available. Oh that doesn’t work, you get an error that says Error: database is locked. This is easy to overcome though, just make a copy of the history file.

cp History History.1
sqlite3 History.1
> .tables
downloads             meta                  urls
downloads_url_chains  segment_usage         visit_source
keyword_search_terms  segments              visits

Now you have access to the database. The url you want is definitely in the urls table, you just have to use your sql skills to find it!