There's an API in Chrome and Firefox (that I know of) that lets you get localized strings with variable replacements from a JSON file that you provide.

var message = browser.i18n.getMessage("messageContent", target.url);
console.log(message);
Read more

Arrays can be copied using spread syntax, introduced in ES6. To illustrate:

let a = [1, 2, 3];

// This won't work.
let b = a;
b[0] = 99;
console.log(a[0], b[0]); // prints "99 99"

// But this will.
let c = [...a]; // before ES6 there was an even uglier way of doing this using "slice", but let's never talk about that
c[0] = 12345;
console.log(a[0], c[0]); // prints "99 12345"
Read more

There are different types of functions in modern-ish JavaScript: regular, async, and generator functions. However, typeof returns "function" for all of them. One way (the only?) to differentiate between them is by using toString.call(myFunc).

Read more

Aggregate Mongo queries accept multiple steps, including SQL-style joins using $lookup. This will add a new property to the results, with an array of documents from the other collection. You can then use $unwind to make each result map to a single document from the other collection. Finally, $project can help you select only the fields you care about.

Read more

You can't directly export an "aggregate" Mongo to CSV using the mongoexport command, as it's intended for simpler data exports. However, there is a way to output the results of one such query to a new collection, which you can then export.

Read more

In Linux, you can make IPv4 traffic have a higher priority than IPv6 by running the following command:

sudo sh -c "echo 'precedence ::ffff:0:0/96 100' >> /etc/gai.conf"

Read more

PHP supports the "data: stream wrapper" natively, so you don't have to do ugly string manipulation to get, for example, the data from a string such as data://text/plain;base64,SSBsb3ZlIFBIUAo=. Instead, you can do this:

$string = 'data://text/plain;base64,SSBsb3ZlIFBIUAo=';
$source = fopen($string, 'r');
$destination = fopen('myfile.txt', 'w');

stream_copy_to_stream($source, $destination);

fclose($source);
fclose($destination);
Read more

If you run out of memory in Linux, you can create a file to hold additional memory using these commands:

/bin/dd if=/dev/zero of=/var/swap.1 bs=1M count=1024
/sbin/mkswap /var/swap.1
/sbin/swapon /var/swap.1
Read more

"Type embedding" allows for something close to inheritance in Go. If you add a type as a nameless parameter on a struct, the field and methods of that type are "promoted" to the new type.

Read more

Go stores interfaces as a pair of values: a type, and the actual value, and will only be equal to nil if both are.

As a consequence, a nil value stored in an interface variable, but as a pointer to another type, will not pass the == nil test.

Read more

On swing jazz, soloists usually play at a different swing ratio than drummers, and actually sync up with the off-beat of the drums. The on-beat will sometimes have a delay of as much as 100 ms.

Read more

Due to a bug in the original C code for the implementation of Javascript, this awesome thing happens:

const a = null;
console.log(typeof a); // prints "object"
Read more

Apparently, PHP can work just fine without loading a php.ini configuration file. I have no idea where it gets its default configuration from (for example, a value of 128M for memory_limit), but luckily phpinfo() will tell you where it's looking for a php.ini (search for "Configuration File" in its output), so you can just add the file in that path and it will get picked up.

Read more

Here's yet another one of Javascript's endless oddities: the switch statement uses strict comparison (think === instead of ==).

Read more

The Node and browser environments provide different functions, in addition to the process (Node-only) and window (browser-only) objects. If you want an NPM package to work on both, there's a way to specify different source files in the package.json file.

Read more

You can find a document, update and return it using a single method: findAndModify. This is useful to deal with concurrency issues when multiple clients are trying to process documents from a collection and you don't want two of them processing the same one.

Read more

Go relies on the operating system for timezone data, so when you do time.LoadLocation("America/Guayaquil"), it runs code that's different in different OSes. If you use a Docker container to run your code, it's possible to include this data in the form of a .zip file.

Read more

If you want to measure the time that it takes to run an operation, a common solution is to look at the current time before and after and compare the results. But what if the computer's time is changed between the two measurements? Then the result could be anything.

To solve this issue, computers provide a "monotonic clock", which doesn't change even if the computer's time does (maybe the system synchronizes with a time server, or the user just manually changed it). Some languages provide ways to access this value, so you have to decide what clock to use based on what you're doing with it.

Read more

In Ubuntu (and probably other OSes) you can create an empty file, resize it to a couple GBs, create a filesystem on it, and then mount it at any location. You can treat this as a virtual drive to, for example, limit the size of a directory:

Read more

There's a bunch of Web APIs that are pretty usable today:

  1. Detect page visibility
  2. Detect online state
  3. Vibration
  4. Detect orientation

...and more! clipboard, ambient light detection, battery status, etc.

Read more

You can run timers on the console object, like this:

console.time('a');
costlyOperation();
console.timeEnd('a'); // outputs how much time has passed since the call above
Read more

From Wikipedia:

In linguistics, an eggcorn is an idiosyncratic substitution of a word or phrase for a word or words that sound similar or identical in the speaker's dialect (sometimes called oronyms). The new phrase introduces a meaning that is different from the original but plausible in the same context, such as "old-timers' disease" for "Alzheimer's disease".

Read more

A bugle is a wind instrument that can only play its key note and notes within its harmonic series, for example, C3 G3 C4 E4 G4. To play different notes, one must change how the lips are placed on the mouthpiece of the instrument, which causes air to vibrate at different speeds, but the options are physically limited to integer multipliers of the base frequency.

Read more

You can think of the denominator of a time signature as a whole note split in as many pieces, so that a time signature that is "weird" (the name is actually "irrational", nothing to do with the mathematical sense) like 5/7 now makes sense as "five sevenths of a whole note", or a bit longer than a 2/4 measure.

Read more

There's a nice utility that you can use to kill a process based on the port it's listening to, so for example if you have a server listening on port 80, you can run $ fkill :80 and it will murder it.

Only problem, it's made using Javascript, but if you're OK with having Node and plain-text JS files in your bin folder, you can install it with $ npm install --global fkill-cli.

Read more

Javascript's Date object has a bunch of methods to format dates as strings, including toLocaleDateString(). This method has options for controlling the format, which include language but also more granular options such as "use 2-digit years" or "show long weekday names".

Here are some examples (tests were done in Chrome 64):

Read more

The most common tuning system in western music nowadays involves dividing an octave into 12 equally spaced "semitones", called "equal temperament". In this system, the octave interval (frequency ratio 2:1) is the only "perfect" one, and, for example, a "perfect fifth" (frequency ratio 3:2) doesn't exactly match a "fifth" (seven semitones). This is the solution people came up with, and we've been using it happily for a while now, but there are other equally valid ways to split the octave.

Read more

In order to use a variable as an object's key, ES6 introduced something called "computed property names", where you add brackets to your variable and it gets replaced with its value.

Read more

You can undo the "eject" operation of a Create React App app by adding the react-scripts package back and changing a couple of lines on the package.json file to their defaults. You can lose those /config and /scripts directories too. The only really ugly thing I found on my test (admittedly on a very simple app which is probably not at all representative of the real world) is that a number of packages were added without an easy way to get rid of. But hey, doesn't that sound like good old npm anyway?

Read more

There's a simple algorithm that uses the Bayes theorem that can be used to classify documents, using their text tokenized into individual words, into categories (e.g. tags on a website). The classifier needs to be trained with existing data, and then it will return which categories a new document probably belongs to.

Read more

JSON.parse() has an optional second parameter meant for a "reviver" function. This function will receive all keys and values from the parsed string, so you can do modifications to the result. This is useful, for example, to convert date strings to objects automatically.

Read more

Object IDs in Mongo store several variables (screenshot from MongoChef), including the time it was created, a machine identifier, a process ID and an internal counter.

Screenshot showing an object ID and its parsed values

Read more

Ruminating is a habit where you keep thinking about recent upsetting events in an obsessing manner. It is a dangerous activity that can lead to depression, but there is something one can do about it: a quick distraction (even a 2-minute one), every time you start thinking about these things, can change the habit.

Read more

Contrary to popular belief, Cinderella is actually a story about a strong woman who helps herself. The fact that she doesn't do so in a traditionally masculine way (she doesn't fight her abusers physically, doesn't plan a spectacular escape, etc.) is the reason why we often think of the prince being her savior in the story, and her being, just, passive.

Read more

In the Go language, when you define an interface, you only need to implement the functions and your type automatically "implements" that interface, without explicitly saying so.

Read more

…how to lock a piece of code so that it's guaranteed to only run once at a time. If it's running and another thread (or Goroutine in my case) reaches the same piece of code, it will wait for the first process to finish before continuing its execution.

I'm using it to lock an entire function, but apparently it works for any section of code.

Read more

Running tests with coverage on the Goland IDE is really easy, you just write the test and it gives you a "play icon" button to the left of each function, and after it runs you get the coverage report in a separate window and within the source code as well, telling you exactly which lines are covered.

Read more