teleren/devto huggingface dataset:
O que é Currying e para o que serve?
Published: 2023-03-17 03:47:34

Currying é uma técnica de programação que permite que uma função com vários argumentos seja transformada em uma sequência de funções que recebem um único argumento cada. Essa técnica recebeu esse nome em homenagem ao matemático Haskell Curry, que a desenvolveu seu trabalho na teoria da computação.

Ao usar o currying, podemos criar funções mais especializadas e reutilizáveis. Em vez de passar todos os argumentos de uma vez, a função pode receber um argumento de cada vez, retornando uma nova função para cada um. A cada nova chamada, a função retornada recebe um novo argumento até que todos os argumentos sejam recebidos e o resultado seja retornado.

Esse recurso é perfeito para Utilização de recursos a medida que nos obtemos eles.

Por exemplo, vamos considerar uma função que recebe dois argumentos e retorna sua soma:

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

Podemos transformar essa função em uma função curried da seguinte forma:

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

Devemos chamar a função da seguinte maneira:

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

Ao chamar "soma(2)", a função retorna uma nova função que espera o segundo argumento b. Quando chamamos essa nova função com 3, ela retorna o resultado 5.

Uma das principais vantagens do currying é a capacidade de reutilizar funções. Por exemplo, podemos criar uma função **adiciona5** que adiciona + 5 a qualquer número:


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

Isso é especialmente útil quando estamos trabalhando com funções que recebem muitos argumentos, pois podemos criar funções mais simples e fáceis de entender.

Outra vantagem do currying é a possibilidade de criar funções parcialmente aplicadas. Isso significa que podemos passar alguns argumentos para a função e receber uma nova função que espera os argumentos restantes. Por exemplo:


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

Podemos criar funções parcialmente aplicadas para criar funções mais flexíveis e reutilizáveis.

Resumindo, o currying é uma técnica de programação funcional que permite criar funções mais especializadas e reutilizáveis. Ao transformar funções com vários argumentos em sequências de funções que recebem um único argumento cada, podemos criar funções mais simples e fáceis de entender. Além disso, o currying nos permite criar funções parcialmente aplicadas, aumentando a flexibilidade e a reutilização do código.
208. Leetcode Solution in CPP
Tags: cpp
Published: 2023-03-17 03:45:50

==============================================================
#description:

A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.

Implement the Trie class:

Trie() Initializes the trie object.
void insert(String word) Inserts the string word into the trie.
boolean search(String word) Returns true if the string word is in the trie (i.e., was inserted before), and false otherwise.
boolean startsWith(String prefix) Returns true if there is a previously inserted string word that has the prefix prefix, and false otherwise.
 

Example 1:

Input
["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
Output
[null, null, true, false, true, null, true]

Explanation
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple");   // return True
trie.search("app");     // return False
trie.startsWith("app"); // return True
trie.insert("app");
trie.search("app");     // return True
 

Constraints:

1 <= word.length, prefix.length <= 2000
word and prefix consist only of lowercase English letters.
At most 3 * 104 calls in total will be made to insert, search, and startsWith.

==============================================================
#Solution:

```cpp
struct TrieNode {
  vector<shared_ptr<TrieNode>> children;
  bool isWord = false;
  TrieNode() : children(26) {}
};

class Trie {
 public:
  void insert(const string& word) {
    auto node = root;
    for (const char c : word) {
      const int i = c - 'a';
      if (!node->children[i])
        node->children[i] = make_shared<TrieNode>();
      node = node->children[i];
    }
    node->isWord = true;
  }

  bool search(const string& word) {
    auto node = find(word);
    return node && node->isWord;
  }

  bool startsWith(const string& prefix) {
    return find(prefix) != nullptr;
  }

 private:
  shared_ptr<TrieNode> root = make_shared<TrieNode>();

  shared_ptr<TrieNode> find(const string& prefix) {
    auto node = root;
    for (const char c : prefix) {
      const int i = c - 'a';
      if (!node->children[i])
        return nullptr;
      node = node->children[i];
    }
    return node;
  }
};

/**
 * Your Trie object will be instantiated and called as such:
 * Trie* obj = new Trie();
 * obj->insert(word);
 * bool param_2 = obj->search(word);
 * bool param_3 = obj->startsWith(prefix);
 */
```

#leetcode
#challenge
Here is the link for the problem:
O que é ORM e para o que serve?
Published: 2023-03-11 04:02:36

ORM é a sigla em inglês para Object-Relational Mapping, que significa Mapeamento Objeto-Relacional em português. Trata-se de uma técnica utilizada em desenvolvimento de software cujo objetivo é facilitar a comunicação entre bancos de dados relacionais e o código da aplicação.

Em um sistema tradicional, o desenvolvedor precisa escrever as consultas SQL diretamente no código da aplicação, o que pode tornar o código mais complexo e difícil de manter. O ORM, por sua vez, permite que o desenvolvedor trabalhe com objetos na linguagem de programação escolhida e que esses objetos sejam mapeados para tabelas no banco de dados, de forma transparente.

Dessa forma, o ORM torna a comunicação com o banco de dados mais fácil e intuitiva, permitindo que o desenvolvedor trabalhe com objetos na linguagem de programação que está acostumado, em vez de ter que lidar diretamente com SQL. Além disso, o ORM também oferece recursos avançados, como controle de transações, caching e relacionamentos entre tabelas, que facilitam ainda mais o desenvolvimento de aplicações complexas.

Existem diversos frameworks ORM disponíveis para diversas linguagens de programação, como o Hibernate para Java, o Entity Framework para .NET, o Django ORM para Python, entre outros. Esses frameworks oferecem uma série de recursos que facilitam o trabalho do desenvolvedor, como geração automática de código, validação de dados e suporte a diferentes bancos de dados.

Alguns dos principais benefícios do uso de um ORM são:

Maior produtividade: ao não precisar escrever consultas SQL diretamente no código da aplicação, o desenvolvedor ganha tempo e pode se concentrar em outras tarefas mais importantes.

Menor complexidade: o ORM simplifica a comunicação com o banco de dados, tornando o código mais fácil de entender e manter.

Maior portabilidade: o ORM permite que o desenvolvedor trabalhe com diferentes bancos de dados sem precisar se preocupar com as diferenças entre eles.

Maior segurança: o ORM oferece recursos avançados de segurança, como a prevenção de SQL injection, que reduzem o risco de vulnerabilidades no sistema.

Em resumo, o ORM é uma técnica muito útil para o desenvolvimento de aplicações que precisam acessar bancos de dados relacionais. Ele simplifica a comunicação com o banco de dados, reduz a complexidade do código e oferece recursos avançados que facilitam o desenvolvimento de sistemas mais robustos e seguros.
Breaking Through Imposter Syndrome: How I Learned JavaScript Variables and Data Types at Flatiron Bootcamp
Tags: javascript, beginners, programming, career
Published: 2023-03-17 03:38:50



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

_Learning JavaScript variables and data types at Flatiron Bootcamp was one of the most challenging but exciting experiences for me. At first, I found it a bit overwhelming to understand the different data types and their uses. However, I was able to overcome the initial difficulties._

Variables are like containers that store different types of data such as numbers, strings, and boolean values. For example, suppose you want to declare a variable to store your name. You can declare a string variable by writing:

javascript

```
let name = "Phoenix";
```

You can then use this variable in your code to refer to your name later on. Similarly, if you want to store a number, you can declare a variable using the Number data type, like so:

javascript

```
let age = 30;
```

In JavaScript, variables can also be reassigned, which means that you can change the value of the variable throughout your code. This feature can be incredibly useful, but it can also lead to confusion if you're not careful. Therefore, it's essential to understand the different data types and their properties when working with variables in JavaScript.

JavaScript has seven* primitive data types, and each has its unique properties and methods. For example, the String data type has various methods that allow you to manipulate the string, such as finding the length or converting it to uppercase or lowercase.

One of the significant challenges I faced when learning JavaScript variables and data types was dealing with imposter syndrome. As a new learner, it can be easy to feel intimidated or inadequate, especially when learning something as complex as coding. However, I realized that everyone starts somewhere, and with practice, I could overcome the obstacles.

To overcome imposter syndrome, I started by reminding myself of my accomplishments and celebrating small wins, like successfully writing a piece of code or figuring out a problem. I also sought support from my peers and instructors, who were always available to answer my questions and provide guidance.

In conclusion, learning JavaScript variables and data types at Flatiron Bootcamp was an incredibly rewarding experience. Despite the challenges, I was able to develop a solid understanding of these fundamental concepts, and I am proud of myself for persevering. If you're struggling with JavaScript variables and data types, remember that it takes time and practice, but with determination and hard work, you can overcome the challenges and become a proficient coder.
Adding life into Second life?
Tags: realtimeengagement, gamedev, metaverse, rte
Published: 2023-03-17 03:08:18

- Second Life, the virtual world that gained massive popularity in the early 2000s, is launching on mobile devices after 20 years.
- The mobile version of Second Life will offer the same features as the desktop version, including custom avatars, virtual real estate, and social interaction.
- The Second Life mobile app will be available for both iOS and Android devices, and it will be free to download.
- The company behind Second Life, Linden Lab, has made significant updates to the platform over the years, including adding support for virtual reality headsets.
- The mobile version of Second Life is expected to attract a new generation of users to the platform and provide existing users with more flexibility and accessibility.

**In addition to the above points, adding real-time audio communication with tools like Agora RTE solution is expected to make the mobile version of Second Life more lifelike and engaging in the following ways:
**
- Real-time audio communication will allow users to interact with each other in a more natural and immersive way, enhancing the social experience.
- Users can have voice conversations with each other during events and meetings, providing a more personal touch to the virtual interactions.
- Real-time audio communication will enable users to coordinate and collaborate more effectively, making group activities and projects more engaging and productive.
- It will also enable users to express themselves more fully and convey emotions more accurately, enhancing the overall realism of the virtual environment.
- Agora RTE solution is known for its low latency and high-quality audio, which will provide a seamless and enjoyable communication experience for Second Life users.

https://arstechnica.com/gaming/2023/03/20-years-later-second-life-is-launching-on-mobile/

https://www.agora.io/en/solutions/gaming/
Learn Dart Programming with ChatCode Tutor and ChatGPT
Tags: flutter, dart, chatgpt, tutorial
Published: 2023-03-17 02:45:11

The world is currently fascinated with large language models (LLMs), and for good reason. LLMs like ChatGPT can teach us incredible and complex things, but how much can you learn if you don't know the right questions to ask? That's where ChatCode Tutor comes in!

I recently started the [#HustleGPT challenge](https://github.com/jtmuller5/The-HustleGPT-Challenge) on Twitter, where I teamed up with a GPT-4 personality called HustleGPT to build a business from scratch on a shoestring budget. After brainstorming ideas with HustleGPT, we came up with a genuinely useful product: the [ChatCode Tutor for Dart](https://joemuller.gumroad.com/l/kylqvn).

ChatCode Tutor is a comprehensive script designed to help you learn Dart programming with ChatGPT. It includes 10 sections that cover everything from the basics to advanced topics, guiding you every step of the way.

**Sections**:

- Introduction to Programming
- Choosing a Programming Language
- Installing and Setting up your Environment
- Basic Concepts and Syntax
- Variables and Data Types
- Control Structures
- Functions
- Error Handling and Debugging
- Intermediate and Advanced Topics
- Practice and Resources
- Interview Prep

Each section comes with a detailed breakdown of topics and a wide range of questions to ask ChatGPT, ensuring a solid understanding of Dart by the end of the tutorial.

Our 10-part Dart tutorial provides a structured and organized approach to learning the language, offering a clear roadmap to follow instead of piecing together information from various sources. This enables efficient and effective learning, so you can start building your own applications with ease.

The true value of ChatCode Tutor though, lies in its ability to teach you how to communicate with ChatGPT effectively. By knowing the right questions to ask and recognizing when to seek elaboration, you can unlock the full potential of the best digital assistant humanity has ever known.

As I stated earlier, the value of these new chatbots is correlated with our ability to communicate with them. Knowing what questions to ask. Recognizing when to ask for elaboration. Identifying when something is plain false. All of these things are critical to extracting knowledge from the internet's new brain. My hope with the ChatCode Tutor is that it gives you the foundation to learn everything you would learn from a full Udemy course while also teaching you how to interact with what is likely the best digital assistant humanity has ever known.
6 steps you must follow to excel as a Software Developer
Tags: beginners, devjournal, programming, software
Published: 2023-03-17 02:32:00

"Software is a great combination of artistry and engineering." -Bill Gates

6 steps you must follow to excel as a software developer👇


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i2augpylxucraj6tjn34.png)
We Coded 2023
Tags: wecoded, braziliandevs
Published: 2023-03-17 02:27:30

## Participando do We Coded 2023: Compartilhe sua história!

As iniciativas de diversidade e inclusão impactaram positivamente minha carreira profissional na tecnologia porque através destas iniciativas conheci comunidades, organizações, instituições que promovem o empoderamento de mulheres e pessoas que se identificam com o gênero feminino, e mulheres inspiradoras na tecnologia que trilham o legado de mulheres pioneiras na área e são referências para mim.

Tão importante quanto iniciativas como o We Coded 2023 é promover, incentivar e dar espaço para que mais mulheres ingressem na tecnologia.

Vamos juntes!

Inspirada por:
### Diversity and inclusion initiatives have positively impacted my workplace by...
📅 GitHub Calendar issue reporting 🎫
Tags: github, datascience, api, python
Published: 2023-03-17 02:18:55

## ❔ About

Each end of year, managers need to produce a report of the activity to put in perspective the load of the organization.

👉 This post will show you some datavisualisations that rely on GitHub issues... as this is, (**_I want to believe_**) the item that :

- 👌 Reflects the **best our activity**
- 🙏 Requires the **less effort to be maintained** by the team

## 😭 The hassle of timesheets

{% youtube HAVXFzZ5tKs %}
## 🏋️ Daily `RUN` tagged issues

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


## 🚨 Daily incidents 

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

## 🎫 Daily issues


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

## 💰 Daily `BUILD` tagged issues


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

## 🐛 Daily bugs

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

## 🔖 Resources

- [`calplot`](https://pypi.org/project/calplot/)

## 🎀 Bonus : GitHub year in review 

{% twitter 1612535936557916190 %}
Capture VS Bubble
Tags: webdev, javascript, programming, tutorial
Published: 2023-03-17 02:10:39

On handling events in Javascript you may come across the bubble and capture phase. In this blog let's learn about both the phase

{% codepen https://codepen.io/harip0200/pen/xxazERd %}

As you can see in the above example we have 3 div's Grandparent, parent, and child let's try to add an on-click listener to each of them.

```javascript
const grandParent = document.getElementById('grandParent'),
    parent = document.getElementById('parent'),
    child = document.getElementById('child');

grandParent.addEventListener('click', () => {
    console.log('grand parent clicked')
})
parent.addEventListener('click', () => {
    console.log('parent clicked ')
})
child.addEventListener('click', () => {
    console.log('child clicked')
})
```
The above code will produce the following output
```javascript
//Clicking the green area
child clicked
parent clicked
grandParent clicked

//Clicking the red area
parent clicked
grandParent clicked

//Clicking the blue area
grandParent clicked
```
As you can see in the above example event fired from the innermost element to the outermost element this phase is called `Bubble`. By default, events will be triggered during the bubble phase

Now let's try capture, To use capture we need to pass `{capture: true}` as the third argument to the `addEventListener`

```javascript
grandParent.addEventListener('click', () => {
    console.log('grandparent clicked')
})
parent.addEventListener('click', () => {
    console.log('parent clicked')
})
child.addEventListener('click', () => {
    console.log('child clicked')
})

grandParent.addEventListener('click', () => {
    console.log('grandparent clicked from the capture')
},{capture:true})
parent.addEventListener('click', () => {
    console.log('parent clicked from the capture')
},{capture:true})
child.addEventListener('click', () => {
    console.log('child clicked from the capture')
},{capture:true})
```
The above code will produce the following output
```javascript
//Clicking the green area
grandparent clicked from capture
parent clicked from the capture
child clicked from the capture
child clicked
parent clicked
grandparent clicked

//Clicking the red area
grandparent clicked from capture
parent clicked from the capture
parent clicked
grandparent clicked

//Clicking the blue area
grandparent clicked from capture
grandparent clicked
```

You can now see during the capture phase event is fired from the outermost element to the innermost element and then it will start the bubbling phase to bubble the event from the innermost element to the outermost element


### Conclusion
Capture will move from the outermost element to the innermost element whereas Bubble moves from the innermost element to the outermost element

---
If you have read this far please leave a like and share your thoughts in the comment section

<center>Happy Coding </center>
Differences between AWS Network ACL & Security Group
Tags: aws, network
Published: 2023-03-17 01:25:28


**1.Network ACL vs Security Group**

| Network ACL   | Security Group |
|------------|----------|
| Firewall of Instances | Firewall of Subnets  |
| Supports allow rules only | Supports allow and deny rules |
| Stateful : only evaluates the packet from the source IP, not the destination | Stateless : evaluates the packet from both the source IP and destination IP  |
| Allows CIDR, IP, and Security Group as destination | Only allows CIDR as a destination    |
| Applies to instances only when a specific group is specified     | Automatically applied to all instances under the set subnet  |

Network ACL first layer of defense, Security group is the second layer of defense for inbound/ingress traffic.
Security group first layer of defense, Network ACL is the second layer of defense for outbound/egress traffic.

**2.Topology**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xgpashqmkj5vlkyhe4jt.png)
PostgreSQL with jsonb object
Published: 2023-03-17 01:17:02

Hi, I have got a requirement where I am storing around 100 fields into jsonb column. Now, my json object has almost 100 fields and each field represented by key and value pair. My requirement is, if the field "Gender" has value "Male" represent this with "M" and if "Female" then represent this by "F" in the result query. It is typically use of "Case" statement which I could not find anywhere. Can someone please help me with my requirement please.