teleren/devto huggingface dataset:
Leveraging useRef in TypeScript for Efficient DOM Manipulation
Tags: typescript, react, useref, dom
Published: 2024-04-06 14:08:25

When it comes to managing DOM elements in React applications, the useRef hook emerges as a powerful ally, particularly when working with TypeScript. useRef allows us to reference DOM elements directly, facilitating tasks such as focusing inputs, measuring elements, or even integrating with third-party libraries.

 
Understanding useRef in TypeScript:
In TypeScript, useRef is declared with a generic type parameter, specifying the type of the referenced element. This enhances type safety, ensuring that the referenced element matches the expected type.

```
import { useRef } from 'react';

// Example of useRef with TypeScript
const myRef = useRef<HTMLDivElement>(null);
```
 
Practical Examples:

## Accessing DOM Elements:

```
import { useRef, useEffect } from 'react';

const MyComponent: React.FC = () => {
  const inputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    if (inputRef.current) {
      inputRef.current.focus();
    }
  }, []);

  return <input ref={inputRef} />;
};
```

## Managing Previous State:

```
import { useRef, useEffect } from 'react';

const MyComponent: React.FC = () => {
  const prevValueRef = useRef<number>(0);
  const [value, setValue] = useState<number>(0);

  useEffect(() => {
    prevValueRef.current = value;
  }, [value]);

  return (
    <>
      <p>Previous Value: {prevValueRef.current}</p>
      <input
        type="number"
        value={value}
        onChange={(e) => setValue(parseInt(e.target.value))}
      />
    </>
  );
};
```

## Interfacing with Third-party Libraries:

```
import { useRef, useEffect } from 'react';
import * as d3 from 'd3';

const MyD3Component: React.FC = () => {
  const svgRef = useRef<SVGSVGElement>(null);

  useEffect(() => {
    if (svgRef.current) {
      const svg = d3.select(svgRef.current);
      // D3 code for visualization
    }
  }, []);

  return <svg ref={svgRef}></svg>;
};
 
```
Benefits of useRef in TypeScript:
Type Safety: TypeScript ensures that the referenced elements adhere to the specified type, reducing runtime errors.
Efficient DOM Manipulation: useRef facilitates direct access to DOM elements, enabling efficient operations like focusing inputs or integrating with external libraries.
Enhanced Code Readability: By providing a clear reference to DOM elements, useRef improves code readability and maintainability.
 
In conclusion, the useRef hook in TypeScript significantly enhances the management of DOM elements in React applications. Its integration provides type safety, efficiency, and clarity, empowering developers to build robust and scalable user interfaces.

Reference:
[Leveraging useRef in TypeScript for Efficient DOM Manipulation](https://fabra.dev/blog/leveraging-useref-typescript-efficient-dom-manipulation)
Learn Crucial ML Math via Interesting Stories : Weighted Sum in Neural N/W
Tags: machinelearning, ai, learning, algorithms
Published: 2024-04-06 13:59:49

**Alex and Straw: The Adaptable Weighted Sum Scarecrow**

[Full Article](https://medium.com/@learn-simplified/learn-crucial-ml-math-via-interesting-stories-weighted-sum-in-neural-n-w-b620fb3eea46)

Join Alex, a budding farmer, and Straw, his extraordinary scarecrow friend, on a journey that demystifies this crucial math concept.

🧠 Learn why understanding Weighted Sum is vital, even if you're not building complex ML models, as it underpins powerful Neural Networks.

🌾 Discover how Straw's clever math formula helped Alex navigate farming challenges, adjusting weights for soil, weather, and market demand.

🔄 Witness the iterative process of "epochs" as Straw refines his formula, adapting to successes and failures, just like Neural Networks learn through feedback.

🚜 Explore the parallels between Straw's ever-evolving Weighted Sum and the ability of Neural Networks to continuously improve through weight adjustments.

💡 Gain profound insights into the iterative nature of learning, the importance of resilience, continuous refinement, and perseverance – applicable to both farming and engineering Neural Networks.

📖 Let's go on this tale that makes complex math concepts accessible, highlighting the transformative power of adaptability and lifelong learning.

🌟 Get ready to uncover the secrets of Weighted Sum in Neural Networks through an engaging story that will leave you inspired and equipped with valuable knowledge.

There's more math w/ fun on the way....
Understanding Intersection Types in TypeScript
Published: 2024-04-06 13:59:19

## Introduction
Intersection types are an essential feature in TypeScript that allow developers to combine multiple types into a single type. This powerful tool enhances type safety and flexibility in codebases. In this article, we'll delve into what intersection types are, how they work, and explore some practical use cases in TypeScript.

 

## What are Intersection Types?
Intersection types in TypeScript are denoted by the & symbol and are used to combine multiple types into a single type that has all the features of each constituent type. When a value is of an intersection type, it must satisfy all the types included in the intersection.

Syntax:

```
type CombinedType = Type1 & Type2;
```

Example:

```
type Dog = {
  name: string;
  breed: string;
};

type Bird = {
  name: string;
  wingspan: number;
};

type Pet = Dog & Bird;

const myPet: Pet = {
  name: "Charlie",
  breed: "Labrador",
  wingspan: 30,
};
```
 
Use Cases:

## Extending Object Types:
Intersection types are useful when extending object types with additional properties while retaining the original properties.

```
type User = {
  id: number;
  name: string;
};

type Admin = {
  id: number;
  role: string;
};

type SuperAdmin = User & Admin;

const superAdminUser: SuperAdmin = {
  id: 1,
  name: "John Doe",
  role: "Super Admin",
};
```


## Combining Function Signatures:
Intersection types can combine multiple function signatures, allowing functions to accept different parameter types or return multiple types.

```
type Logger = (message: string) => void;
type Formatter = (message: string) => string;

type LogFormatter = Logger & Formatter;

const logAndFormat: LogFormatter = (message) => {
  console.log(message);
  return `Formatted: ${message}`;
};
```
 

## Conclusion
Intersection types in TypeScript provide a powerful mechanism for creating complex types by combining multiple types. They offer enhanced type safety and flexibility, enabling developers to express richer data structures and function signatures in their code.

 
Explore more about TypeScript's intersection types and unleash their potential in your projects!

References:
[Understanding Intersection Types in TypeScript](https://fabra.dev/blog/intersection-types-typescript-guide)
[Intersection Types](https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html)
Are Inline Styles Faster than CSS?
Tags: webdev, html, css, performance
Published: 2024-04-06 13:49:20

https://danielnagy.me/posts/Post_tsr8q6sx37pl

TL;DR

I recently migrated my website from CSS-in-JS to inline styles and was pleasantly surprised by the performance improvement. Encouraged by this, I wrote a blog post suggesting that inline styles could enhance website load times.

However, some skeptics rightly pointed out that my migration from a specific CSS-in-JS library to inline styles wasn't sufficient evidence to claim inline styles were faster than CSS. Determined to uncover the truth, I embarked on a comprehensive experiment.

The experiment involved migrating my entire website to CSS, a painstaking process. I meticulously crafted over 2,000 lines of handwritten CSS, utilizing BEM for component styling and atomic CSS for non-component elements. Then, I built three versions of my React app: one with inline styles, one with a separate CSS file, and one with CSS inlined in the document head.

Deploying all versions to a single testing environment, I meticulously measured various metrics including server render time, HTML and JavaScript sizes, browser render time, and web vitals.

Server render times showed no significant correlation between inline styles and CSS. HTML size comparison revealed inline styles producing larger documents, yet after compression, they were smaller than inline CSS due to compression efficiency. JavaScript bundle size increased slightly with inline styles but became negligible after compression, resulting in the fewest bytes over the wire.

Browser render performance favored inline styles, particularly in putting pixels on the screen quickly, especially evident on low-powered devices. Web vitals, including first contentful paint and largest contentful paint, often favored inline styles over CSS.

In conclusion, my experiment suggests that inline styles could offer better performance than CSS, especially considering factors like browser rendering and initial page load. However, I acknowledge that this may not be universally true and encourage others to conduct their own experiments to gather more data.
ثبت نام بازی انفجار
Published: 2024-04-06 13:38:22

## ثبت نام در سایت بازی انفجار و تجربه هیجان بی حد و مرز!

آیا به دنبال یک بازی جذاب و هیجان انگیز هستید که بتوانید در آن پولدار شوید؟
بازی انفجار بهترین گزینه برای شماست! این بازی با ضرایب بالا و گیم پلی ساده، به شما فرصتی برای کسب سودهای میلیونی در کوتاهترین زمان ممکن را می‌دهد.
[ثبت نام بازی انفجار](https://enfejar.website/enfejar-register/) آسان تر از چیزی است که فکر می‌کنید! فقط کافیست مراحل زیر را دنبال کنید:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ttpwd62zy3j3bjhytjaz.jpg)
1. به یکی از سایت‌های معتبر بازی انفجار مراجعه کنید.
2. در صفحه اصلی سایت، گزینه "ثبت نام" را انتخاب کنید.
3. اطلاعات شخصی خود مانند نام و نام خانوادگی، شماره تلفن همراه، آدرس ایمیل، رمز عبور و نام کاربری را وارد کنید.
4. قوانین و مقررات سایت را مطالعه و در صورت موافقت، تیک مربوطه را بزنید.
5. روی دکمه "ثبت نام" کلیک کنید.
پس از ثبت نام، شما می‌توانید:
از بونوس‌های ثبت نام و هدایای ویژه سایت بهره‌مند شوید.
در تورنمنت‌ها و مسابقات مختلف شرکت کنید و جوایز ارزنده‌ای را کسب کنید.
با ضرایب بالا و حداقل واریز و برداشت، شانس خود را برای کسب سودهای میلیونی امتحان کنید.
همین امروز در سایت بازی انفجار ثبت نام کنید و طعم شیرین پیروزی را بچشید!
**چرا بازی انفجار؟
**بازی انفجار یکی از محبوب‌ترین بازی‌های آنلاین در دنیای امروز است و هر روز جذابیت بیشتری برای بازیکنان جدید به خود جلب می‌کند. این بازی با ارائه‌ی گزینه‌های مختلف و جذاب برای شرط‌بندی، موفق به جلب توجه بسیاری از علاقه‌مندان به بازی‌های آنلاین شده است. اما چرا این بازی به این اندازه محبوب است؟
یکی از دلایل اصلی محبوبیت بازی انفجار، سادگی و آسانی در فهم قوانین آن است. بازی انفجار یک بازی شانسی است که در آن شما باید شرط بندی کنید که آیا مقدار انفجار بالا خواهد رفت یا نه. این سادگی باعث شده تا حتی افرادی که تازه وارد دنیای بازی‌های آنلاین شده‌اند، بتوانند به راحتی بازی را فهمیده و لذت ببرند.
یک دلیل دیگر برای محبوبیت بازی انفجار، امکان برنده شدن بزرگ و سریع در این بازی است. با انفجار اعداد بزرگ، شما می‌توانید به سرعت پول زیادی را به دست آورید و این امر باعث می‌شود که بازی برای شما جذاب‌تر شود. این امکان برنده شدن بزرگ و سریع، باعث شده تا بازی انفجار یکی از محبوب‌ترین گزینه‌ها برای کسب درآمد از طریق بازی‌های آنلاین باشد.
همچنین، امکان شرط بندی با مقدار مختلف پول و انتخاب زمان بازی کردن، باعث می‌شود تا بازی انفجار برای هر نوع بازیکنی جذاب باشد. این امکانات و گزینه‌های مختلف، باعث می‌شود تا هر بازیکن بتواند با توجه به تجربه و سلیقه‌ی خود، بازی را به شکلی که دوست دارد تجربه کند.

- ساده و هیجان انگیز: قوانین بازی بسیار ساده هستند و به راحتی قابل یادگیری می‌باشند.
- سودآوری بالا: با استفاده از استراتژی‌های مختلف، می‌توانید شانس برد خود را افزایش داده و سودهای میلیونی کسب کنید.
- قابل دسترس: این بازی در اکثر سایت‌های شرط‌بندی ایرانی ارائه می‌شود و به راحتی قابل دسترسی است.
- پشتیبانی قوی: سایت‌های معتبر بازی انفجار از پشتیبانی قوی و پاسخگو برخوردار هستند.
React + vite porque usar ?
Published: 2024-04-06 12:24:32



### **Primeiro vamos entender os conceito do dois.**


React e Vite são duas ferramentas populares no ecossistema de desenvolvimento web, e elas podem ser usadas juntas para criar aplicações web modernas de forma eficiente. Aqui estão algumas razões pelas quais você pode querer usar React e Vite em conjunto:

React: React é uma biblioteca JavaScript de código aberto mantida pelo Facebook. Ela é amplamente utilizada para criar interfaces de usuário (UI) interativas e reativas. Com React, você pode dividir sua interface de usuário em componentes reutilizáveis, facilitando a construção e manutenção de grandes aplicações web.

Vite: Vite é uma ferramenta de construção de aplicações web extremamente rápida e leve. Ela se destaca por sua inicialização rápida e tempos de compilação instantâneos, graças ao uso de carregamento de módulos em tempo real (ESM) durante o desenvolvimento. Vite suporta React, Vue.js, e outras estruturas populares.

### **Porque usar e qual é a vantagem de se usar vite no react ?**

1- Desenvolvimento rápido: Ao combinar React e Vite, você obtém um ambiente de desenvolvimento rápido que permite visualizar as alterações instantaneamente no navegador. Isso é especialmente útil durante o desenvolvimento iterativo, pois elimina o tempo de espera entre fazer uma alteração no código e ver o resultado.

2- Melhor desempenho: Vite otimiza a compilação e a execução do código, o que pode resultar em uma melhor experiência do usuário final devido a tempos de carregamento mais rápidos e menor utilização de recursos.

3- Suporte a TypeScript: Tanto React quanto Vite têm suporte nativo ao TypeScript. Isso é benéfico se você prefere utilizar TypeScript para adicionar tipagem estática ao seu código, o que pode ajudar a detectar erros mais cedo e a melhorar a manutenibilidade do código.

4- Ecossistema robusto: React possui um vasto ecossistema de bibliotecas e ferramentas que podem ser facilmente integradas ao seu projeto. Vite, por sua vez, é uma ferramenta nova e em rápido desenvolvimento, que está ganhando popularidade rapidamente devido à sua abordagem inovadora para o desenvolvimento web.

Resumindo, usar React e Vite juntos pode proporcionar um ambiente de desenvolvimento ágil e eficiente, permitindo que você construa aplicações web modernas com melhor desempenho e experiência do usuário.

Para saber mais e saber como instalar a biblioteca acesse :
https://vitejs.dev/guide/
Ibuprofeno.py💊| #73: Explica este código Python
Tags: python, spanish, programming, beginners
Published: 2024-04-06 13:00:00

## **<center>Explica este código Python</center>**
#### <center>**Dificultad:** <mark>Fácil</mark></center>

```py
print(list("Hola python"))
```

👉 **A.** `['Hola', ' ', 'python']`
👉 **B.** `['H', 'o', 'l', 'a', ' ', 'p', 'y', 't', 'h', 'o', 'n']`
👉 **C.** `SyntaxError`
👉 **D.** `Ninguna de las anteriores`

---

{% details **Respuesta:** %} 

👉 **B.** `['H', 'o', 'l', 'a', ' ', 'p', 'y', 't', 'h', 'o', 'n']`

En Python podemos usar la función `list()` para convertir valores iterables (como por ejemplo un string) a una lista. De esta manera, cada caracter del iterable se convierte en un item para la lista. 

{% enddetails %}
Viju streaming platform design development
Tags: videostreaming, uidesign, mobiledesign, productdesign
Published: 2024-04-06 12:59:18

Viju streaming platform's design development involved thorough research to enhance user experience. By focusing on user preferences and behaviors, they created kinoms, short film fragments, and conducted MVP discussions. Prototyping and testing ensured usability, while incorporating branding elements and designing for multiple platforms ensured consistency. The result is an improved platform ready to compete in the online entertainment market, thanks to collaborative efforts between Viasat and Evrone.

[Read the full case study here.](https://evrone.com/cases/viasat-design)

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

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

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

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y6j4quq773xm52ls9r9w.png)
Data preprocessing for extractive QA
Tags: beginners, machinelearning, ai, nlp
Published: 2024-04-06 12:49:50

I want to start a new project to do extractive QA based on a certain text corpus that is hundred of pages long but I don't know how to preprocess the data. I was planning on training BERT on the text corpus that looks like this:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o099kv9j4o8eb5zn7gzw.jpg)
How can I turn this into something that BERT can learn from? If you need me to clarify on anything, just ask. All help is appreciated.
Day 6/366
Tags: 1percentplusplus, 100daysofcode
Published: 2024-04-06 12:27:41

🚀 **Today's Learning:**

🌟 DSA

- To Lower Case - Leetcode 709
- Count vowels & consonants in a string

🌟 Dev

- Abstraction and Private Variables/Methods in JS
- Pass by Value vs Pass by Reference
- Callback Hell and Prevention

🔍 **Some Key Highlights:**

DSA

**To Lower Case - Leetcode 709**

Approach → Iterate through the string → if s[i] is ≥ 65 and s[i] ≤ 90 this means it’s a uppercase letter, so just add 32 to it so it goes to lowercase letter range. Note: uppercase and lowercase letters have a fixed difference of 32.


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

**Count vowels & consonants in a string**

Approach → create two variables - vCount and cCount initialized with zero. Iterate through the given string → if (s[i] == ‘a’ || s[i] == ‘A’ || s[i] == ‘e’ ..and so on) increment vCount → else if (s[i] ≥65 && s[i] ≤90 || s[i] ≥ 97 && s[i] ≤ 122) increment cCount. Now we get the count of both vowels and consonants in the string.

DEV

Abstraction in JavaScript involves hiding the complexity of code and showing only the necessary details. Private variables and methods are crucial for encapsulating data and preventing direct access from outside the scope. JavaScript doesn't have built-in support for private variables, but we can achieve this using closures.

In JavaScript, primitive data types like strings and numbers are passed by value, while objects (including arrays and functions) are passed by reference.

Callback hell refers to deeply nested callback functions, making code hard to read and maintain. Promises and async/await are modern solutions to mitigate callback hell.
React + Vite: why use?
Published: 2024-04-06 12:24:49


**First, let's understand the concepts of both.**

React and Vite are two popular tools in the web development ecosystem and can be used together to efficiently create modern web applications. Here are some reasons why you might want to use React and Vite together:

React: React is an open-source JavaScript library maintained by Facebook. It is widely used to create interactive and reactive user interfaces (UIs). With React, you can split your UI into reusable components, making it easier to build and maintain large web applications.

Vite: Vite is an extremely fast and lightweight web application build tool. It stands out for its fast startup and instant compilation times, thanks to the use of real-time module loading (ESM) during development. Vite supports React, Vue.js, and other popular frameworks.

**Why use and what are the advantages of using Vite with React?**

Fast Development: By combining React and Vite, you get a fast development environment that allows you to instantly visualize changes in the browser. This is especially useful during iterative development as it eliminates the waiting time between making a code change and seeing the result.

Better Performance: Vite optimizes code compilation and execution, which can result in a better end-user experience due to faster loading times and lower resource usage.

TypeScript Support: Both React and Vite have native support for TypeScript. This is beneficial if you prefer using TypeScript to add static typing to your code, which can help detect errors earlier and improve code maintainability.

Robust Ecosystem: React has a vast ecosystem of libraries and tools that can be easily integrated into your project. Vite, on the other hand, is a new and rapidly developing tool that is gaining popularity quickly due to its innovative approach to web development.

In summary, using React and Vite together can provide an agile and efficient development environment, allowing you to build modern web applications with better performance and user experience.

To learn more and find out how to install the library, visit: 

https://vitejs.dev/guide/.
Nation Job Connect DevLog #5 - Sprint 2 Planing
Published: 2024-04-06 11:43:33

Today, we focussed on planing Sprint 2 and what stories we should select to make best value for our product.
We have lots of stories in our backlog and we discussed and selected most important stories for the app users and nation admin while using the product. 
I think we have to consider about size of the story and importance of the story while we are going to prioritise the stories for the sprint. If we select stories with least important stories for MVP product it will be useless for the end users. Then we are unable to make good impression on the end user. Therefore we have to seriously focus on the value that story can added into the product. 
We started to use 'Jira' project management tool from our second sprint. Using this kind of rich tool we can maintain our consistent work along with the sprint because it will support to reflect work we have done, work we have to do, what is our efficiency rate and what extent we should improve our working speed etc.. As my point of view, It is crucial to have a project management tool while managing a agile focused project.
Badges for Go Benchmark
Tags: go
Published: 2024-04-06 11:35:13

I would like to share a quick tip about adding badges to Github README for Go Benchmark tests.

Generally the benchmarks output is posted as it is on the README by repo owners. Example:

```sh
1000	   8069938 ns/op	 7360722 B/op	   19794 allocs/op
2000	   8272545 ns/op	 7370076 B/op	   19794 allocs/op
```

Using the following action - it can be both measured and tracked over lifetime of a project.

**Using it as a Badge** in README


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

**Using it as Tiny Widget** in README


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

**Using it as PR Comment**

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


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

You can even view the history of all the benchmark tests within the PR for all commits, such as:

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

Method on how to add this is simple:

```sh
- uses: kevincobain2000/action-coveritup@v2
  with:
    type: allocs-per-op
    command: go test -count 1 -bench=. ./... -benchmem|grep allocs|awk '{ print $(--NF)}'
    record: score
    metric: alloc
```

This method doesn't require publishing the results to separate `gh-pages` and has instant feedback feature which is helpful to the code reviewer when reviewing the code changes instantly.

Similarly - other metrics can also be recorded for test scores or lint errors etc.

Full details link: https://coveritup.app/
Full action's docs: https://github.com/kevincobain2000/action-coveritup
Live Demo pull req link: https://github.com/kevincobain2000/gobrew/pull/191

I hope you found something new in this post.
Thanks for reading.