teleren/devto huggingface dataset:
A practical summary of React State variables & Props!
Tags: reactjsdevelopment, state, props, react
Published: 2024-06-21 20:49:37

There are so many videos and documentation out there to help you learn the concept and usage of _State_ and _Props_ with code examples. this article is not about teaching you these concepts from scratch or providing you with code examples. The main point of this blog is to briefly give you a practical summary of **what they are** and **when to use them**. So, if you are completely new to these concepts, I would suggest you first watch some basic tutorials about them to get the most out of this summary.

## State
### What is State?
The state variable is a plain JavaScript object used by React that includes all information about the component's current situation. State variables are immutable and private to that component.

### When do we need a state for a component?

- Whenever you need to change/update part of the UI
- Whenever the user is supposed to interact with the UI
- Whenever you need to persist local variables between renders

### Using state correctly:
- States are immutable. The component that owns a piece of the state, should be the one that modifies it. Do not modify the state directly. Instead, use **setState()**.
- State updates may be asynchronous. So, if you need to use the value of _this.props_ and _this.state_ to calculate the next state value, instead of directly passing an object to _setState()_ pass a callback function with the _state_ and _props_ as arguments.
- State updates are merged.
- The data flows down.

### How does setState() work? 
This method tells React that we are updating the state. Then, React checks which parts of the state are changed to bring the DOM in sync with the virtual DOM based on those changes.

Note: **props** is basically a plain JavaScript object that includes all the attributes that we set in the parent component. Every React component has the _props property_. It is used to pass data from a parent component to a child. It is _“read-only”_ and cannot be modified, if we need to do so, we should use setState and modify them from the state.

## State vs props
#### Ownership and Control:
**State:** Internal data, owned and controlled by the component itself.
**Props:** External data, owned and controlled by the parent component.

#### Conceptual Understanding:
**State:** Can be thought of as the component's memory, holding data over time across multiple re-renders.
**Props:** Like function parameters, used to pass data from parent to child components.

#### Mutability and Effects:
**State:** Can be updated by the component itself, triggering a re-render.
**Props:** Read-only, cannot be modified by the receiving component. Receiving new props also causes a re-render.

#### Usage: 
**State:** Used to make components interactive.
**Props:** Used to configure child components from the parent component.

**Note:** Whenever a piece of state is updated, the component that owns the state, and all children components that receive the piece of state as props will be re-rendered to keep in sync.
Aplicacion para descargar imagenes de una página web
Tags: csharp, projects
Published: 2024-06-21 20:32:15

Hace algun tiempo tuve la necesidad de descargar las imágenes de una página web. Esto sería tarea sencilla de no ser porque existian mas de 50 imágenes en esa página. ASi que me propuse a realizar una aplicación de escritorio que se encargue de realizar ese trabajo por mi.

Pueden encontrar la aplicación y el codigo fuente [aqui](https://bitbucket.org/re_al_/real.downloadwebimages).

Me comentan que tal les va.
Mostrar archivo PDF alojado en un servidor FTP con C#
Tags: csharp, ftp, pdf
Published: 2024-06-21 20:30:59

Tenemos un repositorio FTP donde varias oficinas en distintos lugares van alojando archivos PDF que generan con información de su respectivo trabajo. Basicamente todos pueden acceder al FTP y consultar los documentos subidos.

Sin embargo, un nuevo requerimiento necesitaba revisar y calificar el documento. Para ello, se necesitaba que el sistema web que se maneja, muestre los archivos PDF desde el FTP (sin necesidad de descargarlos todos al servidor web).

Buscando, pude encontrar soluciones parciales, pero al final llegué a este bloque de código que me permitía visualizar el archivo requerido:

```csharp
FileInfo objFile = new FileInfo(filename);
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + filename));
request.Credentials = new NetworkCredential(Ftp_Login_Name, Ftp_Login_Password);

FtpWebResponse response = (FtpWebResponse)request.GetResponse();

Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);

byte[] bytes = null;
using (var memstream = new MemoryStream())
{
    reader.BaseStream.CopyTo(memstream);
    bytes = memstream.ToArray();
}

Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "inline; filename=" + objFile.Name);
Response.BinaryWrite(bytes);
Response.End();
```
ClosedXML y el uso de plantillas
Tags: netframework, corenet, closedxml, excel
Published: 2024-06-21 20:29:26

Para facilitar la tarea de crear reportes o documentos en formato XLS o XLSX, se tiene el paquete ClosedXML. El mismo tiene soporte para el uso de templates.

Lo primero que tenemos que hacer es instalar el paquete Nuget en nuestro proyecto:

```
PM> Install-Package ClosedXML
```

Después, el bloque de codigo necesario para mostrar un excel a partir de una plantilla es:

```csharp
var strTitulo = "Titulo del reporte";
var dtReporte = ObtenerDatosReporte(); //Funcion que devolverá un DataTable

//Definimos la plantilla y la utilizamos con la libreria ClosedXML
var template = Server.MapPath("~/doc_templates/Reporte.xlsx");
using (var wb = new XLWorkbook(template))
{
    //Ponemos algunos valores en el documento
    wb.Worksheets.Worksheet(1).Cell(5, 1).Value = strTitulo;

    //Podemos insertar un DataTable
    wb.Worksheets.Worksheet(1).Cell(9, 1).InsertTable(dtReporte);
    //Aplicamos los filtros y formatos a la tabla 
    wb.Worksheets.Worksheet(1).Table("Table1").ShowAutoFilter = true;
    wb.Worksheets.Worksheet(1).Table("Table1").Style.Alignment.Vertical =
        XLAlignmentVerticalValues.Center;
    wb.Worksheets.Worksheet(1).Columns(2, 2 + dtReporte.Columns.Count).AdjustToContents();

    //Limitamos el ancho de las columnas a 60
    foreach (var column in wb.Worksheets.Worksheet(1).Columns())
        if (column.Width > 60)
        {
            column.Width = 60;
            column.Style.Alignment.WrapText = true;
        }

    wb.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
    wb.Style.Font.Bold = true;

    //Enviamos el archivo al cliente
    Response.Clear();
    Response.Buffer = true;
    Response.Charset = "";
    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    Response.AddHeader("content-disposition", "attachment;filename=\"" + strTitulo + ".xlsx\"");

    using (var myMemoryStream = new MemoryStream())
    {
        wb.SaveAs(myMemoryStream);
        myMemoryStream.WriteTo(Response.OutputStream);
        Response.Flush();
        Response.End();
    }
}
``` 

Para acceder a la documentación del proyecto, pueden ingresar a su [repositorio](https://github.com/closedxml/closedxml)
Generar colores hexadecimales aleatorios con Postgres
Tags: sql, postgres, hex
Published: 2024-06-21 20:25:18

Hoy me he visto en la necesidad de obtener Varias fechas de una tabla en PostgreSql y mostrar cada una con un color diferente en un Sistema Web.

Mi primera alternativa era buscar una funcion en PHP que me permitiera generar colores hexadecimales aleatorios, pero como tengo más experiencia en PLPgSql, decidí empezar por ahí. 

Primero lo primero: todos sabemos que un color hexadecimal es la presentacion de 3 numeros en el rango de 0-255 convertidos a base 16. Pues bien por ahí es por donde empece: generar un numero aleatorio en el rango de 0 a 255. 

```sql
SELECT trunc(random() * 255)::INTEGER
```

Ahora necesitamos una función que convierta un numero de Base 10 a Base 16: Para ello necesitamos la siguiente funcion: 

```sql
CREATE OR REPLACE FUNCTION b10_b16(digits bigint, min_width integer DEFAULT 0)
  RETURNS character varying AS
$BODY$
DECLARE
    chars char[]; 
    ret varchar; 
    val bigint; 
BEGIN
    chars:=ARRAY['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'];
    val := digits; 
    ret := ''; 
    IF val < 0 THEN 
        val := val * -1; 
    END IF; 
    WHILE val != 0 LOOP 
        ret := chars[(val % 16)+1] || ret; 
        val := val / 16; 
    END LOOP;

    IF min_width > 0 AND char_length(ret) < min_width THEN 
        ret := lpad(ret, min_width, '0'); 
    END IF;

    RETURN ret;
END;
$BODY$
  LANGUAGE plpgsql IMMUTABLE
  COST 100;
```

El uso de ésta función es: 

```sql
SELECT b10_b16(45);
--Devolverá el Dato 2D

SELECT b10_b16(11);
--Devolverá el Dato B

SELECT b10_b16(11,2)
--Devolverá el Dato 0B
```

Con todo ésto tenemos la Base para generar un color aleatorio: 

```sql
SELECT '#' || 
        b10_b16(trunc(random() * 255)::INTEGER,2) || 
        b10_b16(trunc(random() * 255)::INTEGER,2) || 
        b10_b16(trunc(random() * 255)::INTEGER,2) AS color

--Devolvera algo así: #69A51D
```

Y listo!!!

Ya tenemos nuestra función que genera colores hexadecimales ALEATORIAMENTE!!!
6 Captivating Linux Command Line Tutorials from LabEx 🐧
Tags: linux, coding, programming, tutorial
Published: 2024-06-21 20:13:08


Welcome to an exciting journey through the realm of Linux command line mastery! LabEx, the premier platform for hands-on technical education, has curated a collection of six captivating tutorials that will empower you to navigate the Linux ecosystem with confidence and finesse.

## Unravel the Mysteries of Linux Processes 🕰️

Dive into the ancient Empire of Linutopia, where the wise Emperor Forkius Maximus reigns supreme. Explore the mystical prowess of signal handlers and Process Oracles as you learn to master the art of Linux process waiting in our [Linux Process Waiting](https://labex.io/labs/271433) tutorial.

## Streamline Your Text Manipulation with the `nl` Command 📄

Discover the power of the `nl` command in Linux, and learn how to efficiently number lines in your text files with our [Linux nl Command: Line Numbering](https://labex.io/labs/210988) tutorial.

## Conquer the Virtual Battlefield with Directory Mastery 🗂️

As an elite Virtual Reality Military Strategist, you'll navigate through a myriad of data, directories, and software tools in our [Linux Directory Displaying](https://labex.io/labs/271365) tutorial, ensuring a streamlined flow of operations within your digital command center.

## Unveil the Secrets of the Enchanted Forest with Text Display 📖

Step into the role of the Forest's Arcane Hunter and harness the power of Linux commands to unveil the secrets hidden in plain sight, as you explore our [Linux Text Display](https://labex.io/labs/271273) tutorial.

## Showcase Your System's Elegance with Neofetch 🖥️

Learn how to use Neofetch, a command-line tool that displays aesthetic information about your system and its configuration, in our [Display OS Info Stylishly with Neofetch](https://labex.io/labs/299825) tutorial.

## Unlock the Power of Shell Variables 💻

Delve into the world of shell variables and discover how to store and manipulate data in shell scripts, as you work through our [Working with Shell Variables](https://labex.io/labs/153894) tutorial.

Embark on this captivating journey through the Linux command line, and unlock the full potential of your system with the help of these expertly crafted tutorials from LabEx. Happy learning! 🎉

---

## Want to learn more?

- 🌳 Learn the latest [Linux Skill Trees](https://labex.io/skilltrees/linux)
- 📖 Read More [Linux Tutorials](https://labex.io/tutorials/category/linux)
- 🚀 Practice thousands of programming labs on [LabEx](https://labex.io)

Join our [Discord](https://discord.gg/J6k3u69nU6) or tweet us [@WeAreLabEx](https://twitter.com/WeAreLabEx) ! 😄
The "Works on My Machine" Curse: Slaying the Productivity Dragon in Local Development
Tags: developerlife, developerproductivity, devrel, cloudnative
Published: 2024-06-21 19:59:34

## Introduction
Ever spent hours coding something that works perfectly on your machine, only to see it mysteriously fail for others? The "Works on My Machine" (WOMMM) phenomenon strikes again!

We've all been there. Different operating systems, software versions, and local configurations can turn a seemingly perfect solution into a frustrating puzzle.
&nbsp;

## Summary 
**The WOMMM Productivity Drain**
WOMMM isn't just annoying, it's a productivity killer. It leads to:
Debugging black holes: Time wasted chasing ghosts, trying to fix issues specific to your local setup.

- **Version control chaos:** Code that works for you breaks for others, causing merge conflicts and delays.
- **Onboarding roadblocks:** New team members struggle to get started if their environment doesn't match yours.
- **Production pandemonium:** Bugs that go undetected locally cause major headaches when deployed.

&nbsp;

**Taming the Beast**
Don't fret over the "Works on My Machine" monster! We can achieve developer satisfaction by embracing:

- Version control to track code changes
- Standardization to use same versions of libraries and frameworks
- Containerization to allow consistent environments that everyone can use
- Automated testing to catch bugs early before they become major issues
- Collaboration and open communication to reduce onboarding and support challenges

&nbsp;

## The Takeaway
By taming the beast, we can create a unified development experience, boosting productivity and ensuring smooth code deployment. Remember, happy developers lead to better code, and a consistent development environment paves the way for success.

---


Let's keep the conversation going! Share your tips and WOMMM horror stories in the comments below.
Looking for a tech cofounder (golfer desired)
Tags: partner, cofounder, startup
Published: 2024-06-21 19:58:31

Hi guys, I am looking for a technical co-founder for my startup birdiefit.com. If you are or if you know a developer who is also a golfer, comment or DM me.

The app already has paying customers. The ideal person will take care of the technical side of things, making sure the code is neat, new features are implemented, and existing features working properly. We already have a few customers wanting to join, conditioned upon the release of new features.

Knowledge of golf is desired as we will all be in touch with our ideal customer personas - golfers.

The main feature of the app is the ability to create practice programs for months ahead of time in just a few clicks. The library consists of 700+ golf drills.

Cheers,
Luka Karaula
Reach out at info(at)birdiefit.com

#startup #cofounder #golf #business #connection
The RSA Algorithm
Tags: devchallenge, cschallenge, computerscience, beginners
Published: 2024-06-21 19:39:50

*This is a submission for [DEV Computer Science Challenge v24.06.12: One Byte Explainer](https://dev.to/challenges/cs).*

## Explainer

The RSA algorithm encrypts with a public key and decrypts with a private key. The former is based on a product of two primes; these primes generate the latter. Large key size makes factorization hard for unauthorized decryption, guaranteeing security. 


<!-- Please share any additional context you think the judges should take into consideration as it relates to your One Byte Explainer. -->

<!-- Team Submissions: Please pick one member to publish the submission and credit teammates by listing their DEV usernames directly in the body of the post. -->

<!-- Don't forget to add a cover image to your post (if you want). -->

<!-- Thanks for participating! -->
Understanding JavaScript Promises
Tags: webdev, javascript, beginners, programming
Published: 2024-06-21 19:26:37

**Introduction**

JavaScript Promises are a powerful way to handle asynchronous operations, allowing you to write cleaner and more manageable code. In this post, we'll dive deep into Promises and explore how they can improve your code.


**Understanding Promises**
A Promise in JavaScript represents the eventual completion (or failure) of an asynchronous operation and its resulting value.

**How you can create Promises**
You can create a new Promise using the `Promise` constructor, which takes a function with two parameters: `resolve` and `reject`.


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

**Promise Methods**
Promises have several methods to handle the result of the asynchronous operation.

**`.then()`**
The .then() method is used to handle the resolved value.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fz4ds136krhcbmn1et23.png)

**`.catch()`**
The .catch() method is used to handle errors or rejected promises.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mm3pltdvqhcmgx1yjga5.png)

**`.finally()`**
The .finally() method is executed regardless of the promise's outcome.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9b2dqimxz7dwt221zrqd.png)

**Promises Chaining**
Promises can be chained to perform multiple asynchronous operations in sequence.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pmmzf3s96g92uoik8zxk.png)

**Handle Error**
Proper error handling in Promises is crucial for robust code.

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

**Conclusion**
JavaScript Promises provide a powerful way to handle asynchronous operations. By understanding and utilizing Promises, you can write cleaner, more efficient, and more readable code.

Happy Coding (:
Follow for more "_"
Unlock Creativity with MonsterONE!
Tags: website, webcomponents, themes, webdev
Published: 2024-06-21 19:22:09


Hey there! 👋 As a seasoned web developer, I'm excited to share my experience with **MonsterONE** - the ultimate subscription service for all things web development! With **MonsterONE**, I've unlocked a treasure trove of digital assets, from **WordPress themes** to graphic designs and audio/video resources.

The variety and quality of assets available are unmatched, and they've saved me countless hours of design and development work. Whether I'm designing marketing materials, or producing engaging videos, **MonsterONE** has everything I need - and then some!

What's more, **MonsterONE** offers flexible subscription plans tailored to your needs. Plus, you can enjoy an exclusive 10% OFF on any **MonsterONE** plan using the promo code [**HasnainDeveloper**] at checkout!.
So, if you're serious about web development or marketing content creation, I highly recommend giving **MonsterONE** a try.

🔗 Explore **MonsterONE** now: https://monsterone.com/pricing/?discount=HasnainDeveloper
10 secret rules of Development every Programmer should know
Tags: jokes, watercooler
Published: 2024-06-21 19:07:16

Every profession has its quirks and unspoken rules, and development is no exception. 
From the inexplicable faith in turning it off and on again (hey, it often works!) to the mysterious art of centering a div (this doesn't work as often🥲), here are ten secrets that every programmer will nod knowingly about.

### 1. **If It Works, Don't Touch It**
There's code, and then there's code you don't touch because the last time you did, it took three days to fix.

### 2. **The Console Log is Your Best Friend**
Who needs a debugger when you have `console.log()`? It’s the Swiss Army knife of debugging.

### 3. **Comment Your Code As If Your Job Depends on it**
 Self-explanatory, and yet, future you will still wonder what the past you was thinking.

### 4. **Google Is the Co-Developer of Every Project**
Stack Overflow might as well be on your payroll, considering how much it contributes.

### 5. **Not All Heroes Wear Capes, Some Just Write Documentation**
Bless those souls who actually document their code. They save lives.

### 6. **Some Bugs Could Have Been a Feature**
Sometimes the line between a bug and a feature is just a matter of timing and presentation.

### 7. **'It Works on My Machine' Should Be an Official Development Stage**
The first stage of grief in debugging is denial.

### 8. **Every Developer Has a Personal Repository of Snippets They Don’t Share**
These are the family jewels, handed down from one generation of projects to another. 

### 9. **The More Urgent the Deadline, the More Likely You Are to Break the Build**
Murphy’s Law is especially potent in the development environment.

### 10. **The Number of Browser Tabs You Have Open Is Directly Proportional to How Close the Project Deadline Is**
 By the end of a project, you could probably scroll through tabs faster than you can scroll through your code.

## Community is the bigger secret
Just like the secret rules shared in this article, the best tricks in development often come from the collective wisdom and contributions of the community. 
If you enjoyed uncovering these secrets, consider contributing to the magic by starring our project, Webcrumbs, on GitHub. Your support helps us continue to unveil hidden gems and build tools that empower developers like you.

[Star Webcrumbs on GitHub ⭐️](https://github.com/webcrumbs-community/webcrumbs)


Thank you for reading,

Pachi 💚
Recursion: Computer Science Challenge
Tags: devchallenge, cschallenge, computerscience, beginners
Published: 2024-06-21 19:03:05

*This is a submission for [DEV Computer Science Challenge v24.06.12: One Byte Explainer](https://dev.to/challenges/cs).*

## Explainer

<!-- Explain a computer science concept in 256 characters or less. -->
**Recursion**: A function that calls itself! Solves problems by breaking them into smaller, similar problems. Powerful for complex tasks but requires careful design to avoid infinite loops.



## Additional Context

<!-- Please share any additional context you think the judges should take into consideration as it relates to your One Byte Explainer. -->
resources: [About Recursion](https://en.wikipedia.org/wiki/Recursion_(computer_science))


<!-- Don't forget to add a cover image to your post (if you want). -->

<!-- Thanks for participating! -->