teleren/devto huggingface dataset:
Rust vs C and C++: A Concise Comparison for Developers 🚀
Tags: rust, cpp, discuss
Published: 2023-03-25 15:07:25

As developers, we're always looking for the best tools to get the job done. While C and C++ have long been the gold standard for systems programming, Rust is gaining traction as a safer and more modern alternative. In this short blog, we'll provide a concise comparison of Rust, C, and C++ to help you understand their differences and make an informed decision on which language to use for your next project. Let's dive in!

## Memory Safety & Performance 🛡️

**C and C++** have been praised for their performance and low-level capabilities. However, they often come with a price: manual memory management and potential for memory-related bugs. Developers need to be extra cautious with pointers, memory allocation, and deallocation to avoid issues like data races, null pointer dereferences, and buffer overflows.

Rust, on the other hand, prioritizes memory safety while maintaining performance. The Rust compiler enforces strict rules around memory management, preventing issues like data races and null pointer dereferences at compile-time. This means you can write fast and efficient code without the risk of memory-related bugs.

## Syntax & Learning Curve 📚

**C** has a relatively simple syntax and can be learned quickly. However, it lacks some modern features like object-oriented programming and robust error handling.

**C++** builds upon C by introducing object-oriented programming, templates, and other features. The added complexity can make the learning curve steeper, but it offers more powerful abstractions and code reusability.

**Rust** has a more modern syntax that borrows elements from both C and C++, as well as functional programming languages. It introduces concepts like pattern matching and ownership, which might require some getting used to. The learning curve can be steep, but Rust's syntax is designed to be expressive, safe, and efficient.

## Ecosystem & Community 🌐

**C** is ideal for low-level systems programming, embedded systems, and kernel development, where simplicity and performance are critical.

**C++** excels in areas like game development, high-performance computing, and large-scale software systems, where its object-oriented features and rich abstractions come in handy.

**Rust** is an excellent choice for systems programming, web development (via WebAssembly), and projects that demand memory safety and performance. It's especially well-suited for building concurrent and parallel systems, thanks to its strong safety guarantees.

## Conclusion 🔚

Choosing between Rust, C, and C++ depends on your specific needs, preferences, and project requirements. Rust offers memory safety and modern language features but has a steeper learning curve. C and C++ provide performance and a vast ecosystem, but they require extra care to avoid memory-related bugs. Consider these trade-offs when deciding on the best language for your next project, and happy coding!
Paracetamol.js💊| #208: Explica este código JavaScript
Tags: javascript, webdev, spanish, programming
Published: 2023-03-25 14:42:56

## **<center>Explica este código JavaScript</center>**
#### <center>**Dificultad:** <mark>Avanzado</mark></center>

```js
const getName = (name) => {
  return new Promise ((resolve, reject) => {
    setTimeout(() => {
      resolve(name)
    }, 3000)
  })
}


const getAge = (age) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (age < 18) reject(new Error(`${age} no es valido`))
    }, 2000)
  })
}


const counterFriends = (friends) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(friends.length)
    }, 5000)
  })
}

const getPromises = () => {
  const arr = [
        getName("Pepe"), 
        getAge(15), 
        counterFriends(["Ana", "Roberto", "Juan"])];
  return Promise.race(arr)
    .then((response) => {
      console.log(response)
    })
    .catch(err => console.log(err))
}

getPromises()
```

- A. `"Pepe"`
- B. `["Pepe", 3]`
- C. `Promise { <fullfiled> }`
- D. `15 no es edad valida`  
- E. `3`

Respuesta en el primer comentario.

---
I Love GNU Make
Published: 2023-03-25 14:29:18

I love GNU Make and Makefiles. It is designed for compiling C/C++ programs but I use it for almost anything that needs to be scripted as long it makes sense. Like any tool, you use it when it's best suited for the job. My rule of thumb is if it can be done using GNU Make, I would try it first before using a more powerful scripting language like bash or Python. What makes it preferable over bash or Python, assuming it can accomplish the task at hand, is simplicity and readability of the code. That's mostly all about it. Of course, there are things, many things, it cannot do compared to Python or bash scripting. But I only switch to them if GNU Make starts becoming complicated.

I use GNU Make to build Golang programs. Below is a sample Makefile to build a Golang project.

#### Makefile
```
PROG        := helloworld
GOBIN       := $(CURDIR)/bin
PATH        := $(PATH):$(HOME)/go/bin

ifeq ($(DEBUG),true)
    DEBUG_OPT = -gcflags=all="-N -l"
endif

.PHONY: all \
        help \
        lint \
        gosec \
        fmt \
        gomodtidy \
        vet \
        build \
        install \
        test \
        clean

help:
    @echo "Usage:"
    @echo "    make clean all"
    @echo "    make clean build"
    @echo "    make DEBUG=true clean all"
    @echo "    make vet"
    @echo "    make lint"
    @echo "    make gosec"
    @echo "    make test"
    $(info GOBIN=$(GOBIN))

all: link gosec vet test install

build: gomodtidy vet
    go build -o $(PROG) cmd/main.go

install: gomodtidy vet
    @GOBIN="$(GOBIN)" go install $(DEBUG_OPT) ./...

lint:
    @PATH=$(PATH) golint ./...

gosec: gomodtidy
    @PATH=$(PATH) gosec ./...

fmt:
    go fmt ./...

vet: gomodtidy
    go vet ./...
    golangci-lint run

gomodtidy:
    @go mod tidy

test: gomodtidy
    @go test -bench= ./...

clean:
    @$(RM) -rf "$(GOBIN)"
    @$(RM) -f *.o
```

As you can see, it's just a bunch of tasks that you want to run against your code. If you want to build the Golang code and produce the executable binary, you simply run:
```
make clean build
```
If you want to run test, 
```
make test
```
If you want to run a linter against your code,
```
make lint
```
If you want to check for security issues,
```
make gosec
```

All these things can be accomplished using shell scripting. But I think GNU Make is more readable in this scenario. It's easy to spot the targets, which are the tasks intended for the project and how they can be executed. I can easily determine where the main program (package main) is located. I can easily see the name of the executable file and where it will be saved.

If your build script is readable, then it becomes self-documenting. You save yourself of writing a separate documentation, like how to install or build the project.

All my projects use Makefiles. By just looking at the Makefile, I can quickly see how the project is built and other tasks associated with it. To me, the quickest way to learn and understand a code base is if you can build and run it.
Multiple title tags in source code
Tags: javascript, nextjs, react, webdev
Published: 2023-03-25 14:21:46

Hello,

I am using Next.js version 13.2.3.
I use the metadata for server side pages as follows, there is no problem.
(https://beta.nextjs.org/docs/api-reference/metadata#generatemetadata)

`export const metadata = {
    title: 'About'
}`

I use it like this in Layout.jsx;

`export const metadata = {
  title: {
    default: 'Home Page',
    template: '%s | App Name',
  }
}`

Everything works fine so far, but sometimes I have to use "use client"; on some pages and when I do that, the use of `const metadata` doesn't work. As a solution, I create head.jsx in that page folder and it works. Example;

`export default async function Head({ params }) {
    return (
        <>
            <title>Test | App Name</title>
            <meta name="description" content="description is here"></meta>
        </>
    );
}`

But the problem here is that there are two <title> tags in the source code. The first tag is "Home Page" and the other tag is the title I added in head.jsx. Has anyone encountered this problem before? What kind of solution should I follow? I hope I was able to explain.
detect user ⬅️ back button click, when background task is 🔄️ running...
Published: 2023-03-25 14:19:56


We accomplish this behavioral need by the help of **3** things...
**1.** ParentComponent **.jsx** 
**2.** ModalComponent **.jsx** || ChildComponent **.jsx** 
**3.** useBackButtonClick **.js** <-- **custom hook**

[NOTE: ~~CSS Missing...~~]


---



**1. ParentComponent.jsx** 
```js
import useBackButtonClick from '../utils/useBackButtonClick';
import ModalComponent from '../utils/ModalComponent';
import { useState } from 'react';

const ParentComponent = () => {

  const [isAiTaskDialog, setIsAiTaskDialog] = useState(false);

  // custom hook call for back button click...
  const handleCloseAiRequest = useBackButtonClick(setIsAiTaskDialog);

  return (
    <div>
	  ... ... 
      <ModalComponent
        visible={isAiTaskDialog}
        onClose={() => setIsAiTaskDialog(false)}
        onOk={handleCloseAiRequest}
      />
	  
    </div>
  );
};

export default ParentComponent;
```



---



**2. ModalComponent.jsx**
```jsx
const ModalComponent = ({ onClose, onLeave, visible = false }) => {

  return (
    <div style={{ display: visible ? 'block' : 'none' }}>
      <div>

        <h3>Background operation is in progress!</h3>
        <p> Are sure that you want to leave? </p>
        <div>
          <button onClick={onLeave}> Leave </button>
          <button onClick={onClose}> Stay </button>
        </div>

      </div>
    </div>
  );
};

export default ModalComponent;
```



---



**3. useBackButtonClick.js**
```jsx
import { useCallback, useEffect, useState } from 'react';
import { taskInProgress } from '../../services/memory';
import { useHistory } from 'react-router-dom';

// this hook is created only for Back-Button-Click.
function useBackButtonClick(callback) {
  
  const history = useHistory();
  const [triggerExit, setTriggerExit] = useState(
        { onLeave: false, path: '' }
  );

  const handleBackButton = useCallback(
        (location) => history.push(location), [history]
  );

  const handleCloseAiRequest = () => {
    setTriggerExit((obj) => ({ ...obj, onLeave: true }));
    callback(false);
  };

  useEffect(() => {
  
    if (triggerExit.onLeave) handleBackButton(triggerExit.path);

    const unblock = history.block((location) => {
  
      // if task is running at background...
      if (taskInProgress.status) {
	  
        if (location?.pathname !== '') callback(true);
		
        setTriggerExit(obj => ({...obj, path: location?.pathname}));
		
        return triggerExit.onLeave;
      }
    });

    return () => unblock();
  }, [
      triggerExit.onLeave, 
      triggerExit.path, 
      handleBackButton, 
      callback,
      history,
     ]
 );

  return handleCloseAiRequest;
}

export default useBackButtonClick;
```



---



Hope these code blocks are helpful for your project... 
Thank You! 🤗
TIL beginner Javascript
Tags: beginners, javascript, programming
Published: 2023-03-25 14:16:50

I used a video on Youtube by FreeCodeCamp to teach myself the very basics of Javascript today.
I'd start with saying you must sign up for a platform site that will allow you to run Javascript- since I'm going to University this summer I believe they will be telling me which one to use, so I'm going to update which I end up using later. Today is just in theory and in preparation to go to school.
BASIC RULES:
All lines end with a semi-colon // not required just polite//
Capitals matter- must be an exact copy of original spelling with capital placements to be processed.
The intro to Javascript is how to leave comments.
1. //Leave a comment that's one line//
2. /* Leave a 
Comment that is 
mulitple 
lines*/
AND the pieces you need to begin coding like:
1.var variable= "number or script, can change"; 
variable= 9;
2. let allowsNumberScript = "only applicable to a scope of code";
3. const variable = remain constant;
In addition var can be declared or assigned:
//= sign is the assignment operator//
assigned: var a;
declared: var b=2;
assigned:a=7;
assigned: b=a;
a=7;
console.log(a)
console
>7 
//placement of console log matters in Javascript//
var a;
var b=2;
console.log(a)
b=a;
a=7;
console
>null
>7
How to write unit-tests as a beginner in python
Tags: python, beginners, unittesting
Published: 2023-03-25 14:09:52

As a beginner in Python, writing unit tests can seem a bit overwhelming, but it's an essential skill to learn inorder to become a proficient programmer. Unit tests are used to ensure that our code is functioning as expected and can help identify and prevent bugs early in the development process. 

Here are some steps that I followed while writing unit tests in Python:

**Understanding the basic concept of unit tests**:
Unit tests are written to test individual components or functions of a program, independent of the rest of the system. The goal is to ensure that each unit of code works as expected, and the code as a whole works correctly.

**Choosing a testing framework:**
Python has several testing frameworks to choose from, such as Pytest, Unittest, and Nose. Pick one that you feel comfortable with, and start exploring.

**Create a separate test file:**
Create a new file and name it with _"test_"_ prefix like, for example, _"test_math_functions.py."_ This file should contain all the test functions for the code that w want to test. Make sure that you are not mixing your production code with your test code.

**Write your first test function:**
A test function should be named with a prefix of "test_" followed by the function name that you want to test. The test function should then include an assert statement that checks if the function's output matches the expected output.

For example, let's say we want to test the following function:

`def add(x, y):
    return x + y`
You can write a test function like this:

`def test_add():
    assert add(2, 3) == 5`

**Run your tests:**
Use your testing framework to run your tests and check if they pass or fail. If the test passes, you will see a green output, and if it fails, you will see a red output. Fix the code until all tests pass.

**Add more test functions:**
Write more test functions to cover different scenarios and inputs. For example, you can test negative numbers, decimal numbers, or edge cases.

**Refactor your code:**
Refactor your code and run your tests again. Make sure that your tests still pass after refactoring.

In short, unit tests are essential for ensuring code quality, and learning how to write them is a valuable skill for any developer.
Datatype haqida
Tags: beginners, programming, python, github
Published: 2023-03-25 09:15:41

Assalamu aleykum hurmatli dasturchi bugun siz bilan Python dasturlash tilida datatype haqida ko'rib chiqamiz


Dasturlashda ma'lumot turi muhim tushunchadir
#o'rgaruvchilar har xil turdagi ma'lumotni saqlashi mumkin va har xil


`Text Type` - String
`Numeric types` - integer,float,complex
`Sequence types` - list,tuple,range
`Mapping type` - dict
`Set types` - set frozentset
`Boolean type` - bool
`Binery types` - bytes,bytearrey,memoryview
`None type` - NoneType

`title()` -  bu metodlar deyiladi sozining bosh xarfini kichkinada yozilsa katta qilib beradi

`lower ()` - bu metodlar deyiladi isimni kottada kiritsak xamma sozini kichkina qilib beradi

Dasturlashda indekslar bor :
100 = 0 , 
200 = 1 , 
300 = 2, 
400 = 3, 
500 = 4...........

`Float` - bu kasr sonlar uchun 

Keling endi misollar ko'rib chiqamiz :
 
`Floatga` misol:
#a = float(input('Birinchi soni;kiriting'))
#b = float(input ('ikkinchi soni kiriting'))

#c = (a + b)
#print ("Natija:",c)

Javoblar:
birinchi soni kiritamiz keyin esa ikkinchi soni kiriting deb soraydi va bu kiritgan sonlarimizni qoshib beradi

`Complexga` misolar:

a = complex(input("Birinchi sonni kiriting:"))
b = complex(input("Ikkinchi sonni kiriting:"))

sum = a + b

Javoblar:
birinchi soni kiritaiz va keyin ikkinchi soni kiritng deydi va bizga bu ikkilasini qoshib beradi.
Managing Work Scope in Software Project
Tags: starchart, senecaosd700, opensource
Published: 2023-03-25 13:59:59

Understanding the code base, writing good code, and flawless communication with maintainer are the fundamentals of the open source work. Luckily, I work with some of very experienced people in Starchart project. I learned that work can be faster when managing the work efficiently. Here's my lessons learned. 

### Minimize your work scope 
If the PR has thousand line changes, it takes a lot of efforts not just for the code writer, but also the code reviewer. Also it means more chances of breaking existing code base. So it will take more than a week to get merged after rounds of reviews and updates. The longer the PR is under review, the more the PR gets conflicts especially if the project is very active. You can write sub issues of a large issue to minimize the work. If some parts of the issue is not the core of the work, you can separate for later follow-ups. Any work should be planned to finish within a week as project or organization usually is run on a weekly basis. 


### Split large scope of work into different phases
Planning big work into multiple phases is not easy task unless experienced. But this is something that I learned in Starchart project. The experienced code writer plans multiple steps for difficult tasks. I have seen the experienced developers build skeleton code without, write comments to show the intention, and structure the files without functionality yet. You can still have good code review feedbacks based on the function flow. Then slowly build up each module or functions. This way the work can be processed faster as you don't have to finish a large module at once. Instead you can finish your function, get it merged, and work on next function. I know it's not easy to plan things if the area of the code is new to the code writer. But I think it's a great skill and it's better to practice now. 


### Plan future improvement instead of fixing everything in one PR
Often times you get a feedback to change something during the code review. That change request can be essential but sometimes it can be improved later. Then you can suggest that you will write another issue to follow up. This way you can avoid another round of review and keep your change scope as originally intended. 


### Conclusion
When I work alone, I only focus on implementing features and fixing bugs. But larger project with a team requires more than implementing code. Design the system, continuously refactor code for better maintainability, manage issues and review someone else's code. And this planning the work will make a better look of the developer. The work progress is fast and easy to review. This technique will be more obvious in real world projects if you see PRs from the experienced.
HOW TO SHARE A LETTER FROM CHATGPT TO AZURE STORAGE ACCOUNT
Published: 2023-03-25 13:57:24


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

Azure storage account contains all of your Azure Storage data objects, including blobs, file shares, queues, tables, and disks. The storage account provides a unique namespace for your Azure Storage data that's accessible from anywhere in the world over HTTP or HTTPS.

**STEP 1**
login your azure account

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


**STEP 2**
search for storage account


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


**STEP 3**
click on create storage account

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


**STEP 4**
Fill the necessary fields
-Resource group
-Storage account name
-Set performance to Standard


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

**STEP 5**
click on create

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


**STEP 6**
Click on Go to resource

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


**STEP 7**
Storage Account is ready


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


**STEP 8**
Search for containers and click on '+ containers'.
Give the container a name and change access to 'BLOB' "this is to allow access from anywhere"


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


**STEP 9**
Container is ready


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

**STEP 10**
Go to ChatGPT. 
-Create an account and login
-Have the AI help write the letter

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

**STEP 11**
Copy and paste the letter from the ChatGPT to Microsoft Word and save it.


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

**STEP 12**
Go to the containers and click on upload.
-Choose the document and upload it.


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

- The letter has been uploaded to the storage account

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

**STEP 13**
To share the uploaded file, click on the letter and copy the URL.

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


**CONGRATULATIONS! IT IS DONE.**
Decorator Design Pattern in php
Published: 2023-03-05 06:08:39

Decorator design patter is a structural design patter that provide a means of adding new properties to an object.
How?
Let's look at the component of the this pattern
Main components
1. interface (template for the object to be of the same type)
2. Class  to Decorate that implements the interface 
3. class that decorate(decorator) is and abstract  class the implements the interface  

Auxiliary components
4. class that inherit decorator class
```<?php
interface BuidingConcern{

    function addComponent($what);
    function removerComponent();

}


class House implements BuidingConcern{
    /////////class to decorate

    function addComponent($what){
        return  ' has added '. $what;

    }

     function removerComponent(){

     }

    
}

abstract class Worker implements BuidingConcern{
//class that decorate
    protected BuidingConcern $house ; ///protect so that childeren class can access it
    function __construct(BuidingConcern $houseToBuild){
     $this->house  = $houseToBuild;
    }
   abstract function addComponent($toadd);
   abstract  function removerComponent();
   abstract function chargePrice();
  
}

class BrickLayers extends Worker{

    function removerComponent(){

        return  ' old blocks removed';
    }

    function addComponent($what){

        return  __CLASS__. $this->house->addComponent($what) ;
    }

    function chargePrice(){
        return 'I charged 10,000 ';
    }
}


class Painter extends Worker{

    function removerComponent(){
        return ' remove little part of block where to inset pipe wire';
    }

    function addComponent($what){
        return  __CLASS__. $this->house->addComponent($what) ; 
    }

     function chargePrice(){
        return 'I charged 6,800 ';
    }
}

$layers  = new BrickLayers(new House()); 
echo $layers->addComponent('new block and plaster');
///house is decorated by brick layer
////look at BrickLayers class, does it has access to House class to decorate
///yes, it has extends Worker, so BrickLayers has the same constructor as Worker class 
// so inside any method in BrickLayers class, there is access to  House class
/// call $this->house whis is defined in Worker

$painter  = new Painter(new House());
echo $painter->addComponent('remove old paint and added new azure paint');```