Warning: "continue" targeting switch is equivalent to "break". Did you mean to use "continue 2"? in /homepages/2/d463837785/htdocs/clickandbuilds/eloquentcode/wp-includes/pomo/plural-forms.php on line 210

Warning: Cannot modify header information - headers already sent by (output started at /homepages/2/d463837785/htdocs/clickandbuilds/eloquentcode/wp-includes/pomo/plural-forms.php:210) in /homepages/2/d463837785/htdocs/clickandbuilds/eloquentcode/wp-includes/feed-rss2.php on line 8
eloquent code http://eloquentcode.com references, examples and tutorials Tue, 19 Jan 2021 03:06:04 +0000 en-US hourly 1 https://wordpress.org/?v=4.9.3 API Design: Slug Fields and Identifiers http://eloquentcode.com/api-design-slug-fields-and-identifiers http://eloquentcode.com/api-design-slug-fields-and-identifiers#respond Tue, 19 Jan 2021 03:06:04 +0000 http://eloquentcode.com/?p=223 Continue reading "API Design: Slug Fields and Identifiers"

Using slug values and parameters in APIs allows more ‘hackable’ and easier to recall URIs to resources and helps Developer Experience (DX), i.e. API UX.
For example, in a Books API, the resource representing the book “Invisible Man” would have a slug equal to “invisible-man” in addition to its numeric canonical ID.
Slugs should be unique; they can be computed by many library routines widely available, which involves removing punctuation, lower-casing and replacing whitespace by hyphens.
This ability lets us access specific objects much more easily.
For example, we can use:

GET /api/books/invisible-man

In addition to:

GET /api/books/4456234

Both are valid requests for the object:

  "id": "4456234",
  "slug": "invisible-man",
  "title": "Invisible Man",
  "author": "Ralph Ellison"

An API is usually up and running at least in three environments: Dev, Staging and Production, and sometimes more.
With slug values identifying objects, a client need not know or discover IDs in different environments. For example in the books API, we can access the same object’s different versions across environments with /books/invisible-man, e.g. on different hosts such as api.dev.books.com/books/invisible-man or api.books.com/books/invisible-man.
The actual IDs in the underlying databases need not be known; a slug value lets us quickly access the resource’s copy in any environment.

Further, slug values for collection objects can be even more powerful. For example, exploring entire categories of books can be much easier if slug values for categories can be used:

GET /categories/novels/books

Instead of a specific ID-based request:

GET /categories/5423/books

In both cases the result is a list of all books in the category novels.

A frontend app using the API need not know the ID of a category to request objects in the category.
This means the app can make an API call by slug based directly from parsing the web URL, without having determine any resource IDs.
Consequently, slugs are ideal for URL paths for web apps, providing a correspondence between user URLs and API parameters for developers.

If a single object can have multiple kinds of slugs, we can use fields like titleSlug and categorySlug.

http://eloquentcode.com/api-design-slug-fields-and-identifiers/feed 0
Install Keras on macOS http://eloquentcode.com/install-keras-on-macos http://eloquentcode.com/install-keras-on-macos#respond Thu, 10 Dec 2020 03:40:14 +0000 http://eloquentcode.com/?p=218 Continue reading "Install Keras on macOS"

To install the Keras deep learning library on macOS (no GPU required), first make sure to have a recent version of Python3.

The best way to manage recent Python versions is using pyenv. Assuming starting from scratch:

brew install pyenv

Add this line to .bash_profile:

# For pyenv.
if command -v pyenv 1>/dev/null 2>&1; then
  eval "$(pyenv init -)"

Be careful with version compatibility; at the time of writing Python 3.6 works well.

pyenv install 3.6.0

pyenv global 3.6.0

First install the TensorFlow backend, then Keras itself:

pip install tensorflow

pip install keras

Test the installation:


>>> import keras

The import should succeed without error if the installation is complete.


http://eloquentcode.com/install-keras-on-macos/feed 0
Undo a Commit on the Current Branch in Git http://eloquentcode.com/undo-a-commit-on-the-current-branch-in-git http://eloquentcode.com/undo-a-commit-on-the-current-branch-in-git#respond Thu, 22 Oct 2020 01:27:34 +0000 http://eloquentcode.com/?p=214 Continue reading "Undo a Commit on the Current Branch in Git"

To undo a commit made on a branch (e.g. master) as well as unstage the changes and restore the changes to local changes, use the following:

$ git reset HEAD~

Unstaged changes after reset:
M file.js

$ git status
On branch master
Changes not staged for commit:
 (use "git add <file>..." to update what will be committed)
 (use "git checkout -- <file>..." to discard changes in working directory)

modified: file.js

no changes added to commit (use "git add" and/or "git commit -a")

The commit will be permanently removed from the branch, and remain as local changes only.

NOTE: this requires at least 2 commits in the repo or the reference will not exist.


http://eloquentcode.com/undo-a-commit-on-the-current-branch-in-git/feed 0
Increase Readability of Function Calls in JavaScript with an Argument Object http://eloquentcode.com/increase-readability-of-function-calls-in-javascript-with-an-argument-object http://eloquentcode.com/increase-readability-of-function-calls-in-javascript-with-an-argument-object#respond Mon, 12 Oct 2020 03:08:19 +0000 http://eloquentcode.com/?p=210 Continue reading "Increase Readability of Function Calls in JavaScript with an Argument Object"

An argument object is a pattern to create more readable code involving function calls.

As the number of function arguments increases, readability rapidly declines.

We can create cleaner code by using an argument object: an object with keys for each function parameter. The reader does not have to inspect or deduce the meaning of positional arguments.

Suppose we have a function to locate a point based on latitude and longitude, but also with a radius and a flag indicating placing a marker.

A function call would look like this:

geoLocate(40.730610, -73.935242, 100.0, true);

Coming across the above call in code would require digging into the meaning of each positional argument.

We can make this more readable by making the function accept an argument object instead as below:

  lat: 40.730610,
  lng: -73.935242,
  radius: 100.0,
  placeMarker: true 

This approach is especially helpful with boolean flags as arguments, which as positional parameters can be quite unreadable.


http://eloquentcode.com/increase-readability-of-function-calls-in-javascript-with-an-argument-object/feed 0
REST API Design: Health Check Endpoint http://eloquentcode.com/rest-api-design-health-check-endpoint http://eloquentcode.com/rest-api-design-health-check-endpoint#respond Mon, 12 Oct 2020 02:05:34 +0000 http://eloquentcode.com/?p=204 Continue reading "REST API Design: Health Check Endpoint"

A health-check or simply health endpoint can be very useful for testing and inspecting a running API, especially when rather implementation-specific information is used. It can also be used as the endpoint called by automated monitoring and alerting.

For a microservice, the health often depends on several dependencies. The health endpoint can list the status of the dependencies.

An example call:

GET /api/health

  "healthy": true,
  "dependencies": [
      "name": "serviceA",
      "healthy": true
      "name": "serviceB",
      "healthy": true

Some other options for naming: “status”, or “isHealthy”.

The response status code is 200 OK for a healthy API, and a good choice for unhealthy is 503 Service Unavailable.

Getting more specific, we can design sub-resources for health information pertaining to subdomains or functionality of the API.
For a concrete example, imagine an API which can report on the status of a data ingest service as part of its own health:

GET /api/health/data-ingest

  "isHealthy": false,
  "databaseUpdatedAt": 1592716496,
  "memoryUsage": "255MB"

This sub-resource gives us specific information about a data ingest subsystem.

We can use this sort of design to make monitoring more granular: imagine an alert being fired only when certain specific health sub-resources return an error status, but not all.

Using Headers for Health Status

Another option is to use HTTP headers for specific details and keep the JSON result body small, showing only the status. For example:

GET /api/health/data-ingest

Content-type: application/json
X-Health-Database-Updated-At: 1592716496
X-Health-Memory-Usage": 255MB

  "healthy": true


http://eloquentcode.com/rest-api-design-health-check-endpoint/feed 0
Get Current Date in Unix Epoch Time in JavaScript http://eloquentcode.com/get-current-date-in-unix-epoch-time-in-javascript http://eloquentcode.com/get-current-date-in-unix-epoch-time-in-javascript#respond Mon, 12 Oct 2020 01:22:29 +0000 http://eloquentcode.com/?p=202 Continue reading "Get Current Date in Unix Epoch Time in JavaScript"

We can get the current Unix epoch timestamp in JavaScript (e.g. Node.js) with the following:

const epoch = Math.round(new Date().getTime() / 1000) 



We can also use valueOf:

const epoch = Math.round(new Date().valueOf() / 1000)



Probably the best way is using the static method now from Date:

const epoch = Math.round(Date.now() / 1000) 



Note that we need to divide by 1000 because the original result is in milliseconds.


http://eloquentcode.com/get-current-date-in-unix-epoch-time-in-javascript/feed 0
Dynamically Generate Variable Names in Perl http://eloquentcode.com/dynamically-generate-variable-names-in-perl http://eloquentcode.com/dynamically-generate-variable-names-in-perl#respond Mon, 14 Sep 2020 00:47:31 +0000 http://eloquentcode.com/?p=199 Continue reading "Dynamically Generate Variable Names in Perl"

NOTE: this is not recommended, but it is a powerful feature which can be useful.

We can generate dynamic variable names in Perl using Symbolic References. To use the feature, we have to turn off strict refs.

The code below generates the variable names ‘var1’, ‘var2’, ‘var3’ dynamically in a loop as strings, names which can be used as actual variable names with the help of symbolic references.
Of course, hashes should be used instead whenever possible; this is for demonstration.

use strict;
our $var1 = 'a';
our $var2 = 'b';
our $var3 = 'c';

for (my $i = 1; $i < 4; $i++) {
  my $variableName;
    # Symbolic References require 'no strict'.
    no strict 'refs';
    $variableName = ${'var' . $i}; # Dynamic name.
  print $variableName . "\n";




http://eloquentcode.com/dynamically-generate-variable-names-in-perl/feed 0
Istanbul Ignore Syntax for Jest Code Coverage http://eloquentcode.com/istanbul-ignore-syntax-for-jest-code-coverage http://eloquentcode.com/istanbul-ignore-syntax-for-jest-code-coverage#respond Sat, 12 Sep 2020 01:37:08 +0000 http://eloquentcode.com/?p=196 Continue reading "Istanbul Ignore Syntax for Jest Code Coverage"

Istanbul is the tool Jest uses to calculate test coverage. Sometimes we need to exclude some code from the coverage calculations. This is done with special comments which are parsed by Istanbul. There are a few variations of the syntax.

Ignore a Function

/* istanbul ignore next */
const f = () => {
  return 'abc'

This will exclude the entire function from code coverage requirements.

Ignore a Whole File

/* istanbul ignore file */

... file contents ...

Use this as the first line of the file. The entire file will be excluded from code coverage.

Ignore a Method in a Class

class A {
  f() {
    console.log("f called")
  /* istanbul ignore next */ g() {
    console.log("g called")

The comment must be on or above the line defining the method so it is not part of the coverage requirement.

Function Inside an Exported Object

Sometimes we have a module which exports some functions inside an object.
The example below shows how to ignore these for coverage. The comment must be right before the function definition.

module.exports = {
  f: () => { 
    console.log('f called')
  g: /* istanbul ignore next */ () => {
    console.log('g called')
  h: /* istanbul ignore next */ async () => {
    console.log('h called')

Note that for async functions we must place the comment before the async keyword.

Ignore Else Cases

To ignore just the else case of a block of code for test coverage, use the syntax as below.

function f(x) {
  /* istanbul ignore else */
  if (x >= 0) {
  } else { // Ignore this block for code coverage.

NOTE: the ignore-else comment is placed above the if statement to ignore the else case for coverage.




http://eloquentcode.com/istanbul-ignore-syntax-for-jest-code-coverage/feed 0
Log Values Inside Ramda.js Pipelines to the Console http://eloquentcode.com/log-values-inside-ramda-js-pipelines-to-the-console http://eloquentcode.com/log-values-inside-ramda-js-pipelines-to-the-console#respond Sat, 25 Jul 2020 02:09:52 +0000 http://eloquentcode.com/?p=194 Continue reading "Log Values Inside Ramda.js Pipelines to the Console"

It can be difficult to debug by examining intermediate values inside Ramda pipelines with console.log.

The Ramda function tap comes in handy here and is like a wiretap: we can use it to tap into a functional pipeline to insert some behaviour in between steps, while letting the pipeline continue to work as usual. We can insert R.tap in between functions inside pipelines built with R.compose or R.pipe.

In diagram form:

A -> B -> C
A -> B -> R.tap(fn) -> C

(pipeline proceeds as usual, passing output from B to the input of C)

The following simple example reverses a list and then takes the average (mean).

const R = require('ramda')
const f = R.compose(
  R.mean, // Take average.
  R.reverse // Reverse elements.

const result = f([1, 2, 3])


This prints:


Suppose we want to debug this function composition and print out the intermediate reversed list.

We can insert the “wiretap” with R.tap with a function to log the input to see the intermediate value flowing through:

const R = require('ramda')
const f = R.compose(
  R.mean, // Take average.
  R.tap(x => console.log(x)), // Print and continue.
  R.reverse // Reverse elements.

const result = f([1, 2, 3])



[ 3, 2, 1 ]

This technique can be very handy to debug more complex code using pipe and compose by inserting R.tap.




http://eloquentcode.com/log-values-inside-ramda-js-pipelines-to-the-console/feed 0
Require an Object to Contain at Least One Key in a Joi Schema http://eloquentcode.com/require-an-object-to-contain-at-least-one-key-in-a-joi-schema http://eloquentcode.com/require-an-object-to-contain-at-least-one-key-in-a-joi-schema#respond Thu, 23 Jul 2020 23:33:49 +0000 http://eloquentcode.com/?p=191 Continue reading "Require an Object to Contain at Least One Key in a Joi Schema"

When validating JSON objects with Joi in JavaScript we sometimes need an object to have any one of a set of possible keys, i.e. one or more of the specific keys given.

The schema below achieves this with the or() function.

const customerSchema = Joi.object().keys({
  id: Joi.string().optional(),
  accountNumber: Joi.number().optional(),
  emailAddress: Joi.string().optional()
.or('id', 'accountNumber', 'emailAddress') // At least one of these keys must be in the object to be valid.

If we supply a JSON object like below to the Joi schema validate function, we will see a Joi schema validation error similar to the example.

  "name": "test"

Joi validation error:

"message": "object must contain at least one of [id, accountNumber, emailAddress]"

However, any of the following are valid examples:

  "id": "1234"
  "id": "1234",
  "emailAddress": "test@test.com"

Note that we can also use the related functions and(), xor(), nand(), and others to achieve other logical requirements on object keys.


http://eloquentcode.com/require-an-object-to-contain-at-least-one-key-in-a-joi-schema/feed 0