teleren/devto huggingface dataset:
Rust ^ cannot use the `?` operator in a function that returns `()`
Published: 2023-02-27 21:21:18

Problem:

When I try to run code with the following function:

```rust
fn invalid_function() {
    let mut file = File::open("data/AA.csv")?;
}
```

This returns the following error:

```sh
$ cargo run

   Compiling voxide v0.1.0 (/rick/follinge-2020-08-10/projects/voxide)
error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`)
  --> src/main.rs:10:45
   |
9  | fn invalid_function() {
   | --------------------- this function should return `Result` or `Option` to accept `?`
10 |     let mut file = File::open("data/AA.csv")?;
   |                                             ^ cannot use the `?` operator in a function that returns `()`
   |
   = help: the trait `FromResidual<Result<Infallible, std::io::Error>>` is not implemented for `()`

For more information about this error, try `rustc --explain E0277`.
error: could not compile `voxide` due to previous error
```

The 1st clue is in asking ourselves what does the question mark do in this context? The answer is error propagation:

https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html

So basically it worked in main() because that was the top level function, and if we failed, we crashed as the error state was uncaught which is okay.

But if we use the question mark operator in a function, we need to return the Result which tells the caller that they need to handle a potential error state.

A better way to handle it is to either use the if or match keywords.

```rust

fn valid_function() -> () {
    if let Ok(file) = File::open("data/AA.csv") {
        // Do something with the file
    }
    else {
        // Handle the error
    }
}
```

This will open a file, and check for errors.

This pattern is used so often that Rust has a match keyword for dealing with enums:

```rust
fn better_valid_function() -> () {
    let file_result = File::open("data/AA.csv");
    let file = match file_result {
        Ok(file) => file,
        Err(error) => panic!("Problem opening the file: {:?}", error),
    };
}
```

https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html
Certificate pinning and Public key pinning in Kotlin
Published: 2023-02-27 21:16:17

 ![Certificate pinning and Public key pinning in Kotlin](https://needone.app/content/images/2023/02/Cerificate-pinning.png)

With the last article ([Certificate pinning and Public key pinning](https://needone.app/certifate-pinning-public-key-pinning/)), we know the concept of Certificate pinning and Public key pinning, and how to implement them in iOS. This article will demonstrate how to implement them in Kotlin.

## Implement certificate pinning

Certificate pinning is a security technique that involves associating a specific certificate or public key with a particular server. This helps to prevent man-in-the-middle attacks by ensuring that the client only trusts the specific certificate or public key associated with the server, and not any other certificate that may be presented by an attacker.

Here is an example of how to implement certificate pinning in Kotlin using the OkHttp library:

## Implement public key pinning

```kotlin
val certificatePinner = CertificatePinner.Builder()
    .add("example.com", "sha256/1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ")
    .build()

val client = OkHttpClient.Builder()
    .certificatePinner(certificatePinner)
    .build()

val request = Request.Builder()
    .url("https://example.com")
    .build()

client.newCall(request).execute()

```

In this example, we create a `CertificatePinner` object using the `CertificatePinner.Builder` class. We add a pin for the `example.com` domain using the `add` method, specifying the domain name and the SHA-256 hash of the public key.

Next, we create an `OkHttpClient` object using the `OkHttpClient.Builder` class and set the `CertificatePinner` object using the `certificatePinner` method.

Finally, we create a `Request` object using the `Request.Builder` class and specify the URL of the server. We use the `OkHttpClient` object to send the request and execute it.

Ref: https://needone.app/certificate-pinning-and-public-key-pinning-in-kotlin/
Install Python modules for Lambda using Cloud9
Tags: aws, cloud, awscommunity, 100daysofcloud
Published: 2023-02-27 21:15:06

[58/100] #100DaysOfCloud Today, I Installed Python modules for Lambda using Cloud9.

For a Lambda function to work with some libraries it needs to be uploaded as a separate module as lambda doesn't isn't inbuilt with many python libraries. To do that a new Cloud9 environment will be started and in it a pip commands executed in terminal. Then modules will be packed and upload to lambda function.

AWS Cloud9 is a cloud-based integrated development environment (IDE) that lets you write, run, and debug your code with just a browser. It includes a code editor, debugger, and terminal. Cloud9 comes prepackaged with essential tools for popular programming languages, including JavaScript, Python, PHP, and more, so you don’t need to install files or configure your development machine to start new projects. Since your Cloud9 IDE is cloud-based, you can work on your projects from your office, home, or anywhere using an internet-connected machine. Cloud9 also provides a seamless experience for developing serverless applications enabling you to easily define resources, debug, and switch between local and remote execution of serverless applications. With Cloud9, you can quickly share your development environment with your team, enabling you to pair program and track each other's inputs in real time.

You can try do it by yourself by following the steps from the link below: [GitHub](https://github.com/aaditunni/100DaysOfCloud/blob/main/Journey/058/Readme.md)
Purging Deleted Azure Key Vaults
Published: 2023-04-12 14:07:50

---
title: Purging Deleted Azure Key Vaults
published: true
date: 2023-02-27 21:09:20 UTC
tags: 
canonical_url: https://paulyu.dev/code/purge-deleted-azure-vaults/
---

Do you constantly provision and delete Azure Key Vaults? 

If so, you may have noticed attempts to recreate a recently deleted key vault will result in the following error: 

```text
The vault name is already in use.
```

This is because Azure Key Vaults are kept in a deleted state and not automatically purged. You must manually purge these key vaults to be able to reuse the name.

To confirm the key vault in question is in "deleted" state, you can run the following:

```bash
az keyvault list-deleted --query "[].name" -o tsv
```

Using Bash, we can loop through all deleted key vaults and purge them so that the name can be re-used:

```bash
az keyvault list-deleted --query "[].name" -o tsv | while read keyvault; do
  az keyvault purge -n $keyvault;
done
```
Creating a GuestBook in Next.js
Tags: nextjs, javascript, react, webdev
Published: 2023-02-27 21:00:54

To develop my Next.js and React skills, **I decided to create a GuestBook**.
This is what it looks like so far: https://vulcanwm-guestbook.vercel.app

---

### I've learnt how to:
- use loops in React/JSX
- use if statements in React
- connect Next.js to MongoDB
- make an API in Next.js
- set/get cookies in Next.js

---

### The features I've added are:
- seeing all the messages
- messaging on the guestbook
- seeing the timestamp of the message
- censoring all the messages
- ratelimiting a user so they can only message once an hour

---

### Features to come:
- Adding OAuth: GitHub/Google/Replit
- Deleting your own comment
- Admins for the board so they can delete all comments
- Ratelimit on username as well as browser

---

The GitHub repo is here, so contribute to help me on my Next.js journey!
{% embed https://github.com/VulcanWM/guest-book %}
JavaScript Tutorial Series: practice 2
Published: 2023-02-27 21:00:27

In this post you're going to solve a couple of exercises test your previously acquired knowledge. 

## Exercise 1
Create a function that receives an array of numbers as input and outputs the average of those numbers. To implement the function, use the `/` operator, an arrow function, and a higher order function. 

## Exercise 2
Create a function that accepts an array and a value as arguments and outputs a boolean indicating whether the array contains the value or not.

## Exercise 3
Make a function that takes a list of numbers as input and returns a new list with each element in the first list squared.

## Exercise 4
Create a book object that includes the properties of author, title, and number of pages. Afterwards, create a function that accepts that book object as input and logs a message to the console with the book's title, author, and page count.

Good luck !
Structure that MAUI App!
Published: 2023-02-27 20:38:41

---
title: Structure that MAUI App!
published: true
description: How I structured my recent DotNet MAUI app.
tags: 
cover_image: https://cdn-images-1.medium.com/max/4860/1*c2tk17yL1AGjYiLftWPJFg.png
# Use a ratio of 100:42 for best results.
# published_at: 2023-02-27 20:36 +0000
---

## Premise

I recently found myself giving DotNet MAUI a whirl. The goal was to build a desktop app that connects to RabbitMQ, then sends and receives messages that were protobuf serialized. I got to the goal fast and efficiently enough.

Here’s the source code [https://github.com/mariusmuntean/ProtoRabbit](https://github.com/mariusmuntean/ProtoRabbit)

And this is how it looks like on Windows

![ProtoRabbit.](https://cdn-images-1.medium.com/max/4860/1*c2tk17yL1AGjYiLftWPJFg.png)

## Motivation

What I didn’t like was that the main page of the app was a mess, tons of little UI elements, databound to the viewmodel. The viewmodel itself wasn’t much better. It had code to create connections, handle sending and receiving messages and so on. “There must be a way to structure this” I thought, and there was. Read on to find out what I settled on.

## Step #1 — Custom controls

I first split up the code in three [custom controls](https://learn.microsoft.com/en-us/dotnet/maui/user-interface/handlers/create?view=net-maui-7.0):

* *ConnectionControl* — Creates a new connection to RabbitMQ.

* *SendMessageControl* — Sends messages to an exchange.

* *SubscribeAndReceiveMessageControl* — Displays messages.

This cleaned up the main page so much that it only contained a *Grid* layout and the three custom controls. Nice and simple, have a look.

![MainPage and three custom controls.](https://cdn-images-1.medium.com/max/6912/1*KbuMd2t0zfcRcnKeWMqb0g.png)

## Step #2 — Nested ViewModels

Now it was the *MainPageViewModel’s* turn. I almost never used nested viewmodels in the past, except for displaying collections of objects. But this is exactly what helped here to tame the complexity.

Basically, each custom control got a dedicated viewmodel and the *MainPageViewModel* is their parent:

* *ConnectionViewModel* — Established and stops the RabbitMQ connection.

* *SendMessageViewModel* — Defines what message templates can be used and sends protobuf serialized messages to RabbitMQ.

* *SubscribeAndReceiveMessageViewModel* — Manages “subscriptions” to a certain message type from a certain Exchange in RabbitMQ.

This is how the *MainPageViewModel* looks like after extracting the three sub-viewmodels.

![MainPageViewModel and three “child” viewmodels.](https://cdn-images-1.medium.com/max/6904/1*HJqAVeym05DXvgbGi7hllg.png)

## Fin

That’s all I had to say about this topic this time.

As always feel free to browse my GitHub repo and play with the code. It’s all MIT licensed, so go nuts with it.

If you enjoyed this post, follow me to stay up to date.
JSON logging bash scripts
Tags: bash, logging
Published: 2023-02-27 20:30:55

---
title: JSON logging bash scripts
published: true
tags: ['bash', 'logging']
canonical_url: https://sevic.dev/notes/bash-script-json-logging/
---

Logs are usually streamed to the standard output in JSON format so logging aggregators (Graylog, e.g.) can collect and adequately parse them.

The following example shows how bash script output can be formatted with the message, log levels, and timestamp. Error logs are streamed into a temporary file, formatted, and redirected to the standard output.

```bash
#!/usr/bin/env bash

declare -A log_levels=( [FATAL]=0 [ERROR]=3 [WARNING]=4 [INFO]=6 [DEBUG]=7)

json_logger() {
  log_level=$1
  message=$2
  level=${log_levels[$log_level]}
  timestamp=$(date --iso-8601=seconds)

  jq --raw-input --compact-output \
    '{
      "level": '$level',
      "timestamp": "'$timestamp'",
      "message": .
    }'
}

{
  set -e
  echo $? 1>&2
  echo "Finished"
} 2>/tmp/stderr.log | json_logger "INFO"

cat /tmp/stderr.log | json_logger "ERROR"
```

### Boilerplate

Here is the [link](https://sevic.dev/nestjs-starter) to the boilerplate I use for the development.
How can I create a Kivy app with a mouse shader like in p5.js?
Tags: kivy
Published: 2023-02-27 20:26:23

I want to create a Kivy app that displays a real-time mouse shader effect, similar to the one on this OpenProcessing website: https://openprocessing.org/sketch/835887. In the p5.js code, the shader uses the position of the mouse.

So far, I have created mouse cursor trail which changes color every 3 seconds:

```
from kivy.app import App
from kivy.graphics import Color, Line
from kivy.uix.widget import Widget
from kivy.uix.label import Label
from kivy.core.window import Window
from kivy.clock import Clock
from kivy import Config

Config.read("config.ini")

class MyGrid(Widget):
def __init__(self, \*\*kwargs):
super(MyGrid, self).__init__(\*\*kwargs)
self.trail = \[\]
self.color = (1, 0, 0, 0.3)  # set the trail color to red by default
self.label = Label()
self.add_widget(self.label)
Window.bind(mouse_pos=self.mouse_pos)
self.line = Line(points=self.trail, width=20, mode='mesh', blur=10)
self.canvas.add(Color(\*self.color))
self.canvas.add(self.line)
self.color_index = 0
Clock.schedule_interval(self.change_color, 3)

    def on_touch_up(self, touch):
        self.canvas.remove(self.line)
        self.trail = []
        self.line = Line(points=self.trail, width=20, mode='mesh', blur=10)
        self.canvas.add(Color(*self.color))
        self.canvas.add(self.line)
    
    def mouse_pos(self, window, pos):
        self.trail.append(pos)
        if len(self.trail) > 10:
            self.trail.pop(0)
        self.line.points = self.trail
    
    def change_color(self, dt):
        self.canvas.remove(self.line)
        colors = [(1, 0, 1, 0.3), (0, 1, 0, 0.3), (1, 1, 0, 0.3), (1, 0.3, 0, 0.3)]
        self.color_index = (self.color_index + 1) % len(colors)
        self.color = colors[self.color_index]
        self.canvas.add(Color(*self.color))
        self.canvas.add(self.line)

class CursorApp(App):
def build(self):

        return MyGrid()

if __name__ == "__main__":
CursorApp().run()
```
Can someone please provide some guidance on how to implement this effect in Kivy, or suggest some resources that might help me get started?
5 Essential React Libraries for Front-End Web Development
Tags: reactrouter, redux, frontendwebdevelopment, reactmotion
Published: 2023-02-27 20:19:21



React is an incredibly powerful and versatile JavaScript library for building user interfaces and front-end web applications. With its component-based architecture, React enables developers to create complex UIs with reusable components. As the popularity of React continues to grow, the number of available libraries and tools is also increasing. In this article, we’ll be taking a look at five essential React libraries that every front-end web developer should consider adding to their development toolkit. From UI components to data management and more, these libraries provide everything you need to create amazing React applications.


1. **React Router**: React Router is a collection of navigational components that compose declaratively with your application. With React Router, you can create, manage, and manipulate routes in your application to create a natural experience for users.

2. **Redux**: Redux is a predictable state container for JavaScript applications. It helps you write applications that behave consistently and are easy to test, and it enables powerful features like undo and redo, hot reloading, and universal apps.

3. **React Bootstrap**: React Bootstrap is an open source library for building responsive, mobile-first front-end applications. It provides a comprehensive set of components and styles that make it easy to get started quickly.

4. **Styled Components**: Styled components is a library for writing modular, reusable, and maintainable component-based UI code. It allows you to write styles in JavaScript, which are then compiled into valid CSS that can be used in your application.

5. **React Motion**: React Motion is a library for creating smooth, high-performance animations and transitions in React applications. It uses physics-based animation, making it easy to create natural-looking motion with minimal effort.
Entendendo Herança e Composição
Tags: typescript, tutorial, codenewbie, oop
Published: 2023-02-27 20:15:33

A programação orientada a objetos é uma parte importante e muitas vezes necessária na formação de um programador. Um dos conceitos fundamentais dessa abordagem é a herança, que nos permite reutilizar código em nossos projetos, dentre outras coisas. No entanto, além da herança, existe outro conceito básico que pode ajudar no desenvolvimento de aplicações, a composição. Mas qual a diferença entre herança e composição? A diferença está na forma como uma classe interage com outras classes dentro do código.

A herança é um mecanismo em POO onde uma classe herda propriedades e métodos e outra classe permitindo a criação de hierarquia de classes, onde uma classe filho (subclasse) é derivada de uma classe mais geral, ou classe pai (Superclasse):


![Exemplo de herança](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hgj83i9ehbnjqwb3l7pd.png)

No exemplo acima, a classe 'Gato' herda todos os atributos e métodos da classe 'Animal' além de possuir seu próprio atributo e método chamado "raça".

Pro outro lado, a composição é um mecanismo em POO que cria uma relação do tipo 'tem-um' com outra classe:


![Image Exemplo de composicao](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4b9it6mz546q7a8aaezo.png)

No exemplo acima, temos uma classe chamada 'Motor' e logo em seguida uma classe chamada 'Carro'. O que é importante notar aqui é que a classe 'Carro' não estende a classe 'Motor', mas sim cria uma instância da mesma para ser um de seus membros. Assim, a classe 'Carro' terá seus próprios métodos e também poderá acessar os métodos da classe 'Motor' por meio dessa instância criada.

Entre os exemplos do uso de herança, podemos citar:

- A reutilização de código através de uma classe já existente.
- A criação de uma classe genérica que pode ser usada como base para outras classes.
- Definir uma hierarquia de classes dentro do código.

Já os exemplos de uso da composição, podemos citar:

- A criação de objetos complexos através de objetos mais simples.
- A possibilidade de combinar funcionalidades de classes diferentes em um único objeto.
- Permitir a reutilização de código sem a necessidade de criar hierarquias de classes.

A principal diferença entre herança e composição é que a herança é uma relação do tipo "é-um", enquanto a composição é uma relação do tipo "tem-um". Em outras palavras, na herança, uma classe é um tipo de outra classe (ex: Gato é um tipo de Animal), enquanto na composição, uma classe possui objetos de outras classes (ex: Carro tem um Motor).
Java Efetivo - Constantes
Tags: java, webdev
Published: 2023-02-27 20:07:14

## Use as interfaces para definir tipos
 
_Esta é uma série baseada no entendimento de tópicos relacionados ao livro com foco no resumo._

**Interfaces**

Sabemos que quando uma classe implementa uma interface, essa interface a qual ela implementou pode ser utilizada como um tipo.
Sempre precisamos ter em mente que ao criar uma interface podemos ter em mente o que será possível realizar com as instâncias das classes que a implementarem.
Vamos imaginar que temos classes que possuem um comportamente relacionado a pagamentos, ou seja, elas são pagáveis, isso indica que há classes que permitem ações relacionadas a esse assunto.


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

**Não esta correto**

O que não é considerado correto quando utilizamos interfaces.
Usarmos interfaces para qualquer outra coisa que não seja definir uma idéia do que seja possível realiza com as classes que a implementam. 
Exemplo citado no livro é o de criação de "interface constante" onde o único objetivo é agrupamento de constantes para serem utilizadas por outras classes.
Essa abordagem não é considerada correta.

Isso porque interfaces deveriam conter constantes apenas para efeito de implementações internas e não para disponibilizar em suas implementações.
De qualquer forma há situações onde há precisaremos criar uma constante na interface e/ou classe e não devemos ter receio disso desde que realmente a constante esteja ligada diretamente com o propósito da classe e da interface.

**Lembre-se**

lembrando que a melhor maneira de criarmos constantes no Java são através de Enum ou como uma classe utilitária não instanciável.
E não considerando o uso de Interfaces para isso.
Interfaces devem ser utilizadas somente para definir tipos não para agrupamento de constantes.