teleren/devto huggingface dataset:
JUnit: Cómo ejecutar un test N iteraciones
Tags: spring, java, spanish, testing
Published: 2022-11-10 08:00:00

En ciertas ocasiones puede que **necesitemos ejecutar un test N veces** para poder asegurar su correcto funcionamiento.

Para ello, contamos con varias fórmulas. En primer lugar, vamos a considerar el siguiente escenario:

- Queremos testear un método que nos genera un número aleatorio de N dígitos. El valora de N se pasa como parámetro a dicho método.
- Creamos una clase de test de jUnit en la que declaramos el número de repeticiones o iteraciones que queremos ejecutar un determinado test.

```java
private static final int NUMBER_REPETITIONS = 1_000_000;
```
- Creamos los tests para validar la funcionalidad del método. En este ejemplo, he creado un test mediante la anotación de jUnit `@RepeatedTest` y otro test simple en el que realizamos toda la lógica dentro de un bucle do-while.

**Test A**: utilizando la anotación `@RepeatedTest`.

```java
import org.junit.jupiter.api.RepeatedTest;

@RepeatedTest(value = NUMBER_REPETITIONS)
void random_number_with_four_digits() {

    var low = 1000;
    var high = 9999;
    var numOfDigits = 4;
    var actual = RandomUtil.generateNumber(numOfDigits);
    assertTrue(high >= actual, "Error, random is too high");
    assertTrue(low <= actual, "Error, actual is too low");
}
```

**Test B**: utilizando el bucle do-while.

```java
@Test
void random_numbers_generator() {

    int iterationCount = 1;
    do {
        var low = 1000;
        var high = 9999;
        var numOfDigits = 4;
        var actual = RandomUtil.generateNumber(numOfDigits);
        assertTrue(high >= actual, "Error, random is too high");
        assertTrue(low <= actual, "Error, actual is too low");
        iterationCount++;
    } while (iterationCount <= NUMBER_REPETITIONS);
}
```

Como podemos ver **ambos tests afirman lo mismo**, que el método generador de números aleatorios va a devolver un valor que se encuentra entre low y high.
En ambos casos el test se va a ejecutar tantas veces como indiquemos en la constante `NUMBER_REPETITIONS`.

Una vez contamos con este escenario, **podemos realizar distintas pruebas** alterando el valor de `low`, `high`, `numOfDigits` y `NUMBER_REPETITIONS`.

En esta ocasión quería calcular la **diferencia de los tiempos de ejecución** de cada tipos de test, y estas son las pruebas que he realizado:

| Nº Iteraciones | Test A (@RepeatedTest) | Test B (do-while) |
| -------------- | ---------------------- | ----------------- |
| 1_000          | 130 ms                 | 13 ms             |
| 100_000        | 2600 ms                | 20 ms             |
| 1_000_000      | *Indeterminado*        | 55 ms             |

En este ejemplo, los tests ejecutados **mediante el bucle do-while han sido aproximadamente un 90% más rápidos** que los ejecutados mediante la anotación `@RepeatedTest`, además de que para el caso de 1_000_000 iteraciones, no he podido obtener un resultado final ya que la aplicación se quedaba colgada.
Discriminated Unions Without Common Properties
Tags: typescript, programming, tutorial, react
Published: 2022-11-10 07:52:37

If you have two or more types without any common properties (ie., they're mutually exclusive), you can't create a discriminated union with them:

```ts

type Props = { a: boolean } | { b: string }

const obj1: Props = { a: true } // ✅ valid
const obj2: Props = { b: "hello" } // ✅ valid
const obj3: Props = { a: true, b: "hello" } // ✅ valid, but we'd like this to be an error, ie., you can either include a or b, but not both

```
[TS Playground](https://www.typescriptlang.org/play?#code/C4TwDgpgBACgTgezAZygXigbygQwFxQBGCCANhDgHZQC+UAPlkQcsHAJaUDmtAULwGMElVlASEAVgEYC8JKgzZ8UNgFdodAPSaogUHIoANxyl2AE0HDR4iQCZZiFOiaECAIgAWEUqQSvaUbT1DYzMLEWAxSQBme3knJQI1CAAaZigPLx8-LR19IxNTVMJVCIB3CAByUygTAGtoYHd2VGAEImgqKAg4RDhU9ggAOlSQBFUoAU6IdkbuqE4BUlVTDrE4IiKSqEoECOJGoA)

## Solution
If you are dealing with two types, then you can use a custom XOR type ([source](https://stackoverflow.com/a/53229567)):

```ts

type Without<T, U> = { [P in Exclude<keyof T, keyof U>]?: never };
type XOR<T, U> = (T | U) extends object ? (Without<T, U> & U) | (Without<U, T> & T) : T | U;

// USAGE

type Props = XOR<{ a: boolean }, { b: string }>

const obj1: Props = { a: true } // ✅ valid
const obj2: Props = { b: "hello" } // ✅ valid
const obj3: Props = { a: true, b: "hello" } // ❌ error

```

[TS Playground](https://www.typescriptlang.org/play?#code/C4TwDgpgBA6glsAFgewK7ADwBUA0UCqAfFALxQDeUA2gApRwB2UAogB4DGANqgCYQYBrCCGQAzKLihCR4ogF0A-AC4oDCADcIAJygBfANwAoUJCgANAPIAlbHiKkoACixQAPgQCUUCK2AQGPADOUMgARgBWEOzAUApO8EhomJL2AGSebvEIKOgY+HhYxOlYXiou7vhGhgD01QQAygCCAOLMhsbg0DRayGDBZJY2lACGKqHIyJwQw0y6eJShKoHAWowA5nqE7ezIDMshEQCMKt29-RRQo1ArqNC6ULVQgKDkUOrDnHA8hjt7MWHhACYTj0+g4FioAESICCcTjICF6B51F5vD5fH77f4AZmBZzBlxUNwgeEWUChMLhCPuj0AMuTeLQ9LRAA)

You can alternatively use the [ts-xor](https://www.npmjs.com/package/ts-xor) package to do exactly that.

If you have more than two types, you can nest XOR operators, like this:
```ts

type Props = XOR<{ c: number }, XOR<{ a: boolean }, { b: string }>>

```
[TS Playground](https://www.typescriptlang.org/play?#code/C4TwDgpgBA6glsAFgewK7ADwBUA0UCqAfFALxQDeUA2gApRwB2UAogB4DGANqgCYQYBrCCGQAzKLihCR4ogF0A-AC4oDCADcIAJygBfANwAoUJCgANAPIAlbHiKkoACixQAPgQCUUCK2AQGPADOUMgARgBWEOzAUApO8EhomJL2AGSebvEIKOgY+HhYxOlYXiou7vhGhgD01QQAygCCAOLMhsbg0DRayGDBZJY2lOwqDKgAtqHaeniDGJQAhiqhyMicEAtMuniUoSqBwFqMAOZ6hITt7MgMByERAIwq3b39FFBLUIeo0LpQtVCAUHIoOoFpw4DxDFcbjEwuEAExPHp9By7FQAIkQEE4nGQaL0fzqQJBYIhUNusIAzIiXiioCMoAAWOH4-5E0HgyHXckRBnU5FkRYqL4QPB7KAYrE4vG-f6AGXJvFoelogA)

The drawback with this XOR type is that the errors shown are cryptic, so perhaps avoid this if you're creating types for a library.
Docker Certified Associate Exam containerized packages
Published: 2022-11-10 05:32:27

[Docker Certified Associate Exam](https://dumpsarena.com/docker-certification/docker-certified-associate/) Install, hold, and run the Docker platform This could come up with understanding into the internals of Docker. Triage difficulty reviews from companions and remedy. Stand Up new Docker conditions and carry out popular configuration and renovation. Relocate standard packages to bins. This could allow you to expect a key element in transferring current packages as docker containerized packages. Design and troubleshoot Docker platform You get the possibility [Docker Certified Associate Exam](https://dumpsarena.com/docker-certification/docker-certified-associate/) to do a profound soar and analyze standards associated with the subsequent: Networking Volumes and Storage Installation and Configuration Orchestration Image Creation, Management, and Registry Security You Improve as a Developer, a Cloud-Local App Developer Docker field as an innovation modified the factor of software program conveyance. Gone are the times while we used to accumulate an utility through using Java which calls for the help of JVM field. Welcome to the universe of Docker Containers! 

Get 25% Special Discount ……..>>>>>>>>> https://dumpsarena.com/docker-certification/docker-certified-associate/
How does the grocery Delivery app is beneficial for grocery stores?
Tags: grocerydeliveryscript, onlinegrocerydelivery, businessstartup, entreprene
Published: 2022-11-10 07:46:26


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

The digital market grew in different sectors from clothes shopping to grocery shopping only. The Grocery Delivery Business has seen tremendous expansion in the last 3-4 years. 

There are several startups, SMEs, and companies that are supporting the Online Grocery Business. 

Mostly they are evolving characteristic-rich grocery mobile applications. You can have this doubt about how you can keep up with online grocery stores.

The current covid-19 pandemic has played motivated an increasing market for these services. 

Retail healthcare, production, or management in every sector wants to improve the online shopping experience by delivering better consumer services. 

Some of the leading grocery apps available in the global market are Amazon Fresh, Peapod, Big Basket, etc. 

These services are becoming more and more widespread as it is keeping the time and measure of the people by supplying them with a comfortable facility.

The grocery app with user-friendly service and the most suitable features will guide you to increase your business and sales. Online grocery shopping will just fit with today’s system and allow you to resist the challenges.
1047. Leetcode Solution in cpp
Tags: cpp
Published: 2022-11-10 07:33:18

```cpp
class Solution {
 public:
  string removeDuplicates(const string& S) {
    string ans;

    for (const char c : S)
      if (!ans.empty() && ans.back() == c)
        ans.pop_back();
      else
        ans.push_back(c);

    return ans;
  }
};
```
#leetcode
#challenge
Here is the link for the problem:
https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/
Video Production Company in Delhi
Tags: videoproduction
Published: 2022-11-10 07:32:31

A creative [film production house in Delhi](https://3sstudio.in/video-production-service/), 3S Studio is prospering on brilliance and creativity. If you want to impress and engage with your audience, the best medium to insert your idea deep into the hearts of the people is brilliantly filmed, videos and short films.
PHP: FPM | FastCGI | mod_php
Tags: webdev, beginners, programming, tutorial
Published: 2022-11-10 07:19:59

PHP, a widely spread scripting language mainly used for websites or more specifically backend web development. You might have heard these terms mentioned in the title of the post but if you are someone like me, then you probably don't fully understand these things.

So todays post will be more about the definitions, conceptual differences and pros/cons for one over the other.

Whenever I want to learn something new I follow some simple steps:

1. Understand the meaning/definition of the new term
2. Learn about the history
3. Learn with examples and/or learn with alternatives

So let's try to follow this approach.

## PHP

### Meaning/Definition
PHP, originally extracted from Personal Home Page Tools, now stands for PHP: Hypertext Preprocessor.


### History
Rasmus Lerdorf is the guy who created of PHP and Andi Gutmans and Zeev Suraski are the creators of the Zend Engine.
You can read an in detail [historical background on the wiki page](https://en.wikipedia.org/wiki/PHP#History) if you like but the interesting fact is PHP's first version was released way back in June 1995. Yes it's that old.

### Example Usage
PHP executes on the server, while on the hand JavaScript executes on the client.
PHP is mostly used for backend web development but it is also fully capable to make command line applications.

Now as you know that PHP runs on the server, you may ask what servers? how does a server know how to run PHP? And that's where the mod_php, fastCGI and FPM comes into picture.

First things first, let's understand a few terms.
- mod_php: Module PHP
- CGI: Common Gateway Interface
- FastCGI: Fast Common Gateway Interface
FastCGI is a binary protocol for interfacing interactive programs with a web server. It is a variation on the earlier Common Gateway Interface (CGI).
- FPM: FastCGI Process Manager

Ok so now you at least know the definitions of acronyms.

Today we will look into two different ways to run PHP on a server and there are two very well known backend servers used to run PHP [Apache](https://httpd.apache.org/) and [Nginx](https://www.nginx.com/).

So to run PHP on these servers there are two ways:
You can run PHP as a module in Apache server (mod_php) or you can run PHP as an independent process (PHP FPM) and configure the server to use the process to handle PHP files.

A simple google search ("php fpm vs mod_php") will give you a lot of good resources on how to configure these two and what are the benefits of one over the other but there are key differences I would like quickly share with you:

- PHP FPM is way faster then mod_php
mod_PHP locks out processes and disrupts the performance of a website

- HTTP 2 Support
If you want HTTP 2 support you should go with PHP FPM as mod_php does not support it.

A more detailed and in my opinion more accurate reading on this is a stackoverflow answer, [please read here if you are interested](https://serverfault.com/a/645765/468540).
C++ da 5-Dars
Tags: cpp, beginners, programming, tutorial
Published: 2022-11-10 06:41:39

# C++ Operatorlar

Assalomu alaykum bugun siz bilan operatorlar haqida gaplashib olamiz. Agar darsliklarni boshdan o'qib kelayotgan bo'lsangiz unda sizni tabriklashim mumkin chunki **C++** dasturlash tilini tushunib boshlayabsiz! Operatorlar o'zgaruvchilar va qiymatlar bo'yicha operatsiyalarni bajarish uchun ishlatiladi.

Quyidagi misolda biz ikkita qiymatni qo'shish  uchun  **+ ****operatordan** foydalanamiz:

```cpp
int x = 100 + 50;
```
`+` operator ko'pincha yuqoridagi misol kabi, birgalikda ikki qiymatlarni kiritish uchun ishlatiladi, u ham birga, bir o'zgarmaydigan va qiymat yoki o'zgaruvchilar va boshqa o'zgaruvchilar qo'shishingiz uchun foydalanish mumkin.

```cpp
int n1 = 100 + 50;        // 150 (100 + 50)
int n2 = n1 + 250;      // 400 (150 + 250)
int n3 = n2 + n2;     // 800 (400 + 400)
```

## C ++ operatorlarni quyidagi guruhlarga ajratadi:

- **Arifmetik** operatorlar
- **Tayinlash** operatorlari
- **Taqqoslash** operatorlari
- **Mantiqiy** operatorlar
- **Bitwise** operatorlar

> Operator -o'zgaruvchilar va qiymatlar bo'yicha operatsiyalarni bajarish uchun ishlatiladi.

### Arifmetik operatorlar

   Umumiy matematik operatsiyalarni bajarish uchun arifmetik operatorlar qo'llaniladi.



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


### Tayinlash Operatorlari

Belgilash operatorlari o'zgaruvchiga qiymatlarni belgilash uchun ishlatiladi. Quyidagi misol, biz foydalanish **tayinlash** operatori ( `=`qiymati tayinlash uchun) **10** a o'zgaruvchi deb nomlangan uchun **x** :

```cpp
int x = 10;
```
Tayinlash Operatorlari
Belgilash operatorlari o'zgaruvchiga qiymatlarni belgilash uchun ishlatiladi. Quyidagi misol, biz foydalanish tayinlash operatori ( =qiymati tayinlash uchun) 10 a o'zgaruvchi deb nomlangan uchun x :

int x = 10;

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


### Taqqoslash operatorlari

Ikki qiymatni taqqoslash uchun taqqoslash operatorlari ishlatiladi.

> **Izoh**: taqqoslashning qaytarilish qiymati to'g'ri (


` 1`
) yoki noto'g'ri ( `0`).

Quyidagi misolda 5 dan 3 kattaroqligini bilish uchun  operatordan  **( ) dan kattaroq** foydalanamiz `>`:

Barcha taqqoslash operatorlari ro'yxati:


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


## Mantiqiy operatorlar

O'zgaruvchilar yoki qiymatlar o'rtasidagi mantiqni aniqlash uchun mantiqiy operatorlar qo'llaniladi:




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


@dawroun
xmlrpc.client.Fault: <Fault 1: "<class 'rclpy._rclpy_pybind11.InvalidHandle'>:cannot use Destroyable because destruction was...
Tags: ros2, humble
Published: 2022-11-10 06:27:08

After sourcing `. /opt/ros/humble/setup.bash` and running `ros2 topic list`, I got the following error:

```
Traceback (most recent call last):
  File "/opt/ros/humble/bin/ros2", line 33, in <module>
    sys.exit(load_entry_point('ros2cli==0.18.3', 'console_scripts', 'ros2')())
  File "/opt/ros/humble/lib/python3.10/site-packages/ros2cli/cli.py", line 89, in main
    rc = extension.main(parser=parser, args=args)
  File "/opt/ros/humble/lib/python3.10/site-packages/ros2topic/command/topic.py", line 41, in main
    return extension.main(args=args)
  File "/opt/ros/humble/lib/python3.10/site-packages/ros2topic/verb/list.py", line 56, in main
    topic_names_and_types = get_topic_names_and_types(
  File "/opt/ros/humble/lib/python3.10/site-packages/ros2topic/api/__init__.py", line 41, in get_topic_names_and_types
    topic_names_and_types = node.get_topic_names_and_types()
  File "/usr/lib/python3.10/xmlrpc/client.py", line 1122, in __call__
    return self.__send(self.__name, args)
  File "/usr/lib/python3.10/xmlrpc/client.py", line 1464, in __request
    response = self.__transport.request(
  File "/usr/lib/python3.10/xmlrpc/client.py", line 1166, in request
    return self.single_request(host, handler, request_body, verbose)
  File "/usr/lib/python3.10/xmlrpc/client.py", line 1182, in single_request
    return self.parse_response(resp)
  File "/usr/lib/python3.10/xmlrpc/client.py", line 1354, in parse_response
    return u.close()
  File "/usr/lib/python3.10/xmlrpc/client.py", line 668, in close
    raise Fault(**self._stack[0])
xmlrpc.client.Fault: <Fault 1: "<class 'rclpy._rclpy_pybind11.InvalidHandle'>:cannot use Destroyable because destruction was requested">
```

This happens when some node unexpectedly crashed previously. Although `ros2 launch` and `ros2 run` commands still work, `ros2 topic list` doesn't work anymore.

## Solution
1. `ros2 daemon stop`
2. `ros2 daemon start`

This fixed the issue for me.
[Source](https://lightrun.com/answers/ros2-ros2cli-ros2-node-list-stops-working-after-unrelated-node-crashes)
Migrate your free Heroku dynos to Fly.io now!
Tags: heroku, flyio, deployment, migration
Published: 2022-11-10 06:07:02

So I had this blog website of mine hosted in Heroku. I was using one of their free dynos. Life was good. And then I get a mail from Heroku saying that:

> Reminder Upgrade now: Heroku free product plans end November 28th

I was also using their free Heroku Prostgres to store my blog entries. So I was least interested to migrate my *cool* blog from Heroku. I decided to upgrade my free dyno to a basic (paid) dyno. It was after all only 5$ per month. Wait, it was 5$ a month! That is no small amount for me. So I decided not to upgrade (tbh, I went ahead and put in my card details only to know that Indian banks have put a hold to recurring payments, so my card became invalid for Heroku subscription). 

Fortunately on September 27th PyCoder's Weekly [Issue #544](https://pycoders.com/issues/544) had an [article](https://testdriven.io/blog/heroku-alternatives/) about Heroku alternatives. It is from this article that I came to know about [Fly.io](https://fly.io/). 

Fly.io turned out to be cooler than I expected. This is what they say:
> If you can build it into a Dockerfile, we can run it. 

and more importantly:
> If you have a Heroku app you'd like to bring closer to your users, give the Fly [Turboku Launcher](https://fly.io/launch/heroku) a spin.

So guess what I did. I opened up [Turboku Launcher](https://fly.io/launch/heroku) and followed the steps mentioned there. It's only 3 simple steps. 
1. Connect to Heroku
2. Configure Heroku (choose app-name, location, heroku-app-name).
3. Launch on fly.io (On a click of button).

That's it. Fly.io takes care of all the other things. All I needed to do extra was to enter my card details for verification, which surprisingly worked here (stripe gateway).

Up and running :rocket:. My [blog website](https://tsadarsh.fly.dev/) was migrated in less than 5 minutes. Happy again!
Laravel 9 Send Mail Using Queue Example
Tags: laravel, laravel9, mail, queue
Published: 2022-11-10 05:30:00

In this article, we will see you laravel 9 send mail using a queue example, Many times we can see many processes take more time to load like bulk email sending, payment gateway processes, etc.

Whenever you are sending an email for verification then it loads time to send mail because it is services. If you don't want to wait for the user to send an email or other processes on loading server-side process then you can use the queue.

In laravel 9 send mail using a queue example we will set up the mailtrap for sending an email. 

Laravel queues provide a unified queueing API across a variety of different queue backends, such as Amazon SQS, Redis, or even a relational database.

So, let's see send mail using a queue in laravel 9.

How To Send Email Using a Queue In Laravel 9

```
Step 1: Install Laravel 9 Application For Send Mail Using Queue

Step 2: Create Mail Setup

Step 3: Configuration of Queue

Step 4: Create Queue Job

Step 5: Test Queue Job

Step 6: Run Laravel 9 Application
```
Caching
Tags: systems, systemdesign, caching, cache
Published: 2022-11-10 05:23:21

We have all heard about the cached memory that speeds up the performance of the system. This happens by reducing the latency which we have discussed earlier in the section — [latency and throughput](https://dev.to/pragyasapkota/latency-and-throughput-340h). Let’s take a real-life example of caching — imagine a supermarket in the basement of your house. You can have the access to the shop anytime you want but you still buy a week worth of groceries to save time. This is caching.

## Common scenario

If we visit a particular point of a system time and again, the use of a cache can help your data load faster. The required data is saved on memory rather than disk from where the response is so much faster while making the network requests. Most of the websites these days stay cached in the CDNs (Content Delivery networks). This activity has reduced the load on the back-end server of the websites.

You are familiar that every time you make a network request, your backend server must do some computationally intensive and time-consuming work. But with the use of caching, you can convert your previous look-up time from linear O(N) time to constant O(1) time. This does not only limit here but also when your server must make multiple network requests and API calls to compose the data that the requester receives later, the caching data leads to low latency because of the reduced number of network calls.

Caching is usually inserted on the client (browser storage), between the client and server, or on the server itself. It can occur at many levels or points including the hardware level.

## Stale Data Handling

The data caching does not limit itself to the read operations but also to write operations with some of the considerations.

I have listed some of those considerations below: -

- For write operations, you need to keep your cache and database in sync.

- Since there are more operations to perform and new considerations handling the un-synced stale data need to be analyzed continuously, the complexity might increase.

- Sometimes, a new design is needed to handle the syncing with even more considerations like sync method (synchronous/asynchronous), intervals, and so on.

- To keep the cached data up-to-date, data ‘eviction’ or turnover is done with the help of LIFO (Last In First Out), FIFO (First In First Out), LRU (Least Recently Used), and LFU (Least Frequently Used).

## Conclusion

Caching is best on its way when the data is static or rarely changing. Also, when the sources of change are single operations instead of user-generated operations. However, caching may not be efficient if the cache refreshes done in intervals stays away from the purpose and user experience of the application.

{% embed https://github.com/Pragya2056/System-Design-Concepts %}

**_I hope this article was helpful to you._**

**_Please don’t forget to follow me!!!_**

**_Any kind of feedback or comment is welcome!!!_**

**_Thank you for your time and support!!!!_**

**_Keep Reading!! Keep Learning!!!_**