teleren/devto huggingface dataset:
What are test ids in testing library
Tags: testing
Published: 2022-04-14 05:26:23

When working on testing library test cases, you might come across an option when you want to query something that turns out to be super hard to find with normal selectors.

In general, it's best to try and avoid using test-id if you can use any other form of selectors.

For instance, when you want to query for an image element, try to use `findByRole`.

Test-ids are specific attributes you can add to a element and it looks like this:

```html
<div data-testId="your-unique-key">Some value</div>
```

Don't worry. You can filter these out in the outputted code, so they don't appear in the HTML.

## So, when to use test-ids?

We should only use these when we have no other choice.

I'll give some examples of times we used test-ids over something else.

**SVG with multiple paths:**

We have an SVG with multiple paths inside, and we want to track one specific path to control if it is animated or changed color.

```html
<svg viewBox="0 0 48 48" xmlns="http://www.w3.org/2000/svg">
  <defs>
    <g id="1">
      <path d="...path" data-testid="path-1" />
    </g>
    <g id="2">
      <path d="...path" data-testid="path-2" />
    </g>
  </defs>
</svg>
```

As you can see, we don't really have a unique way of identifying the path we want to test for.

It could even be that you have many more paths, and they render dynamically based on some criteria.

You can now get these paths by the following test code.

```js
screen.getByTestId('path-1');
screen.getByTestId('path-2');
```

A quick reminder, you can replace the `getBy` with all the [regular query selectors](https://daily-dev-tips.com/posts/testing-library-query-selectors/).

**A dynamic tag**

You have some components that can render multiple outputs, for instance, a header component that can render `h1` to `h6`.

It might be hard to determine which one should be rendered based on certain conditions. This could be a valid reason to use `data-testid` for this component.

**Duplicate tags**

Another reasonable time to use these is if your component renders multiple almost identical tags.

For instance, it could have two very identical buttons but use a different icon.

You could add a test-id here to identify between the two.

Or it could be you have a span element show twice, once for desktop and once for mobile. (This is a bit of an anti-pattern but could happen in rare cases)

**Input types that recur often**

In some cases, it might occur that you are testing a form where it's super hard to identify unique input elements.

This could again be a super valid case for test-ids.

## Conclusion

Use test-ids only if every other query fails.

They can be easy to default to, but try to see what makes a piece of HTML unique and how you can target it based on that uniqueness.

I'm looking forward to hearing what you used test-ids for?

### 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)
Django Delete Post (Delete view)
Published: 2022-04-14 04:55:19

**views.py**

```python
from django.views.generic import DetailView, DeleteView
from .models import Post

class deletpost(DeleteView):
    model = Post
    success_url = '/'

    def test_func(self):
        post = self.get_object()
        if self.request.user == post.author:
            return True
        return False
```
**urls.py**

```python
from django.urls import path
from . import views

urlpatterns = [
path('post/<int:pk>/delete',views.deletpost.as_view(),name='delete-post')

]

```
create html go by name **post_confirm_delete.html**

```html
{% block content %}
    <form method="POST">
    {% csrf_token %}
        <h1>Are you sure?</h1>
    <button type="submit">Delete</button>
    <a href="{% url 'home' %}">Cancel</a>
    </form>
{% endblock %}

```
Css Shake Animation
Tags: card, shake, animation, css
Published: 2022-04-14 05:15:10

I've always liked the shaking effect on the login screen on Linux 
or Mac systems, yes, but how to make a similar effect through CSS?
In a few lines of code!

```
.card {
    ...
    animation: shake 1s ease-in-out forwards;
}
@keyframes shake {
    0%,100% {
        transform: translate(0, 0);
    }
    10%,30%,50%,70%,90% {
        transform: translate(30px);
    }
    20%,40%,60%,80% {
        transform: translate(-30px);
    }
}
```

In this video guide you can see how to create a super ultra simple shaking effect
via CSS ...
[Video Guide](https://youtu.be/xFUUP7Kd41U)
🆗 👋
Django Update Post
Published: 2022-04-14 05:01:33

**forms.py**

```python
from django import forms

class updateForm(forms.Form):
    title = forms.CharField()
    body = forms.CharField()
```
**urls.py**

```python
from .models import Post
from .forms import updateForm
def posteditpage(request, pk):
    if request.method == 'POST':
        form = updateForm()
        title = request.POST['title']
        body = request.POST['body']
        post = Post.objects.get(id=pk)
        post.title = title
        post.body = body
        post.save()
        return redirect('/post/' + str(pk))
    else:
        form = updateForm()
    return render(request, 'app/update-post.html', {'form': form})


```
urls.py

```python
from django.urls import path
from . import views

urlpatterns = [

    path('update/<int:pk>',views.posteditpage,name='post-edit'),

]

```
**update-post.html**

```html
{% block content %}
    <form method="POST">
    {% csrf_token %}
        {{ form|crispy }}
    <button type="submit">UPDATE</button>
    </form>
{% endblock %}
```
Angular Routing #3
Tags: javascript, webdev, angular, typescript
Published: 2022-04-14 04:03:52

## Query Params:
Simple example 
`<a [routerLink]="['product']" [queryParams]="{ page:2 }">Page 2</a>
The router will construct the URL as /product?pageNum=2
<a [routerLink]="['product']" [queryParams]="{ val1:2 , val2:10}">Whatever</a>
The router will construct the URL as /product?val1=2&val2=10
Programatically also we can pass queryparams
  this.router.navigate(['/product'], { queryParams: { page: pageNum } }); `
here router is of type Router 

`import { Router } from '@angular/router';`

## Reading QueryParams
this.sub = this.Activatedroute.queryParamMap
       .subscribe(params => {
     this.pageNum = +params.get('pageNum')||0;     
});
this.Activatedroute.snapshot.queryParamMap.get('pageNum')||0

why snapshot and subscribe and what is difference between them

Remember, the router populates the snapshot, when the component loads for the first time. Hence you will read only the initial value of the query parameter with the snapshot property. You will not be able to retrieve any subsequent changes to the query parameter.

## query Params Handling
We have three options to handle these query params they are 
Preserve - The Angular preserves or carry forwards the query parameter of the current route to next navigation. Any query parameters of the next route are discarded
Merge - The Angular merges the query parameters from the current route with that of next route before navigating to the next route.
Null - This is default option. The angular removes the query parameter from the URL, when navigating to the next..

Navigate between Routes
We are having 2 ways to navigate Around different routes
Which is one by <a routerLink=""/>
and other would be programatic navigation
this._router.navigate(['product/detail/1']
this._router.navigateByUrl('product')
this._router.navigate(['detail'], { queryParams: { pageNum: this.pageNum + 1 }, relativeTo: this._Activatedroute } );
.navigate or .navigateByurl both always uses absolute path 
So what is difference between absolute and relative path
absolute contains a / before route like /about
absolute path always appends to the base url like in our case locally it would be 
localhost:4000/about
Relative path does not contain a / before it appends the url to currently activates route
if you are in page localhost:4000/career then it would append to this as localhost:4000/career/about

Folder Structure 
./ ../ .../ these type of routes can also be used these comes under relative paths and not as absolute paths 
this would navigate like
./ - appends given route one level up 
../ - appends given route 2 level up
example : 
active route is - localhost:4200/about
./home - localhost:4200/about/home
../home - localhost:4200/home
Choosing the Best Backend Technology- NodeJS vs Python
Tags: nodejsvspython, bestbackendtechnology, selectingpythonornodejs, choosethebestbackendtechnology
Published: 2022-04-14 04:48:09

Here, is an article that depicts all the essential factors that compare Python and Node.JS on various factors and would give you an idea about which to choose for your project. Both Python and NodeJS are vital Backend Technologies offering great service and development support with result-oriented perspective. 
NodeJS possess the key factor- NPM Support which makes it an important technology as it helps in making the developer's task much more quick and easier whereas Python is a rich technology which has proven itself and as a result it is being used in High-Tech development process. Read the article for complete details- https://www.csestack.org/node-js-vs-python-backend-technology/
HOTWIRE:TURBO
Published: 2022-04-14 04:20:29

## HOW TO IMPLEMENT HOTWIRE TURBO IN RUBY ON RAILS


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

To start implement hotwire turbo, first you need to install [Redis](https://redis.io/docs/getting-started/) server. This server need to be start alongside with the rails server in order for the apps to be able use _Turbo Streams_ in your code.

Next, you have to configure your model by adding _broadcast_ for the action that you want to use HOTWIRE:TURBO. eg:

` 
class Comment < ApplicationRecord
    has_many :likes, as: :likeable
    belongs_to :user
    delegate :user_name, to: :user

    after_create_commit {broadcast_prepend_to "comment"}
    after_update_commit {broadcast_replace_to "comment"}
    after_destroy_commit {broadcast_remove_to "comment"}
end
`

When you done with that, select frame of data that you want to be replaced. and put turbo-frame tag and id in the tag to refer it from the other page and close it at the last data. Make sure both frame of data from different page have the correct id. 

`<%= turbo_frame_tag dom_id(comment) do %>
 ***** INSERT YOUR CODE *****
 <%= link_to "Edit this comment", edit_comment_path(comment) %>          
 <% end %>`

The URL link that refer to that frame must be contained inside the turbo-frame tag to successfully retrieved it.


If you do a form and want to be able to display the data that being output from the form, simply just enter turbo_stream_from tag followed by which page that you want to display.

`<div class="container-fluid">
      <% @comments.each do |comment| %>
        <%= turbo_stream_from "new" %>
        <%= turbo_frame_tag dom_id(comment) do %>
        **** YOUR CODE ****
        <% end %>
      <% end %>
</div>
`

It will be displayed inside the turbo-frame tag. So, make sure the tag is already in the form page that you want to get the data.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4ufrie6xvftisqdjljqg.PNG)    

FOR REFERENCE:
1) https://turbo.hotwired.dev/handbook/introduction
2) https://www.youtube.com/watch?v=Qp6sxgjA-xY&t=1026s
3) https://www.youtube.com/watch?v=eKY-QES1XQQ&t=2s

REDIS INSTALLATION:
1) https://www.youtube.com/watch?v=jkWtBN4Aw-I
The Basics of require()
Tags: beginners, todayilearned
Published: 2022-04-14 03:59:43

## Table of Contents
1. [What is JavaScript "require"?](#what-is-require)
2. [JavaScript require vs import](#require-vs-import)
3. [Helpful Links](#helpful-links)

### What is require
`require()` is in Node.js, not the standard JavaScript API, and its a built-in function to [load modules](https://nodejs.org/api/modules.html#modules_modules).

#### What are [modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules)?
A module is a function or group of similar functions that are grouped together within a file and contain the code to execute a very specific task. Modules are created in order to organize and structure code. The main principles of modules include being:

- independent / self-contained
- specific towards a single or related group of tasks
- reusable in order to be integrated into other programs

Each module has its own scope, similar to variables. A module cannot directly access information or data that had been defined in another module unless that module chooses to expose that particular data. To expose certain data, they must be assigned to `exports` or `modules.exports` and it must use `require()`.

### What require would look like:

```
const express = require('express')
const app = express()
```

The above code would load the `express` module, a minimal framework that provides a set of common utilities for building servers and web applications. Before using the `express` module, it also needs to be downloaded through `npm install express`, a command that lets you download packages.

### require vs import
`import()` and `export()` statements are used to refer to an ES module. The import statement *cannot* be used in embedded scripts unless the respective script has a `type="module"`. On the other hand, a dynamic import can be used for scripts whose type is not "module".

#### How are they different?
##### 1. Where they can be called from
Although `require()` can be called anywhere inside the program, `import()` cannot be called upon conditionally. It must be included at the beginning of the file.

##### 2. Working with modules
`require()` is used with NodeJS to read and execute CommonJS modules while `import()` can't be used outside ES modules.

##### 3. Synchronous or asynchronous
`import()` statements are asynchronous and are known to perform well compared to `require()` functions in large-scale applications.

##### 4. Future applications
The ES module system is adopted by TypeScript and was introduced as the standard to maintain Client-side JavaScript modules.

### Helpful Links
- [Requiring modules in Node.js: Everything you need to know](https://www.freecodecamp.org/news/requiring-modules-in-node-js-everything-you-need-to-know-e7fbd119be8/)
- [require() on CodeAcademy](https://www.codecademy.com/courses/introduction-to-javascript/lessons/modules/exercises/require)
- [Introduction to Node.js](https://nodejs.dev/learn)


Happy coding!
💉 Grype 0.35.0 new feature : Indicate location of vulnerability
Tags: docker, devsecops, devops, kubernetes
Published: 2022-04-14 03:32:41

## 👏 Celebrating Issue `#561`

Previously when we were running [`grype`](https://github.com/anchore/grype) on an image, we were could get vulnerabilities

> **_... but not we could be easily aware of where they were coming from._**

In other words its "type" (`deb`, `java`,... ) :

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

See previous demo for more about the previously available datas for vulnerabilities :

{% embed https://dev.to/optnc/about-java-bytecode-native-binaries-security-short-grype-benchmark-4ng9 %}

## 🖕 The new feature

Fortunately, the following issue has been shipped in the latest [v0.35.0](https://github.com/anchore/grype/releases/tag/v0.35.0) `grype` release :

{% embed https://github.com/anchore/grype/issues/561 %}

To get it :

```
brew install grype
```

, to upgrade it :

```
brew upgrade grype
```

## 🎞️ Demo

Now let's see what it does look now : 

{% youtube LzLSWOFQdRU %}

## ⬅️ Shift Left considerations

Since now, programmers can easily be aware of any security flaw during development pahse itself, on their workstation.
What is hoisting in the javascript.
Tags: javascript, webdev, programming, architecture
Published: 2022-04-14 03:10:19

Hoisting is very important  and tricky part in the javascript world .When  a program loads  into the   js engine  for execution it will not executed in the same way as we have writeen it. 

**Hoisting **  means during the declaration phase it will hoist (raise) all the variable declaration and function declaration to the top of the current scope .
Let, s understand it with the help of a example :

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

In the above example you have seen as we  have writeen our program is not executed in the same way  by the Javascript engine .So now its time to go more deep .Then you all  will be able to understand why this happened.

When the js  engine execute the code it will creates a global execution context  and  it has two phases .

**First Phase(Declaration phase) :**
In  the first phase (declaration phase ) it will allocate memory  to all the variables and function .
Highest priority is given to the function declaration. Javascript engine will move all the  function declaration  to the top .
Like this :


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

**var keyword :**
During the Execution phase variable declared with var keyword are initialized with undefined value whereas variable declared with let and const keyword are initialized during the execution time only but memory is being allocated to all  the variables during  the declaration phase only.


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

**let and const keyword**

But if your write the above same code and replace the var keyword  with let and const then it will throw an error Because you can,t  access a variable which is not initialized yet. Because variables declared with let and const are initialized during  the execution phase only.

**Function expressions**
Function expressions are not treated as the same as function declaration .During  the declaration phase they are treated as a variable . 


**Execution Phase**
In the execution phase it will execute code line by line means synchronously . The reason why it will execute all the code line by line is that Javascript engine is single  threaded . 

I hope  now all of you are able to understand what is hoisting in javascript .this article will must help you to understand this topic :)
Easily and safely escape HTML in one line
Tags: javascript, html, webdev
Published: 2022-04-14 02:37:40

```js
x => Object.assign(document.createElement('div'), { textContent: x }).innerHTML
```

True, you could also do it with

```js
x => x.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;")
```

or similar, but if you do it the first way you don't have to remember the HTML entities 🙂
Cara Import Dan Export Table Database Mysql
Tags: mysql, webdev, beginners
Published: 2022-04-14 02:28:48

Tutorial ini dibuat karena masih banyak yang tidak tahu cara export dan import table ke database.Padahal caranya sangat mudah.Disini kita akan menggunakan managemen database standart **PhpMyAdmin**

#### Cara Import Database

1. Masuk ke localhost/phpmyadmin
2. Klik Database yang akan di import.
3. Klik Tab **Import** ,lihat gambar dibawah.
4. Klik **Choose** dan pilih file **.sql** yang akan diimport lalu tekan Button **GO**.Untuk nama button **Choose** bisa berbeda tergantung bahasa.


![Import Database MedanInCode](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sj70j3rxhfhask9y6ehj.png)

Setelah itu tunggu sampai import selesai.Untuk catatan saja kita bisa mengimport file berformat **.sql** ataupun yang sudah dicompress seperti **.zip** ,untuk **.rar** tidak support.

#### Cara Export Database

1. Masuk ke localhost/phpmyadmin
2. Klik Database yang akan di export datanya.
3. Klik Tab **Export** ,lihat gambar dibawah.
4. Ada dua tipe **Quick** dan **Custom**.Tipe **Quick** jika ingin mengexport semuanya,tipe **Custom** jika misalnya hanya ingin beberapa tabel atau hanya tabel tanpa datanya.Jika sudah tekan **Go**


![Export Database MedanInCode](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s3kvkwtaxpqp4z0jnxok.png)

Sekian tutorial kali ini semoga membantu.
How to use Prettier in VS Code
Tags: vscode, webdev, tutorial, beginners
Published: 2022-04-14 01:54:44

Formatting code consistently can be a challenge, particularly when working on a team. Code formatters like prettier can help solve this issue. Consistent code formatting helps with the readability of a project.

In this video I will show you how to install and configure Prettier Code Formatter in VS Code.   

{% embed https://youtu.be/__eiQumLOEo %}
CloudWatch e OpenSearch na AWS com multiplos grupos de logs.
Tags: aws, kibana, elasticsearch, devops
Published: 2022-04-14 01:52:33

Exatamente hoje, passei por uns problemas utilizando o CloudWatch da AWS para receber os logs de uma aplicação e uma instância do OpenSearch para visualização dos dados.

Acontece que foi criado o grupo de logs para ambiente de homologação - `staging/serice/api_sucesso` - e um para produção `production/service/api_sucesso`.

Acontece que os logs do `staging` estavam sendo indexados no OpenSearch perfeitamente, porém, quando testamos em ambiente de `production` os logs não conseguiam ser indexados no OpenSearch. :/

Acontece que por padrão o CloudWatch cria apenas uma função do AWS Lambda para cada domínio do OpenSearch e quando o primeiro grupo invoca a função Lambda, a chamada cria um índice e um campo de tipo no seu domínio.

A solução para isso é alterar a função Lambda na declaração da variável `indexName` de:

```js
var indexName = [
        'cwl-' + timestamp.getUTCFullYear(), // year
        ('0' + (timestamp.getUTCMonth() + 1)).slice(-2), //month
        ('0' + timestamp.getUTCDate()).slice(-2) // day
        ].join('.');
```
para:

```js
 var indexName = [
  'cwl-' + payload.logGroup.toLowerCase().split('/').join('-') + '-' // log group name
  + timestamp.getUTCFullYear(), // year
  ('0' + (timestamp.getUTCMonth() + 1)).slice(-2), // month
  ('0' + timestamp.getUTCDate()).slice(-2) // day
].join('.');
```

Obtendo assim, um prefixo do nome do grupo para indexação.

Para mais detalhes da [documentação](https://aws.amazon.com/pt/premiumsupport/knowledge-center/opensearch-troubleshoot-cloudwatch-logs/).