teleren/devto huggingface dataset:
The Question Mark `?` Operator in Rust
Tags: rust, programming, beginners, tutorial
Published: 2022-10-05 16:18:01

The question mark `?` operator is used for early exit an function with return type that's compatible with the value of the `?` is used on. Such as `Err(e)` but not many people know it can be used on `None` as well.

The `?` operator is commonly used with `Result<T, E>` to propagate error up the call chain. We can define a unified error enum to host all errors. Remember to take advantage of Rust's conversion method `From<T>` to cast foreign errors into the unified error enum. That way, we take advantage of `?` operator, it will perform the conversion behind the scene.

```rust
// Unified `Error` enum
#[derive(Debug)]
enum Error {
    ParseIntError(std::num::ParseIntError),
    ParseFloatError(std::num::ParseFloatError),
}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::ParseIntError(e) => write!(f, "ParseIntError: {}", e.to_string()),
            Self::ParseFloatError(e) => write!(f, "ParseFloatError: {}", e.to_string()),
        }
    }
}

impl std::error::Error for Error {}

// Convert `std::num::ParseIntError` to `Error`
impl From<std::num::ParseIntError> for Error {
    fn from(err: std::num::ParseIntError) -> Self {
        Self::ParseIntError(err)
    }
}

// Convert `std::num::ParseFloatError` to `Error`
impl From<std::num::ParseFloatError> for Error {
    fn from(err: std::num::ParseFloatError) -> Self {
        Self::ParseFloatError(err)
    }
}

fn main() -> Result<(), Error> {
    // Parse an integer and unwrap it, or throw `Error::ParseIntError`
    let _: i32 = "123".parse()?;
    let _: i32 = "not_an_integer".parse()?;

    // Parse a float and unwrap it, or throw `Error::ParseFloatError`
    let _: f64 = "not_a_number".parse()?;

    Ok(())
}

```

The `?` operator could also perform early return on `Option<T>` return type.

```rust
fn get_first_char_of_second_word(phrase: &str) -> Option<char> {
    // Return `None` if the phrase consist of a single word
    phrase.split(" ").skip(1).next()?.chars().next()
}

fn main() {
    assert_eq!(get_first_char_of_second_word("Hello World"), Some('W'));
    assert_eq!(get_first_char_of_second_word("Hello?"), None);
}
```
Fundamental steps for a successful Security Information and Event Management (SIEM) implementation
Tags: security, siem
Published: 2022-10-05 16:17:15

After researching multiple use cases and experiences on successful SIEM implementation projects by CISOs across industries, these are the guidelines that were commonly followed prior to kickstarting SIEM adoption:

1️⃣ Prerequisite 1: Source asset identification
A good SIEM strategy includes the identification of critical assets that send key data, plus the context, logs, and events around the data into the SIEM. 

2️⃣Prerequisite 2: Data quality
Garbage in, garbage out. To get the right type of data fed into the SIEM, source it from the correct sources. 

3️⃣Prerequisite 3: Logging levels
The rules controlling the event stream flowing into the SIEM should not cause too many false positives, but yet maintain a deep level of visibility.
Constants In Ruby
Published: 2022-10-05 16:12:33

Today I learned that variables are always formatted in the 'snake case' like this :my_first_variable.

I also learned that constants are usually connected to a string for example: MY_FIRST_CONSTANT = 10. And once constants are assigned, they cannot be changed, meaning this constant is going to always be 10.

Also, I learned that classes and constants are similar.Classes are the way Ruby organizes."Objects are generally created by instantiating classes using the .new method".
For example,it looks like this:

# Define the class
class Calculator
  #...
end
The companies should have a multi-cloud strategy?
Tags: aws, latam, devops, desarrollador
Published: 2022-10-05 16:12:23

> Multi-cloud is becoming more popular among enterprises, but it's not without its challenges.
 
A multi-cloud strategy can be costly and difficult to manage, and it's important to understand the pros and cons before embarking on such a journey. On the plus side, multi-cloud can give you access to a wider range of services and technologies. But on the downside, it can be very slow to make changes across multiple providers, and you'll need a trained staff that is familiar with each cloud platform. 

![Multi cloud on AWS](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hz1gu8l1zljb7b82x9mh.png)

It's important to weigh the pros and cons carefully before deciding if multi-cloud is right for your organization.
Recently discussing with a coworker, we talked about whether or not a company should have a multi-cloud strategy, we finished to a conclusion that we see again and again:

## The pros you can get:

- Have many services available
- Leverage top-tier technologies

## along with the cons you must face

- a higher cost
- look for a trained staff in each cloud provider.
- very slow process of change
... and the list can continue if you wish


In short, I am not saying that it should NOT be done, but that it is NOT for everyone.

For example, if you have a startup, a change process needs to be fast, and if you are in multiple providers you will not be able to do it.

Don't run your container to multiple clouds and say, Look at me, mom, I'm in the cloud!

The cloud is more than that, and what do you think, is multi-cloud for everyone?

---

Did you find it interesting?
Would you like us to be in contact?

![Hector Fernandez](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bkns07waoe3ixr3uncej.jpg)
Héctor Fernández
AWS Community Builder (Uruguay)
https://hector.builders/
How did I sell my first Python project for over $9,000?
Published: 2022-10-05 16:08:44

I'm still not a Python specialist, yet I sold my first project for over $9,000. I think I'm closer to a junior.

How did I manage to do it and what was the project? Maybe I'll start by saying that there are seemingly a lot of videos and articles on the Internet on how to start programming, and what kind of project to do at the beginning of your career, so that it's not too difficult and can help you grow.

I am not a fan of this approach. I definitely prefer to look from the perspective of the need and try to find a solution.

As a PHP specialist, I wanted to give Python a try, but I didn't have an idea for a project, so I kept putting off learning Python until the need arose. While building a modeling startup. We had to obtain data on all casting agencies in the United States. I learned that python is best for such scraping, so I decided to write a small program that would allow me to obtain data of all agencies.

A program is not enough. How would such a program work, after all, just using Python would not solve the problem that this data had to be found somewhere. That's why I relied on google maps.

After running the program for the first time, I was surprised that everything went so smoothly. I wrote the program itself for a couple of days in coffee breaks. I fell in love.

We managed to collect contact information for all the companies, but unfortunately our startup itself failed. Nothing else was left for me but to go back to my regular job and work on my psyche, which was in decline. I thought that the program itself could also help someone, so I wrote on one startup-related group describing my little data acquisition program.

After a few minutes I fell flat. It turned out that I have customers who already want to buy my program for quite a lot of money (and just hours ago I wanted to make it open-source).

In the end, I sold the tool to as many as four companies and managed to make over $9,000.
Exercism #2: Lasagna Exercise
Published: 2022-10-05 16:08:26

```
class Lasagna
  EXPECTED_MINUTES_IN_OVEN = 40
  def remaining_minutes_in_oven(actual_minutes_in_oven)
    return EXPECTED_MINUTES_IN_OVEN - actual_minutes_in_oven
    raise 'Please implement the Lasagna#remaining_minutes_in_oven method'
  end

  def preparation_time_in_minutes(layers)
    return layers * 2
    raise 'Please implement the Lasagna#preparation_time_in_minutes method'
  end

  def total_time_in_minutes(number_of_layers:, actual_minutes_in_oven:)
    x = number_of_layers * 2
    return actual_minutes_in_oven + x
    raise 'Please implement the Lasagna#total_time_in_minutes method'
  end
end

```

Constants are used in order to create values  that never change, this is similar to variables, but constants can be useful especially with communicating how does your code work

TASK 4
_Define the Lasagna#total_time_in_minutes method that takes two named parameters: the number_of_layers parameter is the number of layers you added to the lasagna, and the actual_minutes_in_oven parameter is the number of minutes the lasagna has been in the oven. The function should return how many minutes in total you've worked on cooking the lasagna, which is the sum of the preparation time in minutes, and the time in minutes the lasagna has spent in the oven at the moment._

The reason why the last test didn't work:

1. You didn't define number_of_layers which is only prevalent to the 3rd def. You need to define it and make it the same code as layers class

Taken from community answers: 

```
class Lasagna
  EXPECTED_MINUTES_IN_OVEN = 40
  PREPARE_MINUTES_PER_LAYER = 2
  def remaining_minutes_in_oven(actual_minutes_in_oven)
    EXPECTED_MINUTES_IN_OVEN - actual_minutes_in_oven
  end
  def preparation_time_in_minutes(layers)
    PREPARE_MINUTES_PER_LAYER * layers
  end
  def total_time_in_minutes(number_of_layers:, actual_minutes_in_oven:)
    preparation_time_in_minutes(number_of_layers) + actual_minutes_in_oven
  end
end

```
PREPARE_MINUTES_PER_LAYER is better because it gives it a unique and constant value
is Long Pressed Name
Tags: javascript, leetcode
Published: 2022-10-05 15:55:37

 Input: name = "alex", typed = "aaleex"
 Output: true
 Explanation: 'a' and 'e' in 'alex' were long pressed.


 Input: name = "saeed", typed = "ssaaedd"
 Output: false
 Explanation: 'e' must have been pressed twice, but it was not in the typed output.

```js
var isLongPressedName = function (name, typed) {
  if (typed.length < name.length) return false;
  let namePtr = 0;
  let typedPtr = 0;

  while (typedPtr < typed.length || namePtr < name.length) {
    if (name[namePtr] === typed[typedPtr]) {
      namePtr++;
      typedPtr++;
    } else if (name[namePtr - 1] === typed[typedPtr]) {
      typedPtr++;
    } else {
      return false;
    }
  }
  return true;
};



```
Compacting historical data in Clickhouse
Tags: database, clickhouse, devops
Published: 2022-10-05 15:54:55

In most cases you need full details on your data collected, so you don’t want to compact (store aggregated) your data. But there are plenty of cases, when you actually need only recent data in full perspective and historical data can be easily compacted.

E.g. you will only want to save, say, last month of collected user events in event-per-row form. But older data is fine to keep aggregated in total events per day format.

This can save space and reduce query execution times. Clickhouse can manage this automatically, [let’s see how](https://medium.com/@golotyuk/compacting-historical-data-in-clickhouse-to-optimize-space-e9e4439caad3).
Top 3 programming languages for beginners
Tags: javascript, java, python, beginners
Published: 2022-10-05 15:51:39

What are the top three programming languages you need to know about if you only start learning about coding?

I would say that these are the good candidates:
1) Java
2) JavaScript
3) Python

None of these languages is perfect though and they would open different career opportunities for you.

To make things simpler for you I made a video describing all pros and cons of those programming languages - the link in the first comment, check this out!

{% embed https://www.youtube.com/watch?v=1X3H7_DnTLo %}
In One Minute : JUnit
Tags: java, beginners, programming, oneminute
Published: 2022-10-05 15:47:26

JUnit is a unit testing framework for the Java programming language. JUnit has been important in the development of test-driven development, and is one of a family of unit testing frameworks which is collectively known as xUnit that originated with SUnit.

{% embed https://youtu.be/EnLfpNbDgDk %}

JUnit is linked as a JAR at compile-time. The latest version of the framework, JUnit 5, resides under package org.junit.jupiter. Previous versions JUnit 4 and JUnit 3 were under packages org.junit and junit.framework, respectively.

A JUnit test fixture is a Java object. Test methods must be annotated by the @Test annotation. If the situation requires it, it is also possible to define a method to execute before (or after) each (or all) of the test methods with the @BeforeEach (or @AfterEach) and @BeforeAll (or @AfterAll) annotations.

Official Website : https://junit.org/
Adding feature to a project
Tags: opensource
Published: 2022-10-05 15:40:03

Hello!

# Static site generator feature

This week I've been working on another [student repo](https://github.com/a-parris21/ap21-ssg). I had to make a feature that will allow user to specify all of their SSG options in a JSON formatted configuration file instead of having to pass them all as command line arguments every time.

It didn't took much time to understand how things work, since I was [writing a code](https://github.com/a-parris21/ap21-ssg/pull/25) in the same language, that I'm familiar with(JavaScript).

# Concern

The only thing I was concerned about is that I need to make sure that I write code in the same style as the project author, so that my code doesn't have any confusions for project maintainer.

I see that some big projects use prettier(or other code formatter). I believe it's a very good idea and I would definitely use it in my next project, because the code will have the same format and won't stand out. 

# Summary

I enjoyed working on open source project and making some improvements. It's a great feeling when you make something working to make other people life easier.
Methods in Methods and Parameters
Published: 2022-10-05 15:36:17

If you need to use a method inside of another method, you need to make sure the right number of arguments are available. 

In this case, there is a key name (that will be provided by the assignment checker), but you need it to replace the parameter (layers) for the method you called on (preparation_time_in_minutes) because where else are you going to get the value from?

Copied from Exercism:
"Units of functionality are encapsulated in methods - similar to functions in other languages.

A method can be defined with positional arguments, keyword arguments (which are defined and called using the : syntax) or have no arguments at all.

Methods either implicitly return the result of the last evaluated statement, or can explicitly return an object via the return keyword."

```
class Lasagna
  
  EXPECTED_MINUTES_IN_OVEN = 40
  TIME_PER_LAYER = 2
  
  def remaining_minutes_in_oven(actual_minutes_in_oven)
    remaining_minutes_in_oven = EXPECTED_MINUTES_IN_OVEN - actual_minutes_in_oven
    return remaining_minutes_in_oven
    # raise 'Please implement the Lasagna#remaining_minutes_in_oven method'
  end

  def preparation_time_in_minutes(layers)
    preparation_time_in_minutes = layers * TIME_PER_LAYER
    return preparation_time_in_minutes
    #raise 'Please implement the Lasagna#preparation_time_in_minutes method'
  end

  def total_time_in_minutes(number_of_layers:, actual_minutes_in_oven:)
    return (number_of_layers * TIME_PER_LAYER) + actual_minutes_in_oven
    #raise 'Please implement the Lasagna#total_time_in_minutes method'
  end
end

fatcat = Lasagna.new
# p fatcat.remaining_minutes_in_oven(10)
# p fatcat.preparation_time_in_minutes(3)
#p fatcat.total_time_in_minutes()

```
🎉  SD Times chooses Luos as the open-source project of the week!
Tags: opensource, embedded, luos, sdtimes
Published: 2022-10-05 15:34:19

Luos is an open-source lightweight library that enables developers to develop and scale their edge and embedded distributed software.

⏩ [read the article](https://sdtimes.com/software-development/sd-times-open-source-project-of-the-week-luos/)

Thanks to Jenna Sargent Barron and the entire SD Times team!
Today I learned about "place-items"
Tags: todayilearned, css, webdev
Published: 2022-10-05 15:26:11

Today I learned about the CSS property `place-items`, it allows you to easily position elements in flex and grid layouts. It also solves the eon old quest to "center something in a div".

To center the single child of a div simply add `display: grid;` and `place-items: center;`.

![Center elements in a div using display:grid and place-items:center.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s6pllkbehjc83atzqki1.png)

[Place-items](https://developer.mozilla.org/en-US/docs/Web/CSS/place-items) takes up to two parameters. The first to place the items vertically and the second to place them horizontally. 

![Examples of place-items.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cqz59lhrunph2o353ffc.png)

This concludes out TIL, see you next time.

```css
.wrapper-that-centers {
  display: grid;
  place-items: center;
}
```

![Teacher Emoji for TIL.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/txg2qg6dst36zrb03zj9.png)
Assigning a Variable May Not Always Be As It Seems
Tags: javascript, beginners, programming
Published: 2022-10-05 15:18:55

So recently while writing some code, I ran into an interesting problem that kind of boggled my mind. Pictured below is the code snippet that I will be discussing today.

```
function handleSubmit(e) {
    e.preventDefault();
    let totalVotes = document.querySelector('#vote-count').textContent
 
    parseTot = parseInt(totalVotes)
    parseTarg = parseInt(e.target.votes.value)
    totalVotes = parseTot + parseTarg
 
    document.querySelector('#vote-count').textContent = totalVotes
 
    currentCharacter.votes = totalVotes
   
    patchCurrentCharacter(currentCharacter)
}

```
The section of code I would like to discuss is the first 6 lines of my function “handleSubmit”. On the second line, I create a variable called totalVotes in which I then assign the value of `document.querySelector(‘#vote-count’).textContent`. So why, then, do I have to restate that exact thing on the sixth line? Why doesn’t the 5th line cover what needs to be stated on line 6, and even then, why couldn’t line 6 run as totalVotes = totalVotes?

This is where the title of my post comes in. On my second line, all I am doing is assigning my totalVotes variable the literal text content at that location, which could be anything. If I console.log(totalVotes) here, I get whatever that text content is, I don’t get back `“document.querySelector(‘#vote-count’).textContent`. This means that I can't alter that html elements text content with my totalVotes variable, because it isn't linked to that element necessarily, it is only assigned that elements text content.

As someone new to programming, this was difficult to catch in code, and was almost just as difficult to understand while someone explained it to me. However, I feel like this particular case is something that requires a sort of Eureka moment: a moment where you don’t understand initially, but once you do, it makes total sense.

Hopefully I was able to help you towards your Eureka moment if you are also struggling with this concept!
Simple avatar with status indicator - CSS only - A step-by-step tutorial
Tags: css, html, webdev, tutorial
Published: 2022-10-05 15:17:40

![Avatar with status indicator](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qpjqhr822sxma1srrfa3.png)

Tutorial on how to create a simple avatar with status indicator using only CSS.

## <u>HTML</u>
For HTML, we need only one div element with "avatar" class and a span element inside with "status" element. This element will indicate status. 

Default value will be offline, by adding the "active" class to it, the status indicator will become green.

For now, we'll add an "active" class to it.

```html
<div class="avatar">
    <span class="status active"></span>
</div>
```

## <u>CSS</u>
For CSS, first we'll style the avatar.

We'll set it's width and height to 40x40 px.

A little rounded border of 3px width, solid dark blue.

We'll set it's position to relative.

And, of course, the image. We'll set the background image to url image, and it's size to cover the whole 40x40 area, with position set to center.

```css
.avatar {
    width: 40px;
    height: 40px;
    border: 3px rgb(48, 69, 96) solid;
    border-radius: 6px;
    position: relative;
    background-image: url('https://www.rd.com/wp-content/uploads/2017/09/01-shutterstock_476340928-Irina-Bg.jpg');
    background-size: cover;
    background-position: center;
}
```

Our status indicator will be 6x6 pixels size with a dark border with radius set to 50%, which will form a circle.

We'll set it's position to absolute, and with top and right set to 0 with transform translate set to 40% and -40%, it will be positioned in the top right corner.

Lastly, we'll set it's background to dark grey. This is the look of offline status. The default one.

```css
.status {
    width: 6px;
    height: 6px;
    border: 2px solid rgb(48, 69, 96);
    border-radius: 50%;
    position: absolute;
    right: 0px;
    top: 0px;
    transform: translate(40%, -40%);
    background-color: rgb(33, 34, 35);
}
```

Now we'll style the "active" class.

This class we'll be appended to a status element.

We'll just override the background-color property, and set it to green.

```css
.active {
    background-color: rgb(48, 249, 75);
}
```

And that's it.

Simply remove the "active" class from the status element when offline and add it when online.

You can find video tutorial with full code [here](https://designyff.com/code/simple_avatar_with_status).

Thanks for reading. ❤️
Paracetamol.js💊| #186: Explica este código JavaScript
Tags: java, webdev, spanish, programming
Published: 2022-10-05 14:50:49

## **<center>Explica este código JavaScript</center>**
#### <center>**Dificultad:** <mark>Básico</mark></center>

```js
class Student {
  constructor(nombre, apellido, edad){
    this.nombre = nombre;
    this.apellido = apellido;
    this.edad = edad;
  }

  getNombreCompleto(){
    return this.nombre + " " + this.apellido;
  }
}

const pedrito = new Student("Pedro", "Romero", 26);

console.log(pedrito.getNombreCompleto()); //??
```

A. `SyntaxError Student.propotype.getNombreCompleto is not a function`
B. `Pedro Romero`
C. `null null` 
D. `undefined undefined`

Respuesta en el primer comentario.

---
How to redirect to another page when we click a button on a form with react-router-dom@v5
Tags: react
Published: 2022-10-05 14:45:32

Lets say we create a form for a login page and when we clicked the div element to sign up, we want to redirect our page to "/createuser" page.


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


- 
 We can import the useHistory hook from react-router-dom:


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

- 
 We can declare the useHistory in a const variable:


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

- 
 We add an event listener to our div, so that it can listen for a click and then passed in a callback function and then push the url route we want our form to redirect to once we click the sign up div to the useHistory that we declared inside the navigation variable.


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

_Note that the useHistory() is for react-router-dom@5_

If you are using the newer version then instead of using the useHistory Hook you can use the useNavigate Hook.

for example: 

**For the V5**
```
const navigate = usehistory();
navigate.push("/");
```

**For the V6**

```
const navigate = useNavigate();
navigate("/")
```