teleren/devto huggingface dataset:
Максимальная высота дерева
Published: 2023-11-25 22:16:13


Ссылка на leetcode: [https://leetcode.com/problems/maximum-depth-of-binary-tree/description/](https://leetcode.com/problems/maximum-depth-of-binary-tree/description/)

**Задача**. Дано бинарное дерево. Найти его максимальную высоту.

Например, для дерева

![](https://cdn-images-1.medium.com/max/2000/1*NZCVMNDyVVPVkyXQpS34Tw.png)

Ответ 4.

**Решение**. Будем использовать in-order алгоритм обхода бинарного дерева ([Алгоритмы обхода двоичного дерева](https://dev.to/faangmaster/alghoritmy-obkhoda-dvoichnogho-dierieva-26l4)):

```java
    public static void dfs(BinaryTree tree) {
      if (tree == null) {
        return;
      }
      visit(tree);
      dfs(tree.left);
      dfs(tree.right);
    }
```

**Вариант 1 решения. Будем высоту считать снизу вверх.** Когда достигли листовой вершины (нет дочерних верших), то вернем ноль. Для каждой вершины будем находить максимальную глубину между левой и правой подветкой и прибавлять 1 к результату.

```java
    class Solution {
        public int maxDepth(TreeNode root) {
            if (root == null) {
                return 0;
            }
            int leftDepth = maxDepth(root.left);
            int rightDepth = maxDepth(root.right);
            return Math.max(leftDepth, rightDepth) + 1;
        }
    }
```

Изобразил на картинке, для нашего примера как будут происходить вычисления. Для каждой вершины нарисовал красным, какие значения будет возвращать функция:

![](https://cdn-images-1.medium.com/max/2000/1*fDYZ-bx1yhrFCMvZpreLXw.png)

**Вариант 2. Считаем высоту сверху вниз, высоту передаем в качестве параметра функции. Сохраняем результат в глобальной переменной.**

```java
    class Solution {
        int max = 0;
        public int maxDepth(TreeNode root) {
            //Высота корня дерева = 1
            traverse(root, 1);
            return max;
        }
        
        private void traverse(TreeNode root, int height) {
            if (root == null) {
                return;
            }
            //обновляем максимум
            max = Math.max(max, height);
            //рекурсивный вызов для левой и правой вершины
            traverse(root.left, height + 1);
            traverse(root.right, height + 1);
        }
    }
```

**Вариант 3. Считаем высоту сверху вниз, высоту передаем в качестве параметра функции. Вычисляем максимальную глубину между левой и правой подветкой и возвращаем результат в качестве возвращаемого значения функции.**

```java
    class Solution {
        public int maxDepth(TreeNode root) {
            //Высота корня дерева = 1
            return dfs(root, 1);
        }
        
        private int dfs(TreeNode root, int height) {
            if (root == null) {
                return height - 1;
            }
            //рекурсивный вызов для левой и правой вершины
            int leftHeight = dfs(root.left, height + 1);
            int rightHeight = dfs(root.right, height + 1);
            
            return Math.max(leftHeight, rightHeight);
        }
    }
```
Проверить скобочное выражение
Published: 2023-11-25 21:54:08


Дана строка, содержащая три вида скобок : (, ), {, }, [ , ], а также буквы латинского алфавита и цифры. Определите, верно ли скобочное выражение.

Для валидности скобочного выражения необходимо:

Открытые скобки должны быть закрыты однотипными скобками.
Открытые скобки должны быть закрыты в правильном порядке.
Каждой закрывающей скобке соответствует открытая скобка того же типа.

Например,

(sdfkhg234(dfg){}fdgfg){dfg(fg)} -> Верное выражение

)(-> Неверное выражение.
(({}))[]()->Верное.

([})-> Неверное.

**Решение.** Для решения можно использовать [стек](https://ru.wikipedia.org/wiki/%D0%A1%D1%82%D0%B5%D0%BA). Работу стека можно себе представить, как работу со стобкой книг. Книги можно класть только сверху, нельзя класть их в середину или в самый низ. Брать книги также можно только сверху. Этот принцип называется LIFO (Last In - First Out).

Для решения пройдем циклом по всех элементам строки. Если это открывающаяся скобка, то просто помещаем ее в стек. Если это закрывающаяся скобка, то сначала проверим не пустой ли стек. Если он пустой, значит не было еще открывающейся скобки до этого. Соответсвенно, выражение не валидно. Если стек не пустой, проверим, какая была предыдущая скобка (она будет на вершине стека). Если она другого типа, то строка не валидна. Если предыдущая открывающаяся скобка соответствует текущей закрывающейся, то просто убираем эту скобку из стека. Все остальные символы просто игнорируем и переходим на следующую итерацию цикла. Если после всех итераций цикла в стеке остались незакрытые открывающиеся скобки, то выражение не валидно. Если стек пуск, значит мы нашли все соответствующией закрывающиеся скобки.

Изобразил работу алгоритма и состояние стека для примера ([]):

![](https://cdn-images-1.medium.com/max/2254/1*YUA0b4SF6WlA9kvMwsTOxg.png)

Реализация на языке Java:

```java
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == '(' || c == '{' || c == '[') {
                stack.push(c);
            } else if (c == ')' || c == ']' || c == '}') {
                if (stack.isEmpty()) {
                    return false;
                }
                char top = stack.peek();
                if ((c == ')' && top != '(') 
                    || (c == '}' && top != '{') 
                    || (c == ']' && top != '[')) {
                    return false;
                }
                stack.pop();
            }
        }
        return stack.isEmpty();    
    }
```
Tailwind Css
Published: 2023-11-23 12:58:57


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/flc11gjwrclwh1je9ef3.jpeg)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/833dds2q8pyktmudc5yh.jpeg)Tailwind CSS is currently the most popular CSS library or framework. But many people come from Bootstrap who might not like writing all the classes from scratch. Again,
Many people can use them in practice projects or client's projects if they want. If PSD, FIGMA to HTML / React then not all matches will be complete but it will be a lot.
And also will work on most projects. I personally have been using it for a long time.
So, I am collecting and posting some Tailwind base libraries/sites, which I use often in practice, I hope you will benefit.
Please share

2. Flowbit
This is probably the one I use the most. Having a separate mindset for Simple + React is very beneficial
Link: https://flowbite.com/docs

2. DasiUI
Many people know about it, maybe it will also get some beautifully designed components. Specialties are various ready-made components + functionality with themes.
Link: https://lnkd.in/gGA3-7h2

3. Meraki UI
It is not an installed library but it has some ready-made components to use. 4. TailBlocks
Many people have watched this video on You Tube and you can find the components that have been fixed.
Link: https://tailblocks.cc/

5. Material Tailwind
Here is MUI's react/html component. The interesting thing is that almost exactly like MUI, MUI + Tailwind 2 doesn't need to be used and it won't have default or unnecessary classes of different libraries, the site will be fast.
Link: https://lnkd.in/gBejbZWD

6. Wind UI
Although it is recent I have exploded, but give feedback using or not you.
Link: https://lnkd.in/gfbZ7erR

7. shadcn/UI
Although it probably should have been put up, but since I just learned about it, I read it a bit. They also provide CLI tools to start projects with Next.js
Link: https://ui.shadcn.com


Note: I am a small learner, just sharing things in my business. If there is a mistake, you will look at it with a forgiving eye
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pq2nhutud4jev85s7h8g.jpeg)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jf2a6gbm4re9zihndz4t.jpeg)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vctzvwgoof52ttq11i19.jpeg)
How to Know if You Will Be a Successful Stock Trader
Published: 2023-11-25 20:51:33

Success in the stock market is a blend of skill, luck, and strategy. For aspiring traders, understanding the key indicators of potential success is crucial. This guide aims to highlight the signs that you might be on the path to becoming a successful stock trader.

## Understanding the Market

Before diving into trading, it's essential to have a thorough understanding of how the stock market works. This includes knowledge of financial instruments, market trends, and the impact of global events on stock prices.

## Analytical Skills

A successful trader often has strong analytical skills. This includes the ability to read and interpret stock charts, understand financial reports, and make decisions based on data analysis.

## Risk Management

Risk management is crucial in trading. Knowing how much risk you can afford to take and setting stop-loss orders to minimize potential losses are vital skills for a trader.

## Emotional Discipline

The ability to remain disciplined and emotionally detached is vital. Market fluctuations can be stressful, and successful traders know how to keep their emotions in check.

## Practice and Patience

Practice makes perfect. Start with a demo account to understand the market without risking real money. Be patient as gaining proficiency in trading takes time.

## Backtracking Your Predictions

One effective way to gauge your skill in predicting market trends is by backtracking your stock price predictions. Go 500 days in the past and compare the market conditions then with your current predictions. You can easily find out what the date was 500 days ago by visiting this [handy date calculator](https://timecompute.com/).

## Continuous Learning

The stock market is ever-evolving. Successful traders continuously educate themselves about new strategies, market changes, and financial instruments.

## Conclusion

Becoming a successful stock trader requires time, effort, and a willingness to learn. By understanding the market, honing analytical skills, managing risks effectively, and maintaining emotional discipline, you can increase your chances of success in the trading world.
How the request handler works with MVC pattern in laravel..
Published: 2023-11-25 20:46:14

In laravel POST method is used to send the request to the server to create and update resources. Request handler manages the incoming HTTP request and prepare the controller to process the request through MVC. MVC contains Model, View and Controller. The over view:

1. Routing: At first the http request goes throungh the routing system. In "web.php" file we define the Route method POST/GET/PUT/PETCH. create the link, give a controller method name and send it to controller.

2.Middleware: Before reaching the controller to process the http request goes through the Middleware. It decides the request is acceptable or not.it is like a filter/guard. We can filter and modify the request. Authentication, modification, logging those are done by middleware.

3.Request Object: After passing from middleware,request object encapsulates the information of the request. When a form is submitted the data of form is stored in "request object" and we fetch the data via "request object".

4.Controller dispatch: Laravel dispatches the request to the appropriate controller method based on the route definition.

5.Controller Logic: We make controller. Controller is a special class in laravel, it helps to reuse our code. in controller we call the methods, rettrive data, do interaction with models. In this page we prepare the response and return the view.

6.Responce: Controller page send the response to .blade pages. In ".blade.php" we show the result/response.it is a page of json data, file or html template. 

7.Middleware (After response): Lastly the result again go through the middleware. we can modify the result before sending it to the client.
CSS Fundamentals TIL Blog
Published: 2023-11-25 20:14:18

CSS: Cascading Style Sheets

CSS is used to help style HTML content in a webpage since html by itself may be bland.

Two methods of writing CSS code, with CSS ruleset or inline code. CSS ruleset contains brackets while inline code contains elements from html like tags 

CSS ruleset has 5 terms:
Selector, Declaration Block, Declaration, Property and Value

CSS inline style also has 5 terms almost similar to ruleset:
Opening tag, attribute, declaration, property and value

when writing using CSS inline code, can add multiple styles by the use of semicolons (Inline code rarely used for websites, but could be used if deemed necessary.)

Can separate HTML and CSS files separately for better readability through the use of external style sheets and in order for those files to be connected a link tag should be within the head section with the attributes href and rel, with href showing the location of the said file and rel showing the kind of relationship between those files.

In CSS ruleset, using * is the universal selector

Use of Class Attribute:
  The class attribute can be used to organize any kind of content within a tag, so if some content is tied to a class, that class instead can be used to manipulate that content for styling, making it much more easier to style multiple things instead of one by one or to specifically select one thing. Multiple Classes can be separated by spacing.

Difference between class and id attribute:
Class can take multiple values while id only takes in one, used once per page, class is more broader while id seems to be more specific. Class starts off with period while id starts off with hashtag when getting called in CSS

-Type, Class Id: Least specific to most specific

-Descendant combinators are when you can also select elements that are nested within another element
-Chaining is when you can specify an element using its type and its class together so that it can ignore other types with the same class.

-The more specific code will be applied instead of the general code

-Can separate selectors through the use of commas

-Difference between foreground and background color, foreground is the color element itself is in while background is the background of the said element

-Using background image in CSS utilizes a URL

-!Important can override any style, best not to use it, very hard to override
O que são microservices (microsserviços)?
Tags: microservices
Published: 2023-11-25 20:07:32

---
title: O que são microservices (microsserviços)?
published: true
description: O que são microservices (microsserviços), qual a diferença para monolitos, como quebrar microservices, como se comunicam entre si e outros esclarecimentos anotados do vídeo da TechWorld with Nana
tags: #microservices
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qhnm4j6k3i1eeqywvg0w.jpg
---

Esse texto são anotações breves tiradas do [vídeo sobre microsevices](https://www.youtube.com/watch?v=rv4LlmLmVWk) do canal [TechWorld with Nana](https://www.youtube.com/@TechWorldwithNana). As anotações são sobre os seguintes tópicos:

- [Arquitetura em monolito](#1)
- [O que são microsserviços](#2)
- [Microsserviços, CI/CD, polyrepo e monorepo](#3)

## <a name="1"></a>Arquitetura em monolito
Quando falamos em um monilito em tech estamos nos referindo a uma **arquitetura onde o código inteiro de uma aplicação é uma unidade**. Aqui, tudo é desenvolvido, deployado e escalado como uma unidade, e uma stack só.

Alguns desafios da arquitetura de monolito:

- A aplicação se torna complexa demais para entender
- As partes da aplicação se tornam muito entrelaçadas
- Só dá para escalar a aplicação inteira, mesmo que só faça sentido escalar uma parte específica
- Demora no release

Como possível solução desses desafios surgiu a arquitetura de microsserviços (em inglês, microservices).

## <a name="2"></a>O que são microsserviços?
Microsserviços são **aplicações que seguem uma arquitetura onde uma aplicação é dividida entre serviços menores, independentes**, que podem ter stacks diferentes, sendo desenvolvidos, deployados e escalados separadamente.

Para se comunicar entre si, é comum que microsserviços utilizem chamadas de APIs. Outra forma de comunicação é através de message brokers, como o RabbitMQ, onde temos filas no modelo publish/subscribe. Além disso, a comunicação pode ser feita também através de service mesh, que é um serviço que lida com toda a lógica de comunicação entre os microsserviços.

Alguns desafios de microsserviços:

- Configurar a comunicação entre esses diversos serviços
- Conseguir monitorar todos os múltiplos serviços entre servidores

## <a name="3"></a>Microsserviços, CI/CD, polyrepo e monorepo
**Polyrepo é uma estratégia de gerência de código onde criamos vários repositórios**, cada um com seu tracking de Git, por exemplo, e com isso acabamos por ter vários pipelines de CI/CD (continuous integration/continous deployment). É muito comum em empresas que seguem a arquitetura em microsserviços.

Por outro lado, a estratégia de **monorepo** nos faz lidar somente com um CI/CD pipeline, já que teremos **várias pastas, com cada serviço, mas sendo trackeadas por um único controle de versão**, por exemplo.

---
_Fontes_:
[Microservices explained - the What, Why and How?, por TechWorld with Nana](https://www.youtube.com/watch?v=rv4LlmLmVWk)

---
_Esse texto não tem intenção de esgotar o tema. Acrescente nos comentários, e também aponte erros quando os identificar._
BUY VERIFIED PAYPAL ACCOUNTS
Published: 2023-11-25 19:45:34

Buy Verified PayPal Accounts - 100% Safe Verified Accounts
We provide low cost Buy verified PayPal accounts We offer 100 money back guarantee with full access and documentation
https://usasafeservice.com/product/buy-verified-paypal-accounts/
If you want to more information just knock us–

Have a Great Day

Email: usasafeservice@gmail.com
Telegram: @usasafeservice
WhatsApp:  +1 (970) 852-4524
Skype: usasafeservice
![Uploading image](...)
BUY YELP REVIEWS
Published: 2023-11-25 19:44:15

Buy Yelp Reviews - With 100% Permanent Reviews
Buy Yelp Reviews is essential for and products selling restaurants and helps develop host, and market Yelp com and Yelp mobile applications
https://usasafeservice.com/product/buy-yelp-reviews/
If you want to know more or any query, just knock us here-
Email: usasafeservice@gmail.com
Telegram: @usasafeservice
WhatsApp: +1 (970) 852-4524
Skype: usasafeservice
![Uploading image](...)
Learn React ASAP...
Tags: webdev, javascript, programming, beginners
Published: 2023-11-25 19:24:01

**GETTING STARTED WITH REACT QUICKLY AND EASILY**

This is a broad overview of getting started on react, it is designed to help you jump into the waters of react as soon as possible.

React is a great Libary for the creation of web applications - frontend, it involves breaking down web applications into reusable components, which makes web development smooth and easier unlike creating web applications with Valina js where if you want to use a component in several places you have created it several time. 

React also allows state management - being able to manipulate states of components in an application be it text, styles, or even elements themselves.

 Join me as I delve into the intricacies of React, unlocking its potential to elevate your web development experience Welcome to a world where innovation meets simplicity, and the possibilities are boundless. Let the React adventure begin!




**1. Set Up Your Environment:**
   - Install Node.js if you haven't already, as it's required for working with React.
   - Use npm to install create-react-app globally by running the following command in your terminal:

     ```bash
     npm install -g create-react-app
     ```

**2. Create a New React App:**
   - Once create-react-app is installed, you can create a new React app by running the following command in your terminal:

     ```bash
     npm create-react-app my-app
     ```
   - Replace "my-app" with the name you want for your app.
Or  you can use vite which I recommend using this command:

     ```bash
     npm create vite@latest my-app
     ```

**3. Understand the Project Structure:**
   - The create-react-app command will generate a basic project structure for you, including the necessary files and folders to get started.
- It’s usually in this structure in its basic form when you use create-react-app:

```
my-app
├── node_modules
├── public
├── src
└── package.json
```


- It’s usually in this structure in its basic form when you use Vite and notice it has more folders:

```
my-app
├── node_modules
├── public
├── src
├── .eslintrc.cjs
├── index.html
├── README.md
├── package.json
└── vite.config.js
```

**NOTE:** These are all directories I’ll go into more detail on them in my next article

**4. Customize Your Template (Optional):**
   - If you want to customize the default template, you can edit and reorganize the files in the project folder. Depending on your preferences, you can also add extra dependencies, such as UI component libraries or code formatting tools.

**5. Start Developing:**
   - Once your template is set up, you can develop your React application by editing the components, adding new features, and building your desired user interface.

Stay tuned for upcoming articles where each step will be explored in detail.

You can refer to the official React documentation at react for more detailed information.dev (https://react.dev) or other online resources such as the [reeCodeCamp article (https://www.freecodecamp.org/news/get-started-with-react-for-beginners/) and W3schools
Rate limiting middleware in .NET 8: Fixed Window Limiter
Tags: net8, csharp
Published: 2023-11-25 19:11:24

<p>This is an example of how to implement rate limiting middleware using fixed window limiter in .NET 8 Minimal Api</p>

<h4>Program.cs</h4>

```csharp
using Microsoft.AspNetCore.RateLimiting;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

// Add rate limiting service and configure the options
builder.Services.AddRateLimiter(options =>
{
    options.AddFixedWindowLimiter("fixed", config =>
    {
        config.Window = TimeSpan.FromSeconds(5);
        config.PermitLimit = 1;

        // Disable Queue
        config.QueueLimit = 0;

        // Enable Queue
        //config.QueueLimit = 1;
        //config.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
    });
    options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
});

var app = builder.Build();
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}
app.UseHttpsRedirection();

// Enables rate limiting 
app.UseRateLimiter();

var summaries = new[]
{
    "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

app.MapGet("/limit", () =>
{
    var forecast = Enumerable.Range(1, 5).Select(index =>
        new WeatherForecast
        (
            DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
            Random.Shared.Next(-20, 55),
            summaries[Random.Shared.Next(summaries.Length)]
        ))
        .ToArray();
    return forecast;
})
.RequireRateLimiting("fixed") // Enables rate limiting on this endpoint
.WithName("Limit")
.WithOpenApi();

app.MapGet("/unlimit", () =>
{
    var forecast = Enumerable.Range(1, 5).Select(index =>
        new WeatherForecast
        (
            DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
            Random.Shared.Next(-20, 55),
            summaries[Random.Shared.Next(summaries.Length)]
        ))
        .ToArray();
    return forecast;
})
.DisableRateLimiting() // Disables rate limiting on this endpoint
.WithName("UnLimit")
.WithOpenApi();

app.Run();

internal record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
{
    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}
```
<h4>Api.http</h4>
```javascript
@BaseAddress = https://localhost:????

###
GET {{BaseAddress}}/limit

###
GET {{BaseAddress}}/unlimit

```
Ref: [Microsoft](https://learn.microsoft.com/en-us/aspnet/core/performance/rate-limit?view=aspnetcore-8.0#fixed)