GatsbyJs - Add environment variables

 https://dev.to/kapilgorve/gatsbyjs-add-environment-variables-1io5

Development Environment

  • Create a new file named as .env.development at the root of your project.
  • Add your variable to the newly created file. Example - TEST_KEY=123
  • Change your npm run develop command to set environment.

For Windows -

    "develop": "set GATSBY_ENV=development && gatsby develop"

For Linux -

    "develop": "GATSBY_ENV=development gatsby develop"
  • Restart your dev environment. So Gatsby will load your new env file.
  • You should be able to access your env variables using process.env.TEST_KEY in any js file.

Production Environment

  • Create a new file named as .env.production at the root of your project.
  • Add your variable to the newly created file. Example - TEST_KEY=123
  • Change your npm run build command to set environment.

For Windows -

    "develop": "set GATSBY_ENV=production && gatsby develop"

For Linux -

    "build": "GATSBY_ENV=production gatsby build",

This is only if you want to build on local.

If you are using any providers like Netlify use the Linux version. You will also need to add environment variables in the service provider.

For Netlify it is in Site Settings > Build&Deploy > Environment

This post was originally published at https://www.jskap.com/blog/gatsby-add-environment-variables/

How to stretch the background image to fill a div

 https://stackoverflow.com/questions/11223585/how-to-stretch-the-background-image-to-fill-a-div

Add

background-size:100% 100%;

to your css underneath background-image.

You can also specify exact dimensions, i.e.:

background-size: 30px 40px;

Axios: chaining multiple API requests

 https://stackoverflow.com/questions/44182951/axios-chaining-multiple-api-requests


        const tokenInput = JSON.stringify({
                ...
            });
        const Agent = new https.Agent({
            rejectUnauthorized: false
        })
        // call for access token
        const [tokenResponse] = await Promise.all([axios
            .post(process.env.TOKEN_URL, tokenInput, {
                httpsAgent: Agent,
                headers: {
                  // Overwrite Axios's automatically set Content-Type
                  'Content-Type': 'application/json'
                }
            })
        ]);
        // check token
        const accessToken = tokenResponse.data.result.accessToken;
        // check access token
        if (!tokenResponse.data.result.accessToken) {
            return;
        }

        /**
         * prepare data to post
         */
        const postData = JSON.stringify({
            ....
        });

        axios
        .post(process.env.FORM_URL, postData, {
            httpsAgent: Agent,
            headers: {
              // Overwrite Axios's automatically set Content-Type
              'Content-Type': 'application/json'
            }
        })
        .then(res => {
          console.log(res);
        })
        .catch(error => {
          console.error(error)
        })

First off, not sure you want to do this in your componentWillMount, it's better to have it in componentDidMount and have some default states that will update once done with these requests. Second, you want to limit the number of setStates you write because they might cause additional re-renders, here is a solution using async/await:

async componentDidMount() {

  // Make first two requests
  const [firstResponse, secondResponse] = await Promise.all([
    axios.get(`https://maps.googleapis.com/maps/api/geocode/json?&address=${this.props.p1}`),
    axios.get(`https://maps.googleapis.com/maps/api/geocode/json?&address=${this.props.p2}`)
  ]);

  // Make third request using responses from the first two
  const thirdResponse = await axios.get('https://maps.googleapis.com/maps/api/directions/json?origin=place_id:' + firstResponse.data.results.place_id + '&destination=place_id:' + secondResponse.data.results.place_id + '&key=' + 'API-KEY-HIDDEN');

  // Update state once with all 3 responses
  this.setState({
    p1Location: firstResponse.data,
    p2Location: secondResponse.data,
    route: thirdResponse.data,
  });

}

WordPress GraphQL vs Gatsby GraphQL

 https://www.gatsbyjs.com/blog/getting-started-with-gatsby-source-wordpress-choose-your-own-adventure/

The query names you see here aren’t the same as the query names you’ll be using in Gatsby, so by all means peruse it at your leisure. However, we won’t be using quite the same query names in the following steps. (This is because with Gatsby, in order to avoid query-clash between different platforms, any WordPress-specific query usually contains the letters “Wp” to identify it as WordPress related. Plural queries are prefixed with “all”. Don’t worry, I’ll show you the diff).

Here’s a side by side equivalent GraphQL query to show an example of one of the main differences: 

 

WordPress GraphQL

Gatsby GraphQL

{
  pages {
    nodes {
      title
    }
  }
}
{
  allWpPage {
    nodes {
      title
    }
  }
}

 

Back on the GraphQL page, below the GraphQL Endpoint item and input field at the very top, you’ll see a url for the new GraphQL endpoint. Make a note of this, since we will be using it in the next step ➡️.

wpgraphql: Node & Global ID

https://www.wpgraphql.com/docs/wpgraphql-concepts/ 

Every object in WordPress is treated as an individual "node" in GraphQL. Posts are nodes. Pages are nodes. Categories, tags, users, comments, menu items, etc are all considered "nodes".

And each "node" in the Graph can be identified by a unique ID.

In WordPress, IDs are not truly unique. There can be a Post with ID 1, a User with ID 1, a Category with ID 1 and a Comment with ID 1. WPGraphQL generates opaque global IDs for entities by hashing the underlying loader type and the database id. So, objects loaded by the Post loader get a global ID of base_64_encode( 'post:' . $database_id );. So, a Post with the database ID of 1 would have a global ID of cG9zdDox.

jquery-tabs

 https://gist.github.com/chrisguitarguy/1237619


<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
	jQuery('ul.tab-nav li').click(function(e){
		var tab_id = jQuery(this).attr('id');
		jQuery('ul.tab-nav li').removeClass('active');
		$(this).addClass('active');
		jQuery('.tab-container div.tab').hide();
		jQuery('.tab-container div#' + tab_id + '-tab').show();
	});
	jQuery('ul.tab-nav li:first-child').trigger('click');
});
</script>


<div class="tab-container">
	<ul class="tab-nav">
		<li id="one">One Tab</li>
		<li id="two">Two Tabs</li>
		<li id="three">Three Tabs</li>
	</ul>
	<div class="tab" id="one-tab">
		test
	</div>
	<div class="tab" id="two-tab">
	        test 1
	</div>
	<div class="tab" id="three-tab">
	        test 2
	</div>
</div>

Match a line with multiple regex using Python

 https://stackoverflow.com/questions/8888567/match-a-line-with-multiple-regex-using-python

You can use the built in functions any (or all if all regexes have to match) and a Generator expression to cycle through all the regex objects.

any (regex.match(line) for regex in [regex1, regex2, regex3])

(or any(re.match(regex_str, line) for regex in [regex_str1, regex_str2, regex_str2]) if the regexes are not pre-compiled regex objects, of course)

However, that will be inefficient compared to combining your regexes in a single expression. If this code is time- or CPU-critical, you should try instead to compose a single regular expression that encompasses all your needs, using the special | regex operator to separate the original expressions.

A simple way to combine all the regexes is to use the string join method:

re.match("|".join([regex_str1, regex_str2, regex_str2]), line)

A warning about combining the regexes in this way: It can result in wrong expressions if the original ones already do make use of the | operator.

PYTHON: Is there a simple way to delete a list element by value?

 python - Is there a simple way to delete a list element by value? - Stack Overflow


To remove an element's first occurrence in a list, simply use list.remove

:
>>> a = ['a', 'b', 'c', 'd']
>>> a.remove('b')
>>> print(a)
['a', 'c', 'd']

Mind that it does not remove all occurrences of your element. Use a list comprehension for that.

>>> a = [10, 20, 30, 40, 20, 30, 40, 20, 70, 20]
>>> a = [x for x in a if x != 20]
>>> print(a)
[10, 30, 40, 30, 40, 70]

Exploring Docker container's file system

 linux - Exploring Docker container's file system - Stack Overflow


docker ps


A) Use docker exec (easiest)

Docker version 1.3 or newer supports the command exec that behave similar to nsenter. This command can run new process in already running container (container must have PID 1 process running already). You can run /bin/bash to explore container state:

docker exec -t -i mycontainer_id /bin/bash

see Docker command line documentation

docker build -t getting-started .

 Sample application | Docker Documentation

docker build -t getting-started .


This command used the Dockerfile to build a new container image. You might have noticed that a lot of “layers” were downloaded. This is because we instructed the builder that we wanted to start from the node:12-alpine image. But, since we didn’t have that on our machine, that image needed to be downloaded.

After the image was downloaded, we copied in our application and used yarn to install our application’s dependencies. The CMD directive specifies the default command to run when starting a container from this image.

Finally, the -t flag tags our image. Think of this simply as a human-readable name for the final image. Since we named the image getting-started, we can refer to that image when we run a container.

The . at the end of the docker build command tells that Docker should look for the Dockerfile in the current directory.

--file , -fName of the Dockerfile (Default is 'PATH/Dockerfile')

Notice there is a dot . at the end of both commands.

docker build -f MyDockerfile .

Or with a tag:

docker build -t mysuperimage -f MyDockerfile .

Modify File Permissions with chmod

 Modify File Permissions with chmod | Linode


Modify File Permissions with chmod

The chmod command allows users to change read and write permissions in Unix systems. In this guide, we will show you how to modify file and directory permissions with chmod.

Unix-like systems, including the Linux systems that run on the Linode platform, have an incredibly robust access control system that allows systems administrators to effectively permit multiple users access to a single system without giving every user access to every file on the file system. The chmod command is the best and easiest way to modify these file permissions.

This guide provides a brief overview of file permissions and the operation of the chmod command in addition to a number of practical examples and applications of chmod. If you find this guide helpful, please consider our basic administration practices guide and the Linux users and groups guide next.

Basics of Linux File Permissions

All file system objects on Unix-like systems have three main types of permissions: read, write, and execute access. Permissions are bestowed upon three possible classes: the owner, the group, and all other system users.

To view the file permissions of a set of files, use:

ls -lha

In the first column of the output, there are 10 characters that represent the permission bits. To understand why they are called permission bits, see the section on octal notation below.

drwxr-xr-x 2 owner group       4.0K 2009-08-13 10:16 docs
-rw-r--r-- 1 owner group       8.1K 2009-07-09 16:23 roster.py
lrwxrwxrwx 2 owner group       4.0K 2009-08-13 10:16 team.docs

A way to understand the meaning of this column is to divide the bits into groups.

File typeUserGroupGlobal
d Directoryrwxr-xr-x
- Regular filerw-r--r--
l Symbolic Linkrwxrwxrwx

The first character represents the type of file. The remaining nine bits in groups of three represent the permissions for the user, group, and global respectively. Each stands for:

  • rRead
  • wWrite
  • x: eXecute

Note that access to files targeted by symbolic links is controlled by the permissions of the targeted file, not the permissions of the link object. There are additional file permissions that control other aspects of access to files.

How to Use chmod

In this guide, chmod refers to recent versions of chmod such as those provided by the GNU project. By default, chmod is included with all images provided by Linode, and as part of the common “base” selection of packages provided in nearly all distributions of Linux-based operating systems.

Changing File Permissions with chmod

To change the file permissions using chmod, run chmod <permission> <directory or filename>, swapping in the desired file permissions and the directory or file. The owner can change file permissions for any user, group or others by adding - to remove or + to add certain permissions. These permissions are categorized into read, write, or executable.

In the next few sections, we are going to dive deep into chmod syntax.

Using Symbolic Notation Syntax with chmod

The format of a chmod command is:

chmod [who][+,-,=][permissions] filename

Consider the following chmod command:

chmod g+w ~/example.txt

This grants all members of the usergroup that owns the file ~/example.txt write permissions. Other possible options to change permissions of targeted users are:

Who (Letter)Meaning
uuser
ggroup
oothers
aall

The + operator grants permissions whereas the - operator takes away permissions. Copying permissions is also possible:

chmod g=u ~/example.txt

The parameter g=u means grant group permissions to be same as the user’s.

Multiple permissions can be specified by separating them with a comma, as in the following example:

chmod g+w,o-rw,a+x ~/example-files/

This adds write permissions to the usergroup members, and removes read and write permissions from the “other” users of the system. Finally the a+x adds the execute permissions to all categories. This value may also be specified as +x. If no category is specified, the permission is added or subtracted to all permission categories.

In this notation the owner of the file is referred to as the user (e.g. u+x).

chmod -R +w,g=rw,o-rw, ~/example-files/

The -R option applies the modification to the permissions recursively to the directory specified and to all of its contents.

Using Octal Notation Syntax with chmod

Another method for setting permissions is through octal notation.

Here is example of a file permission that is equivalent to chmod u=rwx,g=rx,o=.

chmod 750 ~/example.txt

The permissions for this file are - rwx r-x ---.

Disregarding the first bit, each bit that is occupied with a - can be replaced with a 0 while rw, or x is represented by a 1. The resulting conversion is:

111 101 000

This is called octal notation because the binary numbers are converted to base-8 by using the digits 0 to 7:

BinaryOctalPermission
0000
0011–x
0102-w-
0113-wx
1004r–
1015r-x
1106rw-
1117rwx

Each digit is independent of the other two. Therefore, 750 means the current user can read, write, and execute, the group cannot write, and others cannot read, write, or execute.

744, which is a typical default permission, allows read, write, and execute permissions for the owner, and read permissions for the group and “world” users.

Either notation is equivalent, and you may choose to use whichever form more clearly expresses your permissions needs.

Examples of Common Permissions with chmod

chmod 600 (rw-------)

600 permissions means that only the owner of the file has full read and write access to it. Once a file permission is set to 600, no one else can access the file. Example chmod commands (in octal and symbolic notions) setting permissions to 600:

chmod 600 example.txt
chmod u=rw,g=,o= example.txt
chmod a+rwx,u-x,g-rwx,o-rwx example.txt

chmod 664 (rw-rw-r--)

664 (rw-rw-r--) enables the following permissions: read and write for the owner; read and write for the group; read for others. If you trust other users within the same group and everyone needs write access to the files, this is a common setting to use. Otherwise 644 permissions can be used to restrict write access to the group. Example chmod commands (in octal and symbolic notions) setting permissions to 664:

chmod 664 example.txt
chmod u=rw,g=rw,o=r example.txt
chmod a+rwx,u-x,g-x,o-wx example.txt

chmod 777 (rwxrwxrwx)

chmod 777 is used to grant permissions to everyone to read, write, and execute a file. While using these permissions is a quick way to overcome a permissions-based error, it’s not a best practice for securing most files and applications. Example chmod commands (in octal and symbolic notions) setting permissions to 777:

chmod 777 example.txt
chmod u=rwx,g=rwx,o=rwx example.txt
chmod a=rwx example.txt

Making a File Executable

The following examples changes the file permissions so that any user can execute the file “~/example.py”:

chmod +x ~/example.py

Restore Default File Permissions

The default permissions for files on a Unix system are often 600 or 644. Permissions of 600 mean that the owner has full read and write access to the file, while no other user can access the file. Permissions of 644 mean that the owner of the file has read and write access, while the group members and other users on the system only have read access.

Issue one of the following chmod commands to reset the permissions on a file back to one of the likely defaults:

chmod 600 ~/example.txt
chmod 644 ~/example.txt

For executable files, the equivalent settings would be 700 and 755 which correspond to 600 and 644 except with execution permission.

Use one of the following examples to achieve these executable “default” permissions:

chmod 700 ~/example.py
chmod 755 ~/example.py

Removing File Permissions with chmod

In order to remove read write permissions given to a file, use the following syntax:

chmod o-rw example.txt

For our file example.txt, we can remove read write permissions using chmod for group by running the following command:

chmod  g-rx example.txt

To remove chmod read write permissions from the group while adding read write permission to public/others, we can use the following command:

chmod g-rx, o+rx example.txt

But, if you wish to remove all permissions for group and others, you can do so using the go= instead:

chmod go= example.txt

Restrict File Access: Remove all Group and World Permissions

There are a number of cases where administrators and users should restrict access to files, particularly files that contain passwords and other sensitive information. The configuration files for msmtp and Fetchmail (~/.msmtprc and ~/.fetchmailrc) are two common examples.

You can remove all access to these files with commands in one of the following forms:

chmod 600 .msmtprc
chmod g-rwx,o-rwx .fetchmail

Understanding Linux Directory Permissions

While directory permissions within Linux are similar to file permissions, there are a few key differences regarding how these permissions affect user operations:

  • Read (r): User can list the items in a directory (such as when using the ls command).
  • Write (w): User can add, delete, or rename files in a directory - provided the user also has execute permissions.
  • Execute (x): User can navigate to the directory (such as when using the cd command).

To view permissions of all files and directories within the working directory, run ls -la. The output will be similar to snippet below. Directories are differentiated from files by the first bit within the permissions. As was covered previously, d stands for directory and - denotes the item is a file.

total 12
drwxr-xr-x 3 user group 4096 Apr 16 12:34 .
drwxr-xr-x 4 user group 4096 Apr 16 12:33 ..
drwxr-xr-x 2 user group 4096 Apr 16 12:34 example-directory
-rw-r--r-- 1 user group    0 Apr 16 12:34 file1.txt

Permissions on an individual directory can also be viewed by running ls -dl example-directory.

How To Change Directory Permissions using chmod

Directory permissions can be adjusted using the same chmod commands as were previously outlined for modifying file permissions. The following example changes permissions on a directory to 755 (owner has read, write and execute permissions, while users with the group or any other user have read and execute permissions):

chmod 755 /example-directory/

In many cases, the permissions should also be changed recursively on all files and subdirectories. This can be done through chmod by using the -R option. To change all permissions for files within a directory to read and write for the owner, read for the group, and read for other users, run the following command:

sudo chmod -R 644 /var/www/html/

StaticImage

  import React , { useEffect , useRef } from "react" import { StaticImage } from "gatsby-plugin-image" impor...