teleren/devto huggingface dataset:
How to use the useCallback hook in React
Tags: webdev, react, javascript, beginners
Published: 2023-08-27 23:10:54

👋 Introduction

React.js is a popular JavaScript library for building user interfaces, and it provides developers with a wide range of tools and hooks to manage state, effects, and performance optimizations. One such optimization tool is the **useCallback** hook, which is used to memoize functions in React components. In this article, we'll explore what the **useCallback** hook is and how to use it effectively in your React applications.

🚀 Understanding useCallback

Before we dive into code examples, let's understand the purpose of **useCallback**. In React, when a functional component re-renders, any functions defined within it are recreated. This can lead to unnecessary re-renders in child components that rely on these functions as props. The **useCallback** hook addresses this issue by memoizing functions, ensuring they are only recreated when their dependencies change.

🎯 Basic Usage
Here's the basic syntax of **useCallback**:

```
const memoizedCallback = useCallback(
  () => {
    // Your function logic here
  },
  [dependencies]
);
```

📌 Using useCallback with a Click Handler
In this example, **handleClick** is memoized with the **count** variable as a dependency. It ensures that the function reference remains the same between renders, when **count** does not change.

```
import React, { useState, useCallback } from 'react';

function ClickCounter() {
  const [count, setCount] = useState(0);

  // This function is memoized and won't change on re-renders
  const handleClick = useCallback(() => {
    setCount(count + 1);
  }, [count]);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={handleClick}>Increment</button>
    </div>
  );
}
```

📎 Using useCallback to Optimize Child Components
In this example, **updateData** is memoized with an empty dependency array since it doesn't depend on any variables. This optimization ensures that the **ChildComponent** doesn't re-render unnecessarily.

```
import React, { useState, useCallback } from 'react';

function ParentComponent() {
  const [data, setData] = useState(0);

  const updateData = useCallback((newData) => {
    setData(newData);
  }, []);

  return (
    <div>
      <ChildComponent onUpdate={updateData} />
    </div>
  );
}

function ChildComponent({ onUpdate }) {
  // ChildComponent logic here
}
```

🏁 Conclusion
The **useCallback** hook is a valuable tool for optimizing React applications by preventing unnecessary re-renders of components and their child components. By memoizing functions with **useCallback**, you can improve the performance and responsiveness of your React applications.

Github: [@imevanc](https://github.com/imevanc)
Twitter: [@imevancc](https://twitter.com/imevancc)
Unlocking the Strength of Decentralized Exchanges (DEXs)
Tags: decentralizedexchange, web3, blockchain, cryptocurrency
Published: 2023-08-27 23:02:21

In the world of cryptocurrencies, Decentralized Exchanges (DEXs) are superheroes that let you trade digital coins without middlemen.

Think of it like trading Pokémon cards with your friends instead of a store!

## Why DEXs Matter
 

Recent problems with big trading companies losing money have made people think twice about trusting them. That's where DEXs come in - they're like your trustworthy friend who helps you swap coins without any sneaky business.

## Meet Uniswap: The Cool Kid in DEXs

Uniswap is a popular DEX. It's like a special machine that lets you trade one coin for another. But it's not run by a company; it's run by computer programs called smart contracts.

## The Magic of Uniswap V3

Uniswap has a new version called V3. It's like the next level of a video game, with better graphics and more exciting challenges.

In V3, you can trade coins with less risk and more rewards. It's like getting a bonus for being a brave trader. Plus, it helps keep things fair and fun for everyone.

## Imagine Trading Like a Pro

Picture this: you have a bunch of coins, and you want to swap them. Instead of relying on a big company, you use Uniswap V3. It's like a super-smart robot that helps you trade securely and even earn rewards.

## To Sum It Up

Decentralized Exchanges (DEXs) like Uniswap are changing the game of trading. They give you control, security, and rewards. Uniswap V3 is the upgraded version that makes trading even better, like a cool update to your favorite app.

So, whether you're a seasoned trader or just getting started, DEXs like Uniswap are here to make your crypto journey smoother and more exciting.
Understanding Heap Memory Allocation in C - Malloc and Free
Tags: c, programming, tutorial, linux
Published: 2023-08-27 22:24:28

{% embed https://www.youtube.com/watch?v=UPaIAbUklSM %}

Malloc and Free are the most common functions used for heap memory management. These functions provide the following advantages over sbrk and brk:

1. They are standardized as part of the C language.
2. They are easier to use with threaded programs.
2. They provide a simple interface for memory to be allocated, especially in smaller units.
3. Allow the arbitrary deallocation of blocks of memory.

Malloc takes in a size as an argument and returns a pointer to the newly allocated block of memory that is of the size specified in the argument. The allocated memory is not initialized. 

The free function takes in a pointer to a block of allocated memory. The function will then add the block of memory to a list of free blocks, which are recycled by future malloc calls.

When malloc is called, it will generally complete the following steps:

1. Check if there is a block of memory in the list of free blocks large enough to allocate for the memory request.
2. If no free blocks are available, allocate a new block of memory to use.

Based on this process, it is important to note that when malloc is called, it does not always increase the program break. This is because in some cases, the memory may be available in the list of free blocks, meaning no new memory needs to be allocated to the heap. 

With this basic understanding of malloc, let's look at a simple example of a malloc in C.

```c
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

struct s{
    int value;
};

int main(int argc, char *argv[]){

    struct s *newS = malloc(sizeof(struct s));
    newS->value = 10;

    printf("%d\n", newS->value);
    free(newS);

    return 0;
}
```

In this example, we have a struct named s which contains a single property, value. To be able to use this struct, we need to allocate some memory for it. To do this, we use a malloc as shown in the first line of the main function. The argument for our malloc call is *sizeof(struct s)*. This operation determines how much memory is required to contain our struct s, allocates a memory block of this size, and returns a pointer of the block to the variable *newS*. 

With *newS* initialized, we can start to work with its property *value*. To access the property, we use the pointer notation *newS->value*. The line after the allocation shows how to set the value, and the print shows how to access the value.

At the end of the program, we no longer need the memory assocaited with *newS*. We make a call to the *free* function, providing *newS* as an argument. This will add the memory associated with *newS* to the free list, allowing it be used for future malloc calls. 

It’s important to note that when the process terminates, all of its memory is returned to the system, so free isn’t actually required for this simple program. Free is generally used in more complex programs to make the program more readable and to help with efficient memory management.

You now know the basics of working with malloc and free!
error: command yarn run start exited (1)
Published: 2023-08-27 22:20:39


if you got this error on docker container

ERROR: command finished with error: command yarn run start exited (1)

just add `stdin_open: true` to the docker-compose file 

[source](https://github.com/facebook/create-react-app/issues/8688#issuecomment-602110747)
Numerical formatting from 0 to 99 with autocomplete sorted correctly. TypeScript series: Template literal types
Published: 2023-08-27 22:12:09

```ts
type N = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9

type Note = `0${N}` | `${N}0` | `${N}${N}`
```
Typescript cheat sheet
Tags: typescript, webdev, beginners
Published: 2023-08-27 21:49:17

## Introduction

### What is typescript?

A programming language with type systems on top of javascript

### Why do you need typescript?

- **Easy to catch mistakes by specifying types**
- Appropriate for enterprise applications
- **Applying OOP(Object-Oriented Programming) concepts such as interfaces and classes in your codebase**
- Makes it easier to understand your codebase
- Awesome tooling System

### Why don’t you need javascript?

- Learning overhead
- Compile to execute javascript code-it adds another step in the development process

## Best practices

### Use `unknown` type if you need `any`

- `unknown` forces you to narrow down types, so you can deal with the variable case by case, while `any` doesn’t give you any information about its type.

### Don’t use optional parameters in callbacks

- You can pass in functions with fewer arguments even if you don’t use optional parameters in callbacks
- Use it when you mean to explicitly write parameters.
Bring AppSec to your software in just 1 hour per sprint
Tags: tutorial, security, learning
Published: 2023-08-27 21:38:00

> Are you a smaller team who wants to get started in #appsec but don't know where to begin?
> Have you tried before but lost momentum?

I'm running a **free appsec program - One Hour App Sec**, for all teams worldwide and would love for you to join. We aim to help teams everywhere do 1 hour of application security every sprint.

Every 2 weeks we send you:

- Tips and tutorials to build security foundations for your projects

- Templates to get you started

- Videos and watch-alongs to see how things work

You can sign up and find out more (including links to previous sprints) at  https://safestack.io/one-hour-appsec/

No cost, no tricks or gimmicks :)
SVG Thumbnails in Windows 11 with Microsoft PowerToys
Tags: svg, windows11, powertoys, inkscape
Published: 2023-08-27 21:37:49

---
title: SVG Thumbnails in Windows 11 with Microsoft PowerToys
published: true
description: Demo of some Explorer add-on features that come with Microsoft PowerToys.
tags: SVG, Windows11, PowerToys, Inkscape
cover_image: https://i.imgur.com/UXrkfGO.png
# Use a ratio of 100:42 for best results.
# published_at: 2023-08-27 21:07 +0000
---

Install the PowerToys from the [Microsoft Store](https://apps.microsoft.com/store/detail/microsoft-powertoys/XP89DCGQ3K6VLD) so you get the Explorer extensions as shown in the video below.

For avid Inkscape users, this is a great addition and gets you the same level of convenience any Linux system offers by default. 😏 🐧

https://youtu.be/ZAGDNwk7Bd8?si=BCxTVhc04yNb8HD8
Arithmetic Adventures
Tags: newbie, javascript, webdev
Published: 2023-08-27 21:25:53

In this quick read, I journey through key concepts of arithmetic and numbers in JavaScript!

**1.<u>Basic Arithmetic Operations</u>**
The fundamental arithmetic operators (+, -, *, /) are your tools for addition, subtraction, multiplication, and division. But there's more: the modulo operator (%) helps you find remainders, and the exponentiation operator (**) raises the first operand to the power of the second operand.

**<u>2.Math Object</u>**
Meet the Math object, your trusty sidekick for complex mathematical functions. From Math.sqrt() for square roots to Math.random() for random numbers, this object has your back when the math gets tricky.

**<u>3.Numbers in JavaScript</u>**
Numbers in JavaScript are mostly represented as floating-point numbers, which can occasionally lead to precision issues in calculations. The toFixed() method helps control decimal places, ensuring you have the precision you need.

**<u>4. NaN and Infinity</u>**
NaN(Not-a-Number) pops up when a mathematical operation doesn't yield a valid number, and Infinity appears when numbers get too large or too small to be represented.

**<u>5. Converting Strings to Numbers</u>**
JavaScript offers parseInt() and parseFloat() functions which turns string inputs into their numeric counterparts.

**<u>6. Number Methods and Properties</u>**
Numbers in JavaScript come with a handy set of methods and properties. Whether it's Number.isNaN() to check if a value is NaN or Number.MAX_VALUE to access the largest possible value, these tools are important.

**<u>7. Number Precision</u>**
Floating-point numbers may lead to tiny discrepancies in calculations due to their representation in memory. So when you're dealing with important financial computations or precise measurements, be careful and consider using methods like Number.EPSILON for comparison purposes.

Happy coding and calculating.
Help witgh build fail with not explicit error
Tags: vue
Published: 2023-08-27 21:21:53

Hi guys, my vue app had worked on remote, works locally with "vite" command but now fails every new build. Were trying about 2 days how to fix it, can't find problem with files listed in console. Any reason how to fix it?
`12:27:41 AM: $ npm run build
12:27:41 AM: > vuetify1@0.0.0 build
12:27:41 AM: > vite build
12:27:41 AM: vite v4.4.4 building for production...
12:27:41 AM: transforming...
12:27:42 AM: ✓ 141 modules transformed.
12:27:42 AM: ✓ built in 1.02s
12:27:42 AM: [commonjs--resolver] Failed to resolve entry for package /opt/build/repo. The package may have incorrect main/module/exports specified in its package.json.
12:27:42 AM: error during build:
12:27:42 AM:** Error: Failed to resolve entry for package /opt/build/repo. The package may have incorrect ****main/module/exports specified in its package.json.**
12:27:42 AM:     at packageEntryFailure (file:///opt/build/repo/node_modules/vite/dist/node/chunks/dep-abb4f102.js:28698:11)
12:27:42 AM:     at resolvePackageEntry (file:///opt/build/repo/node_modules/vite/dist/node/chunks/dep-abb4f102.js:28695:5)
12:27:42 AM:     at tryCleanFsResolve (file:///opt/build/repo/node_modules/vite/dist/node/chunks/dep-abb4f102.js:28359:28)
12:27:42 AM:     at tryFsResolve (file:///opt/build/repo/node_modules/vite/dist/node/chunks/dep-abb4f102.js:28306:17)
12:27:42 AM:     at Object.resolveId (file:///opt/build/repo/node_modules/vite/dist/node/chunks/dep-abb4f102.js:28102:28)
12:27:42 AM:     at file:///opt/build/repo/node_modules/rollup/dist/es/shared/node-entry.js:25461:40
12:27:42 AM:     at async PluginDriver.hookFirstAndGetPlugin (file:///opt/build/repo/node_modules/rollup/dist/es/shared/node-entry.js:25361:28)
12:27:42 AM:     at async resolveId (file:///opt/build/repo/node_modules/rollup/dist/es/shared/node-entry.js:24035:26)
12:27:42 AM:     at async ModuleLoader.resolveId (file:///opt/build/repo/node_modules/rollup/dist/es/shared/node-entry.js:24449:15)
12:27:42 AM:     at async Object.resolveId (file:///opt/build/repo/node_modules/vite/dist/node/chunks/dep-abb4f102.js:7990:10)
12:27:42 AM: ​
12:27:42 AM: build.command failed        `
Java: "Pass-by-Value" vs "Pass-by-Reference" - Unraveling the Confusion
Published: 2023-08-27 21:04:29


Understanding how Java handles parameter passing is a common source of confusion among developers. In this comprehensive guide, we'll dive into the debate of whether Java is "pass-by-value" or "pass-by-reference," clarifying the concepts with clear code examples and shedding light on the intricacies of Java's parameter passing mechanism.

**The Truth: Java is "Pass-by-Value":**

Contrary to the misconception, Java is strictly "pass-by-value." But the key to understanding this lies in how references are passed.

**Passing Primitive Types:**


![primitive types](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ff4wcqlo503oh2t6h1g1.png)



**Passing Objects (References):**

![primitive type](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jusxkhfmrenltuxqwviz.png)

**Explaining the Behavior:**

In Java, when you pass a primitive type, a copy of its value is passed to the method, leaving the original variable unchanged. When you pass an object reference, the reference's value (memory address) is copied, not the object itself. This means you can modify the object's properties inside the method, but you can't change the reference itself.

**Best Practices:**

`Clear Terminology:` Understand the difference between "passing by value" and "passing by reference" to communicate accurately.

`Immutable Objects: `When passing objects, consider making them immutable to prevent unintended modifications.

**Conclusion:**

Java's parameter passing behavior is often debated, but it's essential to grasp the nuances. By recognizing that Java is "pass-by-value," you can confidently navigate how primitive types and object references are handled in different scenarios.

`LinkedIn Account` : [LinkedIn](https://www.linkedin.com/in/matthew-odumosu/)
`Twitter Account `: [Twitter](https://twitter.com/iamcymentho)
**Credit**: Graphics sourced from [amazon](https://s3.amazonaws.com/s3.timetoast.com/public/uploads/photo/17036447/image/37cfe9febdf6865cf22268fc3775d9f1)
Simple Kubernetes Workflow
Tags: kubernetes, devops, webdev, javascript
Published: 2023-08-27 20:23:53


![Kubernetes Workflow](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iqemsyq47j54d596cb8w.png)

Presenting a meticulously crafted flowchart that captures the nuances of Kubernetes workflows, highlighting every step. Explore seamless management of containerized apps within the 
@kubernetes_pune and ecosystem. Elevate your understanding! 📊🐳 #Kubernetes #OpenSource
Exciting News! 🚀 My Contribution to Microsoft Bing Rewards Got Accepted and Merged!
Tags: webdev, opensource, fullstack, javascript
Published: 2023-08-27 20:14:55

I'm thrilled to announce that my recent contribution to the Microsoft Bing Rewards project has been accepted and merged into the codebase. 🎉 It's been an incredible journey, and I'm grateful for the opportunity to be part of such an amazing open-source community. 

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

**What I Worked On:**

I had the privilege of working on issue in Microsoft Bing Rewards. It was a challenging yet rewarding experience, and I learned a lot along the way.

**Gratitude:**

I want to express my gratitude to the incredible Microsoft Bing Rewards team for their support and guidance throughout this journey. It's amazing to be part of a community that values collaboration and innovation.

**What's Next:**

This is just the beginning! I'm excited to continue contributing to open source and making a positive impact in the tech world. Stay tuned for more updates and projects.
GitHub Commands For Daily Usage
Published: 2023-08-27 20:03:51

In previous articles, we have learned the following:

1. [Need of Version Control System](https://article.hasabtech.com/versioncontrolsystem/Git-What-actually-is-VCS)

2. [Git Basics](https://article.hasabtech.com/versioncontrolsystem/Git-Basics-In-Nutshell)

3. [Setting Up GitHub](https://article.hasabtech.com/versioncontrolsystem/GitHub-Setup)

4. [Creating Repository on GitHub for the First Time](https://article.hasabtech.com/versioncontrolsystem/GitHub-Creating-First-Repo)

Now we are going to learn most important commands which are used on day-to-day tasks.

We will be discussing
- git clone
- git pull
- git fetch
- git push

Their differences and usages.

## Git Clone

`git clone` is a simple command which downloads a local copy of the project from remote repository to your local computer.

Complete syntax is this:
`git clone <link>`

This is how you copy the link:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t67se8g7p3q9q37713u5.png)

This is the result of cloning:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2vaione2w4i3tuqyijvj.png)

`origin` is already set for the remote location from where you clone the project.

## Git Fetch

Since you are working with remote repository so there must be other folks working on it.

At first glance, `git fetch` looks like a command to download the changes locally to your computer but it only downloads the metadata and informs you of the changes.

## Git Pull

`git pull` helps you download the *changes* made by others.

As we studied in last article, you can set pointers for remote locations, i.e., different repositories and choose to pull data from any of your desired repository.

## Git Push

`git push` helps you upload changes back to the repository considering you have the rights to do so.

For remote pointers, you can choose to pull data from one repo and push into another repo.

For example, you are downloading data from `origin` and uploading to `dev` pointer.

This was it.
Try these commands out, let me know of any confusion.

Thank you :)
Graph Databases and Their Applications
Tags: database, bitnine, learning, postgres
Published: 2023-08-27 19:57:01

Real-life relationships and data are usually heavily interconnected and extremely complex. A lot of valuable information cannot be restricted to simple tables and documents. This is where graph databases come in handy.

A graph database (GDB) is a NoSQL database that uses graph structures to store data. It uses nodes, edges, and properties instead of rows, columns, tables, and documents like traditional databases. The edges represent relationships between nodes (can be entities). Graph databases are crucial for applications where relationships between data elements are more important.

## Use Cases and Applications
Graph databases shine the brightest in scenarios where understanding the complexity of relationships is placed at the forefront.
The first such scenario that should come to mind is social networks. Social network platforms rely heavily on the capabilities that GDBs offer. An example would be using a GDB to discover hidden patterns within friend circles, interests, and interactions, and utilizing them to provide users with a more personalized experience.
GDBs are also used in the e-commerce realm to provide personalized recommendations by analyzing past purchases and shared preferences.
Additionally, search engines are also fueled by knowledge graphs and so are fraud detection systems which utilize connections to spot anomalous behaviour.

## Bitnine Global Inc's Graph Database Software
Bitnine is a company that specializes in fully integrated graph databases.
Apache AGE is an open-source GDB offered by Bitnine. Its key features are:
- Is a GDB plugin for PostgreSQL
- Allows hybrid queries (OpenCypher and SQL)
- Fast Graph query processing, and
- Graph visualization and analytics

AgensGraph is their closed-source GDB option. Its key features are:
- Hybrid query processing (Cypher and SQL)
- Enhanced security
- Data sharding
- Native graph storage

### Apache AGE vs AgensGraph
The main difference between the two is that AGE is an openCypher plugin for PostgreSQL whereas AgensGraph is a complete graph database built upon PostgreSQL.

By being a fork of PostgreSQL, AgensGraph is tied to a specific version of PostgreSQL. However, AGE is an extension and is not tied to any specific version of PostgreSQL.

## Learn More
- [Bitnine Global Inc. official website](https://bitnine.net/)
- [Apache AGE repository](https://github.com/apache/age)
- [AgensGraph repository](https://github.com/bitnine-oss/agensgraph)
A book about Javascript...
Tags: javascript, citat
Published: 2023-08-27 19:42:55

Start reading the book **"Mordern JavaScript for the Impatient"**, as a quick update of my old javascript knowledge to day version, soo far a good book.

The lines got me to start thinking...

> “Any application that can be written in JavaScript, will eventually be written in JavaScript.”
> - Jeff Atwood

Here i think is some prof.. 
https://demo.os-js.org/