teleren/devto huggingface dataset:
Introduction to Symbols Using Type Script
Tags: typescript, symbols, webdev, javascript
Published: 2023-03-31 02:32:46

**_Introduction to Symbols Using Type Script_ **

Symbols are a unique data type in TypeScript that allows for the creation of unambiguous and immutable values. Unlike other primitive data types such as strings, numbers, and `booleans`, symbols are not `coercible` and cannot be converted to other types. They are often used to create private members of classes and to define constants that cannot be changed.

Creating a symbol in Type Script is simple, using the `Symbol()` function. The function takes an optional string parameter that serves as a description of the symbol, but this parameter has no impact on the value of the symbol itself.

```
const mySymbol = Symbol();

```
Symbols can be used as property keys in objects, using square bracket notation.

```
const myObject = {
  [mySymbol]: 'hello',
};

```

This allows for the creation of private members in classes, as symbols cannot be accessed from outside the class.


```
class MyClass {
  private [mySymbol] = 'secret';

  public getSecret(): string {
    return this[mySymbol];
  }
}

const myClassInstance = new MyClass();

console.log(myClassInstance.getSecret()); // 'secret'
console.log(myClassInstance[mySymbol]); // ERROR: Property 'Symbol()' does not exist on type 'MyClass'

```

Symbols can also be used to define constants, to ensure that the value cannot be changed or overwritten.

```
const MY_CONSTANT = Symbol();

function myFunction(input: symbol) {
  if (input === MY_CONSTANT) {
    console.log('This is my constant');
  } else {
    console.log('This is not my constant');
  }
}

myFunction(MY_CONSTANT); // 'This is my constant'
myFunction(Symbol()); // 'This is not my constant'

```
In conclusion, symbols are a powerful feature of TypeScript that can be used to create unambiguous and immutable values, and to define private members and constants. They are particularly useful in object-oriented programming, where they can be used to ensure encapsulation and protect sensitive data.
7 advice for a newbie Developer
Tags: developers, programming, software, devjournal
Published: 2023-03-31 02:32:00

The transition from a Junior Developer to a Senior Developer does not happen overnight, it’s a process that takes time.

7 advice for a newbie developer:


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s3fmxx09pedim4iu58ut.png)
Axios em React: como fazer requisições HTTP de forma fácil
Published: 2023-03-31 02:19:05

## AXIOS

Axios é uma biblioteca de requisições HTTP no React. Para usá-la, primeiro você precisa instalá-la com o seguinte comando:
`npm install axios`
Em seguida, você pode importá-la no seu projeto:
`import axios from ‘axios’;`

Para fazer uma requisição GET, utilize o seguinte código:

```
getAllPosts: async () => {
  let response = await axios.get(`${BASE}`)
  return response.data
}
```

Para fazer uma requisição POST, utilize o seguinte código:

```
addNewPost = async (title, body, userId) => {
  let response = await axios.post(`${BASE}/posts`, {
    title,
    body,
    userId
  })
  return response.data
}
```

É possível criar instâncias personalizadas do Axios com configurações específicas:

```
const http = axios.create({
  baseURL: ‘https://jsonplaceholder.typicode.com’
})
```

Para fazer uma requisição GET utilizando a instância personalizada, utilize o seguinte código:

```
getAllPosts: async () => {
  let response = await http.get(`/posts`)
  return response.data
}
```
Simplificando a navegação em React com rotas
Published: 2023-03-31 02:18:01

####React Router

Geralmente fazemos as configurações dentro do index.tsx, para ter acesso aos recursos de rotas precisamos encapsular tudo dentro do` BrowserRouter`

---

######Route
No Route colocamos um atributo path="/", que é o endereço da rota apos o endereço da pagina. E tambem colocamos o element={<Componente/>}.

---

######404
Para criar rota de 404 colocamos path'*' ao final de todas as rotas

---

######Link
Para uma navegação melhor dentro do site utilizamos o componente Link para direcionar as paginas, colocamos a propriedade to:'/'.

---

######Rota Dinamica
Podemos ter uma rota dinamica como camos ':' antes da variavel dinamica, isso é chamado de parametro. Ex: `path: '/album/:albumId'`.

Podemos capturar esse parametro usando o Hook useParams

```
const { albumId } = useParams<{ albumId: string }>();
```

> É recomendado uar o ? antes do parameto pois isso ja fara uma verificação.

---

######useNavigate
É um hook usado geralmente quando queremos voltar uma pagina.

```
const navigate = useNavigate()

const handleBackButton = () =>{
 navigate(-1)
}

<button onClick={handleBackButton}>voltar</button>
```
---
######Query String ?
Query string é uma parte de uma URL que contém dados que são enviados do cliente.
`https://www.example.com/search?q=apple&category=fruits`
Para capturar os queryString usamos o hook useSearchParams,
searchParams.get('q')

---
######Rotas privadas
Para criar uma autentificação nas rotas privadas, primeiro criamos um componente que fara esse autentificação, e colocamos o componente que vai ser renderizado como um children, se a validação passar retornamos o children se nao retornamos um null.
`element={<Autentificacao><Componente /></Autentificacao>}`
Code Check in 03/30/23
Published: 2023-03-31 02:17:55

Link to Github Repo: https://github.com/farisnif/badge-edu

Today in class Fawaz and I worked on debugging some minor issues we were having regarding the collapsible accordion border. Previously the blue bar on the left side had a gap in it due to the 6px border, this was resolved, which was really our last problem when it came to designing our badge. From here out we should be able to easily add the text requirements, and dedicate this weekend and next week to API dev and functioning search bar.
Aprenda a usar hooks em React em poucos minutos
Published: 2023-03-31 02:15:55

## HOOKS
Hooks são códigos prontos que simplificam o desenvolvimento. O estado é uma informação que o componente usa.

---

######useState
O `useState` é um hook do React que permite manipular o estado de um componente de maneira fácil.

---

######State Lift

---

######useEfects
O hook `useEffect` é usado para monitorar as alterações em um elemento. Ele recebe como parâmetro uma função e um array. A função contém o código que será executado quando o elemento for atualizado ou criado, e o array inclui o elemento que será monitorado. Se houver alguma mudança, o hook `useEffect` irá reagir e executar a função correspondente.

```
useEffect(() => {
  document.title = `Você clicou ${count} vezes`;
}, [count]);

```
---

######useReducer
O Reducer é uma alternativa ao useState, é recomendado usar quando vamos manipular listas, objetos...
`const [state, dispatch] = useReducer(reducer, initialState)`

#####state:
é aonde temos acesso as informações
#####dispatch:
é uma função, que quando executada recebe como parametro um objeto com um type, que indica a ação a ser feita dentro do reducer
`<button onClick={() => dispatch({type: 'ADD'})}>`

#####useReducer:
receber como parametro 1 função e os valores iniciais
#####reducer:
sempre vai receber 2 parametros, 1° o valor atual do reducer(state); 2° a função que vai executar(action)
`const reducer = (state, action) => {}`
a função reducer faz as alterações com base no action, e no final retorna o novo state.

para fazer as alterações utilizamos o switch da seguinte forma:

```
switch(action.type){
 case: 'ADD':
  return ... 
 break
}
```

podemos organizar nossos reducers em aquivos diferentres, para fazer isso criamos um hook proprio aonde neel é criado o useReducer e todas as configurações, ao final damos um:
`return useReducer(reducer, initialState)`
para usa-lo basta importar dentro do seu componente e usar:
`const [state, dispatch] = useCriado()`

#####Payload: 
Usamos qunado quremos enviar dados para o action
Transforme seu projeto React com os estilos certos
Published: 2023-03-31 02:14:11

## ESTILOS
No React, o CSS pode ser adicionado globalmente na aplicação através do arquivo `index.css`. Para estilizar componentes individualmente, pode-se usar o `CSSModules`, incluindo o CSS dentro do componente.

<h6>Style Components</h6>
Style Components é uma biblioteca de estilo para componentes React. Ele permite a você escrever estilos CSS diretamente dentro dos seus componentes, tornando mais fácil manter a coesão entre estilo e lógica de componentes. Ao invés de escrever estilos em arquivos CSS separados, você pode definir estilos diretamente em suas classes de componentes e aplicá-los aos elementos renderizados. Style Components oferece uma sintaxe semelhante ao CSS, bem como recursos adicionais como variáveis, herança de estilo e animações.

`npm install styled-components`
`npm install -D @types/styled-components` para Ts

importação styled components:
`import styled from 'styled-components'`

usando styled components:

```
const container = styled.div`
 color: red
`
```
`<Container> Meu texto </Container>`

Uma das maneiras de usar o Styled Components é criando um arquivo `TypeScript` com todos os estilos e importando-o em qualquer lugar que você deseja usá-los. Por exemplo: 
`import * as C from './AppStyles'`.

podemos passar props para o styled
`<Button small > Meu botão </Button>`

```
export const Button = styled.button`
  /* ele verifica se o elemento tem a prop small  */
 font-size: ${(props)=> props.small ? '15px' : '30px' }
`
```
no TypeScript precisamos definir os tipos:

```
type ButtonProps = {
 bg: string
 small?: boolean
}

export const Button = styled.button<ButtonProps>`...`
```
Building my File Organizer: Part 1
Tags: deno, opensource, projects, blogpairprogramm
Published: 2023-03-31 02:12:08

Every day we download and create files, whether it be in Word, Excel, Notepad, etc. And, at least in my case, I always find myself leaving all my downloads in the default folder and all the files I create on the desktop with the promise of someday organizing them in a proper place. Although that day does come because I like to keep my desktop organized, I think it's a task that I shouldn't have to do myself, but that I can automate. With that in mind, I've set out to create my own program to organize my files based on certain criteria that are extensible and customizable, so that it can also be useful to someone else.

I'm doing this mainly to practice and to have different opinions about my software development process, so I encourage you to leave me your opinion.

## The idea

The basic idea is that I can leave files anywhere on my computer and the program will eventually move everything to an appropriate folder based on the purpose of the file, based on criteria applied to the name or extension of the file, and that these criteria can be easily extended by the user.

## Features

1.  **Starting directory**: By default, it could start with the user's directory, but it should be possible to specify, for example, if you want to leave everything on the desktop and that the "magic" happens only from there.
2.  **File organization by extension**: For example, all `.mp3` files should be moved to a folder called _Music_.
3.  **Default criteria**: Once installed, it should have a series of pre-established criteria, for example, to put `.png` files in the _images_ folder.
4.  **Exclude folders**: If you have a folder or set of folders that you consider to be well-organized and you don't want the program to interfere, you should be able to include them so that these folders are ignored.
5.  **Ability to create rules based on the file name**: For example, if a file starts with _AUD_, it should be moved to the _WhatsappAudios_ folder. These criteria would be of the type:
    -   Starts with
    -   Ends with
    -   Contains
6.  **Delete temporary files**: Allow emptying all space occupied by temporary files that we forget to delete.

## Conclusions

Throughout this series, I will be sharing my software development process, hoping that it will help someone with less experience or that someone with more experience will point out my mistakes or share ideas of what could be included.

Here's the link to the repository in case you want to take a look:

> [Repository](https://github.com/oscareduardolp6/file-organizer)
Two trie implementations in Rust (one's super fast)
Tags: rust, datastructures, trie
Published: 2023-03-31 01:58:14

---
title: Two trie implementations in Rust (one's super fast)
published: true
description: Implementing the trie data structure in Rust, once using the standard library and another using third-party library to increase its speed.
tags: rust, datastructures, trie
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
# published_at: 2023-03-31 01:44 +0000
---

A trie is a data structure that enables very fast lookups, while taking up quite a small amount of space. Here's an implementation in Rust:

```rust
use std::collections::HashMap;

#[derive(Default, Debug)]
struct TrieNode {
    is_end_of_word: bool,
    children: HashMap<char, TrieNode>,
}

#[derive(Default, Debug)]
pub struct Trie {
    root: TrieNode,
}

impl Trie {
    pub fn new() -> Self {
        Trie {
            root: TrieNode::default(),
        }
    }

    pub fn insert(&mut self, word: &str) {
        let mut current_node = &mut self.root;

        for c in word.chars() {
            current_node = current_node.children.entry(c).or_default();
        }
        current_node.is_end_of_word = true;
    }

    pub fn contains(&self, word: &str) -> bool {
        let mut current_node = &self.root;

        for c in word.chars() {
            match current_node.children.get(&c) {
                Some(node) => current_node = node,
                None => return false,
            }
        }

        current_node.is_end_of_word
    }
}

fn main() {
    let mut trie = Trie::new();
    trie.insert("hello");
    trie.insert("hi");
    trie.insert("hey");
    trie.insert("world");
    
    println!("{trie:#?}");
    
    println!("hiiii? {}", trie.contains("hiiii"));
}
```

You can gain some extra speed by replacing the standard library's hash map implementation with `fxhash`. To do so, replace the first few lines with this:

```rust
use std::collections::HashMap;
use fxhash::FxBuildHasher;

type FxHashMap<K, V> = HashMap<K, V, FxBuildHasher>;

#[derive(Default)]
struct TrieNode {
    is_end_of_word: bool,
    children: FxHashMap<char, TrieNode>,
}
```

What's happening?

The standard library's `std::collections::HashMap` uses a hash function -- a function which takes an input and morphs it into an output of a fixed size -- that's designed to be cryptographically secure and general purpose at the expense of speed. Because we know that our keys will be the `char` type, which takes up 4 bytes, we can use a hash function that's more suited for short keys. (By the way, in case you were wondering, it probably still makes sense to use a hash function for `char` values, even though we could just use the bits' values directly as they're all a fixed sized. Because human language tends to use a very narrow spectrum of bit patterns within a `char`, and hash tables like keys to be well spread out, the hash function can spread the bits out for what is hopefully a net performance win.)
Day 0: Full-Stack Developer Dives into Python: 100 Days to Python Mastery
Tags: python, 100daysofcode
Published: 2023-03-31 00:44:36

# Leaving the Comfort Zone and Embracing Python

As a software engineer with considerable experience under my belt, I've dabbled in various technologies, from VB.NET, C#, Java, and Spring Boot, to the front-end like vanilla JavaScript, jQuery, Angular, and React. These days, my day job has me doing AWS cloud application development.

**I've decided to take on the challenge of learning Python, and here's why:**

* _Python's popularity is skyrocketing, and I want to jump on the bandwagon._
* _I'm convinced that Python can speed up the development of applications that I find interesting._
* _Back in August 2021, I grabbed Dr. Angela Yu's Udemy course, "100 Days of Code: The Complete Python Pro Bootcamp for 2023," but I never started it so now it's time to dive in.
So, I'm all geared up for my 100 Days of Code!_

But there's one twist though. Since I've already dabbled in Python basics and have some development background, I'll bypass familiar territory. I am going to skim through some of the concepts I'm comfortable with and focus more on complex concepts and master those that developers use more commonly.

The 100 Days of Code challenge, originally crafted by Alexander Kallaway to kickstart his software development career, took Twitter by storm. Eager learners can hop on the bandwagon with the [#100DaysOfCode](https://twitter.com/_100DaysOfCode) hashtag.

The challenge's rule is simple: **code for at least an hour each day for 100 days.**

My plan is to go through the Udemy course, do coding for a minimum of one hour daily throughout the 100-day adventure.

Join me as this blog chronicles my Python journey!

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aqbpcl20osqfal9cavw5.jpg)
Modern Web Development: Centering DIVs in new exciting wrong ways with AI!
Tags: ai, webdev, githubcopilot, chatgpt
Published: 2023-03-31 00:06:29

---
title: Modern Web Development: Centering DIVs in new exciting wrong ways with AI!
published: true
description: A talk at the modern web development meetup at Microsoft Berlin
tags: ai,webdevelopment,githubcopilot,chatgpt
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lp8v3cy4cx23gijc5v0a.png
# Use a ratio of 100:42 for best results.
# published_at: 2023-03-30 23:51 +0000
canonical_url: https://christianheilmann.com/2023/03/31/modern-web-development-centering-divs-in-new-exciting-wrong-ways-with-ai/
---

Earlier today I spoke at the Microsoft Reactor meetup in Berlin about frontend development, LLMs, ChatGPT, GitHub Copilot and what it means to our work and careers. In this [32 minute talk](https://www.youtube.com/watch?v=Ou8S9ovMtVw) and 5 minutes of Q&A, I covered a lot of ground:

{% youtube Ou8S9ovMtVw %}

* Introduction
* Web Development isn't complex technology
* GPT can create web products from a doodle, or can it?
* WYSIWYG was never a thing for the web
* [Building web designs from prompts](https://www.usegalileo.ai/)
* What Web Development is not
* Things a web design needs to cater for
* What Web Development means
* ChatGPT and conversational UI
* AI will take our jobs - and that's OK
* Focusing on productivity
* From Smart Autocomplete to AI Peer Programmers ([GitHub Copilot](https://github.com/features/copilot/), [Amazon CodeWhisperer](https://aws.amazon.com/codewhisperer/) and [GhostWriter AI Mode](https://blog.replit.com/ai))
* Valid criticisms of  machine aided code completion
* The full StackOverflow Developer
* More than Automated Copy + Paste
* Context Recognition
* Code Explanation
* Code Translation
* Benefits of a "learning" code environment
* [Evidence of effectiveness of AI code completion](https://arxiv.org/pdf/2302.06590.pdf)
* Code Brushes as a different interaction model
* [GitHub Copilot X](https://github.com/features/preview/copilot-x)
* Chat inside the code editor
* [Chat interface for docs](https://copilot4docs.githubnext.com/)
* [Pull request generation](https://githubnext.com/projects/copilot-for-pull-requests)
* Copilot for CLI
* Code by voice recognition
* Voice access helps people and shouldn't be a hustle aid
* Augmenting code practices instead of replacing them
* Focus shift from writing to reviewing code
* New skill: Asking the right questions
* [Prompt Engineering](https://lilianweng.github.io/posts/2023-03-15-prompt-engineering/) ([Course on LinkedIn Learning](https://www.linkedin.com/learning/introduction-to-prompt-engineering-for-generative-ai/what-is-prompt-engineering?autoSkip=true&autoplay=true&resume=false&u=0))
* This is a great time to be a developer
* Q&A

It was great to present and I am looking forward to expand on some of these topics as they become more available.
Embedding audio files in a Hugo site
Tags: hugo, webdev, audio, html
Published: 2023-04-03 17:13:41

---
title: Embedding audio files in a Hugo site
published: true
date: 2023-03-31 00:00:00 UTC
tags: hugo,webdev,audio,html
canonical_url: https://jimbobbennett.dev/blogs/playing-audio-files-hugo/
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cg6ijm5izvu3uhu1jh1e.png
---

I was writing a post today and wanted to embed an mp3 file of some text to speech output. Hugo doesn’t support this natively using shortcodes, so I needed a way to add these, ideally without adding any HTML.

To do this, I needed to create my own shortcode implementation. As it turns out, based on the [Hugo shortcode guide](https://gohugo.io/templates/shortcode-templates/), these are not to complicated.

## Create the shortcode

Shortcodes live in a folder called `shortcodes` in your `layout` folder and are implemented as HTML files, named as `<shortcode>.html`. For example, if you wanted to create a shortcode called `audio` you would create the file `layout/shortcodes/audio.html`.

Shortcodes are snippets of HTML that can be passed named parameters. The HTML for an HTML audio player is:

```
<audio controls preload="auto">
 <source src="file.mp3">
</audio>

```

Shortcodes can also be parameterized with name parameters that you can get using the `{{ .Get "name" }}` method, passing the name of the parameter. For the audio shortcode, I need to pass in the audio file, so this can be a parameter. This is set in the `src` field, so I called this parameter `src`:

```
<audio controls preload="auto">
 <source src="{{ .Get "src" }}">
</audio>

```

Done! This is my entire shortcode.

## Use the shortcode

Once my shortcode was written, it was easy to use. I added the mp3 file I want to play to the folder for my blog post, and added the shortcode tag in the markdown file for the post:

```
{< audio src="intro-to-generative-ai.m4a" >}
```

Once done, the audio player appears on my page:

![The audio player on a blog post page](https://jimbobbennett.dev/blogs/playing-audio-files-hugo/audio-player-in-post.png)

## Use this yourself

If you want to use this shortcode, you can find it [on the GitHub repo for this site](https://github.com/jimbobbennett/jims-blog/blob/main/blog/layouts/shortcodes/audio.html).
Content & Tooling Team Status Update
Tags: puppet, community, updates
Published: 2023-03-31 16:26:31

---
title: Content & Tooling Team Status Update
published: true
date: 2023-03-31 00:00:00 UTC
tags: puppet, community, updates
canonical_url: https://puppetlabs.github.io/content-and-tooling-team/blog/updates/2023-03-31-status-update/
---

## Spring has sprung!

Happy Friday everyone. Hopefully you’ve had a good week. We’ve been busy in the CAT team but the brighter mornings and the brighter nights have made it all easier.

## PDK 2.7.1

We have released PDK 2.7.1! It’s a big win for us that we are now able to release PDK on a more frequent cadence; there’s been a lot of effort that has gone into that this year. Shout out to [Craig](craig). This release updates PDK Templates to 2.7.4 and fixes an issue with duplicate build-ids for RedHat 9 packages. You can find the release notes [here](https://www.puppet.com/docs/pdk/2.x/release_notes_pdk.html).

## Adding Puppet 8 support

It’s been all hands on deck this week for our team in getting all of our modules and tools prepared to support Puppet 8 for its planned release later this month. This has involved adding Ruby 3.2 support, upgrading Rubocop, updating code to comply with the new cops, and removing Puppet 6 support. We will be releasing a clean cut of all of our modules and tools before we release the Puppet 8 supported versions.

## Community Contributions

We’d like to thank the following people in the Puppet Community for their contributions over this past week:

- [`puppetlabs-mysql#1551`](https://github.com/puppetlabs/puppetlabs-mysql/pull/1551): “mysql::server: Implement reload\_on\_config\_change”, thanks to [bastelfreak](https://github.com/bastelfreak)

## New Module / Gem Releases

The following modules were released this week:

- [`puppetlabs-scheduled_task`](https://github.com/puppetlabs/puppetlabs-scheduled_task) (`3.2.0`)