teleren/devto huggingface dataset:
JavaScript: Novedades que te conviene conocer (¡sin tecnicismos!)
Published: 2024-03-13 23:29:45



¿Quieres estar al día con las últimas novedades de JavaScript? No te preocupes, no necesitas ser un experto para entenderlas. En este post, te las explico de una forma sencilla y práctica.

**1. Argumentos por defecto y parámetros obligatorios:**

Imagina que creas una función para calcular el área de un rectángulo. Antes, tenías que pasar dos argumentos (largo y ancho) siempre. Ahora, puedes definir un valor por defecto para el ancho si no se indica. ¡Más flexibilidad!

**2. Nuevos métodos para arrays:**

¿Cansado de usar sort y splice? ¡Tenemos buenas noticias! Nuevos métodos como toSorted y toSpliced te permiten modificar arrays de forma inmutable, ¡más fácil y seguro!

**3. Nuevos tipos de datos:**

¡Hola BigInt! Este nuevo tipo de dato te permite trabajar con números enteros gigantes, ideal para operaciones matemáticas complejas.

**4. Clases privadas (en desarrollo):**

¿Quieres proteger el código interno de tus clases? Las clases privadas te permiten hacerlo, mejorando la seguridad y organización de tu código.

**5. Rendimiento mejorado:**

Los navegadores web no se quedan atrás. El motor V8 de Chrome ha recibido mejoras que te permiten ejecutar código JavaScript más rápido que nunca.

**6. Nuevas herramientas y frameworks:**

Vite y Svelte son dos herramientas que te ayudarán a crear aplicaciones web modernas de forma más eficiente. ¡Pruébalas!

**7. TypeScript en auge:**

TypeScript, un lenguaje que añade tipos estáticos a JavaScript, está ganando popularidad. Si buscas mayor seguridad y organización en tus proyectos, ¡es una opción a considerar!

**¿Quieres saber más?**

Novedades de JavaScript en 2023 (video): https://www.youtube.com/watch?v=xm7cc_G9_CE

**¡Empieza a usar estas nuevas funciones en tus proyectos JavaScript y lleva tu código al siguiente nivel!**
30 tips of code in PHP - Generators
Tags: development, php, challenge, 30daysofcode
Published: 2024-03-13 23:20:42

O assunto de hoje é Generator. Neste artigo, vou explicar o que estudei e o link para o repositório com todo o conteúdo.

## Generators

Então, vendo que o 'for' não ia ser a melhor solução sempre, os criadores do PHP decidiram implementar os Generators na versão 5.5 da linguagem. Generators são basicamente funções que retornam o resultado de algo iterável sem precisar salvar o resultado da iteração em uma variável. Uma vez que o generator logo após retornar iterar já retorna o resultado, ou seja, não sendo mais necessário fazer o famoso `$array[] = $value`, economizando então memória e evitando um erro de estouro de pilha de execução.

### 1 - Uso básico

```php
function yieldCall()
{
    for ($i = 0; $i < 10; $i++) {
        yield $i;
    }
}

$generator = yieldCall();
var_dump($generator);

foreach ($generator as $value) {
    echo $value;
}
```

Rodando o código, tu consegue perceber que o valor é impresso na tela normalmente, assim como se fosse feito da forma tradicional.

### 2 - Definindo chave para o iterador

```php
$csv = 'nome;raziel';

function parserYield($input)
{
    foreach (explode(';', $input) as $key => $value) {
        yield uniqid() => $value;
    }
}

foreach (parserYield($csv) as $key => $value) {
    echo ($key);
    echo '<hr>';
    echo $value;
}

echo '<hr>';
```

### 3 - Usando com ponteiros

```php
function &genYield()
{
    $value = 3;

    while ($value > 0) {
        yield $value;
    }
}

foreach (genYield() as &$key) {
    echo (--$key);
}

echo '<hr>';
```

### 4 - Composição de um array

```php
class Test
{
}

function y()
{
    yield 3;
    yield 4;
}

function x()
{
    yield 1;
    yield from y();
}

$x = x();

foreach ($x as $value) {
    var_dump($value);
}

$x->getReturn();

var_dump(is_array($x->getReturn()));

echo '<hr>';
```

# O Motivo Final

```php
echo '<h1> Exemplo benchmark: </h1> <hr>';

function forEachOnly()
{
    $numeros = [];
    foreach (range(1, 1000000) as $value) {
        $numeros[] = $value;
    }

    echo "Memory peak usage FOREACH: " . memory_get_peak_usage(true) . " bytes \n";
}

function generatorCall()
{
    foreach (range(1, 1000000) as $value) {
        yield $value;
    }
}

function generatorOnly()
{
    foreach (generatorCall() as $value) {
        $value;
    }
    echo "Memory peak usage GENERATOR: " . memory_get_peak_usage(true) . " bytes \n";
}

# forEachOnly(); DESCOMENTA PRA VER ESSE
# generatorOnly(); E DEPOIS DESCOMENTA ESSE
```

Irei mostrar aqui o benchmark que você mesmo pode testar:

```
Memory peak usage FOREACH: 44052480 bytes
Memory peak usage GENERATOR: 18878464 bytes
```
OpenSearchCon Europe 2024 - call for presentations (CfP)
Tags: opensource, opensearch, developers, cfp
Published: 2024-03-13 23:19:52

The OpenSearch team is extraordinarily happy to announce the launch of a European edition of OpenSearchCon! We invite you to join us May 6 and 7 at Cafe Moskau in Berlin for OpenSearchCon Europe 2024.

The [Call for Presentations (CfP) is now open](https://pretalx.com/opensearchcon-europe-24/cfp), and we look forward to seeing what everyone turns in. _CfP ends on March 25th, 2024 at 23:59 CET._

We have additional information [available here](https://opensearch.org/blog/announcing-opensearchcon-europe-2024/).

And, [registration is now open](https://tickets.plainschwarz.com/opensearchconeu/) as well. 

Hope to see you there.
Customize Reset Password Mail in Laravel
Tags: php, laravel
Published: 2024-03-13 23:08:49

## Overview

Laravel provides by default a forgot password feature for `User` model, you can find it in `authorizable` alias that extends to `User` model:

```php
class User extends Model implements
    AuthenticatableContract,
    AuthorizableContract,
    CanResetPasswordContract
{
    use Authenticatable, Authorizable, CanResetPassword, MustVerifyEmail;
}
```

`User` model has a method that send the notification to reset password:

```php
sendPasswordResetNotification($token)
```

We can override it to handle or custom messages.


## Customizing Reset Password notification

First, we are going to create or own notification that would extend from the default `ResetPassword` notification from Laravel:

In terminal create a new notification:

```php
php artisan make:notification ResetPassword
```

Then we are going to override `sendPasswordResetNotification` method in `User` model:


```php
use App\Notifications\ResetPassword;

class User
{
    // ...

    public function sendPasswordResetNotification($token)
    {
        $this->notify(new ResetPassword($token));
    }
}
```

Just make sure that you import our custom notification.

## Customize notification

In this example for the sake of simplicity I am going to extend from the default `resetPassword` from Laravel

Eg: replace a subject message:

```php
    protected function buildMailMessage($url)
    {
        return (new MailMessage)->subject('Here a custom subject');
    }
```
Debugging with CSS
Tags: css, debug, html, selector
Published: 2024-03-13 23:08:22

One of the favorite debugging tricks for HTML/CSS is using the CSS snippet you shared, known as the "Rainbow CSS" or "CSS Rainbow Debugging" technique. This technique applies different background colors to elements based on their depth in the DOM tree, making it easier to visualize the layout and identify any inconsistencies.

Another popular debugging technique is using browser developer tools extensively. These tools provide a wide range of features, including inspecting elements, modifying styles in real-time, debugging JavaScript, analyzing network activity, and more. By leveraging developer tools, developers can pinpoint issues in their code, test different styles, and optimize performance.

Additionally, utilizing CSS comments strategically can help in debugging CSS stylesheets. By adding comments to CSS rules, developers can provide context, document their code, and temporarily disable or test specific styles without removing them entirely.

Furthermore, creating custom CSS classes or attributes specifically for debugging purposes can streamline the debugging process. For example, adding a `.debug` class to elements or using data attributes (`data-debug="true"`) can help target specific elements for debugging styles or behavior.

Lastly, logging messages to the browser console using JavaScript's `console.log()` function can be invaluable for debugging complex JavaScript interactions, tracking variable values, and identifying errors in code logic.

```css
* { background-color: rgba(255,0,0,.2); }
* * { background-color: rgba(0,255,0,.2); }
* * * { background-color: rgba(0,0,255,.2); }
* * * * { background-color: rgba(255,0,255,.2); }
* * * * * { background-color: rgba(0,255,255,.2); }
* * * * * * { background-color: rgba(255,255,0,.2); }
* * * * * * * { background-color: rgba(255,0,0,.2); }
* * * * * * * * { background-color: rgba(0,255,0,.2); }
* * * * * * * * * { background-color: rgba(0,0,255,.2); }
```

By combining these debugging techniques and experimenting with different approaches, developers can efficiently troubleshoot HTML/CSS issues, improve code quality, and enhance the overall user experience of their web applications.

source - [medium - Gajus Kuizinas](https://gajus.medium.com/my-favorite-css-hack-a7f447026cf2)
O comando "git checkout -f" e "git reset --hard" para Git.
Tags: webdev, git, github, programming
Published: 2024-03-13 23:03:18


O comando git checkout -f no Git é usado para mudar forçadamente para um ramo ou commit diferente e descartar quaisquer alterações locais ou modificações não confirmadas feitas no ramo atual.
A opção -f significa "forçar" e é utilizada para substituir as verificações de segurança do Git que garantem que as alterações feitas no ramo atual não sejam perdidas. Essa opção é normalmente usada quando você deseja mudar forçadamente para outro ramo e não deseja manter as alterações locais ou modificações.
Aqui está um exemplo de como usar git checkout -f:

`git checkout -f nome_do_ramo`

Este comando mudará para o ramo nome_do_ramo, sobrescrevendo quaisquer alterações locais ou modificações que foram feitas no ramo atual. É importante usar este comando com cautela, pois quaisquer alterações não salvas serão perdidas sem aviso.

O comando git reset --hard é um comando Git usado para redefinir o ramo atual para um commit anterior, descartando quaisquer alterações locais e modificações feitas nos arquivos.
A opção --hard significa "redefinição rígida" e é usada para descartar forçadamente quaisquer alterações locais e modificações feitas nos arquivos. Quando você executa git reset --hard, o Git redefine o ponteiro do ramo para o commit especificado, e quaisquer alterações feitas nos arquivos desde então são perdidas permanentemente.
Aqui está um exemplo de como usar git reset --hard:

`$ git reset --hard HEAD~2`

Este comando irá redefinir o ramo atual para o commit que está duas etapas atrás do HEAD atual. A opção --hard irá descartar quaisquer alterações locais feitas nos arquivos.
É importante usar git reset --hard com cautela, pois pode excluir permanentemente quaisquer alterações não confirmadas feitas nos arquivos. Sempre certifique-se de fazer backup de quaisquer alterações importantes antes de usar este comando.
Postgres in Docker: A Simplified Setup Process
Published: 2024-03-13 23:00:00

Simplify your PostgreSQL setup with Docker through this guide. Learn the basics of installing and running a Postgres database within a Docker container, streamlining your development process.

### Efficient Setup Instructions

1. **Ensure Docker's Presence**: Verify Docker installation.
2. **Acquire Postgres Image**: Pull the image via **`docker pull postgres`**.
3. **Establish Data Volume**: Create persistence with **`docker volume create postgres_data`**.
4. **Container Deployment**: Start with **`docker run --name postgres_container -e POSTGRES_PASSWORD=mysecretpassword -d -p 5432:5432 -v postgres_data:/var/lib/postgresql/data postgres`**.
5. **Confirmation and Connection**: Check with **`docker ps`** and connect using a PostgreSQL client.

### Key Takeaways

- **User-Friendly**: Offers an easy installation route.
- **Isolation Guarantee**: Ensures a conflict-free environment for your database.
- **Deployment Readiness**: Streamlines deployment across Docker-supportive platforms.

### Summary

Setting up PostgreSQL in a Docker container not only enhances development efficiency but also offers a scalable solution for database management. For further insights and a detailed walkthrough, please read [How to Set Up Postgres using Docker.](https://www.dbvis.com/thetable/how-to-set-up-postgres-using-docker/)
Day 926 : What I've Found
Tags: hiphop, code, coding, lifelongdev
Published: 2024-03-13 22:42:06

_liner notes_:
- Professional : No clue where the day went. I woke up. Researched some community questions. Reported back with what I've found. Had a meeting. Cleaned up some code for a couple of sample apps I wrote for some new features and wrote the readmes for them. Next thing I know, the day is over.

- Personal : I went through a bunch of tracks for the radio show and put together some of the choices. Looked up some properties. I also looked up some domain names. It was late and I was tired so I went to bed.

![This is a beautiful landscape photograph of the Tre Cime di Lavaredo, a mountain group in the Dolomites of northeastern Italy. The mountains are rugged and rocky, and are surrounded by lush forests and meadows. The sky is blue and there are some clouds covering the mountains. The sun is shining brightly, and the scene is very peaceful and serene.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/660mxoge151r03ffddy4.jpg)

Going to pick up some tracks on Bandcamp and put together some social media posts. There's a feature I want to add to my side project before I start copying over code to a new repo. Then I'll set up the new repo and start with the transfer and refactor.

Have a great night!

peace piece
Dwane / conshus
https://dwane.io / https://HIPHOPandCODE.com
{% youtube 8dpv06cxW1s %}
Step-by-Step Guide: Deploying Your Backend on Render
Tags: render, webdev, backend, deployment
Published: 2024-03-13 22:41:57

## Introduction
Learn how to deploy your backend on Render effortlessly with this comprehensive guide. Follow these steps to host your backend application on Render, a user-friendly platform built for developers.

## Prerequisites
Before we get started, ensure you have:
- Your backend application is ready for deployment (Node.js, Flask, Django, etc.)
- A Render account (Sign up [here](https://render.com/))

## Step 1: Creating a New Service on Render
1. Log in to your Render dashboard.
2. Click on **New** > **New Service**.
3. Choose your preferred deployment method, such as GitHub or Docker.

## Step 2: Configuring Your Service
1. Name your service and select the GitHub repository containing your backend code.
2. Select the branch you wish to deploy (e.g., main, master, development).
3. Specify the build command for your backend (e.g., `npm install && npm run build` for Node.js).
4. Set up any necessary environment variables for your application.
   

## Step 3: Adding a Web Service
1. Click on **Add Web Service**.

2. Configure your web service settings, including the port and health check options.
3. Save your changes.

## Step 4: Deploying Your Backend Application
1. Hit the **Deploy** button to start the deployment process.
2. Render will build and deploy your backend application.

## Step 5: Verifying Your Deployment
1. After deployment, a green checkmark next to your service indicates it's live.
2. Click on the service URL to view your deployed backend in action!

## Conclusion
Congratulations on successfully deploying your backend on Render! With Render's intuitive interface and robust features, managing your web applications is now more accessible than ever.

Explore Render's [documentation](https://render.com/docs) for advanced configurations and optimizations for your backend services.

Happy coding!
Orijinal Pod Kit Modelleri Satış Sitesi
Tags: vape, podevi, iqos, java
Published: 2024-03-13 22:41:19

Türkiye'nin en orijinal ve güvenilir elektronik sigara sitesi olan **PodEvi** php ile oluşturulmuş bir wordpress tabanlı sitedir. [https://podevi.com](https://podevi.com)
Snowpal Status Management API: Build Slack Apps, Microservices and more
Published: 2024-03-13 22:35:27

In this video, Krish introduces the Snowpal Status API and its purpose. He explains that the API is designed to manage statuses for projects and provides an interface for users to report their status. Krish discusses the features and functionality of the API, including the ability to report status as a user or admin. He also explains the components of a status, such as plan for today, sessions, and blocked by. Krish highlights the details and attributes that can be added to a status, and mentions the integration and licensing options available for the API. The podcast concludes with a summary of the API and resources for further information.

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

### Takeaways

-   The Snowpal Status API is designed to manage statuses for projects and provides an interface for users to report their status.
    
-   The API supports reporting status as a user or admin, allowing for flexibility in how statuses are updated.
    
-   A status consists of components such as plan for today, sessions, and blocked by, which provide a structured format for reporting status.
    
-   The API offers various details and attributes that can be added to a status, including tickets, sessions, and custom attributes.
    
-   Integration and licensing options are available, including SAS-based models, cloud provisioning, and licensing for DevOps and platform engineering infrastructure.
    

### Chapters

00:00 Introduction to Snowpal Status API

02:42 Features and Functionality of the Status API

03:42 Reporting Status as a User or Admin

05:08 Components of a Status

09:00 Details and Attributes of a Status

10:39 Integration and Licensing Options

12:15 Conclusion

### Video

{% embed https://youtu.be/OJ88OFrRrjU %}

### Transcript

https://products.snowpal.com/api/v1/file/4c6f7610-2f42-473c-83ca-1c818220bec1.pdf

### Summary

**Status API Details:**

-   Explanation of the status API and its purpose.
    
-   Mention of other APIs and their related podcasts.
    
-   Explanation of the absence of a user interface for the status API.
    
-   Information on accessing the API through Postman collection and product API documentation.
    

**API Features and Functionality:**

-   Purpose of the status API for managing statuses in projects.
    
-   Details on reporting statuses as a user or team member.
    
-   Features and functionalities supported by the API.
    
    -   Reporting status for today’s plan.
        
    -   Sessions and managing multiple sessions.
        
    -   Adding tickets and other items to sessions.
        
    -   Blocked by category for tracking obstacles.
        

**Technical Details and Customization:**

-   Attributes and details associated with tickets.
    
-   Mention of custom attributes and extending functionalities.
    
-   Overview of SDK availability.
    
-   Details on accessing the API, licensing models, and integration options.
How to use Async/Await with Fetch API in React Component?
Tags: help, beginners, tutorial
Published: 2024-03-13 22:30:39

Hello,

I'm trying to fetch restaurants data in React using async and await and update my restaurants state with the returned restaurants response

In the code below (under Method 2) I created an async function and called `await fetchRestaurants()` which returns a response

I don't understand why within the aync function, I'm able to access the list of restaurants data. However, when I return the data, it's a promise

Can someone explain why this happens?

```
  const fetchRestaurants = () => {
    ...
    // returns {Promise<Array<{ name: string, rating: number,  location: string}>}
  }

   const [restaurants, setRestaurants] = useState([]);

    useEffect(() => {
        // Method 1 - works!
        const promise = fetchRestaurants();

        promise
             .then((data) => {
                 setRestaurants(data);
             })
             .catch((error) => {
                 console.error(error);
             });

        // Method 2 - doesn't work
        const asyncFetchRestaurants = async () => {
            try {
                const data = await asyncFetchRestaurants();
                console.log("INSIDE", data); // this prints out the list of restaurants
                return data; // why does this return a promise?
            } catch (error) {
                console.error(error);
            }
        };

        const data = asyncFetchRestaurants(); // why is data a promise and not a list of restaurants
        console.log("OUTSIDE", data); // this prints out a promise!
        setRestaurants(data) // this doesn't work! 
    }, []);
```
Developer diary #7. Variety
Tags: android, gradle, programming, cicd
Published: 2024-03-13 22:18:47

For the last several months, I have worked with different CI/CD tools. The main reasons to use it were  automation checks, preparation and distribution builds. It was needed for Android and iOS (native or cross-platform). 

Every time, it requires writing several configuration YAML files, that hold different steps of your pipelines. Every approach requires its own syntax and has specific limitations. 

When you read the existing code base and pipelines, in general, you understand what happens in them for the first time. But when you try to write your own pipeline, you spend so much time. Because, you move by the trial-and-error method.

I don't feel very happy with it, because you get very specific knowledge, that you can't use anywhere except this project.