teleren/devto huggingface dataset:
This week I learned...
Tags: ruby, foundations, webdev, beginners
Published: 2023-04-04 15:04:47

## Week: 03/05/2023 - 03/11/2023



**Working with Strings in Ruby**


Input:

```
'Single quoted strings #{represent} "characters" verbatim.'
```

Output:

```
Single quoted strings #{represent} "characters" verbatim.
```
Input:

```
"Double-quoted strings make some substitutions: #{2 + 4}"
```

Output:

```
Double-quoted strings make some substitutions: 6
```

**To join Strings, you can interpolate or concatenate**
- String concatenation
   - joining of strings
   - can join strings together using `""` and `+` between strings
   - you have to add `" "`, an empty string with a space to prevent two words being put together
   - `myvar` can be a variable inserted with a string and can add other strings with the plus sign `+`
   - if you do `+=` the myvar will be have the new concatenation as the new string
   - strings can only be concantenated with other strings

- String interpolation
   - interpolation `#{}` can be used within double quoted strings and it will substitute the result of a ruby code into the middle of the string
   - the interpolation will be evaluated and the result will be converted into a string

**Interactive Ruby (irb)**
- can use IRB (interactive ruby) which is integrated in Ruby if you type "irb" and hit return in terminal
- irb will show you the result of each expression, you dont need to call "puts" or anything
- type "exit" and then enter to exit out of IRB
           
**p vs puts vs print method**          
- Ruby provides a method `p` which is different than `print` and `puts` 
- p method allows us to inspect the values we pass to it and to print them out approximate the same way they would appear in a ruby code

Input: puts
```
            puts "   "
            puts ""
            puts nil
            puts []
```

The output is an empty terminal

Input: print
```
            print "    "
            print ""
            print nil
            print []
```
The output is []%

Input: p
```
            p "    "
            p ""
            p nil
            p []
```
The output is:
```
            "     "
            ""
            nil
            []
```

**Some escape sequences**
    - \n skips to a new line
    - \t    indents a text
    - \" inserts "double quotes"
    - \' inserts 'single quotes'
    - \\ inserts a backslash: \
       
Input: example
```
        puts "first line
        second line"

        puts "     new paragraph"
        puts "  He said, "Whoa.""
```

**to fix the line above use escape sequences**
```
    puts "first line\nsecond line"
    puts "\tnew paragraph"`
    puts "He said, \"whoah\""
```




Next Week: **Ruby Objects**
Launch Week Day 2 - Community Help
Tags: webdev, javascript, github, discord
Published: 2023-04-04 15:03:07

## Being able to find solutions easily and leverage an active community all sharing knowledge together has a huge impact on both the quality of your code and the quality of your life.

With this in mind, we’re excited to introduce our new [Community Help archive.](https://payloadcms.com/community-help) 

Community Help builds upon our active and supportive communities on Discord and GitHub. With over 500 resolved threads, there's a good chance that your question has been asked before, a similar issue has been encountered or a code example that you are looking for has been shared.

But the problem up until now was that GitHub Discussions are terrible for SEO for some reason, and Discord help threads are locked behind needing to download yet another app. 

So to make this information way more accessible, we’re directly fetching all this data from Discord/GitHub and displaying it on the Payload website’s Community Help page. (p.s. don’t forget we are open source so feel free to check out how we did this!)

To help you find what you need faster, we've integrated Algolia Search to index every question, answer, and comment. This lets you use keywords to search on any part of the thread so you won’t miss out on anything relevant. You can also view the thread directly in your browser without needing to visit or sign up for external sites.


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

The first thing most of us do when we need help is turn to a search engine (i.e…. we bing it….just kidding). But when’s the last time you ever landed on a GitHub discussion from Google? Think about it… You might land on an issue, but rarely on a discussion. 

With all of our GitHub Discussions and Discord community help threads output as static pages in our NextJS site, over time, we’re also hoping to start to see way more results from the Payload community directly in your Google search results.
This section of our site will continue to evolve and become more powerful as our archive of answers expands. 

We’re extremely grateful for our enthusiastic and engaging community and this would not be possible without them. A few of you are absolute maniacs about helping each other and we just want to take a second to say - - THANK YOU. 

Head over to the [Community Help page](https://payloadcms.com/community-help) and let us know what you think!
Desvendando o Large Object Heap (LOH): Tudo o que um Desenvolvedor precisa saber
Tags: dotnet, dotnetcore, programming, csharp
Published: 2023-04-04 14:45:00

O Large Object Heap (LOH) é um componente fundamental da coleta de lixo na plataforma .NET. É responsável pelo gerenciamento de objetos grandes na memória, que são aqueles com mais de 85.000 bytes de tamanho.

Embora o LOH seja uma parte importante da coleta de lixo na plataforma .NET, muitos desenvolvedores não têm uma compreensão completa de como ele funciona e como afeta o desempenho do aplicativo. 

Quando um objeto grande é alocado no LOH, ele é alocado em um segmento separado da memória. Este segmento não está vazio como muitos pensam, alguns tipos utilizados pelo CLR são alocados neste segmento.

O LOH é coletado sempre que ocorre uma coleta GC FULL, mas também pode ser responsável por acionar essa coleta. Além disso, ele possui seu próprio valor de Allocation Budget. Para mais informações sobre o Allocation Budget, consulte este [artigo](https://dev.to/unhacked/allocation-budget-voce-sabe-o-que-e-3pnc)).

Conforme os objetos grandes são alocados e desalocados no LOH, a memória pode se tornar fragmentada. Por padrão, o LOH só executa o processo de sweeping, o que significa que a compactação não é realizada. Imagine mover objetos maiores que 85.000 bytes durante o processo de compactação – seria ineficiente.

A falta de compactação pode levar a um problema conhecido como fragmentação de heap, que afeta negativamente o desempenho do aplicativo, pois o GC precisa localizar um espaço contínuo dentro do segmento para alocar o objeto.

Ao contrário do que muitos pensam, é possível definir um limite para o tamanho dos objetos alocados no LOH. Existem várias opções disponíveis.

![Site Microsoft](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ibf8mvqty2p882r5hq1a.png)

O tamanho do segmento LOH pode ser ajustado para otimizar o desempenho do aplicativo e minimizar a fragmentação de heap equilibrando a alocação de memória no LOH.

Embora não seja realizado por padrão, é possível programaticamente realizar a compactação. Para isso, use o seguinte código:

```csharp
GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
GC.Collect();
```

Porém desde o dotnet 3.0, o GC pode pode optar por compactar nos casos de chegar a um limite crítico. 

Se o consumo for maior do que 90% e se a fragmentação LOH for maior que 12,5% ou se parecer produtivo o tamanho estimado dos objetos recuperados (≥ ⅛ limite rígido).

O Large Object Heap é importante na coleta de lixo na plataforma .NET. No entanto, a fragmentação de heap pode afetar negativamente o desempenho do aplicativo, e os desenvolvedores devem minimizar a fragmentação de heap e otimizar o uso do LOH.
HOW TO CREATE A FUNCTION APP WITH A WEBHOOK TO PROVIDE A "HELLO" MESSAGE WITH YOUR NAME.
Tags: azurefunctions, azure, eventgrid
Published: 2023-04-04 14:36:20

**STEP 1**: CREATE A FUNCTION APP

- Search function app' on the search panel and click on create.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bjm5l3cfoqq45tzecijv.png)

- Fill in your required details.Choose your subscription, add a resource group, your "publish" should be on code, give your function app a name, choose .Net for your "runtime stack", leave the rest as default. Click on review+create then click on create.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h7ph85o0eucb4nuaxy2d.png)

**STEP 2**: CREATE A HTTP TRIGGERED EVENT FUNCTION

- Once deployment is completed, click on "Go to resource". 
- Click on fuction and then click on create.
- Select Http trigger and scroll down to input a name for your event function or maintain name given.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dlu0bo1aa3079bqy7f53.png)

**STEP 3**: PROVIDE A HELLO MESSAGE WITH YOUR NAME THEN RUN A TEST

- To run a test, click on "Get function url" to copy the url.
- Paste the url in your web browser.
- At the end of the url code, add "&name=your name" then hit enter. E.g &name=Victor
- You will receive a hello message with your name.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z87ikgb7qvspcxds0zy0.png)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h3xwt8qza91oygxr2atr.png)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gfej7iht1va4iq8xa4bh.png)
The path onward
Tags: opensource, programming, beginners
Published: 2023-04-04 14:19:14

With the release of [Starchart](https://github.com/DevelopingSpace/starchart) 0.8, we as a team are on the path onward to perfect the core features in preparation for shipWith the release of [Starchart](https://github.com/DevelopingSpace/starchart) 0.8, we as a team are on the path onward to perfect the core features in preparation for shipping the first major release. 

### Tasks at hand
Given that the certificate flow is in place this week, I intend to implement support for notifying users via email when their certificate order is ready. Also, I would be adding a button in the UI which leads to an external resource. Lastly, as one of the Sheriffs on duty, I would ensure I do more PR reviews this week. ping the first major release.
10 GitHub Learning Repositories for Beginner Developers
Tags: javascript, webdev, beginners, codenewbie
Published: 2023-04-04 14:02:02

It can be challenging for a beginner developer to know where to begin when learning to code. Fortunately, GitHub has a variety of learning repositories to aid in your initial learning.

We'll introduce 10 GitHub learning repositories for beginner developers in this article.

You will find knowledge about the general web, learning roadmaps, computer science principles, interview preparation guides, additional books and websites to use and so much more.

## 1. [how-web-works](https://github.com/vasanthk/how-web-works)

What happens behind the scenes when we type [www.google.com](https://www.google.com)
> ⭐ GitHub stars 13k

## 2. [developer-roadmaps](https://github.com/kamranahmedse/developer-roadmap)

Community driven roadmaps, articles and resources for developers
> ⭐ GitHub stars 236K

## 3. [Free-Software-Books](https://github.com/EOEboh/Free-Software-Books)

List of Free Learning Books and Resources for Developers
> ⭐ GitHub stars 92

## 4. [ossu-computer-science](https://github.com/ossu/computer-science)

Path to a free self-taught education in Computer Science!
> ⭐ GitHub stars 137k

## 5. [coding-interview-university](https://github.com/jwasham/coding-interview-university)

> ⭐ GitHub stars 253k

## 6. [freecodecamp](https://github.com/freeCodeCamp/freeCodeCamp)

A friendly community where everyone can learn to code for free.
> ⭐ GitHub stars 364k

## 7. [project-based-learning](https://github.com/practical-tutorials/project-based-learning)

A list of programming tutorials in which aspiring software developers learn how to build an application from scratch.

> ⭐ GitHub stars 96k

## 8. [javascript-algorithms](https://github.com/trekhleb/javascript-algorithms)

This repository contains JavaScript based examples of many popular algorithms and data structures.

> ⭐ GitHub stars 166k

## 9. [system-design-primer](https://github.com/donnemartin/system-design-primer)

Learn how to design large-scale systems. Prep for the system design interview.

> ⭐ GitHub stars 216k

## 10. [front-end-interview-handbook](https://github.com/yangshun/front-end-interview-handbook)

Learn how to design large-scale systems. Prep for the system design interview.

> ⭐ GitHub stars 37k

In conclusion, GitHub is a great platform for inexperienced developers who want to brush up on their coding skills and acquire new ones. The ten repositories we've examined in this piece are just a portion of the extensive library of materials on GitHub. Everyone can find something on GitHub to learn, whether they want to study web development, computer science, or a specific programming language. Therefore, get investigating and have fun learning!
How to fix 'Code' command in PopOS terminal
Published: 2023-04-04 13:42:27


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


When you download Visual Studio Code on PopOS! the **Code** command does not work in the terminal, which opens your IDE any project anywhere you are.


To solve this, it's simple.
 
First you will use cd to focus on the bin/ folder:

`$ cd /usr/local/bin/`

Then, using the sudo command will create the code command
`$ sudo ln -s /usr/share/code/bin/code code`

Restart your terminal and the magic is done!
How to make money as a technical writer
Tags: webdev, javascript, programming, beginners
Published: 2023-04-04 13:29:06

You have no excuse in 2023, you have none!!!  thanks to the internet all the information you need to become a technical professional are available, i would like to introduce a topic i find very interesting: _technical writing_ 
A technical writer is a skilled information communicator who takes on the role of breaking down complex technical information into simple pieces of information that can be understood easily,
Technical writing plays a very significant  role in supporting technical products  and services,Technical writing can be found in any industry or field where complex concepts, theories,  procedures need to be communicated, despite the fact that many people identify it with the authoring of computer and software manuals, there are other opportunities like press releases, memos, reports, business proposals, datasheets, product descriptions, specifications, white papers,resumes and also job applications,

Here's what you need to know about writing:
**Research:** before you start writing any articles you need to spend time doing your research, you need to be able to develop your knowledge regularly to keep up with the trend, this might even include  looking up standard best practices, the legality of the information and also product reviews.

**Keep it simple:** the whole concept of technical writing is founded on simplicity, readers need to finish your articles more informed than before they read.

**Write informative articles:** one of the most important aspect of technical writing is to solve problems, so every article written must have this foundation, readers rely on this information to learn how to accomplish basic tasks therefore it has to be written in a structure makes in easy to refer back to when the need arises.

**Write consistently**: you cannot stop with just one article, you have to be able to commit time and effort to build a career in technical writing,  you cannot write just one article and seek community funding, it's a marathon not a sprint.
Technical documents must be thoroughly planned before authoring because they are essential to the company's operational requirements. Additionally, writers outline the the following
determine the project's scope and the resources needed.
learn more, speak with internal experts and management.
keep a work log detailing your daily expirence working with a product

**Conclusion**
technical writing is becoming more and more common, particularly in our quickly developing era of telecommunications. With no signs of slowing down, the practice will remain a significant aspect of our society for many years to come.
Can I manually cache functional component return values?
Tags: react
Published: 2023-04-04 13:41:00

I have a pure functional component that takes in simple data as props and returns a ReactNode.

Is there anything context-specific about the result, or can I cache the result and re-use it in many places?

For example, I have a grid of thousands of cells. The content of the cells never change shape, but they change location in the grid.  Instead of re-rendering each cell, I just want to look up what belongs in each cell and use a previous render.  The built-in memoization options seem ill-suited given I use the same functional component hundreds of times, meaning the cache size of 1 wouldn't work.
Resolvendo problemas no HackerRank: Equalização de Matrix sobre Inteiros.
Tags: javascript, beginners, programming
Published: 2023-04-04 13:29:33

Olá, seja bem vindo a mais um Resolvendo problemas no HackerRank: No caso de hoje, vamos eliminar os menores valores possíveis de elementos. Vejamos mais informações com a explicação detalhada e sua resolução.

**Equalize the Array -**

Dada uma matriz de números inteiros, determine o número mínimo de elementos a serem excluídos para deixar apenas elementos de igual valor.

Exemplo:

arr = [1,2,2,3]

Deletamos dois elementos 1 e 3 deixando apenas um array [2,2].

- Return - int: O número mínimo de exclusões necessárias.

```
function equalizeArray(arr) {
    // Write your code here
  let aux = 0;
  let countRepeticions = 0;
    for( let i = 0; i < arr.length; i++ ){
      for( let j = 0; j < arr.length; j++ ){
        if( arr[ i ] == arr[ j ] ){
          countRepeticions++;
        }
      }
        if( countRepeticions > aux ){
            aux = countRepeticions;
        }

            countRepeticions = 0;
    }

  return arr.length - aux;
}
```

O código acima implementa uma função chamada "equalizeArray" que recebe um array como argumento e retorna o número mínimo de operações necessárias para tornar todos os elementos do array iguais.

Para fazer isso, a função utiliza um algoritmo de força bruta que itera sobre o array duas vezes para contar o número de ocorrências de cada elemento. Em seguida, ele armazena o maior número de ocorrências em uma variável auxiliar "aux".

Finalmente, a função retorna o comprimento do array menos o número de ocorrências do elemento mais frequente.

Por exemplo, se o array de entrada for [1, 2, 2, 3], a função contará o número de ocorrências de 1, 2 e 3 no array e descobrirá que o elemento mais frequente é 2, com duas ocorrências. Portanto, a função retornará o resultado 2, que é o comprimento do array (4) menos o número de ocorrências do elemento mais frequente (2).


```
5
3 3 2 1 3

input: 2
```

Assim, concluímos mais um _Resolvendo problemas no HackerRank:_ até a próxima.
huge windows 12
Published: 2023-04-04 13:22:23


![Windows 12](https://i.ibb.co/6wT3X5C/Win12-1.png)

The Windows logo above has been modified, but the ISO has been modified below.
( There was also Windows 9. https://archive.org/details/windows_9, I made this OS myself. (custom build) )

But I really hope the official Windows 12 is released.
How to check update react PWA app
Tags: javascript, react, pwa
Published: 2023-04-04 13:21:31

first, open your file serviceWorkerRegistration

find this function

```
function registerValidSW(swUrl, config) {
  navigator.serviceWorker
    .register(swUrl)
    .then((registration) => {

```

and add this code below before registration.onupdatefound

```
// Check for updates at start.     
registration.update();     
// Check for updates every 5 min.      
setInterval(() => {        
registration.update();        
console.log("Checked for update...");      
}, (1000 * 60) * 5);
```

and then be 

```
function registerValidSW(swUrl, config) {
  navigator.serviceWorker
    .register(swUrl)
    .then((registration) => {

      // Check for updates at start.     
      registration.update();     
      // Check for updates every 5 min.      
      setInterval(() => {        
        registration.update();        
        console.log("Checked for update...");      
      }, (1000 * 60) * 5);
```
second, and the last find  ` if (config && config.onUpdate) { `

add alert for check if will be update
alert("Update available! To update, close all windows and reopen");

code will be 

```
alert("Update available! To update, close all windows and reopen");

// Execute callback
if (config && config.onUpdate) {
    config.onUpdate(registration);
}
```
run command below:

> npm run build

run your app in server and to test its work or not,
then edit some code 

run command 

> npm run build

then if has pop up alert show up

congratulations your react PWA app has been checked update.
Cette ia transforme le texte en vidéo
Tags: ia, gratuit
Published: 2023-04-04 13:18:59

Cette intelligence artificielle transforme le texte en vidéo .
Je l'ai testé et c'est assez impressionnant.

Tous ceci gratuitement dans un Google Colab.
Je n'en dis pas plus je vous laisse vous régalez.

[Le lien ici](https://colab.research.google.com/#fileId=https%3A//huggingface.co/multimodalart/diffusers_text_to_video/blob/main/Text_to_Video_with_Diffusers.ipynb)
Gerenciando estados globais de forma eficiente
Tags: javascript, webcomponents, webdev, programming
Published: 2023-04-04 13:09:31

Desenvolvendo aplicações complexas, é comum a necessidade de compartilhar estado entre diversos componentes. Para isso, o [kuba](https://github.com/deMGoncalves/kuba) disponibiliza o pacote global, que permite a criação de um objeto de uso global em toda a aplicação.

O objeto global pode ser utilizado para armazenar informações compartilhadas entre componentes, tais como configurações do usuário, informações de autenticação, entre outros dados.

Para atualizar as informações no objeto global, utilizamos a função `setGlobal`, que recebe um objeto e mescla as chaves com o estado atual do objeto global. Dessa forma, é possível alterar os valores das chaves sem precisar recriar todo o objeto global.

Para ficar sempre atualizado com as alterações do objeto global, podemos utilizar o hook `useEffect`. Esse hook nos permite executar uma função sempre que o estado do objeto global for alterado.

Confira abaixo um exemplo de como utilizar o objeto global do Kuba:

```javascript
import global, { setGlobal, useEffect } from '@kuba/global'

useEffect(() => console.log(global.name), [])

setGlobal({
  name: 'deMGoncalves',
  status: 'active'
})
```

O código acima importa o pacote `@kuba/global`, que fornece uma maneira de criar e acessar um objeto global. A função useEffect é usada para imprimir o valor da propriedade `name` do objeto global.

Em seguida, a função `setGlobal` é chamada com um objeto contendo as propriedades `name` e `status`. Isso mescla o objeto com o estado atual do objeto global, atualizando-o com as novas propriedades.

Assim, após a chamada da função `setGlobal`, o objeto global terá a propriedade `name` com o valor 'deMGoncalves' e a propriedade `status` com o valor 'active'. A definição acionará o `useEffect`, que imprimirá o valor de `global.name` no console.

Com o pacote `global` do [kuba](https://github.com/deMGoncalves/kuba), é possível criar aplicações mais eficientes e organizadas, compartilhando informações importantes entre componentes de forma simples e prática.