teleren/devto huggingface dataset:
Ou Isso ou Aquilo: Exemplos com Operador Ternário (Parte 5)
Tags: javascript, algorithms
Published: 2021-09-09 14:56:27

Vou pegar alguns exemplos do livro **Algoritmos: Lógica para Desenvolvimento de Programação de Computadores** de José Augusto N. G. Manzano e Jayr Figueiredo de Oliveira (Editora Érica).

## Exemplo 1

### Desenvolver um programa que efetue a leitura de um valor numérico inteiro e apresente-o caso esse valor seja divisível por 4 e 5. Não sendo divisível por 4 e 5 o programa deverá apresentar a seguinte mensagem "Não é divisível por 4 e 5".

O usuário vai digitar um número inteiro. Um programa vai determinar se esse valor é divisível por 4 e 5 e o mostrará na tela. Vou criar uma variável para esse número:

```javascript
 const valor = Number(prompt("Digite um número inteiro qualquer"));
```

Agora vem a parte legal! Vou criar um operador ternário para fazer a verificação:

```javascript
const numeroDivisivelPor4E5 = (valor % 4 === 0 && valor % 5 === 0) ? console.log(`O número ${valor} é divisível por 4 e 5`) : console.log(`O número ${valor} não é divisível por 4 nem por 5`);
```

Legal, não é mesmo?

## Exemplo 2

### Ler um valor numérico inteiro que esteja na faixa de valores de 1 até 9. O programa deve apresentar a mensagem "O valor está na faixa permitida" caso o valor informado esteja entre 1 e 9. Se o valor estiver fora da faixa, o programa deve apresentar a mensagem "O valor está fora da faixa permitida"

Vou criar uma variável para que o usuário digite um número entre 1 e 9:

```javascript
const valor = Number(prompt("Digite um número inteiro qualquer entre 1 e 9"));
```

Vou criar um operador ternário para verificar se o número digitado está dentro da faixa desejada:

```javascript
const faixa = (valor >= 1 && valor <= 9) ? console.log("O valor está na faixa permitida") : console.log("O valor está fora da faixa permitida");
```

## Exemplo 3

### Ler os valores de quatro notas escolares de um aluno. Calcular a média aritmética e apresentar a mensagem "Aprovado" se a média obtida for maior ou igual a 5; caso contrário, apresentar a mensagem "Reprovado". Informar junto de cada mensagem o valor da média obtida.

Vou criar quatro variáveis para receber as notas que o usuário vai inserir.

```javascript
const nota1 = Number(prompt("Digite a primeira nota"));
const nota2 = Number(prompt("Digite a segunda nota"));
const nota3 = Number(prompt("Digite a terceira nota"));
const nota4 = Number(prompt("Digite a quarta nota"));
```

Vou criar uma variável para calcular a média. Se a média for igual ou maior do que 5, exibir a mensagem "Aprovado". Caso contrário, exibir a mensagem "Reprovado".

```javascript
const somaNotas = nota1 + nota2 + nota3 + nota4;
const media = somaNotas / 4;

const aprovadoOuReprovado = (media >= 5) 
? console.log(`Aprovado. Média ${media.toFixed(2)}`)
: console.log(`Reprovado. Média ${media.toFixed(2)}`);
```

### BIBLIOGRAFIA
MANZANO, José Augusto N. G., OLIVEIRA, Jayr Figueiredo de. **Algoritmos: Lógica para Desenvolvimento de Programação**. São Paulo, Editora Érica Ltda., 2005.

E aí? Gostaram? Até a próxima anotação! ☺
Native Bracket Pair Colourization in VS Code
Tags: vscode
Published: 2021-09-04 20:08:55

I’m a big fan of the [Bracket Pair Colorizer](https://marketplace.visualstudio.com/items?itemName=CoenraadS.bracket-pair-colorizer) extension, but it looks like this is [native in VS Code now](https://code.visualstudio.com/updates/v1_60#_high-performance-bracket-pair-colorization) and much faster!

{%twitter 1434229375860240385 %}

## Configure native bracket pair colourization

1. Make sure to remove the Bracket Pair Colorizer extension.
2. Update VS Code 
3. Open your user settings via <kbd>CMD</kbd>  (<kbd>CTRL</kbd> for non-Mac users) + <kbd>Shift</kbd>  + <kbd>P</kbd>  and type settings. The settings JSON file will open. Add the following:

```json
"editor.bracketPairColorization.enabled": true
```

All colors are themeable and up to six colors can be configured.

James Q. Quick has a video about getting this all set up

{%youtube KZC2_OMaEpc %}

More tips at [https://vscodetips.com](vscodetips.com)!

Happy VS Coding!
Para além das linhas de códigos
Published: 2021-09-06 14:17:05

Eu sempre quis trabalhar com pessoas, ajudar pessoas a resolverem seus problemas e que a tecnologia seria uma ferramenta para isso.

Eu sabia que não queria estudar para um cargo específico, que não mirava um setor específico, mas que sim eu precisava me desenvolver para ajudar pessoas e que ser multidiciplinar seria importante.

Hoje estou desenvolvedor de software, mas já fui técnico de manutenção de hardware, suporte de infraestrutura, vendedor, supervisor financeiro e outros mais...

As linguagens evoluem, novos frameworks são criados, profissões deixam de existir, negócios se transformam.

Quando comecei minha empresa de suporte e consultoria, existia o analista de sistema que era o profissional que traduzia a vontade do cliente em comunicação que os programadores entendiam.

O desenvolvedor de software hoje precisa ter habilidades tanto de negócios quanto de códigos, portanto, Devs de hoje não são os programadores de ontem.

Quanto mais você conhecer sobre os mais diversos tipos de negócios: mineração, logística, marketing, supply chain, aviação civil, processos jurídicos, impostos, comércio, mais rápido será sua evolução como profissional. 

Leva algum tempo para se aprender código e leva o dobro de tempo para conhecer sobre o negócio, assim o melhor investimento do Dev que quer ter uma carreira, é investir tempo para entender o negócio em que sua empresa está inserida, pois essa habilidade é de fora da nossa bolha e exige habilidades que nem sempre são lógicas.
 
Empresas que eu admiro, são empresas que apoiam muito equipes multidisciplinares, pois ninguém faz nada sozinho.

Empresas que realmente estão inovando, estão virando empresas de tecnologia, e com isso entendam, são empresas que cuidam de pessoas usando a tecnologia como ferramenta.

Concordo que ter foco é bastante importante, mas olha só, o mundo não vai parar porquê você precisa ter foco, então Dev Junior, foco na tecnologia e atenção em resolver problemas e aprender sobre negócios, o quanto antes você ficar a vontade com isso melhor será para a sua carreira.

Software é sobre humanidades, sobre como podemos ajudar pessoas, portanto, usar tecnologia é uma forma de conseguirmos isso.

Já rolou por aqui: 

[Pensar em Testes](https://dev.to/biosbug/testes-sao-formas-de-organizar-pensamentos-e-nao-apenas-usar-ferramentas-n3e)

[Básico SQL](https://dev.to/biosbug/o-basico-sobre-sql-5g9g)

[Aprenda GIT](https://dev.to/biosbug/aprenda-git-com-imagens-3f66)
Chakra UI: Theme - Update Tab style
Tags: react, styledcomponent, emotion
Published: 2021-09-05 07:54:34

I'm working on a project with **Chakra UI** where I need to create a navigation but it's more like tabs so I chose to use Chakra UI Tabs. I'm personally not a fan of the approach of writing CSS rules in components so I always prefer to modify the theme to fit my needs.

In this case, I really needed my Tabs to look like a classic `navbar` so I took the `unstyled` **variant**.


```
<Tabs variant="unstyled">
  <TabList>
    <Tab>Tab 1</Tab>
    <Tab>Tab 2</Tab>
  </TabList>
  <TabPanels>
    <TabPanel>
      <p>one!</p>
    </TabPanel>
    <TabPanel>
      <p>two!</p>
    </TabPanel>
  </TabPanels>
</Tabs>
``` 

And here is how to change the style of a `Tab` in the `theme` file 👇🏾
The first thing to note is that all child styles end up in Tabs.
So if you want to change `Tablist` or `TabPanel`, it will also be done in the Tabs attribute at the theme file.

```
export const theme = extendTheme({
    Tabs: {
      variants: {
        unstyled: {
          paddingY: '4',
          marging: '0',
          tab: {
            _selected: {
              color: 'white',
              boxShadow: 'none',
            },
          },
        },
      },
    },
  },
});
``` 
🎉

![Screen Shot 2021-09-05 at 08.53.43](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d8xyqpq7b4nrr0q25ur3.png)
How To Validate 10 Digit Mobile Number Using Regular Expression
Tags: laravel, php, javascript, validation
Published: 2021-09-06 03:27:57

In this article we will see how to validate 10 digit mobile number using regular expression in PHP or Laravel. here i will give you example of regex for 10 digit mobile number in jQuery.

Regular Expression through user can enter numbers in different format as per their requirements. When we are working with form validation at that time you need to restrict user to enter invalid value and users allow only numeric value or valid number.  

So let's see regular expression for 10 digit mobile number

Example : 

```
<html>
<head>
   <title>How To Validate 10 Digit Mobile Number Using Regular Expression - techsolutionstuff.com 
   </title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<form>
    <h1>How To Validate 10 Digit Mobile Number Using Regular Expression - techsolutionstuff.com</h1>
   <div class="col-md-6">
    <label>Mobile Number: </label>
    <input class="form-control" type="text" name="mo_no" placeholder="Mobile Number" minlength="10" maxlength="10" required>
    <br>
    <label>Mobile Number: </label>
  	<input type="text" class="form-control" name="mo_no" placeholder="Mobile Number" pattern="[1-9]{1}[0-9]{9}"  required ><br>
    <button type="submit" class="btn btn-success">Submit</button>
  </div>
</form>
</body>
</html>
```

---

![How To Validate 10 Digit Mobile Number Using Regular Expression
](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cix0g2ws0y9zprzpyni5.png)

---

You might also like :

- **_[Read More : Laravel 6 CRUD Tutorial with Example
](https://techsolutionstuff.com/post/laravel-6-crud-tutorial-with-example)_**

- **_[Read More : Laravel Datatable Example Tutorial](https://www.techsolutionstuff.com/post/laravel-datatable-example-tutorial)_**

- **_[Read More : Create Dummy Data Using Tinker In Laravel](https://www.techsolutionstuff.com/post/create-dummy-data-using-tinker-in-laravel)_**
How to Display the Progress of Promises in JavaScript
Tags: javascript, tutorial, webdev, codenewbie
Published: 2021-09-06 07:33:10

### Contents
1. [Overview](#overview)
2. [Implementation](#implementation)
3. [Conclusion](#conclusion)

-----

### Overview
Displaying the progress of multiple tasks as they are completed can be helpful to the user as it indicates how long they may need to wait for the remaining tasks to finish.

We can accomplish this by incrementing a counter after each promise has resolved.


*The video version of this tutorial can be found here...*
{% youtube I2UPGd0qsfY %}

Our desired output will look something like this, as the tasks are in progress.
```
Loading 7 out of 100 tasks
```

-----

### Implementation

**Let's start with the markup!**

All you need is a script tag to point to a JavaScript file (which will be implemented below), and one div element, whose text will be manipulated to update the progress counter of tasks completed.

```html
<!DOCTYPE html>
<html>
<body>
    <div id="progress"></div>    
    <script src="app.js"></script>
</body>
</html>
```

---
**Next up, the JavaScript!**

We will begin by creating a function which resolves a promise after a random time has passed. 

We do this as it closely resembles how it will work in a real-world application, e.g. HTTP requests resolving at different times.

```javascript
async function task() {
  return new Promise(res => {
    setTimeout(res, Math.random() * 5000);
  })
}
```

---
Secondly, we will create an array of 100 promises and update the progress text to inform the user when **all** of the tasks have finished.

```javascript
const loadingBar = document.getElementById('loadingBar');

(async() => {
  const promises = new Array(100)
    .fill(0)
    .map(task);

  loadingBar.textContent = `Loading...`;
  await Promise.all(promises);
  loadingBar.textContent = `Loading Finished`;
})();
```

Now imagine if this takes 30 seconds to complete. All the user will see on screen is the text 'Loading...' whilst it is in progress. 

That is not a very useful message!

---

Let's improve this now by updating the progress text after each task has resolved.

*The code snippet below is the full implementation.*

```javascript
const loadingBar = document.getElementById('loadingBar');

async function task() {
  return new Promise(res => {
    setTimeout(res, Math.random() * 5000);
  })
}

function loadingBarStatus(current, max) {
  loadingBar.textContent = `Loading ${current} of ${max}`;
}

(async() => {
  let current = 1;
  const promises = new Array(100)
    .fill(0)
    .map(() => task().then(() => loadingBarStatus(current++, 100)));

  await Promise.all(promises);
  loadingBar.textContent = `Loading Finished`;
})();
```

Now, you can see that as each promise is resolved, the counter is incremented and displayed to the user.

---

### Conclusion
In short, all you need to do is update the progress as each promise is resolved.

I hope you found this short tutorial helpful.

Let me know your thoughts in the comments below. 😊
How to implement Stripe revenue verification?
Tags: help
Published: 2021-09-05 17:59:09

I am building [AcquireBase](https://acquirebase.com) - a marketplace for buying and selling side-projects, micro-SaaS, etc.

As part of our upcoming feature, we want to allow our seller to verify their reported MRR via Stripe - something IH already does for products.

It has been over 1 month since I am trying to figure out how to do this. I tried Google search but nothing came up useful. Stripe's documentation did help either. 

Now, I'm getting frustrated. 

Is there anyone who has successfully implemented Stripe revenue verification or knows how to do this? 

I'd highly appreciate it if you share the info with me.

Thanks!
Ruby Conditional Statements
Tags: ruby, rails, programming, webdev
Published: 2021-09-05 19:03:07

In this post we look at if, else, elsif statement .This are the conditional operation which perform an action based on the Boolean response it pretty straight forward to use 


```
state=true

if state
  puts "you pick true"
elsif !state
  puts "you pick false"
else 
  puts "nothing was picked"

end


```
That all thanks for reading
I Created an OpenSource Portfolio Template for Developers 🚀
Tags: career, javascript, css, opensource
Published: 2021-09-06 18:02:29

**Launching** 🚀

## **Dopefolio** 🔥 - **An OpenSource Multipage Portfolio Website Template for Developers** 🚀

---

<div align="center">
  <img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9coge98bpo59p1crr6pc.gif" alt="Dopefolio Demo" width="100%" style="margin: 0;"/>
  <br>
</div>

## **Github Repo Link**: https://github.com/rammcodes/Dopefolio ⭐

---

Creating a **Portfolio Website** from scratch is time-consuming and that's why I have created an **OpenSource Portfolio Website Template for Developers** so developers don't have to build their website from scratch. 💯 

Instead, **Developers** can focus on building better **Projects** for their **Portfolio** without worrying about the **Portfolio** Website itself. 🤘

---

### **Features**:

- **Easy to Setup** ✅
- **Free to Use ( OpenSource )** ✅
- **No Additional Frameworks** ✅
- **No Additional Libraries** ✅
- **Multi Page** ✅
- **Fully Responsive** ✅
- **Super Fast and Optimized for SEO** ✅

<img src="https://i.ibb.co/1dD8Mky/Screenshot-from-2021-08-28-14-38-30.png" alt="Dopefolio Audits"  width="100%" style="margin: 0;" />

---



The project is made with **HTML, CSS**, some **JavaScript**, and **SASS** to write CSS. Don't worry if you don't know any, I have provided the instructions on how to use **Dopefolio** and set up your own Portfolio using it in the **README.md** file inside the Github Repository.


* Check out the **[Github Repository](https://github.com/rammcodes/Dopefolio)** 👨‍💻
* Drop a Github Star ⭐ 😉
* Fork the Repository 🍴
* Start using it for your own Portfolio 🙌

---

The **Demo Link** of the template is also provided in the **[Github Repository](https://github.com/rammcodes/Dopefolio)** along with the **Colors Playground** Link ✅

Hope this Portfolio Template will help you in your journey as a Developer 😇

---

## Important 😸

I regularly post useful content related to **Web Development and Programming** on **Linkedin**. You should consider **Connecting with me or Following** me on **Linkedin**.

**Linkedin Profile**: https://linkedin.com/in/rammcodes

You can also connect with me on **Twitter**

**Twitter Profile**: https://twitter.com/rammcodes

---

## Support 😇

If you find this project to be useful then you can **support** me using the **Buy Me a Coffee** link below so I can continue chasing my dream of building useful **Projects** that will help the developer community and the general audience and will allow me to change my life as well 😇

### **[Buy Me A Coffee](https://www.buymeacoffee.com/rammcodes)** ❤️

---

Feel free to **Like** and **Share** this post 😇

Share your feedback by **Commenting** below 💬

Drop me a **Follow** for more **Awesome** content related to **Web Development** and **Programming** 🙌

#### **Thank you for your support** ❤️
Disable Zoom on pinch in mobile using HTML tag
Tags: html, webdev, beginners, programming
Published: 2021-09-07 16:43:12

As a user when you open a site in mobile, we tend to pinch and zoom the page to see things more clearly. Have you ever wondered if that feature can be disabled?.

Yes, it can be disabled. What's more interesting is that it can be done by just a single line of code in HTML.


### How to disable zoom on pinch

- On the head section of the HTML, include the following piece of line which is a meta tag that tells the browser the details of what should happen on a device's viewport
 
```html
<!doctype html>
<html lang="en">
 <head>
   <meta name="viewport" content="width=device-width, initial-scale=1.0 ,
    maximum-scale=1.0 , user-scalable=no"/>
   ...
 </head>
 <body>...</body>
</html>

``` 

> name="viewport"

this means that this meta tag is used for device viewport

> width=device-width

assigns the width of the device as the viewport width

> initial-scale and maximum-scale is set to 1 -

 which means it occupies the full 100% of the viewport on page load

> user-scalable=no, 

setting the value to no or 0 is what tells the browser to prevent the page from scaling(zoom) in/out


### Things to keep in mind while using this 
- This can affect accessibility, people with poor vision will have concerns when visiting the page, since it will prevent them for zooming/out and viewing content closely when required. So use wisely.
- iOS or safari still lets the users zoom for the above mentioned accessibility reason, so this fix might not work in those platform.


Lets connect on  [Twitter](https://twitter.com/KritikaPattalam)  | [LinkedIn](https://www.linkedin.com/in/kritika-p-296739155/) for more web development related chats.
Hello class!
Published: 2021-09-07 18:11:32

My name is Michael and I am a senior at Penn State University. Currently I am majoring in Cybersecurity Analytics & Operations and minoring in Information Science & Technology. 

This past summer and overlapping into the first week of the semester, I had the opportunity to intern at CrowdStrike, where I was working as a threat intelligence analyst. Though I am not so sure how much web component work I will do in my future career, I am optimistic and excited to learn in this class and discover where I will be able to apply this knowledge in the future.
When Reviewing Others’ Work, Ask ‘How’ Instead of ‘Why’ Questions
Tags: management, sociotechnical, governance, api
Published: 2021-09-07 21:55:44

![A picture of a card from the '75 Tools for Creative Thinking Deck'](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vj1hgx9w2ctm3l2k1k00.png)

In my API governance experience, I interviewed *a lot* of teams. The purpose of those chats was always to reach a better understanding of the problem. A better understanding leads to better design. **Most** of the time, these conversations were amicable, easy-going affairs. One contributing factor that kept these affairs from becoming confrontations was when I switched from asking "Why" to asking "How" questions. 

When you ask someone "Why" they do or don't do something, you'll inevitably provoke a defensive response. For example, when trying to learn more about somebody's API practice, I could ask:

* "Why don't you have 100% contract test coverage?"
* "Why aren't your API descriptions captured in a single, discoverable place?"
* "Why did you produce so many microservices?"
* "Why is your domain terminology inconsistent?"
* And the classic catch-all, *"Why did you do it this way?"*

Each of those may be a legitimate question. However, the nature of the question comes across as a request for justification. Worse, answers to a why question immediately entrenches the person in a list, of their own making, of confirmation bias. What was supposed to be a positive discourse has turned exhausting, as each side attempts to prove that their approach is superior. 

Asking "how" is much more productive. Reframing our points from earlier changes the questions to:

* "How do you detect breaking changes in production?"
* "How do developers discover and learn how to use APIs in your area?"
* "How do you manage the greater complexity with your number of microservices?"
* "How do you describe this concept within your domain?"
* *"How did you work through the difficult decisions in this design?"*

Both the 'how' and 'why' examples address, roughly, the same areas of concern. However, the 'how' questions are more likely to result in people talking in greater length, detail, and thoughtfulness. They assist us in going further in exploration. 

Asking quality, open-ended questions creates a better rapport and a clearer idea of how to help. And the faster we get to help, the sooner our customers will find success. 

 The next time you feel the urge to ask "why", try reaching for "how" instead.
Custom radio button CSS only
Tags: codepen
Published: 2021-09-08 12:24:56

<p>Custom and fancy checkbox style with automatic fallback for older browsers.</p>

<p>Forked from <a href="http://codepen.io/giando110188/">Giandomenico Pastore</a>'s Pen <a href="http://codepen.io/giando110188/pen/zxoboB/">Custom checkbox CSS only</a>.</p>

<p>Forked from <a href="http://codepen.io/giando110188/">Giandomenico Pastore</a>'s Pen <a href="http://codepen.io/giando110188/pen/zxoboB/">Custom checkbox CSS only</a>.</p>

{% codepen https://codepen.io/manabox/pen/raQmpL %}