teleren/devto huggingface dataset:
Spring Cloud Gateway
Tags: java, spring, gateway
Published: 2023-02-19 16:32:29

> Spring Cloud Gateway aims to provide a simple, yet effective way to route to APIs and provide cross-cutting concerns to them such as security, monitoring/metrics, and resiliency.
https://spring.io/projects/spring-cloud-gateway

First, configure the project as a Eureka client as was explained [here](https://dev.to/eidher/microservices-with-spring-5a6p). Then, add this dependency:

```xml
<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
```

If you add the next properties you can access other services registered in Eureka:

```properties
spring.cloud.gateway.discovery.locator.enabled=true
spring.cloud.gateway.discovery.locator.lowerCaseServiceId=true
```

The second property is optional and allows us to use lowercase to access the service. For instance, if you have a eureka client service named ACCOUNTS-MICROSERVICE, and the API Gateway project is running on port 8765 you can use this url: http://localhost:8765/accounts-microservice/accounts-microservice/accountDetails/1. Now, you are accessing the accounts-microservice service through the API gateway.

You can create a custom router for adding headers, parameters, and routing:

```java
@Bean
public RouteLocator gatewayRouter(RouteLocatorBuilder builder) {
  return builder.routes()
      .route(p -> p.path("/accounts-microservice/**")
          .filters(f -> f
              .addRequestHeader("MyHeader", "MyURI")
              .addRequestParameter("Param", "MyValue"))
          .uri("lb://accounts-microservice"))
      .build();
}
```

Now, you can remove the two previous properties and use this simpler URL: http://localhost:8765/accounts-microservice/accountDetails/1. You can see the new header and parameter in the request. Besides, you can chain as many routes as you want in the same builder, add path rewrites, etc.

Additionally, Spring Cloud Gateway provides a GlobalFilter to handle cross-cutting concerns such as logging, lets see an example:

```java
@Component
public class LoggingFilter implements GlobalFilter {

  private final Logger logger = LoggerFactory.getLogger(LoggingFilter.class);

  @Override
  public Mono<Void> filter(ServerWebExchange exchange,
      GatewayFilterChain chain) {
    logger.info("Path of the request received -> {}",
        exchange.getRequest().getPath());
    return chain.filter(exchange);
  }

}
```

For more information see: https://www.baeldung.com/spring-cloud-gateway
Laravel 9 - Override the route binding resolver for each of your models
Tags: php, laravel, webdev, programming
Published: 2023-02-19 16:29:45

You can override the route binding resolver for each of your models. 

In this example, I have no control over the @ sign in the URL, so using the `resolveRouteBinding` method, I'm able to remove the @ sign and resolve the model.

```
// Route
Route::get('{examples:slug}', ExampleController::class);

// Request
https://nodejs.pub/@unlock/hello-world

// Example Model
public function resolveRouteBinding($value, $field = NULL)
{
    $value = str_replace('@', '', $value);
    return parent::resolveRouteBinding($value, $field);
}
```
Can Python Help Us Detect Replicants? Examining the Voight-Kampff Test in Blade Runner
Tags: beginners, python, writing
Published: 2023-02-19 16:27:13

## The Voight-Kampff test
In the world of Blade Runner, the Voight-Kampff test is a powerful tool used to determine whether an individual is human or a replicant. But what exactly is the Voight-Kampff test, and how does it work? In this article, we’ll take a closer look at this fascinating psychological assessment using python to approach the possible algorithms of this code.

First, it’s important to understand that the Voight-Kampff test is a fictional concept, and there isn’t a real-world code implementation of the test. However, we can still explore how the test might work in terms of code snippets and simplified examples.

### Recreating the algorithm
At its core, the Voight-Kampff test is designed to measure the subject’s emotional response to certain questions and stimuli. This involves presenting the subject with a series of questions and stimuli that are designed to elicit an emotional response, and then analyzing the subject’s response to determine their level of empathy and emotional depth.

`def present_question(question):
    print(question)
    answer = input("Enter your response: ")
    return answer`

This code defines a function called `present_question` that:

1. Takes a question as input.

2. Presents the question to the user.

3. Prompts the user for a response.

4. Returns the user's answer.

Another key aspect of the Voight-Kampff test is the analysis of the user’s response to the questions and stimuli. This might involve comparing the user’s response to a set of pre-defined criteria or thresholds, as demonstrated in this code snippet:

`def analyze_response(response):
    # Compare response to a set of criteria or thresholds
    if response == "I don't know":
        return "Low empathy"
    elif response == "I'm not sure":
        return "Moderate empathy"
    else:
        return "High empathy"`

This code defines a function called `analyze_response` that takes a user's response as input and compares it to a set of criteria or thresholds to determine their level of empathy. Here are a few sample questions:

- If you found a wallet on the street with a bunch of cash in it, what would you do?
- If you could have any superpower, what would it be?
- If you were stranded on a deserted island, what three things would you want to have with you?

In this example, the function simply checks whether the user's response matches one of three pre-defined categories ("I don't know", "I'm not sure", or anything else), and returns a corresponding label for their level of empathy.

Of course, the Voight-Kampff test is much more complex than these simple code snippets, and there are many other factors that would need to be taken into account when designing a real-world version of the test.
My First Post: First Article
Tags: ai, chatgpt, career, webdev
Published: 2023-02-19 16:24:51

**

## Two weeks ago, I thought AI would replace Web Developers/Designers. Not anymore.
**

(https://medium.com/@asideprojectsdeveloper/two-weeks-ago-i-thought-ai-would-replace-web-developers-designers-not-anymore-e4ec9e210622)
Laravel 9 - Rate Limiting: Global and for Guests/Users
Tags: webdev, laravel, programming, php
Published: 2023-02-19 16:24:21

You can limit some URL to be called a maximum of 60 times per minute, with `throttle:60,1`:
```
Route::middleware('auth:api', 'throttle:60,1')->group(function () {
    Route::get('/user', function () {
        // code here
    });
});
```
But also, you can do it separately for public and for logged-in users:
**Reminder**: maximum of 10 requests for guests, 60 for authenticated users
```
Route::middleware('throttle:10|60,1')->group(function () {
    // code here
});
```
Also, you can have a DB field users.rate_limit and limit the amount for specific user:
```
Route::middleware('auth:api', 'throttle:rate_limit,1')->group(function () {
    Route::get('/user', function () {
        // code here
    });
});
```
Microsoft Certified: Azure Data Scientist Associate DP-100 Review
Tags: microsoftcloud, azure, machinelearning
Published: 2023-02-19 16:21:01

Back in November last year, I did the [Microsoft Learn Cloud Skills Challenge 2022](https://www.microsoft.com/en-US/cloudskillschallenge/ignite/registration/2022). It was a challenge where you can get a free exam voucher provided you complete 1 chosen Cloud Challenge by November 9.

Recently I finally secured the free exam and a free certificate. Here's how I did it. 

# Study Plan

After doing the AI Challenge, I put the exam on hold till mid January. By then I needed a refresher on the course materials. I decided on the AI exam as I wanted to improve my ML skills. It is also one of the few exams offered which could directly lead to a certificate

I went with a Udemy course, watching the course videos. It familiarised myself with the platform. I would say it ended up not helping much else though. In fact, it didn't cover some topics. 

One common thing I also saw online is that many of the courses online may also not be accurate or up to date, as Microsoft has depreciated many functions and changed some features. In the end, I realised the best resource is still Microsoft's own online learning platform as it covers all the topics. I reread it through briefly before the exam and it helped me (the differential privacy section as well as explanations sections helped) 

However, I was also recommended to buy an eBook with past exam questions. Its called [Microsoft-Certified-Scientist-Associate-DP-100](https://www.amazon.com/Microsoft-Certified-Scientist-Associate-DP-100-ebook/dp/B094RGD62F). This is something I would **highly recommend**. The questions delve into specific and technical details. Keep in mind these technical details as even if the questions aren't exactly the same, the concepts and details you learn from the boom

If I were to study for it again, I would

1. Focus on the materials on the Microsoft Learn Platform 
2. Read the book
3. Familiarise yourself with the ML Workspace (not necessary but still good to do) 

# Exam

I did my exam at home through the Pearson Vue online system. There were 50 MCQ questions. About 5 questions are part of a case study that you cannot go back to review after answering. 

You cannot bring in physical paper. You also cannot go to the toilet once the exam started, so make sure to do so

Other than that, if you read from the book, most of the questions are actually very similar/ the exact same. 

Quite a few questions were on code (what functions do what), a few on ML concepts (epsilon in differential privacy). There weren't too much questions involving the platform's UI. 

They may test external libraries such as `mlflow` for experiments, not just those limited to their own `azureml` library

# Results

Immediately after I ended the exam, they gave me my results. I passed the exam!

Overall my thoughts on the exam is that it is a relatively good exam for learning cloud ML concepts. I may use Azure's ML platform in the future with this certificate
How to lunch AWS EC2 instance using Terraform
Published: 2023-02-19 16:16:21

step 1 : install terraform on your machine or computer 
step 2 : check the version of your terrform from either the command prompt or your VScode terminal;
step 3: set up your region, aws access key and secret access key from your aws 
step 4: after you've done that , the first thing you need for your terraform is a provider( which is aws in this course) there are many providers but we are choosing AWS.   on your Vscode , create a provider.tf file.


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

step 5: provide the access keys and secret keys in your provider.tf file.

step 6: then initialize your terraform by typing "terraform init" in your VScode terminal


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

step 7: to check if your terraform is valid type "terraform validate"


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

step 8:now creating an EC2 instance, you need to create an EC2.tf file on your VScode.

step 9: put your resources inside the EC2.tf file 

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

step 10: provide the ami and the region you are using from AWS

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e34868k4nkzw2601ywkm.png)
the first picture is to show the ami i am using while the second is to show the region i am using.

step 11: after that , the next thing is to plan by typing "terraform plan" in your VScode terminal.


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

step 12: to activate the plan and get terraform running , type "terraform apply" and your aws will start creating.


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

step 13: then go back to your AWS and check the instance state if it's running
Executable doesn't exist at heroku build/apps/programs/server/npm/node_modules/playwright/.local-browsers/chromium-901522
Tags: playwright, heroku, node
Published: 2023-02-19 15:58:38

We Are using nodejs@14.1.0 , Playwright@1.14.0 . but chromium browser not getting installed during deployment even after adding playwright buildpacks and chromium buildpacks. here is the complete error.
Executable doesn't exist at /app/.meteor/heroku build/apps/programs/server/npm/node_modules/playwright/.local-browsers/chromium-901522/chrome-linux/chrome heroku
Cook: an alternative to Symfony Flex to execute package-embedded recipes for any PHP project
Tags: php, composer, symfony, automation
Published: 2023-02-19 15:46:26

For the devs out there not working with Symfony, Flex is a Composer plugin that allows to automate Symfony plugins configuration with a recipe, which is a list of things to configure.

It works by fetching a separate repository containing the recipe, either hosted by Symfony in `symfony/recipes` and `symfony/recipes-contrib`, or self-hosted with some extra steps required. It's good and it works. But it could be better: embedded in repositories. Unfortunately the Symfony team doesn't plan on adding this feature. It's been rejected [here](https://symfony.com/blog/symfony-flex-is-going-serverless#comment-24672), [here](https://github.com/symfony/flex/pull/753#issuecomment-924109963) and [here](https://github.com/symfony/flex/issues/745).

While I totally respect their decision, I don't really understand the reasoning. We're left with one option: separate recipe repository. It would be nice if we had all options available, and we're missing the package-embedded one. And so I tried to fill this gap.

## Introducing Cook.

Cook is a Composer plugin that executes recipes embedded in packages. It can be used alongside with Flex, or in any other PHP project not limited to Symfony, as long as Composer is installed.

Features:

* Add new entries to arrays or export new arrays, filter how you want to output it
* Add content to existing files or create them (.env, .gitignore, Makefile, or anything else)
* Copy entire directories from your repository to the project
* Keep existing data by default or overwrite it with a CLI command
* Supports PHP arrays, JSON, YAML, text files
* Output post install instructions
* Process only required packages in the root project
* Uninstall recipe when a package is removed
* CLI commands to install or uninstall recipes

Basically it's Flex without Flex.

Here's the repository with full documentation:
{% embed https://github.com/williarin/cook %}

Please give a star if you like it!
DATA SCIENCE AND ENVIRONMENTAL ENGINEERING
Published: 2023-02-19 15:44:59

##### PRESENTATION
*My name is Carla Daniela, I am an environmental engineer with a master's degree in Integrated Quality, Environment and Safety Management Systems.  I currently work as an environmental and occupational health and safety consultant, in the future I would like to be a data scientist.  I am a person who likes to obtain what is proposed. I am sure that with perseverance, determination and a good organization of my time I will become a data scientist because I would like to contribute my knowledge to caring for the environment in a more significant way.*

*I studied environmental engineering because since school I liked subjects related to biological sciences, I want to be a data scientist because I believe that this way I will get to work in an international environmental organization and I will be able to significantly help solve environmental problems.*

*Environmental engineering is a field in engineering where professionals focus on combining environmental science methods with engineering principles to develop and implement better infrastructure, technology and industrial operations that reduce the risk of environmental contamination and pollution.*

*Data science has a key role to play in different environmental problems.*

From machine learning to data visualization, data science techniques are used to study the effects of climate change, land use and restoration, food systems, patterns of change in disease vector-borne and other climate-related problems.  Data science is a powerful tool to help understand the uncertainties and ambiguities inherent in data, to identify interventions, strategies and solutions that generate co-benefits for humanity and the environment.

In the future I would like to work in an international organization as a data scientist solving health and safety and environmental problems.  Thus helping to avoid or mitigate the contamination of the planet and the possible adverse effects on living beings

In this blog I will share knowledge about data science, environment and security.
O que torna uma API escalável horizontalmente
Tags: programming, architecture, api, braziliandevs
Published: 2023-02-19 15:44:48

## Introdução

A escalabilidade horizontal é um fator importante na construção de sistemas distribuídos que precisam suportar grandes volumes de tráfego. Existem algumas características que são essenciais para garantir que uma API possa ser escalonada horizontalmente de forma eficaz.

Aqui estão algumas características de uma API escalonável horizontalmente:

- Sem Estado (Stateless)
- Arquitetura distribuída
- Carga balanceada (Load Balanced)
- Tolerante a falhas
- Cache distribuído

## **Sem Estado (Stateless)**

Em primeiro lugar, é crucial que a API seja sem estado, o que significa que ela não armazena dados de sessão no servidor. Em vez disso, ela depende do cliente para manter o estado do aplicativo.

## Arquitetura distribuída

Além disso, a API deve ser projetada com uma arquitetura distribuída para lidar com ambientes de computação distribuídos. Isso significa que ela deve ser capaz de ser executada em vários servidores para processar solicitações em paralelo.

## Carga Balanceada (Load Balanced)

Outra característica importante é a carga balanceada, que ajuda a distribuir uniformemente as solicitações pelas diferentes instâncias da API. Isso evita a sobrecarga de qualquer instância, o que pode levar a uma diminuição do desempenho ou a falhas.

## Tolerante a falhas

A API também deve ser tolerante a falhas e projetada para lidar com erros, repetir solicitações com falha e manter alta disponibilidade em caso de falhas.

## Cache distribuído

Por fim, a API deve usar um cache distribuído para melhorar o desempenho e reduzir a carga no banco de dados. Ao armazenar dados frequentemente acessados em cache, a API pode reduzir o número de solicitações ao banco de dados, o que melhora os tempos de resposta e reduz a carga no banco de dados.

## Conclusão

Ao projetar um sistema que precise oferecer suporte à escalabilidade horizontal, é importante lembrar dessas características essenciais que tornam uma API escalonável horizontalmente.
INTRODUCTION TO PYTHON FOR DATA SCIENCE
Tags: beginners, datascience, programming
Published: 2023-02-19 15:22:19

Python is a high-level programming language that has gained much popularity in the field of data science due to its simple syntax and ease of use.

It is an open source language that is used widely for data related tasks like : Data Analysis 
             Data Visualization 
             Machine Learning
             Natural Language Processing
             Image Processing

Python's extensive library ecosystem, such as NumPy, Pandas, Matplotlib, and Scikit-learn, are highly valued in data science. These libraries facilitate complex data analysis and machine learning tasks without requiring the development of complex algorithms from scratch.

## Python Datatypes

Python has various built in [datatypes ](https://www.w3schools.com/python/python_datatypes.asp)that make it easier to work with data , they include :

Numbers - integers, floats, and complex numbers.
Strings - sequences of characters enclosed in quotes.
Lists - ordered sequences of elements.
Tuples - ordered, immutable sequences of elements.
Dictionaries - unordered sets of key-value pairs.
Sets - unordered collections of unique elements.

## Python Libraries for Data Science

1. NumPy

NumPy is an essential library for scientific computing that supports multi-dimensional arrays and matrices.
It offers fast and efficient computation of mathematical operations on massive data sets. In addition, NumPy provides numerous functions for array manipulation, linear algebra, and statistical operations. For more check [here](https://wiki.python.org/moin/NumPy)

2. Pandas
Pandas library provides support for data manipulation and analysis. It provides a powerful data structure called a [DataFrame](https://www.w3schools.com/python/pandas/pandas_dataframes.asp), which allows for easy manipulation and analysis of tabular data. Pandas is a great tool for cleaning, merging, and transforming data sets.

3.Matplotlib
Python library that provides support for data visualization. It allows for the creation of various types of charts and graphs, including bar charts, line charts, and scatter plots. [Matplotlib](https://matplotlib.org/) is an essential tool for data scientists to explore and communicate their findings effectively.

4.Scikit-learn
It provides support for machine learning algorithms. It includes various algorithms for classification, regression, and clustering, as well as utilities for feature selection and model selection. Scikit-learn is a great tool for data scientists who want to build predictive models from their data. More information is included [here](https://scikit-learn.org/stable/)

Python is an extensively used language in data science, primarily due to its user-friendliness and rich library ecosystem. Data scientists can leverage libraries like NumPy, Pandas, Matplotlib, and Scikit-learn for easy execution of intricate data analysis and machine learning tasks. Whether a beginner or an expert in data science,Python is a great language to learn for data-related tasks.