teleren/devto huggingface dataset:
When to use Microservices?
Tags: devops, distributedsystems, beginners
Published: 2022-12-03 12:26:09

Microservices are a software architecture design pattern in which a large application is built as a collection of small, independent services that communicate with each other over well-defined interfaces, typically using APIs. This approach to software development has become increasingly popular in recent years because it offers several key benefits over traditional, monolithic architecture.

![Microservices vs Monolith](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3p3h0axxewo6n70ew1k6.png)

## Advantages

One of the main advantages of microservices is that they are modular and highly scalable. Because each microservice is a separate and independent component, it can be developed, tested, and deployed independently of the other services. This allows for a high degree of flexibility and agility, making it easier to add new features, make changes, and deploy updates.

Another benefit of microservices is that they are resilient and fault-tolerant. If one microservice fails, it can be restarted or replaced without affecting the overall functionality of the application. This makes it easier to manage and maintain large, complex applications.

## Challenges

One of the main challenges of using microservices is that they require a high degree of coordination and communication between the different services. Each service must be carefully designed and implemented to ensure that it can communicate with the other services in the application, and that it adheres to the overall architecture of the application. This can require a significant amount of planning and design work upfront.

In addition, microservices can be complex to manage and maintain, especially in large applications with many different services. Since each service is independent, it must be managed and deployed independently of the others, which can require a significant amount of infrastructure and tooling.

## Verdict: for complex applications with large team

In general, microservices are a good choice for applications that require a large team and expected to grow and evolve over time, and for applications that require a high degree of scalability and resilience.

---

<sup>Cover Image by Kristijan Arsov</sup>
Rust: Using DateTime in Diesel with MySQL
Tags: rust, mysql, beginners
Published: 2022-12-03 12:23:16

### Problem:

When I tried to map the model with date and time field, I got this compiler error:

```
error[E0277]: the trait bound `(Integer, Datetime): 
load_dsl::private::CompatibleType<myapp::models::MyModel, _>` 
is not satisfied
```

From this set of model and schema:

```rs
// models.rs
pub struct MyModel {
    pub id: i32,
    pub created_at: NaiveDateTime,
}
```

```rs
// schema.rs
diesel::table! {
    my_table (id) {
        id -> Integer,
        created_at -> Datetime,
    }
}
```

### Solution:

Fortunately, I found the document mentioned about the [DateTime field](https://docs.diesel.rs/diesel/mysql/types/struct.Datetime.html). 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e9al1tbrpwnb783buqup.png)



So we just need to put the feature `"chrono"` to enable it.

```toml
# Cargo.toml
diesel = { version = "2.0.0", features = ["mysql", "chrono"] }
```

And it works! ✅ 🎉

### Tips:

For [JSON field](https://docs.rs/diesel/2.0.2/diesel/sql_types/struct.Json.html), you will also need the `serde_json` feature in Cargo.toml.

```toml
diesel = { version = "2.0.0", features = ["mysql", "chrono", "serde_json"] }
```
How to Install Apache Web Server on Amazon Linux 2
Tags: aws, ec2, amazonlinux2, apache
Published: 2022-12-03 12:15:52

## Introduction

In this tutorial, we will learn how to install Apache web server on Amazon Linux 2. We will also learn how to configure Apache web server to run simple HTML web page.

## Prerequisites

To follow this tutorial, you will need:

- An Amazon Linux 2 EC2 instance.
- A user with sudo privileges.

## Install Apache Web Server and run simple HTML web page

### Step 1: Install Apache Web Server

Before we start, we need to update the package list and upgrade the installed packages:

```bash
sudo yum update -y
```

Now, we can install Apache web server:

```bash
sudo yum install httpd -y
```

### Step 2: Start Apache Web Server

Now, we can start Apache web server:

- Start Apache Server

```bash
sudo systemctl start httpd
```

- Configure Apache to run on system boot

```bash
sudo systemctl enable httpd
```

### Step 3: Configure Firewall

Now, we need to configure the firewall to allow HTTP traffic:

```bash
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --reload
```

### Step 4: Create a Simple HTML Web Page

Before we can test Apache web server, we need to change the permissions of the `/var/www/html` directory:

```bash
sudo chmod 777 /var/www/html
```

Now, we can create a simple HTML web page:

```bash
sudo vi /var/www/html/index.html
```

```html
<!DOCTYPE html>
<html>
  <head>
    <title>Apache Web Server</title>
  </head>
  <body>
    <h1>Apache Web Server</h1>
    <p>This is a simple HTML web page.</p>
  </body>
</html>
```

### Step 5: Test Apache Web Server

Now, we can test Apache web server by opening the public IP address of our Amazon Linux 2 EC2 instance in a web browser:


![Apache Web Server](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jj8s2cqt1o0a8c9c6fdv.png)

## Conclusion

In this tutorial, we learned how to install Apache web server on Amazon Linux 2. We also learned how to configure Apache web server to run simple HTML web page.

## References

- [How to Install and Setup FireWall on Amazon Linux 2](/blog/post/how-to-install-and-setup-firewall-on-amazon-linux-2)
- [Install a web server on your EC2 instance](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_Tutorials.WebServerDB.CreateWebServer.html)
- [AWS - Amazon Linux 2 AMI](https://aws.amazon.com/amazon-linux-2/)
Build a Rest API with Django
Tags: python, django, api, pythonapi
Published: 2022-12-03 11:35:55

- Install **Django** using command `pip install django`
- Create a project using command `django-admin startproject <projectname>`

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8uhcezvnk0bes0phijc3.png)

- Move to your project directory like mine is **api**
- Now, it's time to create an app. We can have multiple apps in single project
- The command is `python manage.py startapp Bookapi`

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ssoigm3gg3825pv1b35a.png)

- **Don't forget to write your app name under installed_apps in settings.py file of your project folder**
- Now go to BookApi directory and there click models.py

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g98pek06asioxmgdnlrj.png)

**Model is actually convert your python code to the database which you are using**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ihuvg3kxk4yf6kdsojez.png)

- Now, go to views.py file under BookAPI directory
**Views are used to create and retrieve data from an end point**


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kpkev2bwkq1svh1dk7o6.png)




- Now, create a file urls and copy the code from urls file of your project Folder and paste in the urls file of your application

**Urls are used to create endpoints and call views to send and receive data**


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hscrj84ihdwzbxj0mh1z.png)

- Now, go to urls of your project

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n2ai9z3q1rlv1opx41zg.png)

- Now create migrations using command 
`python manage.py makemigrations`
- Now migrate 
`python manage.py migrate`

Now, run 
`Python manage.py runserver`
Lighthouse Score for Pages behind Authentication with Selenium
Tags: webdev, performance, selenium, lighthouse
Published: 2022-12-03 11:33:28

Default runs of [Lighthouse](https://github.com/GoogleChrome/lighthouse) load a page as a "new user". It needs someone to prepare the pages that are behind authentication to analyze the performance.

The Lighthouse team provides [a way](https://github.com/GoogleChrome/lighthouse/blob/main/docs/puppeteer.md) to achieve this via puppeteer. However, this article explains how it can be achieved with [Selenium](https://www.selenium.dev/).

> The main idea is to create a **WebDriver instance with a remote-debugging-port** and then make Lighthouse target the same port to measure the performance

## How to?

* Initialize a driver with remote-debugging-port and keep it alive.

```python
from selenium import webdriver
from selenium.webdriver.edge.options import Options
from webdriver_manager.microsoft import EdgeChromiumDriverManager
from selenium.webdriver.edge.service import Service as EdgeService

edge_options = Options()
edge_options.add_experimental_option('detach', True)
edge_options.add_argument('--remote-debugging-port=9000')

driver = webdriver.Edge(service=EdgeService(
    EdgeChromiumDriverManager().install()), options=edge_options)
```

* Now use selenium to login to your website. For this article, facebook is taken as an example. 

```python
driver.get('https://www.facebook.com')

emailInput = driver.find_element(By.XPATH, '//input[@id="email"]')
passInput = driver.find_element(By.XPATH, '//input[@id="pass"]')

email = os.getenv('email')
password = os.getenv('password')

emailInput.send_keys(email)
passInput.send_keys(password)

submitButton = driver.find_element(
    By.XPATH, '//button[@type="submit" and @name="login"]')

submitButton.click()
```

![Login](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mi3ietysfbhatwlqltph.gif)

* Now all pages behind authentication should work with Lighthouse. The catch here is the `port`. It targets the **same port** in which the WebDriver was exposed with Selenium. 

```bash
lighthouse "https://www.facebook.com" 
--port=9000 
--preset=desktop 
--output-path='./report.html' 
--view
```

![Lighthouse](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/81qq909fl6rm7tpap2ox.gif)

### Code:
1. [The script used](https://gist.github.com/vishnuvardhan-s/f7e77c74cc42549670e04b08e8628ad9)

### References:
1. [Lighthouse Documentation](https://github.com/GoogleChrome/lighthouse/blob/main/docs/authenticated-pages.md)
How to use UUID in Django
Tags: django, python, argsandkwargs, webdev
Published: 2022-12-03 11:27:30

UUID(Universal Unique Identifier) is a Python library that generates random objects of 128 bits. It is a standard built-in Python library which means you don’t need to install anything. There are three main algorithms used for generating randoms:

Using IEEE 802 MAC addresses as a source of uniqueness
Using pseudo-random numbers
Using well-known strings combined with cryptographic hashing
The UUID uses getnode() to retrieve the MAC value on a given system:

```
import uuid
print(uuid.getnode())
251053329979042
```


First, let’s look at how we can use UUID in general:

```
import uuidp
print(uuid.uuid4())
cae6f5a3-377d-4eaa-8d27-3ff12aece93e
```
UUID usage in Django
Now, let’s look at using UUID usage in Django.

It is commonly used to replace the Django id field. By default, Django gives each model auto-incrementing primary key field:

`id = models.AutoField(primary_key=True)`

if you want to explicitly set the primary key you must specify primary_key=True then Django won’t add this field automatically because it detects that you set it manually.

Now let’s look real example. Assume that you have a Subscription Model

```
class Subscription (models.Model):
name = models.CharField(verbose_name=_("Subcription Name"),
                        help_text=_("Required and unique"),
                        max_length=255,
                        unique=True,
)
cdate = models.DateTimeField(auto_now_add=True)
udate = models.DateTimeField(auto_now=True)
```
In general when we access this model’s detail like below:

`https://domain.com/subcriptions/1`

In the frontend, users can access other’s data by replacing 1 to 2,3,4, etc. We can call it a simple Security leak. For in these cases we can replace the id field with UUID.

```
class Subscription (models.Model):
id = models.UUIDField(primary_key=True,
                      default=uuid.uuid4,
                      editable=False)
                      name = models.CharField(
                      verbose_name=_("Subcription Name"),
                      help_text=_("Required and unique"),
                      max_length=255,
                      unique=True,
                      )
cdate = models.DateTimeField(auto_now_add=True)
udate = models.DateTimeField(auto_now=True)
```
As we showed above UUID generates random and it is not predictable.

> Thanks for reading. I hope you enjoyed it ❤.
> The post first appeared in [my blog](https://sevdimali.medium.com/)
> Keep Learning..!
Create-react-app and apt freezes + script to enable/disable IPv6
Tags: ipv6, react, wireguard, apt
Published: 2022-12-03 11:27:23

Sometimes `npx create-react-app` just freezes and does not work at all:

```
$ npx create-react-app myapp
^C
```

Same problem I had with APT on my debian virtual machine inside LXC/LXD container - it just freezes and not working.

In my case, this is because I use Wireguard VPN and tunnel IPv4, but not IPv6. Yes, right way would be to forward IPv6 over VPN too, but I'm too lazy.

one-line fix:
```
sudo sysctl net.ipv6.conf.all.disable_ipv6=1
```

Optionally, you may put this to /etc/sysctl.conf:
```
net.ipv6.conf.all.disable_ipv6 = 1
net.ipv6.conf.default.disable_ipv6 = 1
```

But if you need to toggle IPv6 on/off often, here is simple script, put it to /usr/local/bin/ipv6:

```bash
#!/bin/bash

case $1 in
	yes | on)
		echo enable IPv6
		sudo sysctl net.ipv6.conf.all.disable_ipv6=0
		;;
	no | off)
		echo disable IPv6
		sudo sysctl net.ipv6.conf.all.disable_ipv6=1
		;;
	*)
		echo on/off?
		if [ `/usr/sbin/sysctl net.ipv6.conf.all.disable_ipv6	| cut -f 2 -d= | tr -d " "` == "0" ]
		then
			echo IPv6 is enabled now
		else
			echo IPv6 is disabled now
		fi
		;;
esac

```
chmod +x it and....
```shell
$ ipv6 on
enable IPv6
net.ipv6.conf.all.disable_ipv6 = 0

$ ipv6 off
disable IPv6
net.ipv6.conf.all.disable_ipv6 = 1
```
Codecademy Intro to IT Project
Published: 2022-12-03 04:06:03

This is my Project for the Intro to IT course from codecademy.com. No cool background for me, taking a few courses for fun. So... here it is.


#Part 1: Plan and write algorithm# 


    1. Create a variable called “text” (text=””), enter the value of “text” (test=”2022 world cup standings”)
    2. Create a variable called “pattern” (pattern=””), enter the value of “pattern” (pattern=” world cup”)
    3. Create “match_count” variable, set the value to 0
    4. Has the text value been searched?
                    ◦ If no, go to step 5	
                    ◦ If yes, skip to step 7
    5. Iterate to the next word in “text”
    6. Is the value of “text” and “pattern” equal?
                    ◦ If yes, go to step 7
                    ◦ If no, return to step 5
    7. If “match_count” is equal to the length of pattern, then pattern found.
       If not, pattern not found.


#Part 2: Create a flowchart#


![Project Flowchart](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mow201o93p6pvdz5pxax.png)



#Part 3: Test the Chart#

    1. text = "ERROR: Invalid function arguments"; pattern = "ERROR"
    2. text = "ERROR: Out of memory"; pattern = "network"
    3. text = "ERROR: The file is write-protected"; pattern = "protected" Solution: I will conduct an analysis inputs to make sure it works as expected.



#Part 4: Produce the Pseudocode# 

Define “text” (text=”?”) 
Define “pattern” (pattern=”?”)
If entire pattern hasn’t been searched: 
	Move on to next character of the text
	Create “match_count” set to 0
	If entire pattern hasn’t been searched:
		if this character from the pattern is equal to the character from text:
			increment match_count variable by 1
	if match_count is equal to the length of the pattern:
	pattern found
	otherwise:
	no pattern found

#Conclusion#


This is the end of my first Software Development Concepts project from Codecademy. Honestly, I’d like to give a shout out to dev.to user Liudmyla, I appreciate the work that was done in this project. It shed a ton of light for me and was as great help. So, thanks to you Liudmyla for your work! Great Job! If anyone sees this and wants to see a better looking project here’s the link to Liudmyla’s project.
 
[Liudmyla’s project](https://dev.to/liudmyla/codecademy-project-1-software-development-concepts-37l5)
Binary, Octal and Hexadecimal Values in Python
Published: 2022-12-03 11:18:53

Converting a decimal number to its binary, octal or hexadecimal value is easier than it looks. A simple way to do this is using the ``bin``, ``oct`` and ``hex`` functions directly:

```py
n = 97

print(bin(n))
print(oct(n))
print(hex(n))
```

Result:

```py
0b1100001
0o141
0x61
```

Note that we have two digits of standardization at the beginning of the results, to solve this, we can slice it as follows:

```py
n = 97

print(bin(n)[2:])
print(oct(n)[2:])
print(hex(n)[2:])
```

Result:

```py
1100001
141
61
```
How to add a condition in SQL with GROUP BY
Tags: sql, beginners
Published: 2022-12-03 11:10:55

To add a condition to a `GROUP BY` clause in SQL, you can use the `HAVING` keyword. The `HAVING` keyword is used to specify a condition that must be met by the grouped records. 

```
SELECT statements... GROUP BY column_name1[,column_name2,...] [HAVING condition];
```

For example, the following query uses the `HAVING` keyword to only include groups that have a count greater than 1:

```
SELECT column1, COUNT(*)
FROM table
GROUP BY column1
HAVING COUNT(*) > 1;
```

This query will group the records in the table by the values in column1 and only include groups that have more than one record. The `HAVING` clause is typically used together with an aggregate function, such as `COUNT` or `SUM`, to check for a condition on the values that are being grouped.

It's important to note that the `HAVING` clause is used after the `GROUP BY` clause and it operates on the grouped records, whereas the `WHERE` clause is used before the `GROUP BY` clause and it operates on the individual records before they are grouped.

Overall, the `HAVING` keyword is a useful tool for adding conditions to `GROUP BY` clauses in SQL.
Shuffling and Sorting in Python
Tags: python, beginners, tutorial
Published: 2022-12-03 11:10:13

Shuffling can be an interesting function in a program, even more if we want to ensure more randomness in a set of data that will be chosen.

We'll import the ``random`` library and create a list of integers to use in our example.

```py
import random
list = [10,20,30,40,50]
```

And finally, to shuffle the list, we'll use the ``shuffle`` method. If we print the list, we can see the shuffled elements.

```py
random.shuffle(list)
print(list)
```

Result example:

```py
[50, 40, 20, 10, 30]
```

And to make a random choice, we use the ``choice`` method.

```py
x = random.choice(list)
print(x)
```

Result example:
```py
30
```
Izyum goes live 🔴
Tags: opensource
Published: 2022-12-03 01:43:47

This week my task was finally to put izyum live and make it available for everybody. Considering the fact that I was using typescript for it's development I pushed it to the npm packages registry. It was a first time experience for me to push some tool to npm registry and I am about to say how it was.

## Code preparation
The first thing I wanted to make sure that my `package.json` file has everything it needs. I added several things like email to the `author` field, also I had to move some packages to the user dependencies because they were needed in the run-time. 

## Continuous Delivery 
After that I created the github action which I called `cd` and it was doing surprise surprise - **Continues Delivery**. This action is triggered when I add the new tag to the main branch and it builds the app and pushes it to the npm registry. Action source looked like this:
```
name: cd

on:
  push:
    tags:
      - 'v**'

jobs:
  release:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v3
      - name: Create Release
        id: create_release
        uses: actions/create-release@v1
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        with:
          tag_name: ${{ github.ref }}
          release_name: ${{ github.ref }}
          draft: false
          prerelease: false
  publish:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Setup .npmrc file to publish to npm
        uses: actions/setup-node@v1
        with:
          node-version: '16.x'
          registry-url: 'https://registry.npmjs.org'
      - name: Install modules
        run: npm install
      - name: Build
        run: npm run build
      - name: Publish to npm
        run: npm publish --access public
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
```
To be honest, nothing makes me more exited and inspired about software development as development automatisations. I just feels like magic every time 🪄

## Versioning 
NPM has pretty decent pre-built functionality for versioning your package, so I just used it to version my app. I created several **minor** and **patch** releases and when I was sure that everything works as expected I created the new **major** version which was `1.0.0`. 

## How to get Izyum
Izyum is now available in npm and you can download it to your project but just a simple and well-known command 
`npm install izyum -g`
Removing all vowels with JavaScript
Tags: javascript, webdev, beginners
Published: 2022-12-03 11:08:52

Today we'll look at a nifty solution to remove all vowels in a string using JavaScript.

The idea is that we get a string and have to return the string without the letters `aeiou`.

## JavaScript remove all vowels

Let's dive right into the solution.

```js
const input = 'daily dev tips';

const removeVowels = input.replace(/[aeiou]/gi, '');

console.log(removeVowels);

// 'dly dv tps'
```

It works!
And yep that's all the code we need, but let's take a closer look at how it works.

The first part is to use the JavaScript replace function to replace a specific match.
The first part is the match, for which we'll use a regular expression. And the second part is the replacement.

We could, say, replace the letter `i` with an empty string like this.

```js
const removeVowels = input.replace('i', '');

console.log(removeVowels);

// 'daly dev tips'
```

However, you'll notice it only replaced the first occurrence. And, of course, we can only target one letter at a time.
So this is where our regular expression comes in.

We start the regular expression by wrapping it in the `/ /` backslashes.
Then we open a pattern matcher with the `[]` brackets. And in between, we specify which letters should be matched.
The last part is to use `gi` at the end, which stands for `global ignore`.

- `global` meaning to apply it to each occurrence, not just the first one
- `ignore` means to perform a case-insensitive search

And that's it. I hope you learned something about removing vowels with JavaScript.

### Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on [Facebook](https://www.facebook.com/DailyDevTipsBlog) or [Twitter](https://twitter.com/DailyDevTips1)