teleren/devto huggingface dataset:
find() vs filter() em JavaScript - Explicando diferenças com exemplos
Tags: javascript, tutorial, programming, braziliandevs
Published: 2023-01-02 20:57:22

Uma pergunta comum em entrevistas que os desenvolvedores de JavaScript costumam fazer, é explicar a diferença entre os métodos `find()` e `filter()`.

Neste tutorial de hoje, mostrarei o que são esses métodos e quando você deve usá-los.

## O que é o método filter()?

Este método retorna todos os elementos da array que satisfazem a condição especificada na função callback.

Vamos ver com um exemplo como realmente funciona:

```jsx
const x = [1, 2, 3, 4, 5];

const y = x.filter(el => el*2 === 2);

console.log("y is: ", y); // y is: [1]
```

Se você verificar a saída do exemplo acima, o valor de y é uma array de **1 elemento** que satisfaz a condição.

Isso ocorre porque o métodos filter() itera sobre todos os elementos da array e, em seguida, retorna uma array filtrada que satisfaça a condição especificada.

## O que é o método find()?

Este método retorna o primeiro elemento da array, que satisfaz a condição especificada na função callback.

Vamos ver com um exemplo como realmente funciona:

```jsx
const x = [1, 2, 3, 4, 5];

const y = x.find(el => el*2 === 2);

console.log("y is: ", y); // y is: 1
```

Agora, se você vir a saída do exemplo acima, o valor de y é 1. Isso ocorre porque o método `find()` procura o primeiro elemento na array, que satisfaça a condição especificada.

### As principais diferenças entre os exemplos acima são:

- `filter()` retorna um array contendo o elemento que satisfaz a condição, mas find() retorna o próprio elemento que satisfaz a condição.

- Em `filter()`, toda a array é iterada apesar do fato de que o elemento que está sendo procurado está presente no início.

## Casos de uso para find() e filter()

Quando você tem um caso de uso em que mais de 1 elemento deve ser retornado e deseja executar a operação em todos os elementos, pode usar o método `filter()`. Mas se você espera que apenas um único elemento seja retornado do array, então você pode usar `find()` e evitar iterações extras.

Vejamos exemplos de ambos os casos de uso:

### 1. Exemplo de caso de uso de filter()

```jsx
const x = [1, 2, 3, 4, 5];

const y = x.filter(el => el%2 === 0);

console.log("y is: ", y); // y is: [2, 4]
```

No exemplo acima, `filter()` faz mais sentido, pois você deseja iterar todos os elementos da array, para encontrar os elementos que são divisíveis por 2.

### 2. Exemplo de caso de uso de find()

```jsx
const emp = [
    {
        name: "Ram",
        empID: 101
    },
    {
        name: "Sham",
        empID: 102
    },
    {
        name: "Mohan",
        empID: 103
    }
];

const res = emp.find(el => el.empID === 102);

console.log("res is: ", res); // res is: {name: 'Sham', empID: 102}
```

No exemplo acima, `find()` faz mais sentido, pois há apenas 1 funcionário que tem 102 como o empID, portanto, `find()` ajuda a evitar a iteração sobre o terceiro objeto na array.

## Obrigado por ler!

Se você achou este artigo útil, compartilhe-o com seus amigos e colegas.
The Ultimate ChatGPT Playlist: 20 Creative Ways to Use This AI Model
Tags: ai, chatgpt
Published: 2023-01-02 20:47:56

**CHATGPT Your Go-To source for fun and innovation**

ChatGPT the AI Companion that offers Endless Entertainment Options.

Here are 20 ideas for entertaining uses of ChatGPT.

    Use ChatGPT to generate ideas for a bucket list.
    Use ChatGPT to generate ideas for a vacation itinerary.
    Have ChatGPT help you come up with ideas for things to do or places to go.

    Use ChatGPT to create a choose-your-own-adventure style story.
    Have ChatGPT play the role of a character in a role-playing game.
    Use ChatGPT to generate jokes or puns.
    Have ChatGPT help you write a letter or email.
    Use ChatGPT to generate ideas for new recipes or meal plans.
    Have ChatGPT write a short story or poem.

For more ....

[ChatGPT 20 Fun Ways to use it](https://www.javaoneworld.com/2022/12/chatgpt-20-fun-ways-to-put-this-clever.html)

Follow me for such well written article.

Happy coding.
how to install assetfinder tool on any linunx distro 🐧
Tags: linux, security, cybersecurity, go
Published: 2023-01-02 20:47:52

With this tool we can find domains and subdomains potentially related to a given domain. this tool is greatly useful in the asset discovery proccess.

## 1- first of all we should install **go** lang on our machine

```
sudo apt install go-lang -y
```

> the command above is for Debian Based Linux distributions, if you are using a different distro find out how to install go.


check if the go lang installed successfully :
```
go version
```
if yes you should see something like this:

```
go version go1.18.1 linux/amd64
```
---

## 2- also we need **git** to be installed on our machine 
```
sudo apt install git
```
check the git installation :
```
git --version
```
---

## 3-now change your directory and move to the downloads folder
```
cd Downloads
```
---

## 4- now we should clone the **assetfinder** repository from _Tomnomnom_ github

```
git clone https://github.com/tomnomnom/assetfinder.git
```
---

## 5-now move into the _assetfinder_ directory
```
cd assetfinder
```
---

## 6- create a go module
```
go mod init assetfinder
```
---

## 7-in this step we should build an executable go package with the command below

> the dot sign means build the package in the current directory

```
go build .
```
---

## 8- now we should move the file to bin folder so we can access _assetfinder_ from anywhere :D

```bash
sudo mv assetfinder /usr/local/bin/
```


and tada we are ready to hack !🗿
Configuração Simples para rodar servidor PHP. (sem senha ADM)
Published: 2023-01-02 20:36:01

Hoje precisei configurar um ambiente de desenvolvimento para rodar script's PHP e consegui de forma simples seguindo os passos abaixo:

1- Baixe a versão mais recente no site oficial php
[](https://windows.php.net/download)

![Pagina oficial de download php](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xvv2z4br2cwnzjmj0262.png)

2- Descompacte e deixe os arquivos em um pasta que possa usar depois (pode ser em qualquer pasta do Windows) no meu caso coloquei no C:\php

![Local dos arquivos descompactados ](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6thrjwr2qt7o9vrzi42u.png)

3- Você já pode subir um servidor executando o seguinte comando no prompt de comando(cmd):
`
C:\php\php.exe -S localhost:8888
`
![prompt de comando servidor ouvindo/iniciado ](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u2tpsape59y55o1xkyv4.png)


4- Observe que o caminho do meu CMD é C:\Git\php_projeto e nesse local que tem que está seus arquivos php:


![Ide VS Code com os arquivos](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ms8wr7l2bpxeai6frsae.png)


![Exemplo de execução do código no navegador](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nz2dujbmv15cm8mb3r7z.png)


5- Para facilitar você pode adicionar o php as variaveis de ambientes para que não precise passar o caminho do php todas as vezes


![Configuração windows](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e6a7vyxjw7hdl89ixpsb.png)
Escolha a segunda opção para nível usuário(sem senha ADM)


![Lista de variáveis de ambiente](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pmb4odc1fh4hfq0h4djf.png)



![Lista de variáveis de ambiente do path e inclusão](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8eox5e5ded0t17ctmcr6.png)


6- Agora pode digitar o comando para iniciar o servidor da seguinte forma:
`php -S localhost:8888`
How to get Wallet Addresses from Comment section of a Tweet
Tags: javascript, twitter, tutorial, web3
Published: 2023-01-02 20:18:36

If you want to perform an airdrop or a marketing campaign on twitter, but wonder how you're going to get all the wallet addresses from comments, Here's a quick and easy way to do that!

Sign up to get twitter development access(https://developer.twitter.com/en/portal/dashboard), once you're done

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

and get your BEARER token

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


Now to the Code!

Requirements
Node Js 16 and Up
Axios

```
import fs from "fs"; 
import axios from "axios";
var resultsNext_token = "";
var count = 0;
var arrayWallets = [] //Array of wallets
var regexPattern = /[^A-Za-z0-9]/g //Removes Pesky emojis and non alphanumerical text; 

async function runthis(id){
while (count < 13) { //Count is num *100(100 comments per request) so this goes through 1,300 comments
  const response = await axios.get(
    `https://api.twitter.com/2/tweets/search/recent?query=conversation_id:${id}&max_results=100&tweet.fields=in_reply_to_user_id,author_id,created_at,conversation_id&${
      resultsNext_token ? `next_token=${resultsNext_token}` : ""
    }`,
    {
      headers: {
        Authorization: `Bearer ${BEARER}`,
      },
    }
  );
  const resultsArray = response.data.data;
  resultsNext_token = response.data.meta.next_token;
  if (resultsArray != undefined) {
    resultsArray.map(data=>{
      const datatext = data.text.replaceAll("\n"," ").split(" ")
      datatext.map((data)=>{
        if(data.length>30){ // Checks for long strings(possibily wallets)
          arrayWallets .push(data.replace(regexPattern, ""))
        }
    })
    })
    // arrayWallets  = [...arrayWallets ,...resultsArray]
   
    count = count + 1;
    if(count ==13){ // after 1300 comments searched
      let data = JSON.stringify(arrayWallets );

fs.writeFileSync("walletArrayOut.json", data); // stores wallets in a json file as an array
    }
  } else {
    return false;
  }
}
```

And There you have it, Hope it helps!
I tried using the Daraja API with Springboot
Tags: mpesa, api, springboot, daraja
Published: 2023-01-02 20:09:34

```
<dependency>
  <groupId>com.mpesa</groupId>
  <artifactId>daraja</artifactId>
  <version>1.0.0</version>
</dependency>

```
```
import com.mpesa.Daraja;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class DarajaConfig {

  private String consumerKey = "your-consumer-key";
  private String consumerSecret = "your-consumer-secret";
  private String shortCode = "your-shortcode";
  private String passkey = "your-passkey";
  private String testUsername = "test-username";
  private String testAmount = "1";

  @Bean
  public Daraja daraja() {
    return new Daraja(consumerKey, consumerSecret, shortCode, passkey, testUsername, testAmount);
  }
}

```
Initiating a Payment

```
import com.mpesa.Daraja;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/payments")
public class PaymentController {

  @Autowired
  private Daraja daraja;

  @GetMapping("/initiate")
  public String initiatePayment(@RequestParam String phoneNumber) {
    return daraja.initiatePayment(phoneNumber);
  }

}

```
To Write or Have Written
Tags: beginners
Published: 2023-01-02 20:07:45

There is a common question amongst writers: "Would you rather write or have written?"

Essentially, do you prefer a) the act of writing or b) the fruits of creating a financial and critical success. 

I keep looking at the stack of technologies that I'm required to master in order to apply for job 'x'. I keep thinking about the last couple years and the places where I could have fit in a few hours / week to be where I want to be right now. 

But I didn't

I have consistently chosen the shinier thing; TV, video games, decent paying job with no future... I would prefer to 'have written.' This is a fundamental flaw. I haven't solved it yet, but I'm going to work on it now that I've pulled it into the spotlight.
Make an extra Income from Technical writing by following these Tips
Tags: technicalwriting, softwaredevelopment, newbie, writing
Published: 2023-01-02 19:54:49


Technical writing is a field that involves creating various types of documents to help people understand and use complex products or technologies. In the software development industry, technical writers are responsible for creating user manuals, online help guides, and product documentation that explain how software applications and systems work. If you're interested in becoming a technical writer in software development, here are some tips on how to get started:

Build your knowledge of software development: To be a successful technical writer in software development, it's important to have a strong understanding of the field. This includes learning about programming languages, software architecture, and software development methodologies. There are many resources available to help you learn about these topics, including online courses, degree programs, and professional organizations. Consider earning a degree in computer science or a related field to give you a solid foundation in software development.

Gain experience with technical writing: In addition to having a strong understanding of software development, it's also important to have experience with technical writing. This can include creating user manuals, online help guides, and product documentation for software applications and systems. You may want to consider taking a technical writing course or interning with a company to gain hands-on experience in this area.

Develop your writing skills: As a technical writer, it's important to have strong writing skills. This includes being able to write clearly and concisely, as well as being able to explain technical concepts in a way that is easy for non-technical readers to understand. Consider taking a writing course to improve your skills, or seek out opportunities to write in your free time, such as starting a blog or contributing to online forums.

Create a portfolio of work: As a technical writer in software development, it's important to have a portfolio of work that you can show to potential clients or employers. This can include documentation you have created for past projects, as well as writing samples that demonstrate your skills and expertise. Keep a record of your work and be sure to update your portfolio regularly.

Network with professionals in the industry: Networking is an important part of any career, and technical writing in software development is no exception. Consider joining professional organizations, attending industry events, and reaching out to other technical writers to build your network and learn about job opportunities. You may also want to consider joining online communities or forums related to technical writing and software development to connect with other professionals in the field.

By following these tips, you can get started on the path to becoming a successful technical writer in software development. With the right knowledge, experience, and skills, you can build a rewarding career in this field.
#58: Length of Last Word
Tags: leetcode, javascript, algorithms
Published: 2023-01-02 19:37:03

Welcome back, LeetCoders! Today I'll be tackling problem #58, which is called [Length of Last Word](https://leetcode.com/problems/length-of-last-word). From the description:

> Given a string `s` consisting of words and spaces, return the length of the last word in the string.
> A word is a maximal substring consisting of non-space characters only.

Now, there's a clean way and a not so clean way to accomplish the task we're given. Being the person I am, I'm going to go the easy route.

My thoughts on solving this problem were to simply strip the whitespace off the ends of the string, then to split it into an array and grab the length of the last word. A bigger challenge would be to deal with all of the spaces in an efficient manner so we're only left with the words in the array and not random spaces - but I'm solving it the quick and dirty way, which is to only strip what we need.

So let's get started. We're given a string `s`, so we'll start by just having the function return the string (makes it easier to debug).
```
var findLengthOfLastWord = function(s) {
   return s;
}
```
Now, let's incorporate some of the logic we talked about. We need to 1) strip both ends of the string, 2) split it into an array, 3) grab the last element of the array, and 4) return that element's length. Fortunately, there's a one-liner that does the job.
```
return s.trim().split(' ').slice(-1)[0].length;
```
You could also use `trimEnd()` instead of `trim()`, because if you think about it, the only trimming we need to do is from the end so we know what the _true_ last word is. Both are about the same speed though, so I'll leave it with `trim()`.

So there you have it. A truly janky solution to a classic LeetCode problem.
```
var lengthOfLastWord = function(s) {
   return s.trim().split(' ').slice(-1)[0].length;
};
```
As always, code can be found in the [Github](https://github.com/jD2R/leetcode) repository.
Happy coding!
Create a Lambda to do Arithmetic Operations
Tags: aws, cloud, awscommunity, 100daysofcloud
Published: 2023-01-02 19:34:42

[2/100] #100DaysOfCloud Today, I created an AWS Lambda with a language of your choice to do arithmetic operations on 2 numbers supplied as input and return the result.

<u>Lambda:</u>

- With AWS Lambda, you can run code without provisioning or managing servers. You pay only for the compute time that you consume—there's no charge when your code isn't running. You can run code for virtually any type of application or backend service—all with zero administration. Just upload your code and Lambda takes care of everything required to run and scale your code with high availability. You can set up your code to automatically trigger from other AWS services or call it directly from any web or mobile app.

- AWS Lambda natively supports Java, Go, PowerShell, Node. js, C#, Python, and Ruby code, and provides a Runtime API which allows you to use any additional programming languages to author your functions.

- You can configure the amount of memory allocated to a Lambda function, between 128 MB and 10,240 MB. 

- Lambda supports two types of deployment packages: container images and . zip file archives.

You can try to do create a Lambda function and do arithmetic operations on two numbers by following the steps from the below link.

[GitHub](https://github.com/aaditunni/100DaysOfCloud/blob/main/Journey/002/Readme.md)
What are the 5 Types of Marketing Data Management?
Published: 2023-01-02 19:32:17

There are multiple operations happening in an average digital marketing data management system. Here are the most common ones.

## Data integration
As marketing typically involves dozens of data sources, from marketing channels to CRMs, data integration is a key process in the data management cycle. It involves taking data from multiple sources that may have different data types and formats and bringing it together in the data storage facility.

Executing it correctly takes a deep understanding of the data systems of each of the sources used and transforms the data to conform to a uniform standard.

## Data refining
Refining data is a process that searches for and eliminates data that is incorrect or corrupted. During data refining, your analytics tools should check for data entry mistakes and other inconsistencies, and catch wrong formatting like mixed-up date formats, duplicate or confusing column names, etc.

This turns raw data into a format that is easy to parse and analyze.

## Data enrichment
Datasets are rarely complete, but thanks to having access to multiple sources, there’s a chance there is plenty of duplicate data. While the bulk of it should be cleansed during the refinement process, you can use some duplicate data to enrich your dataset. This means fixing missing data.

This also means adding more columns of data to a dataset, for instance adding sales data to the Facebook ads dataset. The result is a dataset that may provide much more insight into the effectiveness of your marketing campaigns.

## Data stitching
Data stitching operates on a similar idea. It’s the process of taking customer data that is present across different datasets and integrating it into a single one. This allows for a deeper understanding of how customers interact with different departments like marketing and sales.

## Data mining
Data mining helps businesses make more sense of large volumes of data. This process involves analyzing datasets to find trends and correlations. These are used for further business analysis and can help you arrive at conclusions about your marketing performance that may not be achievable with a simple marketing dashboard.

Check [this useful guide](https://blog.coupler.io/marketing-data-management/) to learn how to manage your marketing data effectively.
Best CSS Reset
Tags: webdev, css, cssreset, cssbestpractice
Published: 2023-01-02 19:27:17

A CSS Reset style is a list of rules that 'reset' all of the default browser styles.

This CSS reset style is not standard, although any CSS reset is not standard. I followed this CSS reset most of the time. This reset has my personal touch, so this is very subjective.


```
*,
*::before,
*::after {
  box-sizing: border-box;
}

* {
  margin: 0;
  padding: 0;
  font: inherit;
}

::-moz-selection {
  background-color: #b3d4fc;
  color: #000000;
  text-shadow: none;
}

::selection {
  background-color: #b3d4fc;
  color: #000000;
  text-shadow: none;
}

html {
  font-size: 62.5%;
  scroll-behavior: smooth;
  height: 100%;
}

html,
body {
  min-height: 100%;
}

ul,
ol {
  list-style: none;
}

a {
  color: inherit;
  display: inline-block;
  text-decoration: none;
}

svg {
  display: inline-block;
  max-width: 100%;
}

img,
picture,
video,
canvas {
  display: block;
  max-width: 100%;
}

button {
  cursor: pointer;
  border-radius: 0;
  border: none;
  background-color: transparent;
}

input,
textarea,
select {
  color: inherit;
  letter-spacing: inherit;
}

p,
h1,
h2,
h3,
h4,
h5,
h6 {
  overflow-wrap: break-word;
}

body {
  line-height: 1.5;
  -webkit-font-smoothing: antialiased;
  text-rendering: optimizeSpeed;
  font-size: 1.6rem;
}

```

Here is my [github](https://github.com/vishalk2512/my-css-reset) repository for the CSS reset stylesheet. if you like give it a star and follow.



Resources 
[https://www.joshwcomeau.com/css/custom-css-reset/](https://www.joshwcomeau.com/css/custom-css-reset/)
[https://piccalil.li/blog/a-modern-css-reset/](https://piccalil.li/blog/a-modern-css-reset/)
First Release of 2023
Tags: webdev, beginners, challenge, design
Published: 2023-01-02 18:51:11

Here is my first challenge of 2023. It is a simple design challenge but I used it to focus on using semantics to make the page more accessible as well as focusing on not repeating style rules to make my code easy to read. 

Leave some feedback here or on my frontend mentor profile.

Links:

https://www.frontendmentor.io/solutions/qr-code-component-EgM_j73pT2

https://github.com/OpenWorldProjectOWP/BetterDev4