teleren/devto huggingface dataset:
Reticências com tooltip automático (Vue)
Tags: webdev, javascript, vue, braziliandevs
Published: 2022-06-13 17:20:00

## TLDR;

[🔗 Resultado final](#working-example)

## A história

Hoje a responsável pela UX da empresa onde trabalho nos trouxe uma solicitação bem simples:

> "quando um determinado texto for muito grande, exiba somente as duas primeiras linhas e, quando o usuário passar o mouse, mostre a dica de tela com o texto completo".
> 
> -- <cite>UX da Empresa</cite>

Num primeiro momento pensamos em limitar o número de caracteres e fazer com o bom velho `substring`:

{% codepen https://codepen.io/jonyhayama/pen/QWQZZRG default-tab=js,result %}

Mas aí veio a pergunta "quantos caracteres perfazem duas linhas?" 🤔

Fica bastante difícil definir essa quantidade quando não estamos utilizando uma fonte monoespaçada... E mesmo assim, fica bastante complicado se trouxermos a responsividade para a equação...

Pensando nisso, resolvemos nos adaptar e utilizar o elegantíssimo `line-clamp` do CSS:

{% codepen https://codepen.io/jonyhayama/pen/JjpmeKx default-tab=js,result %}

🔀 PR criado.

🚀 Solução enviada para *staging*. 

🤞 Só falta aprovação de QA e...

> "Seria interessante que a dica de tela fosse exibida somente se o texto tiver sido truncado".
>
> -- <cite>QA da empresa</cite>

E volta o cão arrependido para pensar mais um pouco sobre o assunto 😢.

Revisitando a solução baseada em quantidade de caracteres, poderíamos resolver assim:

{% codepen https://codepen.io/jonyhayama/pen/KKQGrmy default-tab=js,result %}

Mas eu sou teimoso.

O `line-clamp` é mais elegante. Reflete melhor a problemática de exibir *por quantidade de linhas*.

Depois de pesquisar um pouco, encontrei uma forma de avaliar se o texto foi truncado baseado no tamanho do container utilizando as propriedades `scrollWidth` e `scrollHeight`:

{% codepen https://codepen.io/jonathanhayama/pen/JjpmeJV default-tab=js,result %}

No final do dia, com a lógica na cabeça, criei dois componentes, um baseado na quantidade de caracteres (sim, as vezes queremos limitar um texto por caracteres e não por linhas) e outro baseado em linhas.

Agora, no nosso projeto sempre que precisamos disso basta utilizarmos:

```html
<line-clamp text="texto" :lines="2" />
<truncate-text text="texto" :max-char="50" />
```

<span id="working-example">Exemplo:</span>

{% codepen https://codepen.io/jonyhayama/pen/bGLQqzQ default-tab=js,result %}

> ⚠️ **IMPORTANTE:** Nenhum dos códigos acima foi compartilhado na intenção de ser copiado e colado, é apenas uma forma de exemplificar o recurso 😜

Espero que isso lhe seja útil. Estou sempre aberto à pitacos e sugestões 😀

**PS:** Confesso que adoraria uma solução que não dependesse de JS... juro que tentei...mas não encontrei... se souber, compartilha aí 🙏
Maths x Coding Challenges
Tags: mathematics, programming, challenge
Published: 2022-06-13 17:18:12

Have you ever wanted to do a coding challenge that also relates to maths?

Well, thanks to @jeremyf I discovered Project Euler.

You get an algorithm prompt, and must provide the correct answer. Providing the right answer unlocks the solutions other folks have posted for that problem.

Click [here](https://projecteuler.net/) to check it out!
Why I think the joining & being active on Twitter is so important as a Self-Taught Developer (2 min read)
Tags: codenewbie, twitter, programming, beginners
Published: 2022-06-13 17:17:16

Being a self taught developer can be excited but also very overwhelming as well. Learning on your own without being in a live classroom can be tough sometimes. Especially those who have a family and another job on the side it can be difficult  to find some spare time to learn. 

In this article I want to give you 3 reasons why I think joining Twitter in my opinion is the best decision to make especially for those taking the self taught path learning software development.

- Supportive Community

The community is so supportive especially on twitter. Most of the questions that I asked have been answered. 

- Meet new friends

I have met so many new followers and made new friends. Making new friends will come a long way especially if later on you are looking for a new role.

- Keep up with the latest new on iOS Development

As we all know software development moves very fast. It's hard to keep up with whats going on. Twitter is an amazing place to keep up with the latest trends. For example I like iOS development and this year I saw so many people tweet about what's new that came out on WWDC. It helps me keep up and also gives me ideas for projects.

If you like this short blog post please like and share!

Thanks and have a Bless Day!

Anthony
Flatten Binary Tree to Linked List
Tags: leetcode, dsa, theabbie
Published: 2022-06-13 17:00:47

Given the `root` of a binary tree, flatten the tree into a "linked list":

*   The "linked list" should use the same `TreeNode` class where the `right` child pointer points to the next node in the list and the `left` child pointer is always `null`.
*   The "linked list" should be in the same order as a [**pre-order** **traversal**](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order,_NLR) of the binary tree.

**Example 1:**

![](https://assets.leetcode.com/uploads/2021/01/14/flaten.jpg)

**Input:** root = \[1,2,5,3,4,null,6\]
**Output:** \[1,null,2,null,3,null,4,null,5,null,6\]

**Example 2:**

**Input:** root = \[\]
**Output:** \[\]

**Example 3:**

**Input:** root = \[0\]
**Output:** \[0\]

**Constraints:**

*   The number of nodes in the tree is in the range `[0, 2000]`.
*   `-100 <= Node.val <= 100`

**Follow up:** Can you flatten the tree in-place (with `O(1)` extra space)?**SOLUTION:**

    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, val=0, left=None, right=None):
    #         self.val = val
    #         self.left = left
    #         self.right = right
    class Solution:
        def flatten(self, root: Optional[TreeNode]) -> None:
            if root:
                temp = root.right
                root.right = self.flatten(root.left)
                root.left = None
                curr = root
                while curr and curr.right:
                    curr = curr.right
                curr.right = self.flatten(temp)
            return root
Beginner's Guide to AWS CLI: Download, Install & Configure
Tags: aws, cloud, beginners, nayeemsweb
Published: 2022-06-13 17:00:34

Today's world is totally cloud based and we can hardly think of a software which don't uses Cloud Services. In this article, we will try to get an overview how we can Download, Install and Configure AWS CLI. 

Those of you who don't know much about `AWS` and `AWS CLI`, let me just give you a short overview of these keywords- 

[AWS - Amazon Web Services](https://aws.amazon.com/): This is a cloud service provider. They provide us several cloud services like EC2, Load Balancing, Auto Scaling, AMI, S3 Bucket, No-SQL database like DynamoDB, SQS, SES, RDS etc. In short AWS provides 200+ services. 

[AWS CLI - Command Line Interface](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html): It's a command line tool for configuring and using different amazon web services. It can be used in Windows CMD, PowerShell, Linux Shells and also in MAC OS terminal. 

Let's dive into our today's aim . . . 

### Download
---
Go to the AWS CLI [installation page](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) and download the file based on your Operating System and Architecture.

![Download AWS CLI Installation File](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/17m84yz1i3z6128sr6kc.png)
 

### Install
---
In our case, we are using Windows machine. So we downloaded the `AWSCLIV2.msi` file. The installation process is plain and simple. Just by clicking `Next` and `Finish` buttons on the AWS CLI installation pop-up window you can complete the installation process. 

### Configure
---
Now the AWS CLI is installed in your machine. For cross checking if it is installed correctly you may run this command- 
```
aws --version
```
This will display your AWS CLI version along with some other information. 
Now for configuring your machine, run the following command- 
```
aws configure
```
This will ask for your AWS account credentials like `Key Id`, `Secret Key`, `Region name` and `Output format`. Provide the values accordingly and correctly. You may follow the [AWS documentation](https://docs.aws.amazon.com/cli/latest/userguide/welcome-examples.html).


![AWS Account Configuration using CLI](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/18l0n75a4g2ag9a4ipex.jpg)

Finally, your machine is now connected with your AWS account. Whatever configuration or command you write in the terminal or in your local codebase will ultimately take effect in your AWS account.
Paracetamol.test.js🧪| #2: Testea este código JavaScript
Tags: javascript, testing, webdev, jest
Published: 2022-06-13 16:41:57

## **<center>Testea el siguiente código JavaScript</center>**
#### <center>**Dificultad:** <mark>Básico</mark></center>

```js
//index.js
  const resta =(a, b) => {
    return a - b;
  }

  const mult =(a, b) => {
    return a * b;
  }
  export {
    resta, mult
  }
```

```js
//operaciones.test.js
import { resta, mult as multiplicacion} from "./index.js";

test("5 - 5 es 0", () => {
  // el test esta vacío
});

test.todo("5 * 5  es 25");
```

A. `❌ FAIL tests, 5 - 5 es 0`, `❌ FAIL tests, 5 * 5 es 25`
B. `✅ PASS tests, 5 - 5 es 0`, `❌ FAIL tests, 5 * 5 es 25`
C. `✅ PASS tests, 5 - 5 es 0`, `✏ TODO tests, 5 * 5 es 25`

Respuesta en el primer comentario.

---
Number of Flowers in Full Bloom
Tags: leetcode, dsa, theabbie
Published: 2022-06-13 16:30:43

You are given a **0-indexed** 2D integer array `flowers`, where `flowers[i] = [starti, endi]` means the `ith` flower will be in **full bloom** from `starti` to `endi` (**inclusive**). You are also given a **0-indexed** integer array `persons` of size `n`, where `persons[i]` is the time that the `ith` person will arrive to see the flowers.

Return _an integer array_ `answer` _of size_ `n`_, where_ `answer[i]` _is the **number** of flowers that are in full bloom when the_ `ith` _person arrives._

**Example 1:**

![](https://assets.leetcode.com/uploads/2022/03/02/ex1new.jpg)

**Input:** flowers = \[\[1,6\],\[3,7\],\[9,12\],\[4,13\]\], persons = \[2,3,7,11\]
**Output:** \[1,2,2,2\]
**Explanation:** The figure above shows the times when the flowers are in full bloom and when the people arrive.
For each person, we return the number of flowers in full bloom during their arrival.

**Example 2:**

![](https://assets.leetcode.com/uploads/2022/03/02/ex2new.jpg)

**Input:** flowers = \[\[1,10\],\[3,3\]\], persons = \[3,3,2\]
**Output:** \[2,2,1\]
**Explanation:** The figure above shows the times when the flowers are in full bloom and when the people arrive.
For each person, we return the number of flowers in full bloom during their arrival.

**Constraints:**

*   `1 <= flowers.length <= 5 * 104`
*   `flowers[i].length == 2`
*   `1 <= starti <= endi <= 109`
*   `1 <= persons.length <= 5 * 104`
*   `1 <= persons[i] <= 109`

**SOLUTION:**

    from collections import defaultdict
    import bisect
    
    class Solution:
        def fullBloomFlowers(self, flowers: List[List[int]], persons: List[int]) -> List[int]:
            times = defaultdict(int)
            for s, e in flowers:
                times[s] += 1
                times[e + 1] -= 1
            timekeys = sorted(times.keys())
            prefix = [0]
            for t in timekeys:
                prefix.append(prefix[-1] + times[t])
            answer = []
            for p in persons:
                i = bisect.bisect_right(timekeys, p)
                answer.append(prefix[min(i, len(prefix) - 1)])
            return answer
Paracetamol.js💊| #140: Explica este código JavaScript
Tags: javascript, spanish, webdev, programming
Published: 2022-06-13 16:29:01

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

```js
const f = (inicio, fin) => {
  return Array.from({length:(fin - inicio)}, (_, indice) => (inicio + indice))
}
console.log(f(2,7))
```

A. `[ 2, 7 ]`
B. `[ 2, 3, 4, 5, 6 ]`
C. `[ 3, 4, 5, 6, 7 ]`
D. `[ 0, 1, 2, 3, 4, 5, 6, 7 ]`

Respuesta en el primer comentario.

---
JavaScript DOM
Tags: javascript, programming, react, css
Published: 2022-06-13 16:12:12

##Introduction
JavaScript DOM is essential part of web development and there are multiple methods to manipulate HTML elements using JavaScript DOM. The Document object module(DOM) can dynamically changed the elements of HTML objects there are lot o cool tings you can do with JavaScript DOM.

The DOM follows the methods 

1.**document.getElementById(HTMLElementid)**
select an HTML element by id and manipulating HTML element.

```javascript
<h1 id="title"> Hello readers!</h1>
<script>
document.getElementById('title')
</script> 

```
2.**document.getElementsByTagName(HTMLtag)**
select an HTML element by tag name and manipulating HTML element.

```javascript
<h1> Hello readers!</h1>
<script>
document.getElementByTagName('h1')
</script> 
```
3.**document.getElementsByClassName(HTMLClass)**
select an HTML element by class name and manipulating HTML element.

```javascript
<h1 class="title"> Hello readers!</h1>
<script>
document.getElementByClassName('title')
</script> 
``` <br>

The querySelector() method returns the first element that matches a CSS selector. to select all child node we use querySelectorAll() method

##Event Listeners in DOM
An event is action occurs in the web browsers, there are multiple action listeners available in javascript

1. click event()

```javascript
<button id="btn">Click Me!</button>

<script>


let btn = document.querySelector('#btn');

function display() {
    alert('It was clicked!');
}

btn.addEventListener('click',display);

</script>

```

when button was pressed it will display alert box which show it was clicked! and we mentioned the click event inside the function display.

There are multiple event are available for manipulating HTML content like mouse event mouseover(), keyevent() and keydown() lot of source are available for listeners.

Example:

``` javascript
<button>change color</button>

<script>
 const btn = document.querySelector('button')
   btn.addEventListener('click', () => {
  document.body.style.background = "red"
});

</script>
```

when user click on change color button the body background will automatically change into red colour.

####Repositories to start with Javascript DOM projects 

1. [Github repo with 100 DOM Projects](https://github.com/solygambas/html-css-javascript-projects)
2. [100+ javascript projects](https://jsbeginners.com/javascript-projects-for-beginners/) 


Hey, I'm Ganesh 🖐
I write article on web development and sharing valuable resources which might helps you as developer or beginner.

for more content

follow me [Ganesh_Patil](https://dev.to/patilganesh1010)
You can also connect with me on [twitter](https://twitter.com/PatilGanesh1010) 
to get more content related to web development
Thank you for the support!
C# Export PDFs and Save to MemoryStream
Published: 2022-01-20 08:56:31

---
canonical_url: https://ironpdf.com/docs/questions/export-save-pdf-csharp/
---

IronPDF is a [C# PDF Library](https://ironpdf.com/use-case/csharp-pdf-library/) that allows you to use C# to save your HTML as a PDF. It also allows C# / VB developers to edit PDF documents programmatically.

---

**Step 1**

# 1. Install IronPDF to Your Project

To Install IronPDF into your .NET project use the NUGET package manager: [https://www.nuget.org/packages/IronPdf](https://www.nuget.org/packages/IronPdf)

`PM > Install-Package IronPdf`

Alternatively, the [IronPDF DLL can be downloaded](https://ironpdf.com/packages/IronPdf.Package.For.Export.save.pdf.csharp.zip) and manually installed.

---

**How to Tutorial**

# 2. Options for Saving PDFs

## 2.1 How to Save PDF to Disk

Use [IronPDF.PdfDocument.SaveAs()](https://ironpdf.com/object-reference/api/IronPdf.PdfDocument.html) to save your PDF to disk.

You will find that this method supports adding password protection. You may also wish to explore the PdfDocument documentation to discover methods for digitally signing exported PDFS.

## 2.2 How to Save a PDF File to MemorySteam in C# (System.IO.MemoryStream)

The [IronPDF.PdfDocument.Stream](https://ironpdf.com/object-reference/api/IronPdf.PdfDocument.html) property saves the PDF to memory using a System.IO.MemoryStream

## 2.3 How to Save to Binary Data

The [IronPDF.PdfDocument.BinaryData](https://ironpdf.com/object-reference/api/IronPdf.PdfDocument.html) property exports the PDF document as binary data in memory.

This outputs the PDF as a ByteArray, which is expressed in C# as _byte[]_.

## 2.4 How to Serve from a Web Server to Browser

To serve a PDF to the web, we need to send it as binary data rather than HTML.

### MVC PDF Export

**C#:**
```

/// send MyPdfDocument.Stream to this method
return new FileStreamResult(stream, "application/pdf")
{
    FileDownloadName = "file.pdf"
};
```

**VB:**
```
''' send MyPdfDocument.Stream to this method
Return New FileStreamResult(stream, "application/pdf") With {.FileDownloadName = "file.pdf"}
```

### ASP.NET PDF Export

**C#:**
```
byte[] Binary = MyPdfDocument.BinaryData;
Response.Clear();
Response.ContentType = "application/octet-stream";
Context.Response.OutputStream.Write(Binary, 0, Binary.Length);
Response.Flush();      
```

**VB:**
```
Dim Binary() As Byte = MyPdfDocument.BinaryData
Response.Clear()
Response.ContentType = "application/octet-stream"
Context.Response.OutputStream.Write(Binary, 0, Binary.Length)
Response.Flush()
```
Luos Pipe
Tags: opensource, microservices, tutorial, luos
Published: 2022-06-13 16:04:03

Working closely with the gate, the pipe allows data to be sent or received from the outside world and converted to the Luos side. A Pipe can be USB, serial, Wifi, Bluetooth, an SD card, or anything that allows sending and receiving information to/from another machine.

▶️ https://www.luos.io/docs/tools/inspector#inspector-and-pipe

This new type of driver can be used for different purposes, and the Gate application needs it to exchange information and share its output format.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2pwrryud02jayifnm1ib.png)
ES6? ECMAScript? Entenda o que isso tem a ver com o Javascript
Tags: ecmascript, javascript
Published: 2022-06-13 16:03:41

ES6 se refere a 6ª versão do ECMAScript. 
ECMAScript é uma especificação de uma linguagem de script e o Javascript é a implementação dessa especificação.

O ECMAScript existe pois cada browser, seja chrome, firefox ou qualquer outro, possui diferentes implementações para que você possa rodar seu código Javascript, mas todos devem seguir a mesma especificação. 

Imagina se para cada browser tivesse uma especificação diferente? Seria uma loucura

Algumas features novas no ES6
```js
// Declaração de variáveis com let e const
let varLet = 123;
const varConst = 456;

// Arrow function
const arrowFunction = () => {};

// Classes
class Classes {}

// Template string
const templateStr = `${varLet} ${varConst}`;

// Promises
const delay = (duration = 0) =>
  new Promise((resolve, reject) => {
    setTimeout(resolve, duration);
  });

await delay(1000)

// E muito mais ...
```

ES7
```js
// Array includes
[1, 2, 3].includes(1) // => true
[1, 2, 3].includes(9) // => false
// Operador de exponenciação
10 ** 3 // => 10 * 10 * 10 = 1000
```

ES8
```js
// Async function
const asyncFunc = async () => {
    await delay();
}

// Object.entries e Object.values
const obj = { siga: 'agora', like: true }
Object.entries(obj) 
// => [['siga', 'agora'], ['like', true]]
Object.values(obj)
// => ['agora', 'true']

// E muito mais ...
```

E existem varias outras versões como ES9, ES10, etc.

Se você quer ver todas as versões e entender mais sobre:  
- [Documentação oficial (en-US)](https://www.ecma-international.org/publications-and-standards/standards/ecma-262/)
- [Lista de todas as features (en-US)](https://github.com/daumann/ECMAScript-new-features-list)
- [Artigo mais detalhado sobre ECMAScript e Javascript (en-US)](https://www.freecodecamp.org/news/whats-the-difference-between-javascript-and-ecmascript-cba48c73a2b5/)
Count Primes
Tags: leetcode, dsa, theabbie
Published: 2022-06-13 16:00:44

Given an integer `n`, return _the number of prime numbers that are strictly less than_ `n`.

**Example 1:**

**Input:** n = 10
**Output:** 4
**Explanation:** There are 4 prime numbers less than 10, they are 2, 3, 5, 7.

**Example 2:**

**Input:** n = 0
**Output:** 0

**Example 3:**

**Input:** n = 1
**Output:** 0

**Constraints:**

*   `0 <= n <= 5 * 106`

**SOLUTION:**

    import math
    
    class Solution:
        def countPrimes(self, n: int) -> int:
            if n <= 2:
                return 0
            primes = [1] * n
            primes[0] = 0
            primes[1] = 0
            numprimes = n - 2
            l = int(math.sqrt(n)) + 1
            for i in range(2, l):
                if primes[i] == 0:
                    continue
                for j in range(i, 1 +  n // i):
                    if i * j < n and primes[i * j] == 1:
                        primes[i * j] = 0
                        numprimes -= 1
            return numprimes
Blockchain Development
Published: 2022-06-13 15:57:07

Hello, This is Amit, Full-Stack Blockchain developer with 5 years of experience.

- NFT Marketplace
- DEX & CEX
- Token Deployment, Presale, ICO, IDO, IGO
- LaunchPad.
- DEFI
- Blockchain Game, Gamefi
- DAO

--Skills
React.js(5 years), Next.js(3 years), Vue.js(3 years), Nuxt.js(2 years)
Web3.js(3 years), Ether.js(2 years)
Solidity(4 years), Rust(1 years)

--Availability
Immediately right now.

--Working Timezone
Flexible

--Working hours
Flexible

If you find someone who is experienced and reliable, Please DM.
I am always ready for you.
Thank you

Conact on telegram @Robotechdev
why coding is hard !
Published: 2022-06-13 15:37:34

There are a lot of people who started learning programming because of their hatred of their material and emotional reality, so they decided to become a genius people like Bill Gates …etc, to prove themselves but this keeps them in a cycle of depression and inferiority, and they don’t really know what they will do! web development, or mobile apps, games or cyber security, they don't know themselves, their abilities and their passion, although they really love programming, but they no longer have the will and motivation, and they start self-doubt and why the existence, and this may lead to suicide . 

so you as a good programmer or developer what is your advise for those people to help them exit this loop