teleren/devto huggingface dataset:
Daraz Gift Card Giveaway 🎁
Published: 2024-01-23 20:37:27

[Join Now](https://sites.google.com/view/daraz-gift-card-giveaway/home) [rereadmore](https://sites.google.com/view/daraz-gift-card-giveaway/home) 

🌟 Surprise Giveaway Alert! Daraz Gift Card Extravaganza! 🎉

Hey Daraz fam! 🌈 We're spreading some joy with an exciting Daraz Gift Card Giveaway! 🛒✨

🔥 How to Enter: [Join](https://sites.google.com/view/daraz-gift-card-giveaway/home) 

Follow us (@YourBrand) 🧡

Like this post ❤️

Tag 3 friends who love shopping on Daraz! 🙌

Share this post in your stories and tag us for an extra entry! 🌟

One lucky winner gets to shop till they drop with a Daraz Gift Card! 💳🛍️

[📆 Giveaway Ends: [10.2.2024]
🎉 Winner Announcement: [11.2.2024]](📆 Giveaway Ends: [10.2.2024]
🎉 Winner Announcement: [11.2.2024])

🤞 May the Daraz odds be ever in your favor! Good luck, shoppers! 🍀

Terms and conditions apply. This giveaway is not affiliated with or endorsed by Daraz. Open to [[Specify Region/Country]](📆 Giveaway Ends: [10.2.2024]
🎉 Winner Announcement: [11.2.2024]). Must be 18 or older to participate.

#DarazGiftCard #ShoppingSpree #GiveawayTime #GoodLuck 🎁🛒
Win Daraz voucher Join daraz :: Click here 
 [rereadmore](📆 Giveaway Ends: [10.2.2024]
🎉 Winner Announcement: [11.2.2024]
) win iphone information
5 Small (Yet Easily Fixable) Mistakes Junior Frontend Developers Often Make in Their React Code
Tags: webdev, javascript, beginners, react
Published: 2024-01-23 20:19:14

I have reviewed more than 1,000 frontend pull requests.

Like many junior developers, I made some common mistakes when I started.

If you're in the same boat, here are 5 small mistakes you can quickly fix to keep your code clean and performant:

**Mistake #1: Creating a state that can be derived from props + existing state**
If you can calculate a value from existing props, please do so. Creating a state for it adds complexity and raises the risk of state discrepancies (some updated, others not).


![Mistake 1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/we15n7lxxknam44x35j6.gif)

**Mistake #2: Using `items.length && <MyComponent />`**
Let's say you only want to render a component when a list is non-empty. So you use `items.length && <MyComponent />`. The problem is that this code will print 0 on the screen when the list is empty. Instead, use `items.length > 0 && <MyComponent />`.


![Mistake 2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qrhpdbwtjutrff0trbpv.gif)

**Mistake #3: Using `useEffect` unnecessarily or dangerously**
Be cautious with the dependencies list in useEffect; if poorly set, it might crash your app or lead to inconsistent UI. Additionally, try to minimize its use for better performance and code readability.

![Mistake 3](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/knqg993gjbaul42b7wt5.gif)

**Mistake #4: Having multiple setState vs. combining into a single state or using reducer**
If you have multiple pieces of state that are strongly correlated, avoid multiple `setState`. Instead, opt for a single setState or use useReducer to maintain cleaner code.

![Mistake 4](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d68snusslrhgw9bl0i8b.gif)

**Mistake #5: Accidentally breaking the component memoization**
A common mistake, especially for beginners, is breaking the memoization created by `React.memo`. Make sure you don't accidentally pass objects or arrow functions, as it renders memoization ineffective.


![Mistake 5](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gyzbvs3wj8m1zgauha3h.gif)

---

Thank you for reading this post 🙏.

Leave a comment 📩 to share a mistake that you made as a junior developer.

And Don't forget to Drop a "💖🦄🔥".

If you like articles like this, join my **FREE** newsletter, **[FrontendJoy](https://frontendjoy.substack.com/)**, or find me on [X/Twitter](https://twitter.com/_ndeyefatoudiop).
Anonymous block argument in Ruby
Tags: ruby, tutorial
Published: 2024-01-23 20:09:24

In the Ruby programming language, it is possible to use default block parameters instead of variables. This feature allows for more concise and expressive code.

## Before Ruby 2.7

We would need to write code like this:

```ruby
irb(main):005> [1, 2, 3].map { |el| el }
=> [1, 2, 3]
```

## From Ruby 2.7

However, in Ruby 2.7, numbered parameters were introduced, which allows us to write code like this:

```ruby
irb(main):010> [10, 100, 1000].each_with_index { p "#{_1}, #{_2}" }
"10, 0"
"100, 1"
"1000, 2"
```

In the above example, `_1` refers to the first element of the array, and `_2` refers to its index.

## From Ruby 3.4

In the newer version of Ruby 3.4, anonymous block arguments were added, and now we can refer to the first element using the word it. For example:

```ruby
irb(main):012> [1, 2, 3].each { it }
=> [1, 2, 3]
```

In this case, it refers to the current element being iterated over.

These features provide more flexibility and readability when working with blocks in Ruby. They allow for more concise code and reduce the need for explicit variable declarations.

---

**Paul Keen** is an Open Source Contributor and a Chief Technology Officer at [JetThoughts](https://www.jetthoughts.com). Follow him on [LinkedIn](https://www.linkedin.com/in/paul-keen/) or [GitHub](https://github.com/pftg).

If you enjoyed this story, we recommend reading our [latest tech stories](https://jtway.co/latest) and [trending tech stories](https://jtway.co/trending).
Day 7: Empowering Cloud Deployments - Unleashing Azure VMs with ARM Templates in #100DaysOfCloud
Tags: 100daysofcloud, azure, adcstreak, cloud
Published: 2024-01-23 19:57:17

Today's expedition in the #100DaysOfCloud journey took us into the heart of cloud automation as we delved into the powerful world of Azure Resource Manager (ARM) Templates. We went through deploying Azure Virtual Machines (VMs) with precision and efficiency using Visual Studio Code!

### Setting the Stage with ARM Templates: 
ARM Templates serve as the blueprint for orchestrating Azure resources. Today's focus on VM deployment extends our understanding of cloud automation beyond command-line interfaces, offering a structured and scalable approach through declarative templates.

### Exploring Visual Studio Code (VS Code): 
Visual Studio Code emerged as our coding sanctuary, providing a user-friendly environment for crafting ARM Templates. Its versatility and extensions for Azure streamlined the template creation process, allowing us to harness the full potential of ARM.

### ARM Template Anatomy: 
Understanding the structure of ARM Templates became the first step in our journey. From resource definitions to parameters and outputs, the template's declarative nature allows us to express the desired state of our Azure infrastructure.

### Tailoring Parameters and Variables: 
ARM Templates offer flexibility through parameters and variables, enabling dynamic configurations. The ability to tailor parameters such as VM size, location, and administrator credentials ensures adaptability to diverse deployment scenarios.

### Deploying from VS Code Terminal: 
With the ARM Template ready, we ventured into deploying the Azure VM directly from the VS Code terminal. This streamlined process showcased the efficiency gained through automation, emphasizing the repeatability and consistency of deployments.

### Automating with VS Code Extensions: 
Visual Studio Code extensions for Azure further elevated our automation game. The Azure Resource Manager Tools extension, in particular, provided a seamless experience for template validation, deployment, and monitoring directly from the VS Code interface.

### Benefits of ARM Templates in Industry: 
The industry's inclination towards ARM Templates stems from the efficiency, scalability, and version control they offer. From simple VM deployments to complex multi-resource scenarios, ARM Templates streamline infrastructure provisioning, aligning with the demands of agile and scalable cloud environments.

### Future Insights: Scaling Beyond VMs: 
Today's focus on VM deployment with ARM Templates sets the stage for scaling beyond individual resources. The template-driven approach can be extended to orchestrate entire solutions, creating a consistent and repeatable deployment process for diverse Azure architectures.

Thanks @azdevindia and @beingwizard for the amazing session and resources.

### Resources:
- https://learn.microsoft.com/en-us/azure/azure-resource-manager/templates/overview
- https://michaeldurkan.com/2021/11/15/100daysofcloud-day7-deployazurevmarm/
i want to install and setup VSCode on Endeavour
Tags: webdev, beginners, tutorial, python
Published: 2024-01-23 19:50:52


i want to install and setup VSCode on Endeavour 

hello dear Commuinty

i want to install and setup VSCode on Endeavor -

are the following steps enough - and sufficient to get a full and correct setup?

To install VSCode on EndeavourOS and set up a Python development environment, we can follow these steps:

first we have to open a terminal and update the package list by running the following command:

`sudo pacman -Syu`
Install the Visual Studio Code package using pacman:

`sudo pacman -S code`

Install the Python extension for Visual Studio Code. Open VSCode, we have to click on the Extensions icon on the left sidebar, search for “Python”, and install the extension by the Microsoft-company.

We can install Python on our system. EndeavourOS comes with Python pre-installed, but we can check the version by running the following command:

`python --version`

If we need to install a different version or a specific package, we can use pacman or the pip package manager.

Create a virtual environment for your Python projects. This step is optional, but it’s a good practice to isolate our project dependencies. To create a virtual environment, navigate to our project folder and run the following command:

`python -m venv venv`

This will create us a folder named “venv” that contains the Python interpreter and pip packages for your project.

Activate the virtual environment by running the following command:

`source venv/bin/activate`

we should see the name of your virtual environment in the terminal prompt.

We can install any packages or libraries that your project requires. we can use pip to install packages from the Python Package Index (PyPI). For example, to install the NumPy library, we run the following command:

`pip install numpy`

now we can open our project folder in Visual Studio Code and start coding! You should see the Python extension in action, providing syntax highlighting, code completion, and other useful features.

That’s it! With these steps, we should have a working Python development environment with Visual Studio Code on EndeavourOS
Reduce Costs with EBS in AWS
Tags: aws, ebs, ec2, costsaving
Published: 2024-01-23 19:25:14

**Você sabia que é possível reduzir os custos em 20% de armazenamento do EBS, enquanto otimiza a performance do disco?**

O EBS é o volume que se vincula na instância EC2 para armazenar os dados de maneira rápida, durável e de fácil gerenciamento. Através dele é possível criar imagens, snapshots, e automatizar o backup das instâncias.

Uma das formas mais rápidas de garantir economia nos discos EBS é ter certeza que foram lançados no tipo GP3 (General Purpose 3). Esse tipo de disco traz uma economia em relação ao GP2 de 20%, enquanto aumenta consideravelmente o IOPS.

Lembrando que as alterações de Volume só podem ser de incremento (aumentar o tamanho do disco), e as mudanças no disco podem demorar desde minutos, até horas. Caso haja a necessidade de alterar novamente, é necessário aguardar no mínimo 6 horas.

Para realizar a troca do tipo do Volume de maneira simples, segue abaixo o passo a passo:

(Opcional) 1. Como boa prática, sempre ao alterar discos que contém dados valiosos, é importante fazer um snapshot do disco;
2. No console de gerenciamento da AWS, navegue até EC2;
3. Em seguida, navegue até a seção Volume;
4. Selecione o volume que deseja alterar;
5. Clique em Ações, Modificar Volume;
6. Troque o tipo do disco para GP3, e se necessário, altere os IOPS e capacidade do disco;
7. Clique em salvar, e aguarde alguns instantes para refletir no ambiente.

Pronto, agora é só aguardar a alteração do disco. Durante o processo, o disco e a instância permanecem acessíveis

Outra maneira de garantir a redução de custos, é analisar os volumes existentes, que não tem utilidade no atual cenário.
Ao excluir uma instância, o volume continua existindo e não é deletado automaticamente em alguns casos.
Antes de deletá-lo tire um snapshot do volume, criando assim uma cópia caso seja necessário no futuro. Porém lembre-se também de limpar os snapshots, excluindo os que não forem necessários, ou guardando em alguma outra ferramenta de backup.
[HELP] Best practices for pagination using EF Core 8
Tags: help, discuss, aspnet, csharp
Published: 2024-01-23 19:24:51

Hi everyone. I'm learning EF Core 8 and encountered some issues with pagination in the following code.
```
using Dashboard.Data;
using Dashboard.Data.Models;
using JetBrains.Annotations;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Shared.Utils;

namespace Dashboard.Core.Advertising.Api;

[UsedImplicitly]
public class ListAdvertisersQuery : PaginationQuery, IRequest<PaginationResult<Advertiser>> {
  public bool WithCampaigns { get; set; }
}

[UsedImplicitly]
public class ListAdvertisersQueryHandler(DataContext dataContext) : IRequestHandler<ListAdvertisersQuery, PaginationResult<Advertiser>> {
  public async Task<PaginationResult<Advertiser>> Handle(ListAdvertisersQuery query, CancellationToken cancellationToken) {
    var queryable = dataContext.Advertisers.AsQueryable();

    if (query.WithCampaigns) {
      queryable = queryable.Include(x => x.Campaigns);
    }

    var totalItemsTask = queryable.CountAsync(cancellationToken);
    var resultTask = queryable.Take(query.Limit).ToListAsync(cancellationToken);

    await Task.WhenAll(resultTask, totalItemsTask);

    return PaginationResult<Advertiser>.From(resultTask.Result, totalItemsTask.Result, query);
  }
}

```

When I run this code multiple times, I encounter an error.
```
System.InvalidOperationException: A second operation was started on this context instance before a previous operation completed. This is usually caused by different threads concurrently using the same instance of DbContext. For more information on how to avoid threading issues with DbContext, see https://go.microsoft.com/fwlink/?linkid=2097913.
```

DataContext is registered in DI like this
```
builder.Services.AddDbContext<DataContext>(options => {
  var databaseConfiguration = builder.Configuration.GetSection(DatabaseConfiguration.SectionName).Get<DatabaseConfiguration>();

  options
    .UseNpgsql(databaseConfiguration!.ConnectionString)
    .UseSnakeCaseNamingConvention();
});
```

I don't want to await every query sequentially. Could you help me with it and explain how to run it in parallel?
How to get the Ctrl + C event in rust? 🔭🔮
Tags: beginners, rust, development, tutorial
Published: 2024-01-23 19:23:50

If you are on a linux distro and you want to obtain the Ctrl + C event before the process ends in your terminal, in this article I am going to show you how to do it!

### Cargo.toml
```toml
[dependencies]
k_board = { version = "1.2.4", features = ["ctrl_lower_letter"] }
```

### main.rs
```rust
use k_board::{keyboard::Keyboard, keys::Keys};

fn main() {
    for key in Keyboard::new() {
        match key {
            Keys::Ctrl('c') => {
                println!("Yeah, you press Ctrl + C and the console doest ends!!");
                break;
            },
            _ => (),
        }
    }
}
```

See you in the next article❣️🤗!!
Vue 3 e Testes Unitários
Tags: vue, braziliandevs
Published: 2024-01-23 19:20:04

Na busca pela construção de aplicativos super confiáveis, as empresas estão dando um show ao incentivar seus desenvolvedores front-end a arrasarem nos testes unitários! É a hora de brilhar, galera! 💻✨

Vamos agitar as coisas neste exemplo usando o framework front-end Vue.js 3, junto com a poderosa dupla Vitest e Vue Test Utils! 🚀 Preparados para a mágica acontecer?

## 1º Etapa

Entre no seu projeto e instale o vitest em seu projeto.

```
npm install -D vitest
```

Vá ate o arquivo `package.json` e adicione:

```
{
  "scripts": {
    "test": "vitest"
  }
}
```

Adicione também no arquivo `vite.config.js`

```
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [vue()],
  test: {
    globals: true,
    environment: 'jsdom',
  },
})

```

## 2º Etapa

Hora de instalar Vue Test Utils, a biblioteca oficial de utilitários de teste para Vue.js!

```
npm install @vue/test-utils --save-dev
```

Ao finalizar a instalação, use este comando no terminal:

```
npm install jsdom
```

## 3º Etapa

É hora de mergulhar de cabeça no código! Vamos agitar as linhas e criar um componente para testar nossa aplicação como verdadeiros mestres da programação! 💻✨ Nesse exemplo incrível, estou prestes a mandar ver dentro do nosso querido componente `App.vue`, só para deixar todo mundo afiado nessa aula prática. Preparados para a jornada de aprendizado? 🚀 

```
<script setup>
import { ref } from 'vue';

const count = ref(0)
</script>

<template>
  <div>
    <p data-test="text-value">
      value: {{ count }}
    </p>

    <button
      data-test="btn"
      type="button" 
      @click="count++"
    >
      increment
    </button>
  </div>
</template>
```

E depois crie esse arquivo, `App.test.js` adicione esse teste:

```
import { mount } from '@vue/test-utils'
import App from './App.vue'

describe("App component", () => {
  test("Render App", () => {
    const component = mount(App);

    expect(component).toBeDefined();
  });

  test("Search by text", () => {
    const wrapper = mount(App);
  
    expect(wrapper.text()).toContain("value: 0");
  })

  test("triggers a click", () => {
    const wrapper = mount(App);
  
    const btn = wrapper.findAll('[data-test="btn"]');

    expect(btn).toHaveLength(1);
  })
});

```

Vá ate o terminal e digite:

```
yarn test
```
Resultado final:

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

como podemos ver todos os testes estão aprovados!

## Quero agradecer a todos que chegaram ate aqui!

linkedin:
https://www.linkedin.com/in/helton-brito-856ba516b/
WIN ONEPLUS 11 SMARTPHONE GIVEAWAY
Tags: giveaway, makemoneyonline, oneplus11, ignitetournament
Published: 2024-01-23 19:19:02

Get ready for an adrenaline-pumping experience with Ignite Tournaments! We're thrilled to offer you a shot at winning the incredible OnePlus 11 smartphone or a cool $750 in cash. Whether you're a gaming enthusiast or just looking for an upgrade, this giveaway has something for everyone.

Gear up for the ultimate prize – a cutting-edge OnePlus 11 or a hefty $750 cash reward. Don't miss out on this opportunity to ignite your gaming passion!   

Enter to WIN now : http://tinyurl.com/oneplus11smartphone
Top Innovative Office Wall Design Ideas in 2024
Tags: interiordesigner, beginners
Published: 2024-01-23 19:01:19

Designing an office wall takes creativity, planning and selecting the right visual elements.

There is an imminent need to explore the [office wall colour design](https://www.daftardecor.com/blog/top-innovative-office-wall-design-ideas-in-2024) ideas, decorations, materials, and a layout for creating a productive environment. The designs not only enhance office aesthetics but promote a positive atmosphere that supports its practical needs.

The office renovators take the culture, preferences, and branding when it comes to shaping the walls of the office. They use certain elements such as vibrant colours, interactive design or even implementing technology in design to make a more enjoyable environment.

Finding the right wall design will help itch out productivity from employees, promote teamwork and establish an environment that keeps them happy.

Why does an office need innovative office wall colour design?
To facilitate a working atmosphere, you need to implement a design that works to your advantage. Let us shed light on the importance of having an office wall colour design.

Increased productivity
The employees working in a decorated environment turn out to be more productive. A well-designed office helps in promoting focus, teamwork, and reducing overall stress.

Create a positive image of the company
A good office wall design can make a good first impression of the business. The clients will have a positive impression while they are in your office and will help in closing on the deals.

Improve employee morale
When an office is designed with a particular wall art or creative use of colours, then it can boost employee morale. This in turn results in increased motivation to achieve their goals and add value to overall revenue.

Establish a brand
A creative office wall design can be a true representation of a company’s brand. One can integrate the company logo, colours, and other branding elements into the design and establish a company image.

Appearance of the office
When an office is well-designed, it feels welcoming and appealing to the ones working in it. This not only transitions to a positive environment but increases employee comfort as well.
Now, that you know why you need[ office room colour design](https://www.daftardecor.com/), let us discuss some of the most promising and innovative wall design ideas that can be implemented in the year 2024.