teleren/devto huggingface dataset:
"Not a number is a number."
Tags: javascript, webdev, beginners, programming
Published: 2022-10-08 10:36:44

> 
In mathematics, zero divided by zero is undefined and is therefore represented by NaN in computing systems. The square root of a negative number is not a real number, and is therefore also represented by NaN in compliant computing systems. NaNs may also be used to represent missing values in computations.

Source: https://en.wikipedia.org/wiki/NaN
Intersection Observer API
Tags: discuss, webdev, javascript, api
Published: 2022-10-08 10:18:42

Did you read about it?

It helps to track the element viewport with respective to the root.

I mean when we scroll Youtube app on our phone the video  automatically starts as soon as it comes in the viewport so how to add these features?

It can be achieved using Intersection Observer API and we can add lazy-loading and infinite scrolling using this API.

What you think?

[Intersection Observer API](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API)
How to Create a Unit Test for a NestJS Service with a TypeORM Repository (MySQL)
Tags: nestjs, testing, unittest, typeorm
Published: 2022-10-08 09:57:46

NestJS is a great framework for building scalable and modular server-side applications. One of its key features is the ability to easily inject dependencies, including TypeORM repositories, into your service classes. In this tutorial, we'll show you how to create a unit test for a service that uses a TypeORM repository in a MySQL database.

First, let's take a look at how to inject the task repository into our service class:

```ts
// task.servic.ts

@Injectable()
export class TaskService {
  constructor(
    @InjectRepository(Task)
    private readonly taskRepository: Repository<Task>,
  ) {}
  ...
}
```
We can then use the TypeOrmModule to configure the database connection in our AppModule. However, for testing purposes, it's a good idea to separate this configuration into a separate file that can be imported into our testing module. This keeps our code clean and makes it easier to reuse for testing other parts of our application.

Here's an example of how to create a database configuration file for testing:

```ts
// src/test-utils/TypeORMMySqlTestingModule.ts

import { TypeOrmModule } from '@nestjs/typeorm';

export const TypeORMMySqlTestingModule = (entities: any[]) =>
  TypeOrmModule.forRoot({
    type: 'mysql',
    host: process.env.MYSQL_HOST || 'localhost',
    port: 3306,
    username: process.env.MYSQL_USERNAME || 'nest',
    password: process.env.MYSQL_PASSWORD || 'nest',
    database: process.env.MYSQL_DATABASE || 'test',
    entities: [...entities],
    synchronize: true,
  });
```
Then, in our testing module, we can import this configuration file and use it to set up our database connection:

```ts
// task.service.spac.ts
...
beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      imports: [
        TypeORMMySqlTestingModule([Task]),
        TypeOrmModule.forFeature([Task]),
      ],
      providers: [TaskService],
    }).compile();

    service = module.get<TaskService>(TaskService);
  });
...
```
Finally, we can run our tests by using the following command:
```sh
$ yarn test src/task/task.service.spec.ts
```

And that's it! You now have a fully functional unit test for a NestJS service with a TypeORM repository in a MySQL database.

For more information, check out the following resources:

- https://stackoverflow.com/a/55717767
- https://dev.to/webeleon/unit-testing-nestjs-with-typeorm-in-memory-l6m
Use .env files in vue vite
Tags: vue, vite, env, javascript
Published: 2022-10-08 09:32:27

vite is a handy tools that provide many advantage, im very happy developing vue project with vite, thanks to [Evan You](https://github.com/yyx990803).

lets get started,

lets make some `.env` files first in the root project and insert some key `SOME_VARIABLE = value`, now how to access it? 

> Vite exposes env variables on the special `import.meta.env` object.

as vite documentation said, we can access the env variable using `import.meta.env` so we access with `import.meta.env.SOME_VARIABLE`, lets do some console log

`console.log(import.meta.env.SOME_VARIABLE) //undefined`, why it undefined?

> To prevent accidentally leaking env variables to the client, only variables prefixed with VITE_ are exposed to your Vite-processed code

vite only showing the variable with prefix `VITE_`, its very nice to prevent leaked data to client, so change your key to `VITE_SOME_VARIABLE`, now it can be viewed


vite also support mode, if you change your `.env` file into `.env.development` that file only used in development mode

and if you change to `.env.production` it only used in production mode.

thats all i know about using .env in vite, further reading https://vitejs.dev/guide/env-and-mode.html


Thanks for reading.
This week’s newsletter is out! (08-10-2022) - Maximly Maximiser
Tags: javascript, tech, webdev, discuss
Published: 2022-10-08 08:53:30

---
title: This week’s newsletter is out! (08-10-2022) - Maximly Maximiser
published: true
description: Another week of great javascript, tech and web development links.
tags: javascript, tech, webdev, discuss
---

Maximly Maximiser

https://markjgsmith.substack.com/p/mark-smiths-newsletter-08-10-2022

Would love to hear any comments and feedback you have.

[@markjgsmith](https://twitter.com/markjgsmith)
Empty phone number field validation using yup-phone
Tags: yup, yupphone
Published: 2022-10-08 08:45:23

---
title: Empty phone number field validation using yup-phone
published: true
date: 2022-10-08 08:42:19 UTC
tags: yup, yupphone
canonical_url: https://sainath.tech/empty-phone-number-field-validation-using-yup-phone
---

I recently encountered an issue while using the library [yup-phone](https://github.com/abhisekp/yup-phone)

yup-phone is a react-library that can be used to validate phone numbers entered in the form field. It uses google-libphonenumber to validate any given phone number in the input field.

Sample usage of yup-phone is given below,

```
const validationSchema = Yup.object().shape({
    mobile: Yup.string().phone()
})

```

The above schema validates if the given number is a valid phone number format or not. You can read in detail about its usage on the [official page](https://github.com/abhisekp/yup-phone/blob/master/docs/index.md).

The problem with the above snippet is it makes the form submission mandatory to provide a phone number even if it is not required. If the field is left empty the validation is made against the empty field. Yup methods `optional` and `notRequired` didn't work either. ( **_Note: This error is not resolved by yup-phone at the time of writing this post. Please check the official page for tracking the issue._** )

Here is a workaround to fix the empty field validation.

```
const validationSchema = Yup.object().shape({
        mobile: Yup.string().when('mobile', {
            is: (value) => value?.length > 0,
            then: Yup.string().phone(),
            otherwise: Yup.string(),
        }),
    },
    [
        ['mobile', 'mobile']
    ]
)

```

Note that the mobile property is written twice in the list of dependencies. This is to avoid cyclic dependency errors as explained in the StackOverflow [post](https://stackoverflow.com/a/67629576).

Below is the code snippet for multiple phone number fields.

```
const validationSchema = Yup.object().shape({
        mobile: Yup.string().when('mobile', {
            is: (value) => value?.length > 0,
            then: Yup.string().phone(),
            otherwise: Yup.string(),
        }),
        phone: Yup.string().when('phone', {
            is: (value) => value?.length > 0,
            then: Yup.string().phone(),
            otherwise: Yup.string(),
        }),
    },
    [
        ['mobile', 'mobile'],
        ['phone', 'phone']
    ]
)

```

- Official page for yup-phone: https://github.com/abhisekp/yup-phone
- Issue: https://github.com/abhisekp/yup-phone/issues/313
Beautiful color scheme for iTerm2/Terminal
Published: 2022-10-08 08:38:29


**Grey Green**

https://raw.githubusercontent.com/mbadolato/iTerm2-Color-Schemes/master/schemes/Grey-green.itermcolors


**How to Use:**


- > `iTerms2` menu
- >> `Preferences`
- >>> `Profiles` tab
- >>>> `Colors` tab
- >>>>> `Color Presets` dropdown
- >>>>> Import downloaded color file
- >>>>> Choose imported color scheme from list



Enjoy!
C developer to simulate amplification attacks
Published: 2022-10-08 08:35:02

Hello,
I need a developer who can simulate these attacks in .c format which are performed against CoAP protocol in IoT network. Attacks include:


1)Amplification attacks with IP address spoofing
2)Amplification attack using a single response
3)Amplification attack using observe
4) Amplification attack using multicast
5) Amplification attack using multicast and observe

This task can be taken in a paid manner.
Thank you
Summary of Smart Home Features Using Matter Protocol
Tags: mattermost
Published: 2022-10-08 08:26:22


Smart home devices with the Matter Protocol logo have the following characteristics:

1. Simple, easy to buy and use.

For consumers, they would try their best to choose smart products of the same brand before, otherwise it will affect the experience of using smart homes, because there will be multiple control centers, such as APPs, and products of different brands cannot be exchanged; now a set of Matter is established in the ecosystem In a smart home, purchasing related equipment is made easy because Matter can add a logo device as long as it is included.

Amazon, Apple, Google, and Samsung have all announced support for the Matter protocol. This means the Matter protocol for the control terminals of smart devices (such as iOS/Android phones, voice assistants, smart smart speakers, etc.) that are common in our daily life. Consumers don't even need a standalone Matter device App, they can directly control Matter devices.


matterSmart Home Products

2. Reliable, secure, consistent and responsive local connections.

The security mechanism jointly initiated, developed and verified by a number of industry leading companies means that Matter-certified devices also have excellent security performance.

3. Compatibility and interoperability, devices from multiple brands can work together locally.

Matter Alliance members use open source methods to develop and implement this new unified connection protocol, which is a set of open and standardized matter protocols. We leverage best-in-class contributions from market-tested smart home technologies such as Amazon, Apple, Google, Connectivity Standards Alliance, etc. capacitive and device interoperability.
Today's Daily Humor For Devs - Daily Developer Jokes
Tags: jokes, dailydeveloperjokes
Published: 2022-10-08 08:00:27

---
title: "Today's Daily Humor For Devs - Daily Developer Jokes"
description: "Check out today's daily developer joke! (a project by Fred Adams at xtrp.io)"
series: "Daily Developer Jokes"
published: true
tags: #jokes, #dailydeveloperjokes
---

Hi there! Here's today's Daily Developer Joke. We hope you enjoy it; it's a good one.

![Joke Image](https://private.xtrp.io/projects/DailyDeveloperJokes/public_image_server/images/5e125905d1ad3.png)

---

For more jokes, and to submit your own joke to get featured, check out the [Daily Developer Jokes Website](https://dailydeveloperjokes.github.io/). We're also open sourced, so feel free to view [our GitHub Profile](https://github.com/dailydeveloperjokes).

### Leave this post a ❤️ if you liked today's joke, and stay tuned for tomorrow's joke too!

_This joke comes from [Dad-Jokes GitHub Repo by Wes Bos](https://github.com/wesbos/dad-jokes) (thank you!), whose owner has given me permission to use this joke with credit._

<!--
Joke text:
___Q:___ Why do programmers always mix up Halloween and Christmas?

___A:___ Because 31 OCT == 25 DEC
 -->
Function in bash
Tags: bash
Published: 2022-10-08 07:45:43

## Function

Function is a familiar topic from mathematics to many programming languages. Function has a defined operation or computation, *example: f(x)=x ^ 2*. 

Function, generally, takes one or more input, operates on the input and returns output. As in the example, given *x*, the function returns *x ^ 2*.

## Function in bash

Bash scripts can have functions too - tricky part is to return the result of a computation. There are a few options to return the result of the computation in function back to the caller of the function. 

## Using *return* keyword

*return*, in bash, is used to status of execution. Status of execution is represented as integers ranging from *0 - 2 ^ 7* with *0* indicating and the rest indicating failure. The caller of such a function should use *$?* to read the returned value. This approach is restrictive that the result of computation may not always be returned with loss. Range 0-255 is too small range of integer probably my niece from kindergarten could use !

```bash
#!/bin/bash
function add() {
  return $(expr 200 + 200)
}

# main
add
echo $?
```

Try this one out ! Expect 400 but result is going to be different (_144_). Clearly *return* is not meant return result of computation. It is meant to return the state of computation. 0 return code means and any other integer just means something went wrong in the computation.

## Using global variable

Using global variable is a naive approach that leads mutation of state. Relying on the global variable based approach would nearly make the script stateful.

## Using *echo* keyword

Using *echo* is open ended. Any arbitrary type can be returned, example Int, String. Caller of such a function should use evaluation to consume the output of computation. Unlike *return* statement, there is no limitation in the range, datatype and there is no mutation state. 

```bash
#!/bin/bash
function add() {
   echo $(expr 200 + 200)
}

# main
sum=$(add 200 + 200)
echo $sum
```

Using the *echo* approach is closer to how the commands are used within the script.

```bash
#!/bin/bash
today=$(date)
```

Command `date` is a builtin tool and the example shows the usage. Now, I can relate to using `echo` more. I can build shell with all such library functions and import them into any necessary shell scripts. 

### Gotcha with echo
As the purpose of *echo* is only to return values, echo should not be used to perform console logging.  However, logging to file is still fine with `echo "My log message" > logfile`

There is no one specific recommended approach. It depends on the scenario and the principles followed by the team. When the principles of referential transparency, purity has to be strictly followed, the preferred approach is to use **echo** approach.
Create a service account in the Google Cloud Platform using the command line:
Tags: googlecloud
Published: 2022-10-08 07:27:49

Use this command to create the service account:

```
gcloud iam service-accounts create test-service-account2 --display-name "test-service-account2"
```
Note: If you see the following output, type y and press ENTER


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

Now if you go to the Navigation bar and then IAM & Admin and then Service accounts, you can see out service account:

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

Also we can give it a role using command line. For example, lets give this service account the project viewer role:

```
gcloud projects add-iam-policy-binding $GOOGLE_CLOUD_PROJECT --member serviceAccount:test-service-account2@${GOOGLE_CLOUD_PROJECT}.iam.gserviceaccount.com --role roles/viewer
```


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



Done!

<img src="https://media0.giphy.com/media/Nfs5y1kzJKfu/giphy.gif?cid=ecf05e472d3w835ptrri5m1p6ifnwl9mi7ope9pifvhpcxf6&rid=giphy.gif&ct=g">
Day 17-18: The API is on its way...
Tags: 100daysofcode, devjournal
Published: 2022-10-08 07:24:34

So, here is today's progress:

{% embed https://api.passwordless.id/ %}

The api is functional, although incomplete, and security kind of turned off for easier testing during development.

As usual, I'm grossly underestimating the time to do things. I thought this would be a quick and easy project but I feel like going down a rabbit hole, deeper and deeper.

After all, even if the project is conceptually simple, you still have the whole stack:

- UI
- API
- DB

Each part with its own set of technologies, choices, logic, details, documentation, testing ...and all the glue in between. Even the most simple things tend to grow bigger than expected.
And that's not counting the learning process, the many changes along the way, with code adapted, refactored or even removed. These intermediary steps are kind of invisible in the end result.

I probably also spend more time than desired because of my shift in the technology stack. Until now, I mainly used Java and Spring Boot, so switching to Typescript and Cloudflare Workers adds time consuming learning. ...And oh boy do I miss some things from the Java world! With Typescript, I feel like back in the middle ages, with lots of manual labor.

Nevertheless, the progress is steady. The API is now roughly halfway done. It's a bit rough, with edge cuts, but enough to start with the proof-of-concept next week.

Have a nice week end, and thanks for reading!
Create a Virtual Machine Using the command line in Google Cloud Platform
Tags: googlecloud
Published: 2022-10-08 07:21:46

Lets first select the Region and zones:
Assume that we want to select us-central1 region:
Set this in your GCP terminal
```
MY_REGION=us-central1
```

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


To check the zones we have
```
gcloud compute zones list | grep $MY_REGION
```

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


Now select anyone of the zones and copy paste it for the value 

```
MY_ZONE=<Your desired zone>
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/alzg3rbi7d9f8iyepbw1.png)

Set this zone to be your default zone by executing the following command

```
gcloud config set compute/zone $MY_ZONE
```
Execute the following command to store a name in an environment variable you will use to create a VM. You will call your  VM `second-vm`

```
MY_VMNAME=second-vm
```
Create a VM in the default zone that you set earlier in this task using the new environment variable to assign the VM name

```
gcloud compute instances create $MY_VMNAME \
--machine-type "e2-standard-2" \
--image-project "debian-cloud" \
--image-family "debian-11" \
--subnet "default"
```


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

Go to Navigation bar  and then Compute Engine and then VM instances.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cr75xxczzx2gckcc3rp8.png)
So, you can see your vm created.

Although you can check out using this command line:

```
List the virtual machine instances in your project
```



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


Done!

<img src="https://media0.giphy.com/media/Nfs5y1kzJKfu/giphy.gif?cid=ecf05e472d3w835ptrri5m1p6ifnwl9mi7ope9pifvhpcxf6&rid=giphy.gif&ct=g">
Bongvip - Bongvip88
Published: 2022-10-08 07:07:52

[https://bongvip88.mobi/](https://bongvip88.mobi/) Nhà cái Bongvip - Bongvip88 là một trong những sân chơi cá cược trực tuyến hot nhất hiện nay✔️ Link đăng ký✔️ đăng nhập tải app nhận ưu đãi lên đến 88k✔️✔️✔️
Đường Lê Văn Thịnh, Cát Lái, Quận 2, Thành phố Hồ Chí Minh
0373 698 347
Give me your GraphQL use case
Tags: discuss
Published: 2022-10-08 07:06:23

Over the last couple of months [Aista](https://aista.com) have experienced what I consider to be unethical business methods, where the feeling has been that somebody is _"out to get us"_. Now of course, I am admittedly slightly more _"paranoid"_ than the average guy, but when somebody registers a domain I consider is rightfully ours, and somebody opens a company in Japan sharing our name, delivering cloud services, it's easy to see why I reacted the way I did I presume.

I thought [Hasura](https://hasura.io) had something to do with it, and hence I became angry, and I started thinking about _"how to get revenge"_. It seems Hasura is equally surprised as me about the situation, and I've spoken to Tanmai about it, and I believe him when he says Hasura has nothing to do with neither the domain issue nor the company in Japan parts. Hence, I owe Hasura an apology, which is one of the reasons why I'm writing this article.

> I apologise to Hasura and Tanmai for blaming them for something they had nothing to do with.

## Give me your GraphQL use case

I still believe Hasura and GraphQL doesn't have an adequate solution for business logic code, so I would love to reach out to the GraphQL and Hasura community and ask for specific use cases where they require business logic that's not adequately solved by GraphQL or Hasura. The point is to get ideas for articles where I will solve these problems using our own [Hyperlambda](https://aista.com/hyperlambda/), showing how we and Hasura can co-exist peacefully, and _"play each other better"_, instead of perceiving each others as competitors. Hence ...

1. Where did you get stuck with GraphQL and Hasura?
2. What did you want to accomplish where you got stuck?
3. What prevented you from moving forward at this point?

Answer the above questions in a comment here, and I might use your problem as an example for a use case which I will solve by creating a YouTube video, and writing an article here at DEV solving it using Hyperlambda. Below is one example of such a solution where I'm sending an email using Hyperlambda by creating an interceptor where I apply the business logic in Hyperlambda, before forward evaluating my GraphQL endpoint ...

{% embed https://www.youtube.com/watch?v=Zvklionkzo0 %}