teleren/devto huggingface dataset:
How to Clone a CloudFront Distribution in Minutes
Tags: aws, cloudfront, cloud
Published: 2021-07-02 02:03:54

For the past few months, we have been creating a new CloudFront distribution for each one of our customers with around 13 or more behaviors. This process can be quite tedious. Doing this task from GUI can become an exhausting task where you need to create these behaviors from scratch every time, which is not only boring but also difficult when it comes down to remembering all that needs to be done in order to get your distributions up-and-running. In this article, we are going to see how you can clone an existing distribution in a couple of minutes and enjoy doing it :)

![doit](https://media.giphy.com/media/BpGWitbFZflfSUYuZ9/giphy.gif)

## Install AWS CLI
The AWS CLI is a powerful tool for managing your cloud computing resources, and it makes life so much easier to do from the command line.

If you haven't done it already, make sure you follow AWS official docs to install AWS CLI. https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html

## Export existing distribution configs
First, let's create new directory to save configs there
```
mkdir aws-cloudfront-configs && cd aws-cloudfront-configs
```
## Edit configuration

### `get-distribution-config`

```
aws cloudfront get-distribution-config --id [ID-OF-YOUR-DISTRIBUTION] --output json > distributionConfigs.json
```
If you have multiple profiles, make sure you use `--profile ` in the command.

### Edit the config file
Remove `ETag` and `DistributionConfig` and it's closing curly brackets. Following should be removed.
```
    "ETag": "XXXXXXXXX",
    "DistributionConfig": {
```
### `CallerReference`
Change `CallerReference` to a unique number.

### Change `Aliases`
Change `Aliases` data to reflect new site information. If you don't have any Alias for new site yet, remove the section. This part should be removed
```
        "Aliases": {
            "Quantity": 1,
            "Items": [
                "oldDOmain"
            ]
        },
```

### Replace old domain with new one
Now for `DefaultCacheBehavior`, `Origins` and `CacheBehaviors` make sure to replace old domain with new one

### `ViewerCertificate`
If you have generated SSL cert in ACM, replace what you have under `ViewerCertificate` with new certificate information if not remove the `ViewerCertificate` section completely.
```
        "ViewerCertificate": {
            "ACMCertificateArn": "XXXX",
            "SSLSupportMethod": "XXXX",
            "MinimumProtocolVersion": "TLSv1.2_2019",
            "Certificate": "XXXX",
            "CertificateSource": "acm"
        },
```

## Create new distribution
Make sure you are in the folder you created the `distributionConfigs.json` file, create a copy of it for example `myNewSite.json` and run the following command.
```
aws cloudfront create-distribution --distribution-config file://myNewSite.json
```
Don't forget to add `file://` before the filename. If you don't do that, get an error.
How is JS Asynchronous?
Tags: javascript, beginners
Published: 2021-07-02 01:54:27

####How does the JS engine execute code using the call stack?
Once a function is invoked and it is pushed into the call stack, the call stack executes the code immediately without waiting. So, how are asynchronous tasks possible?

####How does JS perform asynchronous tasks?
Asynchronous tasks are possible in JS because of the browser(runtime environment). The browser consists of the callback queue, web api, etc. which are utilized to carry out asynchronous tasks.

Let's use setTimeout as an example. As you can see in the snapshot below setTimeout is a web API. The browser holds the function for whatever time you assigned which is 5000 milliseconds in the snapshot below. Then once the time you assigned is up the browser puts the function in the callback queue. The function waits in the callback queue until the event loops puts the function in the call stack to be executed.

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h5hcjy1j96amjc36g48s.png)

####What is the event loop?
The event loop exists to constantly monitor the callback queue and the call stack. Once the call stack is empty then the event loop pushes the first task in the callback queue into the call stack to be executed.

Let's use fetch as another example because it is also an asynchronous task but works a little differently. Fetch is also a web API that is used to request an API call. It returns a promise and we have to pass in a callback function that will be executed once the requested data is returned or the promise is resolved. Let's go over the steps on how it works.
1) It first goes to the web API to fetch data from some external server.
2) It waits in the web API environment for the requested data.
3) Once the data is returned the callback function is passed into not the callback queue but the **microtask** queue.

####What is the microtask queue in JS?
The microtask queue serves a similar purpose as the callback queue except it has higher priority. The event loop will always check the microtask queue and carry out the functions waiting there first before it checks the callback queue. 

######What kind of tasks go in the microtask queue and the callback queue?
All callback functions from promises & mutation observers go into the microtask queue. Everything else goes into the callback queue.
LeetCode 26
Published: 2021-07-02 01:37:47

I divided the array into two parts: one is processed, the other one is unprocessed.
So I need two pointers (i, j)to go.
'i' is the slow one, it only move forward by 1 if 'j' find different value from 'i'. Then j will copy the value to i's next position. After j finishes all elements in nums, return i+1 as the length result.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qpiq9th4xnhq0zpr4xxt.png)
LeetCode 1
Published: 2021-07-02 01:31:19

I used dictionary to solve this problem.
I create a dictionary named 'seen' to store the nums.
The code will search for the other part of one of num to make the target in 'seen', if there is, then return its index as well as its partners. If there isn't, then store this number to the 'seen' dictionary. And repeat the process till one number find its partner in the dictionary. This way has more space complexity, but low time complexity ,O(n).

Then other way to solve this is traverse each num in nums to search its partner. This use less space while more time, since the time complexity is o(n^2)

Code:
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/04dup12kt4lwx8phd74r.png)
How to stop an Apache 2 server or service in Linux?
Tags: resource
Published: 2021-07-02 00:00:00

---
  title: How to stop an Apache 2 server or service in Linux?
  published: true
  tags: Resource
  date: Fri Jul 02 2021 05:30:00 GMT+0530 (India Standard Time)
  canonical_url: https://melvingeorge.me/blog/stop-apache2-server-service-linux
  cover_image: https://melvingeorge.me/_next/static/images/main-92e6bceb3690cfb1605582ade63fb5ff.jpg
  ---
  [Originally posted here!](https://melvingeorge.me/blog/stop-apache2-server-service-linux)
  
To stop an Apache 2 server or service, we can use the `systemctl` command-line utility followed by the `stop apache2.service` command in Linux.

```bash
# Stops apache 2 service
sudo systemctl stop apache2.service
```

### What is `systemctl`?

- The `systemctl` is a command-line utility that is used to control and manage the `systemd` services.
- It is widely used with web server services like Apache, Nginx, etc.

### Feel free to share if you found this useful 😃.

---
Indicadores de precios en el Blockchain
Tags: blockchain, ethereum, chainlink, solidity
Published: 2021-07-01 23:24:46

---
title: Indicadores de precios en el Blockchain
published: true
description: 
tags: #blockchain, #ethereum, #chainlink, #solidity
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1gb5lgkjcmh1azs99f7h.png
---

Con ayuda del oráculo de Chainlink podemos acceder a precios de muchas monedas desde solidity. La buena noticia es que es totalmente gratis.

{% youtube _lQMDDxeGkU %}

Para hacerlo solo asegurate de inializar el `priceFeed` con el address del par de precios deseas. Puedes acceder al listado de addresses vista [esta página](https://docs.chain.link/docs/reference-contracts/).

```solidity
pragma solidity 0.8.5;

import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";

contract PriceConsumerV3 {

    AggregatorV3Interface internal priceFeed;

    constructor() public {
        priceFeed = AggregatorV3Interface(0x8A753747A1Fa494EC906cE90E9f37563A8AF630e); // Rinkeby ETH/USD price
    }

    function getThePrice() public view returns (int) {
        (
            uint80 roundID, 
            int price,
            uint startedAt,
            uint timeStamp,
            uint80 answeredInRound
        ) = priceFeed.latestRoundData();
        return price;
    }
}
```

[Documentación oficial](https://docs.chain.link/docs/using-chainlink-reference-contracts/)

**Gracias por ver este tutorial!**

Sígueme en dev.to y en [Youtube](https://www.youtube.com/channel/UCNRB4tgwp09z4391JRjEsRA) para todo lo relacionado al desarrollo en Blockchain en Español.
How to deploy a NodeJS server with NGINX on a VPS
Tags: node, nginx, vps
Published: 2021-07-07 15:25:45

---
title: How to deploy a NodeJS server with NGINX on a VPS
published: true
date: 2021-07-01 23:22:00 UTC
tags: 
 - NodeJS
 - NGINX
 - VPS
canonical_url: 
---

This is how I (currently, as of July 2, 2021) deploy NodeJS servers. Eventually I will figure out Docker, but for right now this is good enough. This tutorial also includes information for using [Redis](https://redis.io/) on the same VPS for caching.

## 1. Prepare a VPS
Create a VPS (I use [Vultr](https://www.vultr.com/?ref=8752906)–that's my referral link). I use Ubuntu; if you use another distro you will have to use your distro's package manager for installing software.

You'll probably want a domain name anyways, so point a domain (I will use example.com for the tutorial) at the VPS.

SSH into the VPS:

    ssh root@example.com

Update the machine:

    sudo apt update; sudo apt upgrade

Install programs that will be useful:

    sudo apt install nginx redis-server python3-certbot-nginx

Install a text editor (I prefer Neovim):

    sudo apt install neovim

## 2. Edit your NGINX files

    nvim /etc/nginx/sites-available/example.com

In the `proxy_pass` value, the port should be whichever port you plan to run your NodeJS server on.

```nginx
server {
    listen 80;
    server_name example.com www.example.com;
    location / {
        proxy_pass http://localhost:3000/;
    }
}
```

Run

    sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled

## 3. Configure Redis

Edit your `redis.conf` file:

    nvim /etc/redis/redis.conf

Find the `supervised` key; set the value to `systemd`.

Restart Redis:

    sudo systemctl restart redis.service
    sudo systemctl restart redis

## 4. Install NodeJS (via `nvm)

    curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.11/install.sh | bash

Exit your SSH session and start a new one:

    ssh root@example.com

Install NodeJS:

    nvm install v15.11.0

## 5. Clone your repo

    git clone https://probablygithub.com/yourusername/yourrepo.git

## 6. Start your server

Change directory into your server directory:

    cd yourrepo.git

Install your packages:

    npm install

Install `pm2` globally:

    npm install pm2 -g

Start your server (change `server.js` to the path of your main file):

    pm2 start server.js
    pm2 startup
    pm2 save
    sudo reboot

## 7. Configure SSL

Use LetsEncrypt:

    sudo certbot --nginx -d example.com -d www.example.com

Enter the required information, and soon enough you will have SSL for your server.

Congrats! You have a deployed NodeJS server with Redis for caching and SSL through LetsEncrypt!

## Other considerations

You may want to create a different user so you are not running the server as `root`.

You may want to use `ufw` for added security. I would reference Brad Traversy's [deployment strategy](https://gist.github.com/bradtraversy/cd90d1ed3c462fe3bddd11bf8953a896).

If this tutorial is broken at any point in the process, let me know by leaving a comment below. Thank you!
How to ensure only one instance of a Bash script is running 🏃
Tags: bash, security, architecture, linux
Published: 2021-07-30 00:18:28

---
title: How to ensure only one instance of a Bash script is running 🏃
published: true
date: 2021-07-01 23:15:00 UTC
tags: bash, security, architecture, linux
canonical_url: https://www.benjaminrancourt.ca/how-to-ensure-only-one-instance-of-a-bash-script-is-running
cover_image: https://www.benjaminrancourt.ca/images/how-to-ensure-only-one-instance-of-a-bash-script-is-running.jpg
---
At work, we have an **cron** job in **Bash** which can sometimes **take a long time** to run, depending on some external conditions. So, it was therefore possible that script would not be finished **before its next execution**. In our case, we really didn't want this to happen, as it could have corrupted some sensitive data if two instances were running at the same time... 🤢

So, one way to ensure that only one instance is running is to introduce the concept of a lock. Fortunately, it was _much_ easier than we think to implement, thanks to a [Stack Exchange answer](https://unix.stackexchange.com/a/398710) by [Sethu](https://unix.stackexchange.com/users/256053/sethu). 🥳

```bash
#!/bin/bash

# Check if another instance of this script is running
pidof -o %PPID -x $0 >/dev/null && echo "ERROR: Script $0 already running" && exit 1

# ... Rest of your script
```
<figcaption>Just add the <code>pidof</code> line at the top of your Bash script, and you'll be sure that only one instance of your script can be running at a time.</figcaption>

A powerful line, right? 😉
The NEW Manual Validation Task for Azure DevOps YAML Pipelines Demystified
Tags: azuredevops, pipelines, cicd, yaml
Published: 2021-07-01 23:04:13

With the newly released Manual Validation task you can pause a YAML pipeline mid-stage. This allows you to perform manual or offline activities and then resume (or reject) the run. 

### Intro

As I've mentioned, you can use this new task in a YAML pipeline to pause a run within a stage, typically to perform some manual actions or validations, and then resume/reject the run.

This is especially useful in scenarios where you want to pause a pipeline and validate configuration settings, build package, etc. before moving on to a long-running, compute-intensive job.

When the Manual validation task is activated during a pipeline, it displays a message bar containing a link that opens the Manual validation dialog containing the instructions. After carrying out the manual steps, the administrator or user can choose to resume the run or reject it.

### Demo

Let's see this in action. We will cover how to configure Azure Pipelines to use it and how to use it.

Here you have __the video with the whole demo and explanation__.

{% youtube sfb3d100JPo %}

[Link to the video: https://youtu.be/sfb3d100JPo](https://youtu.be/sfb3d100JPo)

### Limitations

Remember that, as I've mentioned in the video, you can use this new approach only in an agentless job of a YAML pipeline. If like in my example you have other jobs already, you would need to add a job with pool: server to make this work.

### Conclusions

I wanna know what you think about this feature, so let me know in the comment section below.

Also, check [this video over here](https://youtu.be/3cGtA__dKUc), where I talk about the differences between Classic and YAML pipelines for both Build and Release.

__Like, share and follow me__ 🚀 for more content:

📽 [YouTube](https://www.youtube.com/CoderDave)
☕ [Buy me a coffee](https://buymeacoffee.com/CoderDave)
💖 [Patreon](https://patreon.com/CoderDave)
🌐 [CoderDave.io Website](https://coderdave.io)
👕 [Merch](https://geni.us/cdmerch)
👦🏻 [Facebook page](https://www.facebook.com/CoderDaveYT)
🐱‍💻 [GitHub](https://github.com/n3wt0n)
👲🏻 [Twitter](https://www.twitter.com/davide.benvegnu)
👴🏻 [LinkedIn](https://www.linkedin.com/in/davidebenvegnu/)
🔉 [Podcast](https://geni.us/cdpodcast)

<a href="https://www.buymeacoffee.com/CoderDave" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" style="height: 30px !important; width: 108px !important;" ></a>

{% youtube sfb3d100JPo %}
Top 5 DEV Comments from the Past Week
Tags: bestofdev
Published: 2021-07-01 22:58:09

This is a weekly roundup of awesome DEV comments that you may have missed.  You are welcome and encouraged to boost posts and comments yourself using the **[#bestofdev](/t/bestofdev)** tag.

Starting off Top Comments with a movie quote on this post about [being a hipster in tech](https://dev.to/knajjars/learnings-after-5-years-of-being-a-hipster-in-tech-1b0n) is exactly what we needed this week, thanks @booyouon !
{% devcomment 1fmb7 %}

[Weekly Wins](https://dev.to/devteam/what-was-your-win-this-week-10c6) keep us going. Congrats, @cenacr007_harsh !
{% devcomment 1fl62 %}

Sometimes we all need to be explained things [like we're five](https://dev.to/peter/explain-a-memory-leak-like-i-m-five-2664). Thanks for the great walkthrough, @glsolaria !
{% devcomment 1fkk7 %}

[Stress during coding](https://dev.to/chetan_atrawalkar/how-to-avoid-stress-during-coding-56f1) can be a huge roadblock to a successful launch, day, or project. Meditiation really is a great way to help relieve the pain - good tip, @qwby !
{% devcomment 1fn2p %}

@jonsilver really adds to this post on [things to master before working with React.js](https://dev.to/mayank0508/things-you-should-master-before-you-jump-on-react-js-4d1a)! Thanks for the comment!
{% devcomment 1fm8b %}


See you next week for more great comments ✌
First VueJS Project -  Domains For Developers
Tags: vue, javascript, showdev, webdev
Published: 2021-07-01 22:53:46

I came across **“domaining”**, or **“domain flipping”** by accident. I had an idea for an NFT platform (a little late to the party I know, but whatever), so I went to GoDaddy to buy a domain name. I found one I liked, and only $12.00 to register - great! But, I wasn’t sure if it was right, so I hesitated - wrong move! An hour later, not only had someone bought it, but they were now reselling it for $10,000. **Yes $10,000! WTF!!!!** 

So I looked into this, and found people making a living buying domains and selling them for a profit. Who knew!??? So I bought some of my own, and guess what - they sold! Granted, for a couple hundred, rather than thousands of dollars, but still I was pleased. So I scrubbed the NFT idea (probably for the best), and built a site to sell my domains. 

Ladies and Gentlemen, I give you [DiscountDom.com](https://discountdom.com/) -  my first project built with Vue JS, which I’m really enjoying. Plan on doing more to it, but I'd love to know your thoughts on how it's turned-out.

Also please checkout out the domain names - some might work for your projects. I’m very open to offers, (low ones are fine). Currently featured (discounted even more), “Domains for Developers” - naturally!

Thanks
Day 400 : Go hard
Tags: hiphop, code, coding, lifelongdev
Published: 2021-07-01 21:53:11

_liner notes_:
- Professional : Knocking out these tickets again today. Got a few set to done. Just have one more and it's writing a blog post about the stuff I've been working on. For some reason, blog posts are the most difficult thing for me. haha Time to go hard and finish the week strong!

- Personal : Went through a bunch of tracks for the radio show. I also caught up on 'Loki'. It's a really good show. Looking forward to the next episode. As for the side project, I looked into a library I'm looking to use for the videos.

![Looking at a very tall snow covered mountain surrounded by clouds with a pine tree forest at the base in Zermatt, Switzerland](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/28wgwn6obckatb2kpef6.jpg)

Going to go through some more tracks for the radio show. Then I want to start coding up part of the side project where I will let the user know that there highlight video is ready and a link to post to Twitter. That's going to require some other stuff though. We'll see.

Have a great night!

peace piece
Dwane / conshus
https://dwane.io / https://HIPHOPandCODE.com
{% youtube UmoCQ2D_hFE %}
Combining an Array into a String Using the join Method
Tags: javascript, devops, beginners, programming
Published: 2021-07-01 21:32:09

* The `join` method is used to join the elements of an array together to create a string. It takes an argument for the delimiter that is used to separate the array elements in the string.

* Example:
```
let arr = ["Playstation", "Rules"];
let str = arr.join(" ");
```
* `str` would have a value of the string `Playstation Rules`.

* Let's use the `join` method inside the `word` function to make a sentence from the words in the string `str`. The function should return a string.
```
function sentence(str) {
  // Only change code below this line


  // Only change code above this line
}
sentence("This-is-where-the-fun-begins");
```
* Answer:
```
function sentence(str) {
return str.split(/\W/).join(" ")

}
console.log(sentence("This-is-where-the-fun-begins")); will return This is where the fun begins
```
Split a String into an Array Using the split Method
Tags: javascript, devops, programming, beginners
Published: 2021-07-01 21:22:11

* The `split` method splits a string into an array of strings. It takes an argument for the delimiter, which can be a character to use to break up the string or a regular expression. For example, if the delimiter is a space, you get an array of words, and if the delimiter is an empty string, you get an array of each character in the string.

* Ex: Here we use split one string by spaces, then another by digits using a regular expression:
```
let str = "Hello Alan";
let byWords = str.split(" ");

let otherString = "=Wanna9play7rocket2league";
let byDigits = otherString.split(/\d/);

// byWords would have the value ["Hello", "Alan"]
// byDigits would have the value ["Wanna", "play", "rocket", "league"]
```
* Now let's use the `split` method inside the `splitify` function to split `str` into an array of words. The function should return the array. Note that the words are not always separated by spaces, and the array should not contain punctuation.
```
function splitify(str) {
  // Only change code below this line


  // Only change code above this line
}
splitify("Hello World,I-am code");
```
* A simple regular expression can be used to achieve this result.
* `/\W/` Matches any non-word character. This includes spaces and punctuation, but not underscores. It’s equivalent to `/[^A-Za-z0-9_]/`

* Answer:
```
function splitify(str) {
return str.split(/\W/)

}
console.log(splitify("Hello Randy, I-am playing video games"));
// would return ["Hello", "Randy", "I", "am", "playing", "video", "games"]
```

Larson, Quincy, editor. “Split a String into an Array Using the split Method.” https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/functional-programming/split-a-string-into-an-array-using-the-split-method, Class Central, 2014, twitter.com/ossia.