teleren/devto huggingface dataset:
Principios SOLID V: Principio de segregación de interfaces
Tags: solid, cleancode, cleanarchitecture, isp
Published: 2023-04-13 22:00:00

El principio de segregación de interfaces establece que una clase no debe ser obligada a implementar métodos que no utilizará. En otras palabras, una clase debe implementar solo los métodos necesarios para su comportamiento específico.

Traduciendolo al mundo real, debemos diseñar las interfaces pensando en quien las usará, sus clientes, no en implementaciones concretas que pudieran tener.

Veámoslo con un ejemplo, como hasta ahora, seguimos con Pokemons.

Tenemos una interfaz PokemonActions que define métodos para realizar acciones comunes a todos los Pokemon, como atacar, defenderse, etc. Además, se tiene una clase FlyingPokemon que representa a un Pokemon volador y otra clase ElectricPokemon que representa a un Pokemon eléctrico.

```kotlin

interface PokemonActions {
    fun attack()
    fun defend()
    fun fly()
    fun electricShock()
}

class FlyingPokemon : PokemonActions {
    override fun attack() {
        // codigo ataque
    }
    override fun defend() {
        // codigo defensa
    }
    override fun fly() {
        // codigo vuelo
    }
    override fun electricShock() {
        // codigo imposible de ejecutar
    }
}

class ElectricPokemon : PokemonActions {
    override fun attack() {
        // codigo ataque
    }
    override fun defend() {
        // codigo defensa
    }
    override fun fly() {
        // codigo imposible de ejecutar
    }
    override fun electricShock() {
        // codigo electricShock
    }
}
```

En este ejemplo, la interfaz **PokemonActions** obliga a las clases **FlyingPokemon** y **ElectricPokemon** a implementar el método **fly()**, a pesar de que solo es relevante para los Pokemon voladores, y **electricShock()**, solo relevante para los Pokemon eléctricos. Por lo tanto, se viola el principio de segregación de interfaces ya que se obliga a las clases a implementar métodos que no utilizarán.

La forma correcta de implementarlo siguiendo el principio de segregación de interfaces:

```kotlin
interface FlyingPokemonActions {
    fun attack()
    fun defend()
    fun fly()
}

interface ElectricPokemonActions {
    fun attack()
    fun defend()
    fun electricShock()
}

class FlyingPokemon : FlyingPokemonActions {
    override fun attack() {
        // codigo ataque
    }
    override fun defend() {
        // codigo defensa
    }
    override fun fly() {
        // codigo vuelo
    }
}

class ElectricPokemon : ElectricPokemonActions {
    override fun attack() {
        // codigo ataque
    }
    override fun defend() {
        // codigo defensa
    }

```

De esta manera, todo está en su sitio, ninguna clase tiene métodos inservibles y el código es claro y más descriptivo. El objetivo es tener alta cohesión y bajo acoplamiento.
How to fix Undefined type 'Spatie\Permission\Models\' . 'Permission' | 'Role' | 'HasRoles'
Tags: webdev, laravel, php, vscode
Published: 2023-04-13 21:53:41

VSCode with intelephense throws a strange and hard to debug error when using the spatie/laravel-permissions package even when you follow the docs to the letter. Here is how to fix it.

I was very frustrated for more than a few minutes with this after installing the great [Spatie package for permissions](https://spatie.be/docs/laravel-permission/v5/introduction) in a project I am working on that requires teams, roles and permissions. Click the link above to check out the documentation and you'll see immediately the appeal it has for any Laravel developer.

> Sidenote: These guys really do churn out an ever growing collection of the most helpful packages that will save you hours of thinking and development, so if you don't know about them... **get to know!**

### The Error

The error itself is the VSCode extension [Intelephense](https://intelephense.com/), that is usually very helpful when writing PHP in VSCode, telling you that there is an error with an `Undefined type ...` after you have followed the steps [outlined here in detail](https://spatie.be/docs/laravel-permission/v5/installation-laravel) to install the permissions package on your Laravel app.

We have:

- Used composer to pull in the package
- Manually registered the service provider
- Published migration and configuration files
- Adjusted to allow for teams
- Cleared the configuration cache
- Run the migrations
- Added the trait to out `User` model

**And BOOM!**... error.

![Y THO](https://www.mizouzie.dev//images/y-tho.png)

I tried `composer dump-autoload`, `./artisan config:clear` (again), `./artisan config:optimize`, all to no avail. Double checked I had followed all the steps... I had. So??

### The Solution

The short answer is, there is no reason. But here is the solution. Just reload the window.

```php
Ctrl + Shift + P // To open the editor commands

// then type in or scroll down and select...
>Developer:Reload Window
```

It's a simple as that. How annoying.

### Credit

I need to shoutout [Akshay K Nair](https://github.com/akshayknz) for replying somewhere deep in a github issue and pointing me to this. I just hope that someone else finds this a lot easier than I did!
O segredo do JSDoc + Styled Components no VSCode.
Tags: design, frontend, designpatterns, styled
Published: 2023-04-13 21:53:04

_Esse é um artigo curto, objetivo e simples... mas vai te ajudar demais!_

---

> _Essa técnica não é exclusiva para projetos grandes, mesmo num projeto que apenas você seja o Front End, você vai me agradecer_.

---

## Que negócio é esse de JSDoc?

Se você ainda não está familiarizado, JSDoc é uma ferramenta para documentar seu código JavaScript ou TypeScript. Ele permite que você descreva sua API usando comentários especiais e tags para descrever o propósito, os parâmetros, o tipo de retorno e outras informações relevantes sobre a função ou método.

Usar JSDoc pode ajudar a melhorar a legibilidade do seu código e facilitar a manutenção, mesmo em projetos pequenos. Além disso, muitos IDEs usam as informações fornecidas pelo JSDoc para fornecer sugestões úteis e melhorar a experiência de desenvolvimento.


## Vamos aos Exemplos
Você já deve ter notado que, quando você passa o mouse sobre um parâmetro em uma função, o VSCode exibe informações sobre aquele parâmetro, como o tipo e a descrição. Isso pode ser especialmente útil quando você está trabalhando com funções complexas e precisa lembrar o que cada parâmetro faz.

![detalhes em um parametro](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pinpnqivdo18qdkxc7hv.png)

Quando paro o mouse em `COLORS` ele mostra os tipos definidos pra esse `THEME`. 

Mas você concorda que isso ajuda pouco, diz apenas que o valor é uma `string`, embora no caso das cores não seja um grande problema, pois o nome é a cor.


## Exemplo Prático
Agora aqui começa a ficar interessante, veja nesse caso do `SPACING`, apenas o nome não ajuda nada, eu sei que o valor é um `number`, mas qual é o número?

![sem jsdoc](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/27aqaal8nw68djr2xihy.png)
---
Aqui entra o JSDoc no VSCode.

```javascript
/** Esses são os números definidos em cada propriedade
   *
   * xxSmall: 2,
   * xSmall: 4,
   * small: 8,
   * medium: 16,
   * large: 32,
   * xLarge: 64,
   * xxLarge: 128,
   */
  SPACING: {
    xxSmall: number;
    xSmall: number;
    small: number;
    medium: number;
    large: number;
    xLarge: number;
    xxLarge: number;
  };
```

Eu adicionei essas linhas acima do SPACING e temos a mágica.

```jsdoc
/** Esses são os números definidos em cada propriedade
   *
   * xxSmall: 2,
   * xSmall: 4,
   * small: 8,
   * medium: 16,
   * large: 32,
   * xLarge: 64,
   * xxLarge: 128,
   */
```

![com jsdoc](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6xzpza0kgmgsvet1vsro.png)


>Pronto! Agora sabemos o valor de cada parâmetro.

---
Usar JSDoc é uma forma prática de documentar e visualizar diretamente no VSCode enquanto você codifica, e pode ser especialmente útil em projetos maiores e mais complexos.

Espero que este artigo tenha sido útil! Até a próxima!
Apache2 (Optimisations)
Tags: host, programming, tutorial
Published: 2023-04-13 21:42:15

## ⚡ Installation

### Global

```bash
apt-get install apache2-utils
```

### PHP-FPM

```bash
apt-get install php7.4-fpm
```

## ⚡ Calculation

(1 CPU cores, 2 GB RAM)

### Process size

Size per each single process.

```bash
wget https://raw.githubusercontent.com/pixelb/ps_mem/master/ps_mem.py -O usage.py
chmod a+x usage.py
python usage.py
lscpu
top
top -c -p `pgrep apache -d','`
top -c -p `pgrep mariadb -d','`
top -c -p `pgrep php -d','`
```

```
{Process size} = {Used RAM (Item)} / {Process (Item)}

# Apache:
# 50M / 5P
# 10M
# (~ 150)

# PHP-FPM:
# 200M / 5P
# 40M
# (~ 256M)

# MySQL:
# (~ 256M)
```

### MaxRequestWorkers

```
MaxRequestWorkers = ({Total RAM} - {Used RAM (Kenel, MySQL...)}) / {Process size}
# (2000 - 600) / 50M
# 28M
```

### PHP-FPM max-children

```
maxclients = ({Total RAM} - {Used RAM (Kenel, MySQL...)}) / {Process size}
# (2000 - 600) / 50M
# 28M
```

## ⚡ Configuration

### Global

```bash
a2enmod deflate # GZIP
a2dismod mod_ruby # Unused
a2dismod mod_perl # Unused
```

@ */etc/apache2/apache2.conf*

```
Timeout 120
KeepAlive On
MaxKeepAliveRequests 500
KeepAliveTimeout 3
```

### Cache

```bash
a2enmod cache
a2enmod cache_disk
a2enmod expires
a2enmod headers
```

@ */etc/apache2/sites-available/{domain}.{tld}.conf*  
@ */etc/apache2/sites-available/000-default.conf*

```
<IfModule mod_disk_cache.c>
	CacheQuickHandler off
	CacheLock on
	CacheLockPath /tmp/mod_cache-lock
	CacheLockMaxAge 5
	CacheIgnoreHeaders Set-Cookie
	CacheEnable disk
	CacheHeader on
	CacheDefaultExpire 800
	CacheMaxExpire 64000
	CacheIgnoreNoLastMod On
	ExpiresActive on
	ExpiresDefault A300
</IfModule>
```

### MPM (Multi-Processing)

```bash
a2dismod mpm_prefork
a2dismod mpm_event
a2enmod mpm_worker
```

@ */etc/apache2/mods-available/mpm_worker.conf*  

```
<IfModule mpm_worker_module>
	StartServers 1 # {CORES}
	ServerLimit 150 # {RAM}
	MinSpareThreads 25
	MaxSpareThreads 75
	ThreadLimit 64
	ThreadsPerChild 25
	MaxRequestWorkers 150 # {RAM}
	MaxConnectionsPerChild 1000
</IfModule>
```

### PHP-FPM

```bash
a2enmod proxy_fcgi setenvif
a2enconf php7.4-fpm
```

@ */etc/php/7.4/fpm/pool.d/www.conf*

```
pm = dynamic
pm.max_children         256 # ({Total RAM} - {Used RAM (Kenel, MySQL...)}) / {Process size}
pm.start_servers        4 # ({CORES} * 4)
pm.min_spare_servers    2 # ({CORES} * 2)
pm.max_spare_servers    4 # ({CORES} * 4)
pm.max_requests         1000
```

### Restart

```bash
service apache2 restart
service php7.4-fpm restart
systemctl start apache-htcacheclean
```

### Test

**PHP-FPM**

```bash
php-fpm7.4 -t
```

**Cache**

```bash
ls -la /var/cache/apache2/mod_cache_disk/
```

**ApacheBench**

```bash
ab -n 1000 -c 100 -k -H "Accept-Encoding: gzip, deflate" [http[s]://]hostname[:port]/path
```

---

## Authors:

* **Jihad Sinnaour** - [Jakiboy](https://github.com/Jakiboy) (*Initial work*)

## ⭐ Support:

Please give it a Star if you like the project.
Start Your Cloud Journey: Understanding IaaS, PaaS, and SaaS for Beginners
Tags: cloud, beginners, career, googlecloud
Published: 2023-04-13 21:36:41

If you're new to cloud computing, you might have heard of IaaS, PaaS, and SaaS. These acronyms represent the three main service models of cloud computing. Understanding their differences can help you navigate Cloud Confusion and choose the right cloud services.

## Infrastructure as a Service provides you with virtual machines.

Infrastructure as a Service (IaaS) is the simplest cloud computing model; you're simply renting resources from your provider.

These resources can include virtual machines, storage, and network resources. With IaaS, you can build and manage your infrastructure on top of the cloud provider's infrastructure. Examples of IaaS providers include Google Cloud Compute Engine, Amazon Web Services EC2, and Microsoft Azure Virtual Machines.

Use IaaS when you want to maintain complete control over your infrastructure.

## Platform as a Service provides ready-made environments for you to build on.

The Platform as a Service (PaaS) model provides a set-up environment where you don't have to care about infrastructure.

With PaaS, you can focus on developing your applications while the cloud provider manages the underlying infrastructure. You can still use your own tools on top of PaaS to control your environment. Examples of PaaS providers include Google Cloud App Engine, Microsoft Azure App Service, and Salesforce Heroku.

Use PaaS when you want to focus on your application rather than infrastructure.

## Software as a Service gives you a final application to use.

SaaS is the model you are most familiar with; you pay for a service and use it online.

SaaS (Software as a Service) is a cloud computing model that provides access to software applications over the Internet. With SaaS, you don't need to install and maintain software on your devices; instead, you can access the software through a web browser or mobile app. Examples of SaaS providers include Google Workspace, Microsoft Office 365, and even Netflix is a SaaS.

I recommend a SaaS solution when you want to solve a problem without building your own solution.
Fresher Data Scientist Intro.
Tags: dataanalytics, datascience, machinelearning, ai
Published: 2023-04-13 21:33:54

Hi everyone! I'm a fresher data scientist who is learning ML/AI for my next job role and I want guidance from related professionals. In this blog post, I will share my journey so far and some of the challenges I face as a beginner in this field.

I have always been fascinated by the power of data and how it can be used to solve real-world problems. I studied statistics and computer science in college and learned the basics of data analysis, programming and machine learning. I'm an undergraduate student, mainly worked on data cleaning, visualization and reporting.

However, I soon realized that I wanted to do more than just analyze data. I wanted to create data-driven solutions that can make an impact on the world. I wanted to learn how to use advanced ML/AI techniques such as deep learning, natural language processing and computer vision to build intelligent systems that can understand, interact and learn from data.

That's why I decided to pursue a career as a data scientist and started learning ML/AI on my own. I enrolled in some online courses, read books and blogs, watched videos and podcasts, and joined online communities. I also started working on some personal projects to apply what I learned and build my portfolio.

It has been an exciting and rewarding journey so far, but also a challenging one. There is so much to learn and so many resources to choose from that it can be overwhelming sometimes. I also face some difficulties such as finding good quality data sets, choosing the right tools and frameworks, debugging errors and optimizing performance.

That's why I'm reaching out to you, the ML/AI professionals who have more experience and expertise than me. I would love to hear your advice on how to overcome these challenges and improve my skills as a data scientist. How did you learn ML/AI? What are some of the best resources you recommend? How do you approach a ML/AI problem? What are some of the best practices and tips you follow? How do you keep up with the latest trends and developments in the field?

Please share your thoughts and insights in the comments section below. I'm eager to learn from you and grow as a data scientist. Thank you for reading my blog post and for your support!
NoSQL Databases and My Adventure with Redis
Published: 2023-04-13 21:10:16

<!-- wp:paragraph -->
<p>Last year I built a Laravel app with Redis as the primary database. It was for a hackathon, the goal was to use Redis as much as possible, and I practically used Redis for everything. Cache, Queue, Event System, and the primary database. The only thing I didn’t use it for was error logging.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>For my fellow Laravel developers, you might be wondering (or already know) how I used a NoSQL database alongside the Laravel framework (even though it’s built to use MySQL.) It was super easy due to the awesome way Laravel is set up. I updated two classes. One is for providing the user to the framework. The other is for accessing key fields for authorization to the framework. All I had to do was design how we get the user from Redis (rather easy). Everything else slid right into place.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Using Redis as your primary database is pretty awesome. You can add any field you want to the user at any time. No migrations. It’s very fast. The way I set it up, I was able to access the user via token, email, and id. But any key can be set up for our user. You don’t have to set up relationships but you can if you would like to. I ended up having a lot of fun with this project.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>I use Redis in all my projects… But I’ve never used it as the primary database since this hackathon challenge.</p>
<!-- /wp:paragraph -->

<!-- wp:quote -->
<blockquote class="wp-block-quote"><!-- wp:paragraph -->
<p>But why not?</p>
<!-- /wp:paragraph --></blockquote>
<!-- /wp:quote -->

<!-- wp:paragraph -->
<p>I told you Redis was fast, fun, and easy to set up. Why wouldn’t I keep using it as my primary database? Because it cannot do what I want my database to do in the long run. Since when did queries become a hassle instead of a feature? I like being able to query large amounts of data and produce specific metrics quickly. I like to know what my data model is going to look like when I’m accessing it. Using MySQL lets me request data in a structured way and then cache it using Redis. I guess what I’m trying to say is that I think MySQL is easier to use than NoSQL so long as you know how to use it.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>I can only speak from my experience as a developer. Maybe I’m not using NoSQL databases correctly and there is a far better process I could implement. Please let me know. I’m open-minded on the subject and would love to hear from people who use NoSQL databases and scale them up. I’ve never seen this happen before and would love to learn what NoSQL databases can do.</p>
<!-- /wp:paragraph -->
Weekly Challenge #6 - Weather App
Tags: codenewbie, weeklychallenge, beginners, challenge
Published: 2023-04-13 21:08:17

---
title: Weekly Challenge #6 - Weather App
series: Weekly Challenge
published: true
tags: codenewbie, weeklychallenge, beginner, challenge
---
Hey all! I'm not sure about you, but the weather's been pretty turbulent where I live. Last week we had really cold 30°F/0°C days and now this week we're having a streak of 85°F/30°C days, with thunderstorms in between. Let me know if you've had any similar experiences with your local weather recently. 

On theme, this week's programming challenge is to build a web-based weather application that allows users to view weather forecasts for their location. Your web-based application should retrieve weather data from a weather API and display it to the user. The application should be able to detect the user's location and display the weather forecast for that location. It should also be able to display current weather conditions, such as temperature and humidity. By participating in this challenge, you'll not only improve your coding skills, but also create a useful and informative application that can help users plan their day and stay safe in inclement weather.

To get started, you'll need to choose a weather API to use. There are many weather APIs available, including OpenWeatherMap and Weather Underground. Once you've chosen an API, you'll need to sign up for an API key, which will allow you to access the API's data.

Next, start building your application! You can use any programming language or framework you like, but some good options for this challenge might include JavaScript, React, or Vue.js. You'll also need to use HTML and CSS to create the user interface for your application. Once you've written your code, test it out by entering different locations and verifying that the weather data is accurate. You can also customize your application by adding additional features, such as a 7-day forecast or the ability to search for weather data by city or ZIP code.

When you're happy with your application, share it on DEV Community and challenge other developers to create their own weather applications. You can also encourage them to customize their applications by adding additional features or using different weather APIs.

Thanks for following along! I'll be posting my own version of this app in the comments below. Remember to follow [CodeNewbie](https://dev.to/codenewbieteam) on DEV for more beginner tutorials, tips, and discussion!
Lagoon at KubeCon EU!
Tags: kubecon, event, conference, talk
Published: 2023-04-13 21:02:25

If you’re attending KubeCon EU next week, either in-person in Amsterdam or virtually, we’ll be there! Alanna, our Community Manager and Developer Advocate, will be giving a talk on [Creating a Culture of Documentation](https://kccnceu2023.sched.com/event/aa028b4181617bedca7864c622c6099f) on Wednesday, April 19 at 5:25 PM.

We’ll be at the Mirantis booth along with the awesome Lens team, so come say hi, or request a demo!
Build a Generative AI on AWS using AWS BedRock and Titan
Tags: aws, awscommunitybuilders
Published: 2023-04-13 19:42:00

AWS Announced “Amazon Bed Rock” a new service that makes Foundation Model from AI21 Labs, Anthropic, Stability AI, and Amazon accessible via an API. 

Bedrock helps us to access all the Foundation Models which are pre-trained with a large amount of dataset and Billions of Parameters. 

Amazon announced the Amazon Titan Foundation Models.

1. Generate AI - Large Language Model LLM


Titan Text is a powerful large language model (LLM) that can automate natural language tasks such as summarization and text generation. It can also be used for classification, open-ended Q&A, and information extraction, making it a versatile tool for various language-related applications.

2. Embedding.

Embeddings are used to represent queries and documents in a vector space, where the similarity between vectors can be used to rank search results. By using embeddings, search engines can better understand the meaning of queries and documents, and return more relevant results.

For example, suppose a user searches for "best Pizza restaurant in New York City." By using embeddings, a search engine can represent this query as a vector in a high-dimensional space, where words like "Pizza," "restaurant," "best," and "New York City" are mapped to specific coordinates in the vector space. Similarly, each document in the search index can also be represented as a vector.

The search engine can then rank search results based on the similarity between the query vector and the document vectors. Documents that are more similar to the query vector will be ranked higher, and returned as the top search results. By using embeddings, search engines can better understand the meaning of queries and documents, and return more relevant results.

3. Responsible AI 

AWS is Committed to advance the design and deployment of safe and trustworthy artificial intelligence which benefits all of humanity by becoming a member of https://www.responsible.ai/

Titan FMs are designed to promote responsible use of AI by identifying and mitigating inappropriate or harmful content. They are capable of detecting and eliminating harmful content in the data, preventing inappropriate content in user input, and filtering out model outputs that contain inappropriate content such as hate speech, profanity, or violent language.


For More details
https://aws.amazon.com/blogs/machine-learning/announcing-new-tools-for-building-with-generative-ai-on-aws/