teleren/devto huggingface dataset:
El uso del Null y Undefined en la definición y envío de data (Angular - TypeScript)
Published: 2022-12-19 14:26:52

Regularmente cuando desarrollamos aplicaciones que reciben y envían data al backend, tenemos al menos un proceso en el cuál preparamos la data para su parseo hacia un formulario o template o su envío al backend.
Soy **consciente** que esta propuesta en cierta forma es debatible, por lo cuál resulta una suerte de opinión sobre el tratamiento de la información, para colocarnos en contexto debemos de tener en cuenta las definiciones del null y undefined.

**Null - definición**:

> El Valor null es un literal de Javascript que representa intencionalmente un valor nulo o "vacío". ([MDN](https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Operators/null))

**Undefined - definición**

> Una variable a la que no se le ha asignado valor, o no se ha declarado en absoluto (no se declara, no existe) ... ([MDN](https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/undefined))

Con ambas definiciones en cuenta podemos decir en resumen qué, aunque en la práctica indiquen la ausencia de valor, null agrega un sentido de intencionalidad la ausencia de dicho valor; esto resulta útil, en el control del código que realizamos en el sentido de ser conscientes de lo que envíamos

Ahora bien supongamos que tenemos el siguiente método **senData** que se recibe como argumento el **form.value** de un formulario reactivo en Angular que envía los datos al backend a través de un servicio. 

```
sendData(model: T): void {
   this.servicio.enviar(model).subscribe(...)
} 
```
El servicio recibe enteramente el objeto, tenemos una fe ciega de lo que se envía. En mi opinión resulta más saludable controlar el envío ya sea desde la  inicialización o del método que prepara la data de envío; la inicialización indica el momento en el que en un formulario se define e inicializa el formControl

```
z:FormControl = new FormControl(null)
```

O del método preparativo

```
senData(model:T):void {
 const dataToSend: T = {
     a:model.a ?? null,
     b: +(model.b ?? null),
}

this.servicio.enviar(dataToSend).subscribe(...)

}

```
Y es que este ejercicio trae un trasfondo, al ser conscientes de la data que deseamos enviar también realizamos los parseos adecuados de la data.

Y en definitiva, también puede resultar en que decantes en que el diseño de las propiedades del objeto que envías no sea el más adeacuado, ¿Por qué enviar elementos que el backend no requiere?, ¿O cómo tratamos los datos sensibles?, y ahí es donde evolucionamos hacia los DTO's (próximo post)
Vamos Argentina: lionel Messi finally gets his world cup!
Tags: javascript, css, python, node
Published: 2022-12-19 14:12:29

## Golden words by Messi
I dreamed it so many times, I wanted it so much that I still haven't fallen, I can't believe it......

Thank you very much to my family, to all who support me and also to all who believed in us. We demonstrate once again that Argentines when we fight together and united we are capable of achieving what we set out to do. The merit belongs to this group, which is above individualities, it is the strength of all fighting for the same dream that was also the dream of all Argentines... We did it!!!

GO ARGENTINA FUCK!!!!! 🙌🏻🙌🏻


![lionel messi finally gets his world cup](https://pbs.twimg.com/media/FkR01MnWYAEVtzt?format=jpg&name=900x900)



## Match Insights
- Argentina have won the World Cup for a third time (also 1978 and 1986), 36 years since their last triumph in 1986. Only Italy (44 years from 1938 to 1982) has ever had a longer gap between winning two World Cups.

---


- Each of the last three reigning champions to reach the World Cup final failed to win that final, with France joining Argentina in 1990 and Brazil in 1998 in doing so.


---
- Argentina have won more penalty shootouts than any nation in World Cup history, with this their sixth such triumph. They are the third nation to win a World Cup final shootout, after Brazil in 1994 and Italy in 2006.


## Best Tweets

{% embed https://twitter.com/sundarpichai/status/1604693748767608832?s=20&t=E2m7BdI36b1NclNSyKHg2A %}


![Emiliano Martinez makes lewd gesture with the Golden Glove award](https://images.indianexpress.com/2022/12/Emiliano-Martinez-3.jpg)
how /etc/hosts file works
Tags: linux, beginners, cloud, tutorial
Published: 2022-12-19 14:05:45

In the Linux operating system, the `/etc/hosts` file is a simple text file that maps hostnames to IP addresses. It is used to resolve hostnames to IP addresses without the need for a DNS (Domain Name System) server.

The `/etc/hosts` file has the following format:


`IP_address hostname aliases` 

For example:

```
127.0.0.1 localhost
192.168.0.100 server1
```
In this example, the `/etc/hosts` file maps the hostname `localhost` to the IP address `127.0.0.1`, and the hostname `server1` to the IP address `192.168.0.100`.

You can also specify multiple aliases for a hostname by separating them with spaces. For example:


`192.168.0.100 server1 server1.example.com` 

In this case, both `server1` and `server1.example.com` will be resolved to the IP address `192.168.0.100`.

Note: In some cases, one server can have multiple IP addresses. Be sure to [get the correct IP address](https://www.howtouselinux.com/post/check-ip-address-in-linux) and add it to the file.

The `/etc/hosts` file is usually the first place the operating system looks for hostname-to-IP address mappings. If the hostname is not found in the `/etc/hosts` file, the operating system will consult a DNS server to resolve the hostname to an IP address.

You can edit the `/etc/hosts` file to add your own hostname-to-IP address mappings. This can be useful for testing purposes, or for setting up a small network without the need for a DNS server.

It is important to note that the `/etc/hosts` file does not support wildcards or regular expressions, and each entry must be specified individually.

reference: https://manpages.ubuntu.com/manpages/xenial/man5/hosts.5.html
Rails 7.1 supports password challenge via has_secure_password
Tags: rails, ruby, hassecurepassword
Published: 2022-12-19 13:54:36

From Rails 7.1 has_secure_password now includes a password_challenge accessor to validate it against the currently persisted password.

Check out my blog on this for more info
https://blog.kiprosh.com/has_secure_password-supports-password-challenge/
Calculating DMI (Directional Movement Index) with JavaScript
Tags: algorithmictrading, javascript, trading
Published: 2022-12-19 13:34:29

DMI (Directional Movement Index) is a technical analysis indicator that shows the strength of a price trend. It is calculated using the following steps:

1. Calculate the positive directional index (PDI) and the negative directional index (NDI).
2. Calculate the average true range (ATR).
3. Calculate the directional movement index (DMI).

Here is some example code in JavaScript that demonstrates how to calculate DMI using the above steps:

```
function calculateDMI(prices, periods) {
  let pdi = [];
  let ndi = [];
  let atr = [];
  let dmi = [];

  for (let i = 0; i < prices.length; i++) {
    // Calculate the positive directional index (PDI)
    let upMove = prices[i].high - prices[i - 1].high;
    let downMove = prices[i - 1].low - prices[i].low;
    let pdiValue = 0;
    if (upMove > downMove && upMove > 0) {
      pdiValue = upMove;
    }
    pdi.push(pdiValue);

    // Calculate the negative directional index (NDI)
    let ndiValue = 0;
    if (downMove > upMove && downMove > 0) {
      ndiValue = downMove;
    }
    ndi.push(ndiValue);

    // Calculate the average true range (ATR)
    let tr = Math.max(
      prices[i].high - prices[i].low,
      Math.abs(prices[i].high - prices[i - 1].close),
      Math.abs(prices[i].low - prices[i - 1].close)
    );
    let atrValue = 0;
    if (i < periods) {
      atrValue = tr;
    } else {
      atrValue = (atr[i - 1] * (periods - 1) + tr) / periods;
    }
    atr.push(atrValue);

    // Calculate the directional movement index (DMI)
    let dmiValue = 0;
    if (atrValue > 0) {
      dmiValue = (pdi[i] / atrValue) - (ndi[i] / atrValue);
    }
    dmi.push(dmiValue);
  }

  return { pdi, ndi, atr, dmi };
}
```
In this example, the **calculateDMI** function takes an array of price data and the number of periods to use in the calculation as input, and returns an object with the PDI, NDI, ATR, and DMI arrays.

You can use this function to calculate DMI for any security by passing in an array of its historical price data and the desired number of periods.
Calculating ATR (Average True Range) using JavaScript
Tags: javascript, algorithmictrading, calculation
Published: 2022-12-19 13:32:45

ATR (Average True Range) is a technical analysis indicator that shows the average range of a security’s price over a given period of time. It is calculated using the following steps:

1. Calculate the true range (TR) of each period.
2. Calculate the ATR for each period using the previous periods’ ATR values.

Here is some example code in JavaScript that demonstrates how to calculate ATR using the above steps:

```
function calculateATR(prices, periods) {
  let atr = [];

  for (let i = 0; i < prices.length; i++) {
    // Calculate the true range (TR)
    let tr = Math.max(
      prices[i].high - prices[i].low,
      Math.abs(prices[i].high - prices[i - 1].close),
      Math.abs(prices[i].low - prices[i - 1].close)
    );

    // Calculate the ATR
    let atrValue = 0;
    if (i < periods) {
      atrValue = tr;
    } else {
      atrValue = (atr[i - 1] * (periods - 1) + tr) / periods;
    }
    atr.push(atrValue);
  }

  return atr;
}
```
In this example, the **calculateATR** function takes an array of price data and the number of periods to use in the calculation as input, and returns an array of ATR values.

You can use this function to calculate ATR for any security by passing in an array of its historical price data and the desired number of periods.
Google Cloud Platform Tutorial | What is Google Cloud Platform | GCP Training
Tags: gcp, beginners
Published: 2022-12-19 13:31:18

This Edureka video on 'Google Could Platform Tutorial' will introduce you to Google Cloud Platform and help you understand various important concepts that concern Cloud Computing and Google Cloud Platform with practical implementation.

{% embed https://www.youtube.com/watch?v=J73_IPP9nDs %}
Avalonia ubuntu22.04.1 display error
Published: 2022-12-19 13:30:27

myAvalonia app set
Setter Property="SystemDecorations" Value="None"
it works well on windows/Ubuntu20.04.3 ,
but it works badly on Ubuntu22.04.1 some areas become tansparent or black when i scroll the listbox how can i fix the problem?


It seems when thecontrol's background is set to Transparent, it will cause this problem,how can i fixed it?
TRIM THEM ALL!
Tags: csharp, programming, github
Published: 2022-12-19 08:06:54

## Introduction
Once upon a time, I was diving into a new codebase and came upon an intriguing issue. StringTrim() calls polluted the entire codebase. I was taken aback. All user input, in my opinion, should be sanitized by calling at least the Trim function over all string properties. I discovered the problem root after digging a bit dipper. Users frequently copy and paste dates from local notebooks, communications, and so on. In addition, after selecting a string, it occasionally selects with surrounding space and newline characters.
As a result, a simple UserName field could be filled all possible ways:
- "John Doe "
- " John Doe"
- " John Doe "
- "John Doe"

Finally, separate program components treat this as if it were one or four different users. Simply because certain components clip spaces while others leave UserName alone.
One amusing (actually not) outcome appears to be a success story: a man registered to the internet business twice (with space difference in the userName). However, the login component treats usernames with and without a leading space as one user. The same is true for the payment subsystem. However, the order handling component sees two distinct users. As a result, the user places one order, pays once, and receives it twice. :-)

## Solve the problem with one smart enough nuget Package
Soling this and similar situations as easy as pie. You should never trust user input and always remove leading and trailing spaces. Additionally it's a good practice to remove duplicate spaces inside the strings.

Recommended nuget package is: [StringTrimmer](https://www.nuget.org/packages/DimonSmart.StringTrimmer/)

Usage is very simple. Just call TrimExtraSpaces() extension method over any user provided class. And this method automatically trim all public string properties.

``` csharp
public void CreateUser (User user)
{
   user.TrimExtraSpaces(); // Just one line
}
```

P.S. All string properties are found and trimmed using reflection in this nuget package. This method is better than nothing, but it is not the quickest! To increase class properties trimming speed I'm working on Source Generated StringTrimmmer code.
[StringTrimmerGenerator](https://github.com/DimonSmart/StringTrimmerGenerator)

Feel free to conact me and contribute to the project to make user input safer to use.
What is Algorithmic Trading
Tags: algorithmictrading
Published: 2022-12-19 13:30:19

Algorithmic trading, also known as automated trading or black box trading, refers to the use of computer programs to automatically execute trades in the financial markets. These programs, also known as trading algorithms, use mathematical models and historical data to make decisions about buying and selling securities.

Algorithmic trading has become increasingly popular in recent years due to the speed and accuracy with which it can execute trades. It allows traders to take advantage of market opportunities and make trades in a more efficient and timely manner than is possible with manual trading.

There are different types of algorithmic trading strategies that traders can use, including trend-following strategies, arbitrage strategies, and statistical arbitrage strategies. These strategies can be used to trade a variety of securities, including stocks, bonds, currencies, and commodities.

Algorithmic trading has both advantages and disadvantages. Some of the advantages include increased speed and accuracy, reduced transaction costs, and the ability to trade 24/7. However, algorithmic trading can also be risky, as it relies on complex mathematical models and can be affected by unforeseen events or market changes.

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

**Algorithmic trading** involves using computer programs to automatically execute trades in the financial markets based on a set of predefined rules. These rules, which are based on mathematical models and historical data, dictate when to buy and sell securities and at what price.

Traders use algorithmic trading for a variety of reasons, including to take advantage of market inefficiencies, to diversify their portfolio, and to reduce transaction costs. Algorithmic trading can be used to trade a wide range of securities, including stocks, bonds, currencies, and commodities.

There are different types of algorithmic trading strategies that traders can use, including trend-following strategies, arbitrage strategies, and statistical arbitrage strategies. Trend-following strategies aim to buy securities that are trending upwards and sell securities that are trending downwards. Arbitrage strategies aim to take advantage of price differences in different markets by buying low and selling high. Statistical arbitrage strategies aim to identify mispricings in the market and profit from them.

Algorithmic trading has both advantages and disadvantages. Some of the advantages include increased speed and accuracy, reduced transaction costs, and the **ability to trade 24/7**. However, algorithmic trading can also be risky, as it relies on complex mathematical models and can be affected by unforeseen events or market changes. It is important for traders to carefully consider the risks and benefits of algorithmic trading before deciding to use it in their trading activities.
Algorithmic Trading Strategies
Tags: algorithmictrading, strategy, trading
Published: 2022-12-19 13:28:12

There are many different algorithmic trading strategies that traders can use to execute trades in the financial markets. Some common strategies include:

**1. Trend-following strategies:** These strategies aim to buy securities that are trending upwards and sell securities that are trending downwards. They use technical indicators, such as moving averages, to identify trends in the market and make trades accordingly.

**2. Arbitrage strategies:** These strategies aim to take advantage of price differences in different markets by buying low and selling high. For example, a trader might buy a security on one exchange and sell it on another exchange where the price is higher.

**3. Statistical arbitrage strategies:** These strategies aim to identify mispricings in the market and profit from them. They use statistical analysis and machine learning techniques to identify mispricings and make trades accordingly.

**4. Mean reversion strategies:** These strategies aim to profit from securities that are trading away from their historical averages. They assume that prices will eventually return to their mean and make trades accordingly.

**5. High-frequency trading (HFT) strategies:** These strategies use advanced technology and fast trading algorithms to make trades at high speeds. They aim to profit from small price movements and can make a large number of trades in a short period of time.

It is important for traders to carefully consider the risks and benefits of each algorithmic trading strategy before deciding to use it in their trading activities.
Faster unit tests
Published: 2022-12-19 13:26:45

Unit tests are an integral part of any software development process. They help ensure that the codebase is stable, reliable, and easy to maintain. However, as the codebase grows and evolves, it's not uncommon for unit tests to become slower over time. This can be frustrating for us developers, who have to spend more time waiting for tests to complete, and it can also be costly in terms of machine time.

That's where BlueRacer.io comes in. BlueRacer.io is a free GitHub app that helps you keep your unit tests fast by posting a performance summary on every Pull Request. With BlueRacer, you can prevent slow tests from creeping into your codebase and save heaps of developer as well as machine time.

So, how does it work? When you use your unit tests with BlueRacer, it tracks the performance of each test and generates a report. This report is then automatically posted to your Pull Request, allowing you to see at a glance how your tests are performing. If any tests are running slower than expected, you'll be alerted, so you can take action to improve their performance.

BlueRacer is easy to use and integrates seamlessly with your existing workflow. Install the GitHub App, upload the `junit.xml` in your CI job, and that's it! No need to worry about manually tracking test performance or manually generating reports.

In addition to saving time and improving developer productivity, BlueRacer can also help improve the overall quality of your codebase. By catching slow tests early on, you can prevent them from becoming a burden on the rest of the team and ensure that your code is as efficient as possible.

Overall, BlueRacer is a powerful tool for keeping your unit tests fast and ensuring the stability and reliability of your codebase. So if you're looking to improve your unit test performance and save time and resources, give BlueRacer a try at https://github.com/apps/blueracer-io.

Happy to hear any and all feedback!
How to make an arbitrage trade
Tags: arbitrage, trading, strategy
Published: 2022-12-19 13:26:01

Arbitrage is a trading strategy that aims to take advantage of price differences in different markets by buying low and selling high. It is a way to profit from inefficiencies in the market.

Here are the steps to make an arbitrage trade:

**1. Identify price differences:** Look for price differences between different markets, exchanges, or assets. For example, you might find that the price of a stock is higher on one exchange than on another.

**2. Calculate the profit potential:** Determine how much profit you can make from the price difference by subtracting the purchase price from the sale price.

**3. Make the trade:** Buy the security on the market where the price is lower and sell it on the market where the price is higher.

**4. Close the trade:** Once the trade is complete, close the position by buying the security back on the market where you sold it and selling it on the market where you bought it.

It is important to keep in mind that arbitrage opportunities may not always be available and that there may be risks involved, such as the risk of price movements or the risk of not being able to execute the trade. It is important to carefully consider the risks and benefits of arbitrage before deciding to use it in your trading activities.
React useState unexpected extra render
Tags: react
Published: 2022-05-08 10:14:16

Taking this simple `React` counter example:


    `const { useState } = React;
    
    function Example() {
      // Declare a new state variable, which we'll call "count"
      const [count, setCount] = useState(0);
    
      console.log("Example")
    
      return (
        <div>
          <p>You clicked {count} times</p>
          <button onClick={() => setCount(1)}>
            Click me
          </button>
        </div>
      );
    }
    
    const rootElement = document.getElementById("root");
    ReactDOM.render(<Example />, rootElement);`


I've intentionally set the `setCount` handler to just const value for experimental reasons. And there is something very strange to me - the App re-renders the second time when I click the button the second time! (I'm getting `Example` output on the first and ALSO on the second click!) 

My BIG question is HOW can it happen if in the case of the second click the value of the `count` variable HASN'T changed since the first click!? (by clicking the first time is set to just `1` and the second time ALSO to `1`!)

When I click the third time and more it seems to work as expected - there are no further re-renders...

Can someone please explain me the reason of this extra render after the second click?

P.S.

PLEASE don't tell me that the cause of this may be the `react strict mode` - As anyone can CLEARLY see I'm NOT using the `strict mode` anywhere!!!
Top 100+ AWS Architect Interview Questions and Answers
Tags: awsinterview, aws
Published: 2022-12-19 13:18:24

In this Edureka AWS Interview Questions video, you will get to know the questions which you may face in the interview, the concepts explained here are essential for any Solution Architect in the making.	

{% embed https://www.edureka.co/blog/interview-questions/top-aws-architect-interview-questions/ %}