teleren/devto huggingface dataset:
String Manipulation Tricks (Day 1)
Tags: java
Published: 2024-04-19 01:42:33

(First post. Don't know what to blog about. I'll start by recording some random coding thought whenever they occur to me and I happen to have time to write it down)

I've recently been thinking about Java string manipulation. Then I stumbled upon this string parsing code:

```java
private static final Pattern THE_NUMBER =
    Pattern.compile("^\\s\\(([1-9][0-9]*)\\)$");

// Find the number from string with header.
// example: parseTheNumber("foo", "foo (123)") -> 123
//          parseTheNumber("foo", "bar (123)") -> empty
//          parseTheNumber("foo", "foo (str)") -> empty
Optional<Integer> parseTheNumber(String header, String string) {
  if (!string.startsWith(header)) {
    return Optional.empty();
  }
  Matcher matcher = THE_NUMBER.matcher(
      string.substring(header.length()));
  try {
    return matcher.matches()
        ? Optional.of(Integer.parseInt(matcher.group(1)))
        : Optional.empty();
  } catch (NumberFormatException e) {
    return Optional.empty();
  }
}
```

As a [racist against Java Regex](http://github.com/google/mug/wiki/Just-Say-No-to-Regex), I can't help wanting to try it out without regex (using [Guava](http://github.com/google/guava) and [Mug](http://github.com/google/mug), my all-in-one toolbox).

```java
import com.google.common.primitives.Ints;
import com.google.mu.util.StringFormat;

private static final StringFormat THE_NUMBER =
    new StringFormat("{type} ({num})");

Optional<Integer> parseTheNumber(String header, String string) {
  // StringFormat.parse() will return empty()
  //     if failed to parse, or if the lambda returns null
  return THE_NUMBER.parse(
      string,
      // Ints.tryParse() returns null if failed to parse
      (type, num) -> type.equals(header) ? Ints.tryParse(num) : null);
}
```

[`StringFormat`](http://github.com/google/mug/wiki/StringFormat-Explained) performs well compared to Java regex. And to me it's more readable.

What do you think?
Exploring Vue.js Directives
Tags: javascript, beginners, programming, tutorial
Published: 2024-04-19 00:30:04

## Introduction

Vue.js is a progressive JavaScript framework that is gaining popularity among developers due to its simplicity and flexibility. One of its key features is the use of directives, which allow developers to extend HTML with new attributes and create reusable components. In this article, we will explore the different types of directives in Vue.js and their advantages and disadvantages.

## Advantages of Vue.js Directives

One of the major advantages of using Vue.js directives is that they provide a clean and concise way of manipulating the DOM. They also allow for easy communication between components, making it easier to manage a large and complex codebase. Moreover, directives can be easily customized to suit specific requirements, giving developers more control over their code. They also promote reusability of code, thus making development more efficient.

## Disadvantages of Vue.js Directives

While Vue.js directives offer many benefits, they also have some drawbacks. One of the main concerns is the steep learning curve for beginners as the syntax for creating custom directives can be complex. Furthermore, debugging and troubleshooting can become challenging when multiple directives are being used in a single component.

## Features of Vue.js Directives

Vue.js includes a variety of built-in directives such as `v-if`, `v-for`, `v-bind`, and `v-model`, which make it easy to manipulate the DOM. It also allows for the creation of customized directives to suit specific needs. Additionally, Vue.js offers a comprehensive guide on using directives and their associated APIs, making it easier for developers to utilize them effectively.

### Example Usage of Built-in Vue.js Directives

```html
<template>
  <div>
    <!-- Conditional rendering -->
    <p v-if="isVisible">Visible Content</p>
    
    <!-- List rendering -->
    <ul>
      <li v-for="item in items" :key="item.id">{{ item.text }}</li>
    </ul>
    
    <!-- Data binding -->
    <input v-model="message" placeholder="Enter your message">
    
    <!-- Dynamic attribute binding -->
    <a v-bind:href="url">Visit</a>
  </div>
</template>
```

This example demonstrates how to use Vue.js directives to perform conditional rendering, list rendering, data binding, and dynamic attribute binding in a Vue component.

## Conclusion

In conclusion, Vue.js directives offer a wide range of advantages such as code reusability, better code organization, and easy communication between components. While they may have a few limitations, the benefits outweigh these shortcomings. With proper understanding and practice, Vue.js directives can greatly enhance the development process and produce efficient and maintainable code. So why not give it a try and explore the power and convenience of Vue.js directives in your next project?
DevX Status Update
Tags: puppet, community
Published: 2024-04-26 19:32:21

---
title: DevX Status Update
published: true
date: 2024-04-19 00:00:00 UTC
tags: puppet,community
canonical_url: https://puppetlabs.github.io/content-and-tooling-team/blog/updates/2024-04-19-devx-status-update/
---

## Hello!

Hello again, we’re back again with another one of our updates before we all sign off for the weekend. Hope you all either have some plans, or get the chance to relax at the weekend, I have a busy one coming up so I’ll be taking any chance I can get to stick the feet up.

## You asked, we listened

Our collection of analytics from the PDK has always been somewhat of a touchy subject. On one hand, analytics help us to make informed decisions about the PDK, gauge its usage and identify possible improvements, but on the other hand we can see how some of you aren’t too keen on your PDK usage data being collected. The PDK always made it easy for it’s users to opt-out of analytics collection, but due to recent events with dependencies, and the fact it decided to break on us, we as a team have made the decision to completely remove the analytical code from the PDK. That’s right, as of the next PDK release (which will be coming shortly…), the PDK will no longer collect any analytics, regardless whether you had them enabled or not. We are hoping this will open up the PDK to a whole lot more users from the Puppet Community!

## Some other small bits and pieces

In admittingly less exciting news, we have been working on some maintenance, bugfixes and feature requests in the background across our tooling suite. We had noticed some transient errors caused by the ENV’s in our GitHub action runners, so are working to implement some automatic retries to failed workflow runs, which will help give us a truer representation of the health of our developer tooling repos.

Additionally, [puppetlabs\_spec\_helper](https://github.com/puppetlabs/puppetlabs_spec_helper) received a recent update, and will now validate your bolt plans as well as your manifests when you run the `bundle exec rake validate` rake task that is shipped in puppetlabs\_spec\_helper. This change is still awaiting release, but will go out the next time the gem is published.

## That’s all folks

That’s all for this week. See you again next friday!
Modules Status Update
Tags: puppet, community
Published: 2024-04-26 19:32:54

---
title: Modules Status Update
published: true
date: 2024-04-19 00:00:00 UTC
tags: puppet,community
canonical_url: https://puppetlabs.github.io/content-and-tooling-team/blog/updates/2024-04-19-modules-status-update/
---

## Hello Again!!

Happy Friday! While there’s not much news from the Modules team this week, rest assured that we’ve been hard at work preparing for the next Forge release. Exciting updates are on the way, so stay tuned and keep those contributions coming!

## Community Contributions

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

- [`puppetlabs-lvm#333`](https://github.com/puppetlabs/puppetlabs-lvm/pull/333): “Allow modifying the physical extent size for volume groups”, thanks to [glangloi](https://github.com/glangloi) and the following people who helped get it over the line ([bastelfreak](https://github.com/bastelfreak))
- [`puppetlabs-lvm#328`](https://github.com/puppetlabs/puppetlabs-lvm/pull/328): “README, metadata: correct name of LVM in summaries”, thanks to [kenyon](https://github.com/kenyon)
- [`puppetlabs-vcsrepo#635`](https://github.com/puppetlabs/puppetlabs-vcsrepo/pull/635): “Fix acceptance test on Ubuntu ARM”, thanks to [smortex](https://github.com/smortex)

## New Module Releases

- [`puppetlabs-java`](https://github.com/puppetlabs/puppetlabs-java) (`11.0.0`)
Meet Auty, a bot designed to support and guide autistic individuals - on Coze
Tags: cozechallenge, devchallenge, ai, machinelearning
Published: 2024-04-18 23:45:22

*This is a submission for the [Coze AI Bot Challenge](https://dev.to/devteam/join-us-for-the-coze-ai-bot-challenge-3000-in-prizes-4dp7): Bot Innovator.*

## What I Built
Meet Auty, your new friend and personal helper! Auty is a friendly AI companion designed to support individuals in various ways. Feeling overwhelmed? Auty can offer calming techniques and activity suggestions. Need help practicing social interactions? Auty can simulate conversations to help you build confidence. Auty is also here to assist with communication by translating text to speech or offering picture cards. Let Auty be your partner on your journey!

## Demo

Demo can be [seen here](https://www.coze.com/store/bot/7359342720202227717?bid=6c8d296v89006&panel=1) 

![demo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xw86a1uclgxexqrvy029.png)

## Your Configuration


![first prompt](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ftkpz4tz2mfnhhfw9163.png)


![long prompt is long](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/975tdp0ked16r75pyhuk.png)

## Journey

I'm in the process of diagnosis and self-discovery, being an adult who learned how to socially mask basically everything is kinda crazy, so I'm reading **a lot** and getting help from my therapist. I have thousands of different AI bot ideas in my mind, but when I saw what Coze offered, the first thing that popped into my mind was to create something helpful that had a meaning to what I went through during my adolescence and early adult life. 

So **Auty** was born. A bot that is oriented to talk and help people in the spectrum, but not in a professional way, just as a cool friend. "Auty" came naturally: it's a gender-neutral name, catchy, relates to autism, and fulfills my life need of naming everything involving AI with a pun. (_A_ut_I_).

The avatar was a long trial and error with DiffusionBee, but in the end, I think it's perfect: calming, friendly, and approaching.

Coze is... honestly? Amazing. I had tested some bot creators before, but never like Coze. It's simple, user-friendly and direct. It's a little sad that some resources aren't available for public bots (like Knowledge Base) but it's easy to work around it. There are still a lot of things I want to do with Auty on Coze, especially how it talks, but I can fine-tune it over the weekend and next week with professional help from my therapist. For now, I hope that everyone likes the idea, and if in some way my idea offended someone, I'm truly sorry, just reach me so I can fix it
Computer Vision Meetup: GraphRAG with a Knowledge Graph
Tags: computervision, ai, machinelearning, datascience
Published: 2024-04-18 23:15:13

Knowledge Graphs place information in context using graph structures to express local and global semantics. When used in a RAG context, particular access patterns emerge that map natural language to different graph data patterns. We’ll review both the model and the matching code.

**Speaker:** [Andreas Kollegger](https://www.linkedin.com/in/akollegger/?originalSubdomain=uk) is a founding member of Neo4j, now responsible for researching the use of Knowledge Graphs for GenAI applications.

Not a Meetup member? Sign up to attend the next event:

https://voxel51.com/computer-vision-ai-meetups/

Recorded on April 18, 2024 at the AI, Machine Learning and Data Science Meetup.
Computer Vision Meetup: Towards Resource Efficient Robust Text-to-Image Generative Models
Tags: ai, computervision, datascience, machinelearning
Published: 2024-04-18 23:14:56

Text-to-image (T2I) diffusion models (such as Stable Diffusion XL, DALL-E 3, etc.) achieve state-of-the-art (SOTA) performance on various compositional T2I benchmarks, at the cost of significant computational resources. For instance, the unCLIP (i.e., DALL-E 2) stack comprises T2I prior and diffusion image decoder. The T2I prior model itself adds a billion parameters, increasing the computational and high-quality data requirements. Maitreya propose the ECLIPSE, a novel contrastive learning method that is both parameter and data-efficient as a way to combat these issues

Speaker: [Maitreya Patel](https://www.linkedin.com/in/maitreya-patel-a37a16139/) is a PHD student studying at Arizona State University focusing on model performance and efficiency. Whether it is model training or inference, Maitreya strives to make optimizations to make AI more accessible and powerful.

Not a Meetup member? Sign up to attend the next event:

https://voxel51.com/computer-vision-events/

Recorded on April 18, 2024 at the AI, Machine Learning and Data Science Meetup
Ideia
Published: 2024-04-18 23:09:11

Ideia

Uma plataforma que possua comunidades. Em essência, uma comunidade é um
conglomerado de contas que praticam um X esporte/prática em N endereços.
Usuários vão utilizar para achar comunidadese no que adentrararem numa comunidade Y,
será criada uma Conta para o usuário que representa a participação do Usuário na Comunidade Y.
Comunidades são criadas por uma Conta de um Usuário, que podem escolher aceitar ou não a Conta que está tentando adentrar.
A Conta criadora de uma comunidade possui um "cargo" de dono da comunidade, enquanto os participantes terão cargo de "Membro"

# --------------------------------------- #

Requerimentos obrigatórios para uma Comunidade existir
- Nome da comunidade
- Ao menos um endereço
- Ao menos um usuário
- Ao menos uma prática informada
- Timeline com posts dos usuários

Requerimentos opcionais
- Descrição
- Imagem de "perfil" da comunidade

Ideias de validações para uma comunidade legítima
- Endereço deve ser um local público

# -------------------------------------- #

Requerimentos obrigatórios para um Usuário existir
- Nome
- Sobrenome
- E-mail
- CPF

Requerimentos opcionais
- Endereço
- Ao menos uma prática informada

Ideias de validações para um Usuário legítimo
- Validação do CPF
- Validação do e-mail
- Validação do endereço

# ------------------------------------- #

Requerimentos obrigatórios para uma Conta existir
- Cargo
- Permissões

# ------------------------------------- #

Requerimentos obrigatórios para uma Prática existir
- Nome
- Categoria (E-sport, Esporte, Exercício, etc)

# ------------------------------------- #

O usuário se cadastra na plataforma
O usuário com apenas informações obrigatórias terá acesso a comunidades com maior média de pessoas e práticas
O usuário com informações opcionais (endereço e uma prática informada) terá acesso a comunidades perto do endereço e práticas cadastradas.


O Usuário que criar uma Comunidade, terá uma Conta atrelada a Comunidade criada e sua Conta com cargo de Dono e permissões de Dono.
O Usuário pode pedir para entrar uma Comunidade, caso permitido terá uma Conta atrelada a Comunidade e com cargo de Membro com permissões de Membro.
O Usuário pode ter N Contas (Ou seja, participar de múltiplas comunidades)
O Usuário pode interagir na timeline da Comunidade, bem semelhante ao Twitter. (necessário detalhar como será elaborado as mensagens dos usuários nessa timeline)
The Magic of Semantic on HTML
Tags: html, webdev, beginners, programming
Published: 2024-04-18 23:08:04

> If you're taking your first steps into web programming, you've probably already heard about HTML, the markup language used to create web pages. But have you ever stopped to think about what "semantics" means when it comes to HTML? Let's explore this fundamental concept together.

## What is HTML and why is semantics important?
HTML, or Hypertext Markup Language, is the backbone of the web. It's used to structure the content of a web page, defining elements such as headings, paragraphs, images, links, and much more. Without HTML, the web as we know it wouldn't exist.

Semantics in HTML refers to the practice of choosing the correct HTML elements to represent the meaning and structure of a web page's content. This means using the right elements for the right types of content, instead of just using whatever works.

## Why is semantics important?
Semantics is important for several reasons:

1. **Accessibility:** By using semantically correct HTML elements, you make your page more accessible to people with visual impairments or other disabilities. Screen readers and other assistive devices can better understand the structure and meaning of your content.
2. **SEO (Search Engine Optimization):** Search engines like Google use the semantics of your HTML to understand what your page is about. Using semantically correct elements can help search engines index and rank your content better.
3. **Code maintenance:** Writing HTML semantically means your code is clearer and more understandable to other developers (including yourself in the future). This makes maintenance and updating your code easier.

## Examples of semantic HTML elements
Here are some examples of semantic HTML elements and how they can be used:

- `<header>`: Used for the header of a page or a specific section.
- `<footer>`: Used for the footer of a page or a specific section.
- `<nav>`: Used to group navigation links.
- `<article>`: Used for standalone content, such as blog posts.
- `<section>`: Used to group related content within a page.
- `<aside>`: Used for related content that is tangential to the main content of the page.

## Conclusion
Understanding and applying semantics in HTML is fundamental for creating accessible, well-ranked web pages and easy-to-maintain code. By choosing the right HTML elements to represent the meaning and structure of your content, you're building a better web for everyone. So, next time you create a web page, remember the importance of semantics in HTML.
A Magia da Semântica no HTML
Tags: html, programming, webdev, beginners
Published: 2024-04-18 22:58:57

> Se você está dando os primeiros passos na programação web, é provável que já tenha ouvido falar sobre HTML, a linguagem de marcação usada para criar páginas da web. Mas você já parou para pensar no que significa "semântica" quando se trata de HTML? Vamos explorar esse conceito fundamental juntos.

## O que é HTML e por que a semântica é importante?

HTML, ou Hypertext Markup Language, é a espinha dorsal da web. Ele é usado para estruturar o conteúdo de uma página da web, definindo elementos como cabeçalhos, parágrafos, imagens, links e muito mais. Sem o HTML, a web como a conhecemos não existiria.

A semântica no HTML se refere à prática de escolher os elementos HTML corretos para representar o significado e a estrutura do conteúdo de uma página da web. Isso significa usar os elementos certos para os tipos certos de conteúdo, em vez de apenas usar qualquer coisa que funcione.

## Por que a semântica é importante?
A semântica é importante por várias razões:
1. **Acessibilidade:** Ao usar elementos HTML semanticamente corretos, você torna sua página mais acessível para pessoas com deficiências visuais ou outras deficiências. Leitores de tela e outros dispositivos assistivos podem entender melhor a estrutura e o significado do seu conteúdo.
2. **SEO (Search Engine Optimization):** Os mecanismos de busca como o Google usam a semântica do seu HTML para entender o que sua página está falando. Usar elementos semanticamente corretos pode ajudar os mecanismos de busca a indexar e classificar melhor o seu conteúdo.
3. **Manutenção do código:** Escrever HTML semanticamente significa que seu código é mais claro e compreensível para outros desenvolvedores (incluindo você mesmo no futuro). Isso facilita a manutenção e a atualização do seu código.

## Exemplos de elementos HTML semânticos
Aqui estão alguns exemplos de elementos HTML semânticos e como eles podem ser usados:

- `<header>:` Usado para o cabeçalho de uma página ou de uma seção específica.
- `<footer>:` Usado para o rodapé de uma página ou de uma seção específica.
- `<nav>:` Usado para agrupar links de navegação.
- `<article>:` Usado para conteúdo independente e autônomo, como postagens de blog.
- `<section>:` Usado para agrupar conteúdo relacionado dentro de uma página.
- `<aside>:` Usado para conteúdo relacionado, mas que é tangencial ao conteúdo principal da página.

## Conclusão
Entender e aplicar a semântica no HTML é fundamental para criar páginas da web acessíveis, bem classificadas nos mecanismos de busca e fáceis de manter. Ao escolher os elementos HTML corretos para representar o significado e a estrutura do seu conteúdo, você estará construindo uma web melhor para todos. Então, da próxima vez que você criar uma página da web, lembre-se da importância da semântica no HTML.
Priorize os tipos genéricos
Tags: java, programming, development, javaefetivo
Published: 2024-04-18 22:48:58

Item 29: Priorize os tipos genéricos (Java Efetivo)

É importante priorizar o uso de tipos genéricos em projetos Java.
A implementação genérica de uma pilha é discutida aqui, ressaltando a necessidade de parametrização para melhorar a segurança e a legibilidade do código.

Ao transformar uma classe não genérica em genérica, é necessário substituir todos os usos do tipo Object pelo parâmetro de tipo apropriado.

A criação de um array de um tipo genérico pode causar problemas de compilação devido à falta de reificação do tipo. São apresentadas duas maneiras de resolver esse problema: a primeira envolve a criação de um array de Object e a supressão da advertência, enquanto a segunda envolve a alteração do tipo do array para Object[].

São discutidos os prós e contras de cada técnica de eliminação do erro de criação de array genérico.

Em contras:
Alguns exemplos de problemas são apresentados nos exemplos do livro, a seguir:

Exemplo de pilha normal
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6pg850mty5fwf52hy7np.jpg)

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

Alguns error e problemas que podem ocorrer são abordados a seguir:

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


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


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


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


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

Outro exemplo de uso da classe genérica Stack é fornecido para ilustrar a eliminação da necessidade de cast explícito.
Embora seja recomendado preferir listas sobre arrays, algumas situações exigem o uso de arrays em tipos genéricos.

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

Limitações dos tipos genéricos do Java são discutidas, como a impossibilidade de criar uma pilha de tipos primitivos.
Tipos genéricos com parâmetros de tipo limitado são introduzidos, exemplificados pela classe DelayQueue.


**Conclui-se** que tipos genéricos tornam o código mais seguro e legível, especialmente ao evitar a necessidade de casts explícitos no código cliente. Recomenda-se que tipos existentes sejam transformados em genéricos sempre que possível para melhorar a experiência do usuário sem quebrar a compatibilidade com clientes existentes.